From 33008644c40ffc6f9923ad5ad37c4ded32d0bd43 Mon Sep 17 00:00:00 2001 From: huolibo Date: Mon, 6 Jun 2022 23:01:37 +0800 Subject: [PATCH] fix(driver): delete java connector in TDengine (#13309) * fix(driver): delete java connector in TDengine * fix(driver): change jdbc test * ci: pull java connector code * fix: rollback pull java connector code * tests: remove test_R.sh temporary Co-authored-by: tangfangzhi Co-authored-by: Bo Ding --- Jenkinsfile2 | 10 +- src/CMakeLists.txt | 1 - src/connector/jdbc/CMakeLists.txt | 25 - src/connector/jdbc/deploy-pom.xml | 218 --- src/connector/jdbc/pom.xml | 156 -- src/connector/jdbc/readme.md | 595 -------- .../jdbc/src/main/assembly/assembly-jar.xml | 18 - .../jdbc/src/main/assembly/assembly.xml | 24 - .../com/taosdata/jdbc/AbstractConnection.java | 504 ------- .../jdbc/AbstractDatabaseMetaData.java | 1299 ---------------- .../com/taosdata/jdbc/AbstractDriver.java | 96 -- .../jdbc/AbstractParameterMetaData.java | 159 -- .../com/taosdata/jdbc/AbstractResultSet.java | 1189 --------------- .../com/taosdata/jdbc/AbstractStatement.java | 360 ----- .../com/taosdata/jdbc/ColumnMetaData.java | 65 - .../jdbc/DatabaseMetaDataResultSet.java | 239 --- .../com/taosdata/jdbc/EmptyResultSet.java | 986 ------------ .../com/taosdata/jdbc/SchemalessWriter.java | 67 - .../com/taosdata/jdbc/TSDBConnection.java | 104 -- .../java/com/taosdata/jdbc/TSDBConstants.java | 225 --- .../taosdata/jdbc/TSDBDatabaseMetaData.java | 95 -- .../java/com/taosdata/jdbc/TSDBDriver.java | 254 ---- .../java/com/taosdata/jdbc/TSDBError.java | 87 -- .../com/taosdata/jdbc/TSDBErrorNumbers.java | 99 -- .../java/com/taosdata/jdbc/TSDBException.java | 22 - .../com/taosdata/jdbc/TSDBJNIConnector.java | 384 ----- .../taosdata/jdbc/TSDBParameterMetaData.java | 8 - .../taosdata/jdbc/TSDBPreparedStatement.java | 971 ------------ .../java/com/taosdata/jdbc/TSDBResultSet.java | 490 ------ .../taosdata/jdbc/TSDBResultSetBlockData.java | 552 ------- .../taosdata/jdbc/TSDBResultSetMetaData.java | 205 --- .../taosdata/jdbc/TSDBResultSetRowData.java | 516 ------- .../taosdata/jdbc/TSDBResultSetWrapper.java | 1172 --------------- .../java/com/taosdata/jdbc/TSDBStatement.java | 148 -- .../java/com/taosdata/jdbc/TSDBSubscribe.java | 60 - .../com/taosdata/jdbc/TaosGlobalConfig.java | 30 - .../java/com/taosdata/jdbc/WrapperImpl.java | 21 - .../jdbc/enums/SchemalessProtocolType.java | 18 - .../jdbc/enums/SchemalessTimestampType.java | 13 - .../taosdata/jdbc/enums/TimestampFormat.java | 7 - .../jdbc/enums/TimestampPrecision.java | 8 - .../taosdata/jdbc/rs/RestfulConnection.java | 103 -- .../jdbc/rs/RestfulDatabaseMetaData.java | 87 -- .../com/taosdata/jdbc/rs/RestfulDriver.java | 173 --- .../jdbc/rs/RestfulParameterMetaData.java | 10 - .../jdbc/rs/RestfulPreparedStatement.java | 445 ------ .../taosdata/jdbc/rs/RestfulResultSet.java | 738 --------- .../jdbc/rs/RestfulResultSetMetaData.java | 187 --- .../taosdata/jdbc/rs/RestfulStatement.java | 165 -- .../jdbc/utils/HttpClientPoolUtil.java | 157 -- .../com/taosdata/jdbc/utils/NullType.java | 107 -- .../java/com/taosdata/jdbc/utils/OSUtils.java | 17 - .../jdbc/utils/SqlSyntaxValidator.java | 22 - .../com/taosdata/jdbc/utils/StringUtils.java | 7 - .../com/taosdata/jdbc/utils/TaosInfo.java | 73 - .../taosdata/jdbc/utils/TaosInfoMBean.java | 13 - .../java/com/taosdata/jdbc/utils/Utils.java | 233 --- .../taosdata/jdbc/ws/AbstractWSResultSet.java | 130 -- .../com/taosdata/jdbc/ws/BlockResultSet.java | 1040 ------------- .../com/taosdata/jdbc/ws/InFlightRequest.java | 73 - .../com/taosdata/jdbc/ws/ResponseFuture.java | 43 - .../java/com/taosdata/jdbc/ws/Transport.java | 50 - .../java/com/taosdata/jdbc/ws/WSClient.java | 159 -- .../com/taosdata/jdbc/ws/WSConnection.java | 64 - .../taosdata/jdbc/ws/WSPreparedStatement.java | 575 ------- .../com/taosdata/jdbc/ws/WSStatement.java | 118 -- .../com/taosdata/jdbc/ws/entity/Action.java | 48 - .../com/taosdata/jdbc/ws/entity/Code.java | 34 - .../taosdata/jdbc/ws/entity/ConnectResp.java | 25 - .../jdbc/ws/entity/FetchBlockResp.java | 21 - .../jdbc/ws/entity/FetchJsonResp.java | 24 - .../com/taosdata/jdbc/ws/entity/FetchReq.java | 18 - .../taosdata/jdbc/ws/entity/FetchResp.java | 61 - .../com/taosdata/jdbc/ws/entity/Payload.java | 16 - .../com/taosdata/jdbc/ws/entity/QueryReq.java | 18 - .../taosdata/jdbc/ws/entity/QueryResp.java | 114 -- .../com/taosdata/jdbc/ws/entity/Request.java | 41 - .../jdbc/ws/entity/RequestFactory.java | 48 - .../com/taosdata/jdbc/ws/entity/Response.java | 29 - .../META-INF/services/java.sql.Driver | 2 - .../java/com/taosdata/jdbc/JsonTagTest.java | 1330 ---------------- .../com/taosdata/jdbc/ParameterBindTest.java | 190 --- .../taosdata/jdbc/SchemalessInsertTest.java | 195 --- .../jdbc/SetConfigurationInJNITest.java | 249 --- .../java/com/taosdata/jdbc/SubscribeTest.java | 100 -- .../com/taosdata/jdbc/TSDBConnectionTest.java | 391 ----- .../jdbc/TSDBDatabaseMetaDataTest.java | 1107 -------------- .../com/taosdata/jdbc/TSDBDriverTest.java | 160 -- .../taosdata/jdbc/TSDBJNIConnectorTest.java | 255 ---- .../jdbc/TSDBParameterMetaDataTest.java | 204 --- .../jdbc/TSDBPreparedStatementTest.java | 1245 --------------- .../com/taosdata/jdbc/TSDBResultSetTest.java | 682 --------- .../com/taosdata/jdbc/TSDBStatementTest.java | 390 ----- .../jdbc/annotation/CatalogClass.java | 86 -- .../jdbc/annotation/CatalogListener.java | 104 -- .../jdbc/annotation/CatalogMethod.java | 52 - .../jdbc/annotation/CatalogRunner.java | 36 - .../taosdata/jdbc/annotation/Description.java | 19 - .../taosdata/jdbc/annotation/TestTarget.java | 18 - .../jdbc/block/TSDBBlockJsonTagTest.java | 1338 ----------------- .../jdbc/block/TSDBBlockResultSetTest.java | 687 --------- .../jdbc/cases/AppMemoryLeakTest.java | 32 - .../jdbc/cases/AuthenticationTest.java | 88 -- .../jdbc/cases/BatchErrorIgnoreTest.java | 126 -- .../taosdata/jdbc/cases/BatchInsertTest.java | 116 -- ...iTaosdByRestfulWithDifferentTokenTest.java | 56 - .../jdbc/cases/ConnectWrongDatabaseTest.java | 20 - .../jdbc/cases/DatetimeBefore1970Test.java | 259 ---- .../jdbc/cases/DoubleQuoteInSqlTest.java | 70 - .../jdbc/cases/DriverAutoloadTest.java | 43 - .../com/taosdata/jdbc/cases/FailOverTest.java | 39 - ...etLongWithDifferentTimestampPrecision.java | 59 - .../com/taosdata/jdbc/cases/ImportTest.java | 97 -- .../jdbc/cases/InsertDbwithoutUseDbTest.java | 79 - .../cases/InsertSpecialCharacterJniTest.java | 438 ------ .../InsertSpecialCharacterRestfulTest.java | 402 ----- .../cases/InvalidResultSetPointerTest.java | 187 --- .../cases/JDBCTypeAndTypeCompareTest.java | 50 - .../cases/MicroSecondPrecisionJNITest.java | 93 -- .../MicroSecondPrecisionRestfulTest.java | 162 -- .../MultiConnectionWithDifferentDbTest.java | 106 -- .../cases/NanoSecondTimestampJNITest.java | 168 --- .../cases/NanoSecondTimestampRestfulTest.java | 170 --- .../cases/NullValueInResultSetJNITest.java | 55 - .../NullValueInResultSetRestfulTest.java | 57 - .../jdbc/cases/NullValueInResultSetTest.java | 95 -- .../PreparedStatementBatchInsertJNITest.java | 98 -- ...eparedStatementBatchInsertRestfulTest.java | 87 -- .../taosdata/jdbc/cases/QueryDataTest.java | 63 - .../jdbc/cases/ResetQueryCacheTest.java | 49 - ...sultSetMetaShouldNotBeNullRestfulTest.java | 71 - .../com/taosdata/jdbc/cases/SelectTest.java | 71 - .../com/taosdata/jdbc/cases/StableTest.java | 104 -- .../TimestampPrecisionInNanoInJniTest.java | 510 ------- .../TimestampPrecisonInNanoRestTest.java | 570 ------- .../jdbc/cases/UnsignedNumberJniTest.java | 167 -- .../jdbc/cases/UnsignedNumberRestfulTest.java | 177 --- .../jdbc/cases/UseNowInsertTimestampTest.java | 90 -- .../jdbc/confprops/BadLocaleSettingTest.java | 55 - .../jdbc/confprops/BatchFetchTest.java | 93 -- .../taosdata/jdbc/confprops/CharsetTest.java | 55 - .../jdbc/confprops/HttpKeepAliveTest.java | 59 - .../jdbc/confprops/TaosInfoMonitorTest.java | 54 - .../taosdata/jdbc/confprops/TimeZoneTest.java | 69 - .../jdbc/confprops/TimestampFormatTest.java | 181 --- .../jdbc/rs/DatabaseSpecifiedTest.java | 72 - .../jdbc/rs/RestfulConnectionTest.java | 394 ----- .../jdbc/rs/RestfulDatabaseMetaDataTest.java | 1111 -------------- .../taosdata/jdbc/rs/RestfulDriverTest.java | 47 - .../com/taosdata/jdbc/rs/RestfulJDBCTest.java | 152 -- .../taosdata/jdbc/rs/RestfulJsonTagTest.java | 1280 ---------------- .../jdbc/rs/RestfulParameterMetaDataTest.java | 200 --- .../jdbc/rs/RestfulPreparedStatementTest.java | 414 ----- .../jdbc/rs/RestfulResultSetMetaDataTest.java | 220 --- .../jdbc/rs/RestfulResultSetTest.java | 686 --------- .../jdbc/rs/RestfulStatementTest.java | 365 ----- .../java/com/taosdata/jdbc/rs/SQLTest.java | 586 -------- .../com/taosdata/jdbc/rs/WasNullTest.java | 86 -- .../jdbc/utils/HttpClientPoolUtilTest.java | 103 -- .../com/taosdata/jdbc/utils/OSUtilsTest.java | 30 - .../taosdata/jdbc/utils/TimestampUtil.java | 24 - .../com/taosdata/jdbc/utils/UtilsTest.java | 208 --- .../taosdata/jdbc/ws/WSConnectionTest.java | 81 - .../com/taosdata/jdbc/ws/WSJsonTagTest.java | 1277 ---------------- .../com/taosdata/jdbc/ws/WSQueryTest.java | 63 - .../com/taosdata/jdbc/ws/WSSelectTest.java | 83 - .../test/resources/commons-logging.properties | 2 - .../src/test/resources/simplelog.properties | 5 - tests/develop-test/3-connectors/R/test.sh | 4 +- tests/parallel_test/cases.task | 2 +- tests/perftest-scripts/coverage_test.sh | 4 +- tests/test-all.sh | 4 +- 172 files changed, 16 insertions(+), 38803 deletions(-) delete mode 100644 src/connector/jdbc/CMakeLists.txt delete mode 100755 src/connector/jdbc/deploy-pom.xml delete mode 100644 src/connector/jdbc/pom.xml delete mode 100644 src/connector/jdbc/readme.md delete mode 100644 src/connector/jdbc/src/main/assembly/assembly-jar.xml delete mode 100755 src/connector/jdbc/src/main/assembly/assembly.xml delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractConnection.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDatabaseMetaData.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDriver.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractParameterMetaData.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractResultSet.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractStatement.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ColumnMetaData.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/DatabaseMetaDataResultSet.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/EmptyResultSet.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/SchemalessWriter.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConnection.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConstants.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBDatabaseMetaData.java delete mode 100755 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBDriver.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBError.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBErrorNumbers.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBException.java delete mode 100755 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBJNIConnector.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBParameterMetaData.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBPreparedStatement.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSet.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetBlockData.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetMetaData.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetWrapper.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBStatement.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBSubscribe.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TaosGlobalConfig.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/WrapperImpl.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/SchemalessProtocolType.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/SchemalessTimestampType.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/TimestampFormat.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/TimestampPrecision.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulConnection.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDatabaseMetaData.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDriver.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulParameterMetaData.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulPreparedStatement.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSet.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSetMetaData.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulStatement.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/HttpClientPoolUtil.java delete mode 100755 src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/NullType.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/OSUtils.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/SqlSyntaxValidator.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/StringUtils.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/TaosInfo.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/TaosInfoMBean.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/Utils.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/AbstractWSResultSet.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/BlockResultSet.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/InFlightRequest.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/ResponseFuture.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/Transport.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSClient.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSConnection.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSPreparedStatement.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSStatement.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Action.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Code.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/ConnectResp.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchBlockResp.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchJsonResp.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchReq.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchResp.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Payload.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/QueryReq.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/QueryResp.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Request.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/RequestFactory.java delete mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Response.java delete mode 100644 src/connector/jdbc/src/main/resources/META-INF/services/java.sql.Driver delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/JsonTagTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/ParameterBindTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/SchemalessInsertTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/SetConfigurationInJNITest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/SubscribeTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBConnectionTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBDatabaseMetaDataTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBDriverTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBJNIConnectorTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBParameterMetaDataTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBPreparedStatementTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBResultSetTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBStatementTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogClass.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogListener.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogMethod.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogRunner.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/Description.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/TestTarget.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/block/TSDBBlockJsonTagTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/block/TSDBBlockResultSetTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/AppMemoryLeakTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/AuthenticationTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/BatchErrorIgnoreTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/BatchInsertTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ConnectMultiTaosdByRestfulWithDifferentTokenTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ConnectWrongDatabaseTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DatetimeBefore1970Test.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DoubleQuoteInSqlTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DriverAutoloadTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/FailOverTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/GetLongWithDifferentTimestampPrecision.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ImportTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertDbwithoutUseDbTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertSpecialCharacterJniTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertSpecialCharacterRestfulTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InvalidResultSetPointerTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/JDBCTypeAndTypeCompareTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/MicroSecondPrecisionJNITest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/MicroSecondPrecisionRestfulTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/MultiConnectionWithDifferentDbTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NanoSecondTimestampJNITest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NanoSecondTimestampRestfulTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NullValueInResultSetJNITest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NullValueInResultSetRestfulTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NullValueInResultSetTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/PreparedStatementBatchInsertJNITest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/PreparedStatementBatchInsertRestfulTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/QueryDataTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ResetQueryCacheTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ResultSetMetaShouldNotBeNullRestfulTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/SelectTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/StableTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TimestampPrecisionInNanoInJniTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TimestampPrecisonInNanoRestTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/UnsignedNumberJniTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/UnsignedNumberRestfulTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/UseNowInsertTimestampTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/BadLocaleSettingTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/BatchFetchTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/CharsetTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/HttpKeepAliveTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TaosInfoMonitorTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TimeZoneTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TimestampFormatTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/DatabaseSpecifiedTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulConnectionTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulDatabaseMetaDataTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulDriverTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulJDBCTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulJsonTagTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulParameterMetaDataTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulPreparedStatementTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetMetaDataTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulStatementTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/SQLTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/WasNullTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/HttpClientPoolUtilTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/OSUtilsTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/TimestampUtil.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/UtilsTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSConnectionTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSJsonTagTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSQueryTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSSelectTest.java delete mode 100644 src/connector/jdbc/src/test/resources/commons-logging.properties delete mode 100644 src/connector/jdbc/src/test/resources/simplelog.properties diff --git a/Jenkinsfile2 b/Jenkinsfile2 index fceaa6554f..f213afe3b9 100644 --- a/Jenkinsfile2 +++ b/Jenkinsfile2 @@ -87,7 +87,9 @@ def sync_source() { cd ${WKC} git fetch origin +refs/pull/${CHANGE_ID}/merge git checkout -qf FETCH_HEAD - + ''' + sh ''' + cd ${WKC} if [ ! -d src/connector/python/.github ]; then rm -rf src/connector/python/* || : rm -rf src/connector/python/.* || : @@ -95,7 +97,6 @@ def sync_source() { else cd src/connector/python || echo "src/connector/python not exist" git pull || : - cd ${WKC} fi ''' } else if (env.CHANGE_URL =~ /\/TDinternal\//) { @@ -104,7 +105,9 @@ def sync_source() { cd ${WK} git fetch origin +refs/pull/${CHANGE_ID}/merge git checkout -qf FETCH_HEAD - + ''' + sh ''' + cd ${WKC} if [ ! -d community/src/connector/python/.github ]; then rm -rf community/src/connector/python/* || : rm -rf community/src/connector/python/.* || : @@ -112,7 +115,6 @@ def sync_source() { else cd community/src/connector/python || echo "community/src/connector/python not exist" git pull || : - cd ${WK} fi ''' } else { diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 8186c42084..5e9487e5a1 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -20,5 +20,4 @@ ADD_SUBDIRECTORY(wal) ADD_SUBDIRECTORY(cq) ADD_SUBDIRECTORY(dnode) ADD_SUBDIRECTORY(connector/odbc) -ADD_SUBDIRECTORY(connector/jdbc) diff --git a/src/connector/jdbc/CMakeLists.txt b/src/connector/jdbc/CMakeLists.txt deleted file mode 100644 index 0647f17fc1..0000000000 --- a/src/connector/jdbc/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -CMAKE_MINIMUM_REQUIRED(VERSION 3.0...3.20) - -PROJECT(TDengine) - -IF (TD_MVN_INSTALLED) - SET(JDBC_CMD_NAME "jdbc_cmd") - SET(JDBC_TARGET_NAME "jdbc_target") - SET(_output "${CMAKE_CURRENT_BINARY_DIR}/${JDBC_CMD_NAME}") - file(GLOB_RECURSE _depends "${CMAKE_CURRENT_SOURCE_DIR}/src/*") - ADD_CUSTOM_COMMAND(OUTPUT ${_output} - POST_BUILD - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/pom.xml - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/deploy-pom.xml - DEPENDS ${_depends} - COMMAND mvn -Dmaven.test.skip=true install -f ${CMAKE_CURRENT_SOURCE_DIR}/pom.xml - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/target/taos-jdbcdriver-2.0.38-dist.jar ${LIBRARY_OUTPUT_PATH} - COMMAND mvn -Dmaven.test.skip=true clean -f ${CMAKE_CURRENT_SOURCE_DIR}/pom.xml - COMMAND ${CMAKE_COMMAND} -E touch "${_output}" - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} - VERBATIM - COMMENT "build jdbc driver") - ADD_CUSTOM_TARGET(${JDBC_TARGET_NAME} ALL WORKING_DIRECTORY ${EXECUTABLE_OUTPUT_PATH} DEPENDS ${JDBC_CMD_NAME}) - UNSET(_depends) - UNSET(_output) -ENDIF () diff --git a/src/connector/jdbc/deploy-pom.xml b/src/connector/jdbc/deploy-pom.xml deleted file mode 100755 index 54eb18e8d5..0000000000 --- a/src/connector/jdbc/deploy-pom.xml +++ /dev/null @@ -1,218 +0,0 @@ - - - 4.0.0 - - com.taosdata.jdbc - taos-jdbcdriver - 2.0.38 - jar - - JDBCDriver - https://github.com/taosdata/TDengine/tree/master/src/connector/jdbc - TDengine JDBC Driver - - - - GNU AFFERO GENERAL PUBLIC LICENSE Version 3 - https://github.com/taosdata/TDengine/blob/master/LICENSE - repo - - - - - scm:git:git://github.com/taosdata/TDengine.git - scm:git:git@github.com:taosdata/TDengine.git - https://github.com/taosdata/TDengine/tree/master/src/connector/jdbc - HEAD - - - - - taosdata - support@taosdata.com - https://www.taosdata.com/ - https://www.taosdata.com/ - - - - - - junit - junit - 4.13 - test - - - - org.apache.httpcomponents - httpclient - 4.5.13 - - - com.alibaba - fastjson - 1.2.79 - - - com.google.guava - guava - 30.1.1-jre - - - org.java-websocket - Java-WebSocket - 1.5.2 - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 3.0.0 - - - src/main/assembly/assembly-jar.xml - - - - - make-assembly - package - - single - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.6.1 - - UTF-8 - 8 - 8 - true - true - - - - - org.apache.maven.plugins - maven-source-plugin - 3.2.1 - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.2.0 - - UTF-8 - UTF-8 - UTF-8 - - - - attach-javadocs - - jar - - - none - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.6 - - - sign-artifacts - verify - - sign - - - - - - org.apache.maven.plugins - maven-deploy-plugin - 2.8.2 - - - default-deploy - deploy - - deploy - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - true - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - ossrh-td - https://oss.sonatype.org/ - true - - - - org.apache.maven.plugins - maven-release-plugin - 2.5.3 - - true - false - forked-path - -Dgpg.passphrase=${gpg.passphrase} - - - - org.apache.maven.scm - maven-scm-provider-gitexe - 1.11.2 - - - - - - - - - - ossrh-td - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh-td - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - diff --git a/src/connector/jdbc/pom.xml b/src/connector/jdbc/pom.xml deleted file mode 100644 index b5db1d781d..0000000000 --- a/src/connector/jdbc/pom.xml +++ /dev/null @@ -1,156 +0,0 @@ - - 4.0.0 - com.taosdata.jdbc - taos-jdbcdriver - 2.0.38 - jar - JDBCDriver - https://github.com/taosdata/TDengine/tree/master/src/connector/jdbc - - TDengine JDBC Driver - - - GNU AFFERO GENERAL PUBLIC LICENSE Version 3 - https://github.com/taosdata/TDengine/blob/master/LICENSE - repo - - - - scm:git:git://github.com/taosdata/TDengine.git - scm:git:git@github.com:taosdata/TDengine.git - https://github.com/taosdata/TDengine/tree/master/src/connector/jdbc - HEAD - - - - taosdata - support@taosdata.com - https://www.taosdata.com/ - https://www.taosdata.com/ - - - - UTF-8 - 1.8 - 3.6.0 - - - - - org.apache.httpcomponents - httpclient - 4.5.13 - - - com.alibaba - fastjson - 1.2.83 - - - com.google.guava - guava - 30.1.1-jre - - - org.java-websocket - Java-WebSocket - 1.5.2 - - - junit - junit - 4.13.1 - test - - - - commons-logging - commons-logging - 1.2 - test - - - - - - - src/main/resources - - **/*.md - - - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 3.0.0 - - - src/main/assembly/assembly-jar.xml - - - - - make-assembly - package - - single - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - UTF-8 - ${java.version} - ${java.version} - true - true - - - - org.apache.maven.plugins - maven-surefire-plugin - 3.0.0-M6 - - pertest - ${maven.test.jvmargs} - - **/*Test.java - - - **/HttpClientPoolUtilTest.java - **/AppMemoryLeakTest.java - **/JDBCTypeAndTypeCompareTest.java - **/ConnectMultiTaosdByRestfulWithDifferentTokenTest.java - **/DatetimeBefore1970Test.java - **/FailOverTest.java - **/InvalidResultSetPointerTest.java - **/TSDBJNIConnectorTest.java - **/TaosInfoMonitorTest.java - **/UnsignedNumberJniTest.java - **/TimeZoneTest.java - - true - - - - - diff --git a/src/connector/jdbc/readme.md b/src/connector/jdbc/readme.md deleted file mode 100644 index 9bad1effb7..0000000000 --- a/src/connector/jdbc/readme.md +++ /dev/null @@ -1,595 +0,0 @@ -# Java Connector - -TDengine 提供了遵循 JDBC 标准(3.0)API 规范的 `taos-jdbcdriver` 实现,可在 maven 的中央仓库 [Sonatype Repository][1] 搜索下载。 - -`taos-jdbcdriver` 的实现包括 2 种形式: JDBC-JNI 和 JDBC-RESTful(taos-jdbcdriver-2.0.18 开始支持 JDBC-RESTful)。 JDBC-JNI 通过调用客户端 libtaos.so(或 taos.dll )的本地方法实现, JDBC-RESTful 则在内部封装了 RESTful 接口实现。 - -![tdengine-connector](https://github.com/taosdata/TDengine/blob/develop/documentation20/cn/images/tdengine-jdbc-connector.png) - -上图显示了 3 种 Java 应用使用连接器访问 TDengine 的方式: - -* JDBC-JNI:Java 应用在物理节点1(pnode1)上使用 JDBC-JNI 的 API ,直接调用客户端 API(libtaos.so 或 taos.dll)将写入和查询请求发送到位于物理节点2(pnode2)上的 taosd 实例。 -* RESTful:应用将 SQL 发送给位于物理节点2(pnode2)上的 RESTful 连接器,再调用客户端 API(libtaos.so)。 -* JDBC-RESTful:Java 应用通过 JDBC-RESTful 的 API ,将 SQL 封装成一个 RESTful 请求,发送给物理节点2的 RESTful 连接器。 - -TDengine 的 JDBC 驱动实现尽可能与关系型数据库驱动保持一致,但时序空间数据库与关系对象型数据库服务的对象和技术特征存在差异,导致 `taos-jdbcdriver` 与传统的 JDBC driver 也存在一定差异。在使用时需要注意以下几点: - -* TDengine 目前不支持针对单条数据记录的删除操作。 -* 目前不支持事务操作。 -* 目前不支持嵌套查询(nested query)。 -* 对每个 Connection 的实例,至多只能有一个打开的 ResultSet 实例;如果在 ResultSet 还没关闭的情况下执行了新的查询,taos-jdbcdriver 会自动关闭上一个 ResultSet。 - - -## JDBC-JNI和JDBC-RESTful的对比 - - - - - - - - - - - - - - - - - - - - - - - - - - -
对比项JDBC-JNIJDBC-RESTful
支持的操作系统linux、windows全平台
是否需要安装 client需要不需要
server 升级后是否需要升级 client需要不需要
写入性能JDBC-RESTful 是 JDBC-JNI 的 50%~90%
查询性能JDBC-RESTful 与 JDBC-JNI 没有差别
- -注意:与 JNI 方式不同,RESTful 接口是无状态的,因此 `USE db_name` 指令没有效果,RESTful 下所有对表名、超级表名的引用都需要指定数据库名前缀。 - -## 如何获取 taos-jdbcdriver - -### maven 仓库 - -目前 taos-jdbcdriver 已经发布到 [Sonatype Repository][1] 仓库,且各大仓库都已同步。 - -* [sonatype][8] -* [mvnrepository][9] -* [maven.aliyun][10] - -maven 项目中使用如下 pom.xml 配置即可: - -```xml - - com.taosdata.jdbc - taos-jdbcdriver - 2.0.18 - -``` - -### 源码编译打包 - -下载 [TDengine][3] 源码之后,进入 taos-jdbcdriver 源码目录 `src/connector/jdbc` 执行 `mvn clean package -Dmaven.test.skip=true` 即可生成相应 jar 包。 - - - -## JDBC的使用说明 - -### 获取连接 - -#### 指定URL获取连接 - -通过指定URL获取连接,如下所示: - -```java -Class.forName("com.taosdata.jdbc.rs.RestfulDriver"); -String jdbcUrl = "jdbc:TAOS-RS://taosdemo.com:6041/test?user=root&password=taosdata"; -Connection conn = DriverManager.getConnection(jdbcUrl); -``` - -以上示例,使用 **JDBC-RESTful** 的 driver,建立了到 hostname 为 taosdemo.com,端口为 6041,数据库名为 test 的连接。这个 URL 中指定用户名(user)为 root,密码(password)为 taosdata。 - -使用 JDBC-RESTful 接口,不需要依赖本地函数库。与 JDBC-JNI 相比,仅需要: - -1. driverClass 指定为“com.taosdata.jdbc.rs.RestfulDriver”; -2. jdbcUrl 以“jdbc:TAOS-RS://”开头; -3. 使用 6041 作为连接端口。 - -如果希望获得更好的写入和查询性能,Java 应用可以使用 **JDBC-JNI** 的driver,如下所示: - -```java -Class.forName("com.taosdata.jdbc.TSDBDriver"); -String jdbcUrl = "jdbc:TAOS://taosdemo.com:6030/test?user=root&password=taosdata"; -Connection conn = DriverManager.getConnection(jdbcUrl); -``` - -以上示例,使用了 JDBC-JNI 的 driver,建立了到 hostname 为 taosdemo.com,端口为 6030(TDengine 的默认端口),数据库名为 test 的连接。这个 URL 中指定用户名(user)为 root,密码(password)为 taosdata。 - -**注意**:使用 JDBC-JNI 的 driver,taos-jdbcdriver 驱动包时需要依赖系统对应的本地函数库。 - -* libtaos.so - 在 linux 系统中成功安装 TDengine 后,依赖的本地函数库 libtaos.so 文件会被自动拷贝至 /usr/lib/libtaos.so,该目录包含在 Linux 自动扫描路径上,无需单独指定。 - -* taos.dll - 在 windows 系统中安装完客户端之后,驱动包依赖的 taos.dll 文件会自动拷贝到系统默认搜索路径 C:/Windows/System32 下,同样无需要单独指定。 - -> 在 windows 环境开发时需要安装 TDengine 对应的 [windows 客户端][14],Linux 服务器安装完 TDengine 之后默认已安装 client,也可以单独安装 [Linux 客户端][15] 连接远程 TDengine Server。 - -JDBC-JNI 的使用请参见[视频教程](https://www.taosdata.com/blog/2020/11/11/1955.html)。 - -TDengine 的 JDBC URL 规范格式为: -`jdbc:[TAOS|TAOS-RS]://[host_name]:[port]/[database_name]?[user={user}|&password={password}|&charset={charset}|&cfgdir={config_dir}|&locale={locale}|&timezone={timezone}]` - -url中的配置参数如下: -* user:登录 TDengine 用户名,默认值 root。 -* password:用户登录密码,默认值 taosdata。 -* cfgdir:客户端配置文件目录路径,Linux OS 上默认值 /etc/taos ,Windows OS 上默认值 C:/TDengine/cfg。 -* charset:客户端使用的字符集,默认值为系统字符集。 -* locale:客户端语言环境,默认值系统当前 locale。 -* timezone:客户端使用的时区,默认值为系统当前时区。 - - - -#### 指定URL和Properties获取连接 - -除了通过指定的 URL 获取连接,还可以使用 Properties 指定建立连接时的参数,如下所示: -```java -public Connection getConn() throws Exception{ - Class.forName("com.taosdata.jdbc.TSDBDriver"); - // Class.forName("com.taosdata.jdbc.rs.RestfulDriver"); - String jdbcUrl = "jdbc:TAOS://taosdemo.com:6030/test?user=root&password=taosdata"; - // String jdbcUrl = "jdbc:TAOS-RS://taosdemo.com:6041/test?user=root&password=taosdata"; - Properties connProps = new Properties(); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - Connection conn = DriverManager.getConnection(jdbcUrl, connProps); - return conn; -} -``` - -以上示例,建立一个到 hostname 为 taosdemo.com,端口为 6030,数据库名为 test 的连接。注释为使用 JDBC-RESTful 时的方法。这个连接在 url 中指定了用户名(user)为 root,密码(password)为 taosdata,并在 connProps 中指定了使用的字符集、语言环境、时区等信息。 - -properties 中的配置参数如下: -* TSDBDriver.PROPERTY_KEY_USER:登录 TDengine 用户名,默认值 root。 -* TSDBDriver.PROPERTY_KEY_PASSWORD:用户登录密码,默认值 taosdata。 -* TSDBDriver.PROPERTY_KEY_CONFIG_DIR:客户端配置文件目录路径,Linux OS 上默认值 /etc/taos ,Windows OS 上默认值 C:/TDengine/cfg。 -* TSDBDriver.PROPERTY_KEY_CHARSET:客户端使用的字符集,默认值为系统字符集。 -* TSDBDriver.PROPERTY_KEY_LOCALE:客户端语言环境,默认值系统当前 locale。 -* TSDBDriver.PROPERTY_KEY_TIME_ZONE:客户端使用的时区,默认值为系统当前时区。 - - - -#### 使用客户端配置文件建立连接 - -当使用 JDBC-JNI 连接 TDengine 集群时,可以使用客户端配置文件,在客户端配置文件中指定集群的 firstEp、secondEp参数。 -如下所示: - -1. 在 Java 应用中不指定 hostname 和 port - -```java -public Connection getConn() throws Exception{ - Class.forName("com.taosdata.jdbc.TSDBDriver"); - String jdbcUrl = "jdbc:TAOS://:/test?user=root&password=taosdata"; - Properties connProps = new Properties(); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - Connection conn = DriverManager.getConnection(jdbcUrl, connProps); - return conn; -} -``` - -2. 在配置文件中指定 firstEp 和 secondEp - -``` -# first fully qualified domain name (FQDN) for TDengine system -firstEp cluster_node1:6030 - -# second fully qualified domain name (FQDN) for TDengine system, for cluster only -secondEp cluster_node2:6030 - -# default system charset -# charset UTF-8 - -# system locale -# locale en_US.UTF-8 -``` - -以上示例,jdbc 会使用客户端的配置文件,建立到 hostname 为 cluster_node1、端口为 6030、数据库名为 test 的连接。当集群中 firstEp 节点失效时,JDBC 会尝试使用 secondEp 连接集群。 -TDengine 中,只要保证 firstEp 和 secondEp 中一个节点有效,就可以正常建立到集群的连接。 - -> 注意:这里的配置文件指的是调用 JDBC Connector 的应用程序所在机器上的配置文件,Linux OS 上默认值 /etc/taos/taos.cfg ,Windows OS 上默认值 C://TDengine/cfg/taos.cfg。 - -#### 配置参数的优先级 - -通过以上 3 种方式获取连接,如果配置参数在 url、Properties、客户端配置文件中有重复,则参数的`优先级由高到低`分别如下: -1. JDBC URL 参数,如上所述,可以在 JDBC URL 的参数中指定。 -2. Properties connProps -3. 客户端配置文件 taos.cfg - -例如:在 url 中指定了 password 为 taosdata,在 Properties 中指定了 password 为 taosdemo,那么,JDBC 会使用 url 中的 password 建立连接。 - -> 更多详细配置请参考[客户端配置][13] - -### 创建数据库和表 - -```java -Statement stmt = conn.createStatement(); - -// create database -stmt.executeUpdate("create database if not exists db"); - -// use database -stmt.executeUpdate("use db"); - -// create table -stmt.executeUpdate("create table if not exists tb (ts timestamp, temperature int, humidity float)"); -``` - -> 注意:如果不使用 `use db` 指定数据库,则后续对表的操作都需要增加数据库名称作为前缀,如 db.tb。 - -### 插入数据 - -```java -// insert data -int affectedRows = stmt.executeUpdate("insert into tb values(now, 23, 10.3) (now + 1s, 20, 9.3)"); - -System.out.println("insert " + affectedRows + " rows."); -``` - -> now 为系统内部函数,默认为服务器当前时间。 -> `now + 1s` 代表服务器当前时间往后加 1 秒,数字后面代表时间单位:a(毫秒), s(秒), m(分), h(小时), d(天),w(周), n(月), y(年)。 - -### 查询数据 - -```java -// query data -ResultSet resultSet = stmt.executeQuery("select * from tb"); - -Timestamp ts = null; -int temperature = 0; -float humidity = 0; -while(resultSet.next()){ - - ts = resultSet.getTimestamp(1); - temperature = resultSet.getInt(2); - humidity = resultSet.getFloat("humidity"); - - System.out.printf("%s, %d, %s\n", ts, temperature, humidity); -} -``` - -> 查询和操作关系型数据库一致,使用下标获取返回字段内容时从 1 开始,建议使用字段名称获取。 - -### 处理异常 - -在报错后,通过SQLException可以获取到错误的信息和错误码: - -```java -try (Statement statement = connection.createStatement()) { - // executeQuery - ResultSet resultSet = statement.executeQuery(sql); - // print result - printResult(resultSet); -} catch (SQLException e) { - System.out.println("ERROR Message: " + e.getMessage()); - System.out.println("ERROR Code: " + e.getErrorCode()); - e.printStackTrace(); -} -``` - -JDBC连接器可能报错的错误码包括3种:JDBC driver本身的报错(错误码在0x2301到0x2350之间),JNI方法的报错(错误码在0x2351到0x2400之间),TDengine其他功能模块的报错。 -具体的错误码请参考: -* https://github.com/taosdata/TDengine/blob/develop/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBErrorNumbers.java -* https://github.com/taosdata/TDengine/blob/develop/src/inc/taoserror.h - -### 通过参数绑定写入数据 - -从 2.1.2.0 版本开始,TDengine 的 **JDBC-JNI** 实现大幅改进了参数绑定方式对数据写入(INSERT)场景的支持。采用这种方式写入数据时,能避免 SQL 语法解析的资源消耗,从而在很多情况下显著提升写入性能。(注意:**JDBC-RESTful** 实现并不提供参数绑定这种使用方式。) - -```java -Statement stmt = conn.createStatement(); -Random r = new Random(); - -// INSERT 语句中,VALUES 部分允许指定具体的数据列;如果采取自动建表,则 TAGS 部分需要设定全部 TAGS 列的参数值: -TSDBPreparedStatement s = (TSDBPreparedStatement) conn.prepareStatement("insert into ? using weather_test tags (?, ?) (ts, c1, c2) values(?, ?, ?)"); - -// 设定数据表名: -s.setTableName("w1"); -// 设定 TAGS 取值: -s.setTagInt(0, r.nextInt(10)); -s.setTagString(1, "Beijing"); - -int numOfRows = 10; - -// VALUES 部分以逐列的方式进行设置: -ArrayList ts = new ArrayList<>(); -for (int i = 0; i < numOfRows; i++){ - ts.add(System.currentTimeMillis() + i); -} -s.setTimestamp(0, ts); - -ArrayList s1 = new ArrayList<>(); -for (int i = 0; i < numOfRows; i++){ - s1.add(r.nextInt(100)); -} -s.setInt(1, s1); - -ArrayList s2 = new ArrayList<>(); -for (int i = 0; i < numOfRows; i++){ - s2.add("test" + r.nextInt(100)); -} -s.setString(2, s2, 10); - -// AddBatch 之后,缓存并未清空。为避免混乱,并不推荐在 ExecuteBatch 之前再次绑定新一批的数据: -s.columnDataAddBatch(); -// 执行绑定数据后的语句: -s.columnDataExecuteBatch(); -// 执行语句后清空缓存。在清空之后,可以复用当前的对象,绑定新的一批数据(可以是新表名、新 TAGS 值、新 VALUES 值): -s.columnDataClearBatch(); -// 执行完毕,释放资源: -s.columnDataCloseBatch(); -``` - -用于设定 TAGS 取值的方法总共有: -```java -public void setTagNull(int index, int type) -public void setTagBoolean(int index, boolean value) -public void setTagInt(int index, int value) -public void setTagByte(int index, byte value) -public void setTagShort(int index, short value) -public void setTagLong(int index, long value) -public void setTagTimestamp(int index, long value) -public void setTagFloat(int index, float value) -public void setTagDouble(int index, double value) -public void setTagString(int index, String value) -public void setTagNString(int index, String value) -``` - -用于设定 VALUES 数据列的取值的方法总共有: -```java -public void setInt(int columnIndex, ArrayList list) throws SQLException -public void setFloat(int columnIndex, ArrayList list) throws SQLException -public void setTimestamp(int columnIndex, ArrayList list) throws SQLException -public void setLong(int columnIndex, ArrayList list) throws SQLException -public void setDouble(int columnIndex, ArrayList list) throws SQLException -public void setBoolean(int columnIndex, ArrayList list) throws SQLException -public void setByte(int columnIndex, ArrayList list) throws SQLException -public void setShort(int columnIndex, ArrayList list) throws SQLException -public void setString(int columnIndex, ArrayList list, int size) throws SQLException -public void setNString(int columnIndex, ArrayList list, int size) throws SQLException -``` -其中 setString 和 setNString 都要求用户在 size 参数里声明表定义中对应列的列宽。 - -### 订阅 - -#### 创建 - -```java -TSDBSubscribe sub = ((TSDBConnection)conn).subscribe("topic", "select * from meters", false); -``` - -`subscribe` 方法的三个参数含义如下: - -* topic:订阅的主题(即名称),此参数是订阅的唯一标识 -* sql:订阅的查询语句,此语句只能是 `select` 语句,只应查询原始数据,只能按时间正序查询数据 -* restart:如果订阅已经存在,是重新开始,还是继续之前的订阅 - -如上面的例子将使用 SQL 语句 `select * from meters` 创建一个名为 `topic` 的订阅,如果这个订阅已经存在,将继续之前的查询进度,而不是从头开始消费所有的数据。 - -#### 消费数据 - -```java -int total = 0; -while(true) { - TSDBResultSet rs = sub.consume(); - int count = 0; - while(rs.next()) { - count++; - } - total += count; - System.out.printf("%d rows consumed, total %d\n", count, total); - Thread.sleep(1000); -} -``` - -`consume` 方法返回一个结果集,其中包含从上次 `consume` 到目前为止的所有新数据。请务必按需选择合理的调用 `consume` 的频率(如例子中的 `Thread.sleep(1000)`),否则会给服务端造成不必要的压力。 - -#### 关闭订阅 - -```java -sub.close(true); -``` - -`close` 方法关闭一个订阅。如果其参数为 `true` 表示保留订阅进度信息,后续可以创建同名订阅继续消费数据;如为 `false` 则不保留订阅进度。 - -### 关闭资源 - -```java -resultSet.close(); -stmt.close(); -conn.close(); -``` - -> `注意务必要将 connection 进行关闭`,否则会出现连接泄露。 - - - -## 与连接池使用 - -**HikariCP** - -* 引入相应 HikariCP maven 依赖: - -```xml - - com.zaxxer - HikariCP - 3.4.1 - -``` - -* 使用示例如下: - -```java - public static void main(String[] args) throws SQLException { - HikariConfig config = new HikariConfig(); - // jdbc properties - config.setJdbcUrl("jdbc:TAOS://127.0.0.1:6030/log"); - config.setUsername("root"); - config.setPassword("taosdata"); - // connection pool configurations - config.setMinimumIdle(10); //minimum number of idle connection - config.setMaximumPoolSize(10); //maximum number of connection in the pool - config.setConnectionTimeout(30000); //maximum wait milliseconds for get connection from pool - config.setMaxLifetime(0); // maximum life time for each connection - config.setIdleTimeout(0); // max idle time for recycle idle connection - config.setConnectionTestQuery("select server_status()"); //validation query - - HikariDataSource ds = new HikariDataSource(config); //create datasource - - Connection connection = ds.getConnection(); // get connection - Statement statement = connection.createStatement(); // get statement - - //query or insert - // ... - - connection.close(); // put back to conneciton pool -} -``` - -> 通过 HikariDataSource.getConnection() 获取连接后,使用完成后需要调用 close() 方法,实际上它并不会关闭连接,只是放回连接池中。 -> 更多 HikariCP 使用问题请查看[官方说明][5] - -**Druid** - -* 引入相应 Druid maven 依赖: - -```xml - - com.alibaba - druid - 1.1.20 - -``` - -* 使用示例如下: - -```java -public static void main(String[] args) throws Exception { - - DruidDataSource dataSource = new DruidDataSource(); - // jdbc properties - dataSource.setDriverClassName("com.taosdata.jdbc.TSDBDriver"); - dataSource.setUrl(url); - dataSource.setUsername("root"); - dataSource.setPassword("taosdata"); - // pool configurations - dataSource.setInitialSize(10); - dataSource.setMinIdle(10); - dataSource.setMaxActive(10); - dataSource.setMaxWait(30000); - dataSource.setValidationQuery("select server_status()"); - - Connection connection = dataSource.getConnection(); // get connection - Statement statement = connection.createStatement(); // get statement - //query or insert - // ... - - connection.close(); // put back to conneciton pool -} -``` - -> 更多 druid 使用问题请查看[官方说明][6] - -**注意事项** -* TDengine `v1.6.4.1` 版本开始提供了一个专门用于心跳检测的函数 `select server_status()`,所以在使用连接池时推荐使用 `select server_status()` 进行 Validation Query。 - -如下所示,`select server_status()` 执行成功会返回 `1`。 -```shell -taos> select server_status(); -server_status()| -================ -1 | -Query OK, 1 row(s) in set (0.000141s) -``` - - - -## 与框架使用 - -* Spring JdbcTemplate 中使用 taos-jdbcdriver,可参考 [SpringJdbcTemplate][11] -* Springboot + Mybatis 中使用,可参考 [springbootdemo][12] - - - -## TAOS-JDBCDriver 版本以及支持的 TDengine 版本和 JDK 版本 - -| taos-jdbcdriver 版本 | TDengine 版本 | JDK 版本 | -| -------------------- | ----------------- | -------- | -| 2.0.31 | 2.1.3.0 及以上 | 1.8.x | -| 2.0.22 - 2.0.30 | 2.0.18.0 - 2.1.2.x | 1.8.x | -| 2.0.12 - 2.0.21 | 2.0.8.0 - 2.0.17.x | 1.8.x | -| 2.0.4 - 2.0.11 | 2.0.0.0 - 2.0.7.x | 1.8.x | -| 1.0.3 | 1.6.1.x 及以上 | 1.8.x | -| 1.0.2 | 1.6.1.x 及以上 | 1.8.x | -| 1.0.1 | 1.6.1.x 及以上 | 1.8.x | - - - -## TDengine DataType 和 Java DataType - -TDengine 目前支持时间戳、数字、字符、布尔类型,与 Java 对应类型转换如下: - -| TDengine DataType | Java DataType | -| ----------------- | ------------------ | -| TIMESTAMP | java.sql.Timestamp | -| INT | java.lang.Integer | -| BIGINT | java.lang.Long | -| FLOAT | java.lang.Float | -| DOUBLE | java.lang.Double | -| SMALLINT | java.lang.Short | -| TINYINT | java.lang.Byte | -| BOOL | java.lang.Boolean | -| BINARY | byte array | -| NCHAR | java.lang.String | - - - -## 常见问题 - -* java.lang.UnsatisfiedLinkError: no taos in java.library.path - - **原因**:程序没有找到依赖的本地函数库 taos。 - - **解决方法**:windows 下可以将 C:\TDengine\driver\taos.dll 拷贝到 C:\Windows\System32\ 目录下,linux 下将建立如下软链 `ln -s /usr/local/taos/driver/libtaos.so.x.x.x.x /usr/lib/libtaos.so` 即可。 - -* java.lang.UnsatisfiedLinkError: taos.dll Can't load AMD 64 bit on a IA 32-bit platform - - **原因**:目前 TDengine 只支持 64 位 JDK。 - - **解决方法**:重新安装 64 位 JDK。 - -* 其它问题请参考 [Issues][7] - -[1]: https://search.maven.org/artifact/com.taosdata.jdbc/taos-jdbcdriver -[2]: https://mvnrepository.com/artifact/com.taosdata.jdbc/taos-jdbcdriver -[3]: https://github.com/taosdata/TDengine -[4]: https://www.taosdata.com/blog/2019/12/03/jdbcdriver%e6%89%be%e4%b8%8d%e5%88%b0%e5%8a%a8%e6%80%81%e9%93%be%e6%8e%a5%e5%ba%93/ -[5]: https://github.com/brettwooldridge/HikariCP -[6]: https://github.com/alibaba/druid -[7]: https://github.com/taosdata/TDengine/issues -[8]: https://search.maven.org/artifact/com.taosdata.jdbc/taos-jdbcdriver -[9]: https://mvnrepository.com/artifact/com.taosdata.jdbc/taos-jdbcdriver -[10]: https://maven.aliyun.com/mvn/search -[11]: https://github.com/taosdata/TDengine/tree/develop/tests/examples/JDBC/SpringJdbcTemplate -[12]: https://github.com/taosdata/TDengine/tree/develop/tests/examples/JDBC/springbootdemo -[13]: https://www.taosdata.com/cn/documentation/administrator/#client -[14]: https://www.taosdata.com/cn/all-downloads/#TDengine-Windows-Client -[15]: https://www.taosdata.com/cn/getting-started/#%E5%AE%A2%E6%88%B7%E7%AB%AF - diff --git a/src/connector/jdbc/src/main/assembly/assembly-jar.xml b/src/connector/jdbc/src/main/assembly/assembly-jar.xml deleted file mode 100644 index 23ba5529f9..0000000000 --- a/src/connector/jdbc/src/main/assembly/assembly-jar.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - dist - - jar - - false - - - / - true - true - runtime - - - \ No newline at end of file diff --git a/src/connector/jdbc/src/main/assembly/assembly.xml b/src/connector/jdbc/src/main/assembly/assembly.xml deleted file mode 100755 index bdeaacfb6e..0000000000 --- a/src/connector/jdbc/src/main/assembly/assembly.xml +++ /dev/null @@ -1,24 +0,0 @@ - - dist - - tar.gz - - - - true - / - - - - \ No newline at end of file diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractConnection.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractConnection.java deleted file mode 100644 index 15695ae920..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractConnection.java +++ /dev/null @@ -1,504 +0,0 @@ -package com.taosdata.jdbc; - -import com.taosdata.jdbc.enums.TimestampFormat; - -import java.sql.*; -import java.util.Enumeration; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.*; - -public abstract class AbstractConnection extends WrapperImpl implements Connection { - - protected volatile boolean isClosed; - protected volatile String catalog; - protected final Properties clientInfoProps = new Properties(); - - protected AbstractConnection(Properties properties) { - Set propNames = properties.stringPropertyNames(); - for (String propName : propNames) { - clientInfoProps.setProperty(propName, properties.getProperty(propName)); - } - String timestampFormat = properties.getProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, String.valueOf(TimestampFormat.STRING)); - clientInfoProps.setProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, timestampFormat); - } - - @Override - public abstract Statement createStatement() throws SQLException; - - @Override - public abstract PreparedStatement prepareStatement(String sql) throws SQLException; - - @Override - public CallableStatement prepareCall(String sql) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public String nativeSQL(String sql) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - // do nothing - - return sql; - } - - - @Override - public void setAutoCommit(boolean autoCommit) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - //do nothing - } - - @Override - public boolean getAutoCommit() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - return true; - } - - @Override - public void commit() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - // do nothing - } - - @Override - public void rollback() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - // do nothing - } - - @Override - public abstract void close() throws SQLException; - - @Override - public abstract boolean isClosed() throws SQLException; - - @Override - public abstract DatabaseMetaData getMetaData() throws SQLException; - - @Override - public void setReadOnly(boolean readOnly) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - //do nothing - } - - @Override - public boolean isReadOnly() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - return true; - } - - @Override - public void setCatalog(String catalog) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - this.catalog = catalog; - } - - @Override - public String getCatalog() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - return this.catalog; - } - - @Override - public void setTransactionIsolation(int level) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - switch (level) { - case Connection.TRANSACTION_NONE: - break; - case Connection.TRANSACTION_READ_UNCOMMITTED: - case Connection.TRANSACTION_READ_COMMITTED: - case Connection.TRANSACTION_REPEATABLE_READ: - case Connection.TRANSACTION_SERIALIZABLE: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - default: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - } - //do nothing - } - - @Override - public int getTransactionIsolation() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - return Connection.TRANSACTION_NONE; - } - - @Override - public SQLWarning getWarnings() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - return null; - } - - @Override - public void clearWarnings() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - // do nothing - } - - private void checkResultSetTypeAndResultSetConcurrency(int resultSetType, int resultSetConcurrency) throws SQLException { - switch (resultSetType) { - case ResultSet.TYPE_FORWARD_ONLY: - break; - case ResultSet.TYPE_SCROLL_INSENSITIVE: - case ResultSet.TYPE_SCROLL_SENSITIVE: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - default: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - } - - switch (resultSetConcurrency) { - case ResultSet.CONCUR_READ_ONLY: - break; - case ResultSet.CONCUR_UPDATABLE: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - default: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - } - } - - @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - checkResultSetTypeAndResultSetConcurrency(resultSetType, resultSetConcurrency); - return createStatement(); - } - - @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - checkResultSetTypeAndResultSetConcurrency(resultSetType, resultSetConcurrency); - return prepareStatement(sql); - } - - @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Map> getTypeMap() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setTypeMap(Map> map) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setHoldability(int holdability) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - switch (holdability) { - case ResultSet.HOLD_CURSORS_OVER_COMMIT: - break; - case ResultSet.CLOSE_CURSORS_AT_COMMIT: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - default: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - } - //do nothing - } - - @Override - public int getHoldability() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - return ResultSet.HOLD_CURSORS_OVER_COMMIT; - } - - @Override - public Savepoint setSavepoint() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Savepoint setSavepoint(String name) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void rollback(Savepoint savepoint) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void releaseSavepoint(Savepoint savepoint) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - switch (resultSetHoldability) { - case ResultSet.HOLD_CURSORS_OVER_COMMIT: - break; - case ResultSet.CLOSE_CURSORS_AT_COMMIT: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - default: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - } - - return createStatement(resultSetType, resultSetConcurrency); - } - - @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - switch (resultSetHoldability) { - case ResultSet.HOLD_CURSORS_OVER_COMMIT: - break; - case ResultSet.CLOSE_CURSORS_AT_COMMIT: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - default: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - } - return prepareStatement(sql, resultSetType, resultSetConcurrency); - } - - @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - switch (autoGeneratedKeys) { - case Statement.RETURN_GENERATED_KEYS: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - case Statement.NO_GENERATED_KEYS: - break; - } - return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); - } - - @Override - public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Clob createClob() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Blob createBlob() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public NClob createNClob() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public SQLXML createSQLXML() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean isValid(int timeout) throws SQLException { - //true if the connection is valid, false otherwise - if (isClosed()) - return false; - if (timeout < 0) //SQLException - if the value supplied for timeout is less than 0 - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - - ExecutorService executor = Executors.newCachedThreadPool(); - Future future = executor.submit(() -> { - int status; - try (Statement stmt = createStatement()) { - ResultSet resultSet = stmt.executeQuery("select server_status()"); - resultSet.next(); - status = resultSet.getInt("server_status()"); - resultSet.close(); - } - return status == 1; - }); - - boolean status = false; - try { - if (timeout == 0) - status = future.get(); - else - status = future.get(timeout, TimeUnit.SECONDS); - } catch (InterruptedException | ExecutionException ignored) { - } catch (TimeoutException e) { - future.cancel(true); - } finally { - executor.shutdownNow(); - } - return status; - } - - @Override - public void setClientInfo(String name, String value) throws SQLClientInfoException { - if (isClosed) - throw (SQLClientInfoException) TSDBError.createSQLException(TSDBErrorNumbers.ERROR_SQLCLIENT_EXCEPTION_ON_CONNECTION_CLOSED); - - clientInfoProps.setProperty(name, value); - } - - @Override - public void setClientInfo(Properties properties) throws SQLClientInfoException { - if (isClosed) - throw (SQLClientInfoException) TSDBError.createSQLException(TSDBErrorNumbers.ERROR_SQLCLIENT_EXCEPTION_ON_CONNECTION_CLOSED); - - for (Enumeration enumeration = properties.keys(); enumeration.hasMoreElements(); ) { - String name = (String) enumeration.nextElement(); - clientInfoProps.put(name, properties.getProperty(name)); - } - } - - @Override - public String getClientInfo(String name) throws SQLException { - if (isClosed) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - return clientInfoProps.getProperty(name); - } - - @Override - public Properties getClientInfo() throws SQLException { - if (isClosed) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - return clientInfoProps; - } - - @Override - public Array createArrayOf(String typeName, Object[] elements) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Struct createStruct(String typeName, Object[] attributes) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setSchema(String schema) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - //do nothing - } - - @Override - public String getSchema() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - return null; - } - - @Override - public void abort(Executor executor) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - // do nothing - } - - @Override - public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - if (milliseconds < 0) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - - // do nothing - } - - @Override - public int getNetworkTimeout() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - return 0; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDatabaseMetaData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDatabaseMetaData.java deleted file mode 100644 index 3cd6f45bf0..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDatabaseMetaData.java +++ /dev/null @@ -1,1299 +0,0 @@ -package com.taosdata.jdbc; - -import com.taosdata.jdbc.utils.StringUtils; - -import java.sql.*; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public abstract class AbstractDatabaseMetaData extends WrapperImpl implements DatabaseMetaData { - - private final static String PRODUCT_NAME = "TDengine"; - private final static String PRODUCT_VESION = "2.0.x.x"; - private final static String DRIVER_VERSION = "2.0.x"; - private final static int DRIVER_MAJAR_VERSION = 2; - private final static int DRIVER_MINOR_VERSION = 0; - - private String precision = TSDBConstants.DEFAULT_PRECISION; - - public boolean allProceduresAreCallable() throws SQLException { - return false; - } - - public boolean allTablesAreSelectable() throws SQLException { - return false; - } - - public abstract String getURL() throws SQLException; - - public abstract String getUserName() throws SQLException; - - public boolean isReadOnly() throws SQLException { - return false; - } - - public boolean nullsAreSortedHigh() throws SQLException { - return false; - } - - public boolean nullsAreSortedLow() throws SQLException { - return !nullsAreSortedHigh(); - } - - public boolean nullsAreSortedAtStart() throws SQLException { - return true; - } - - public boolean nullsAreSortedAtEnd() throws SQLException { - return !nullsAreSortedAtStart(); - } - - public String getDatabaseProductName() throws SQLException { - return PRODUCT_NAME; - } - - public String getDatabaseProductVersion() throws SQLException { - return PRODUCT_VESION; - } - - public abstract String getDriverName() throws SQLException; - - public String getDriverVersion() throws SQLException { - return DRIVER_VERSION; - } - - public int getDriverMajorVersion() { - return DRIVER_MAJAR_VERSION; - } - - public int getDriverMinorVersion() { - return DRIVER_MINOR_VERSION; - } - - public boolean usesLocalFiles() throws SQLException { - return false; - } - - public boolean usesLocalFilePerTable() throws SQLException { - return false; - } - - public boolean supportsMixedCaseIdentifiers() throws SQLException { - return false; //像database、table这些对象的标识符,在存储时是否采用大小写混合的模式 - } - - public boolean storesUpperCaseIdentifiers() throws SQLException { - return false; - } - - public boolean storesLowerCaseIdentifiers() throws SQLException { - return true; - } - - public boolean storesMixedCaseIdentifiers() throws SQLException { - return false; - } - - public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { - return false; - } - - public boolean storesUpperCaseQuotedIdentifiers() throws SQLException { - return false; - } - - public boolean storesLowerCaseQuotedIdentifiers() throws SQLException { - return false; - } - - public boolean storesMixedCaseQuotedIdentifiers() throws SQLException { - return false; - } - - public String getIdentifierQuoteString() throws SQLException { - return " "; - } - - public String getSQLKeywords() throws SQLException { - return null; - } - - public String getNumericFunctions() throws SQLException { - return null; - } - - public String getStringFunctions() throws SQLException { - return null; - } - - public String getSystemFunctions() throws SQLException { - return null; - } - - public String getTimeDateFunctions() throws SQLException { - return null; - } - - public String getSearchStringEscape() throws SQLException { - return null; - } - - public String getExtraNameCharacters() throws SQLException { - return null; - } - - public boolean supportsAlterTableWithAddColumn() throws SQLException { - return true; - } - - public boolean supportsAlterTableWithDropColumn() throws SQLException { - return true; - } - - public boolean supportsColumnAliasing() throws SQLException { - return true; - } - - public boolean nullPlusNonNullIsNull() throws SQLException { - // null + non-null != null - return false; - } - - public boolean supportsConvert() throws SQLException { - // 是否支持转换函数convert - return false; - } - - public boolean supportsConvert(int fromType, int toType) throws SQLException { - return false; - } - - public boolean supportsTableCorrelationNames() throws SQLException { - return false; - } - - public boolean supportsDifferentTableCorrelationNames() throws SQLException { - return false; - } - - public boolean supportsExpressionsInOrderBy() throws SQLException { - return false; - } - - public boolean supportsOrderByUnrelated() throws SQLException { - return false; - } - - public boolean supportsGroupBy() throws SQLException { - return true; - } - - public boolean supportsGroupByUnrelated() throws SQLException { - return false; - } - - public boolean supportsGroupByBeyondSelect() throws SQLException { - return false; - } - - public boolean supportsLikeEscapeClause() throws SQLException { - return false; - } - - public boolean supportsMultipleResultSets() throws SQLException { - return false; - } - - public boolean supportsMultipleTransactions() throws SQLException { - return false; - } - - public boolean supportsNonNullableColumns() throws SQLException { - return false; - } - - public boolean supportsMinimumSQLGrammar() throws SQLException { - return false; - } - - public boolean supportsCoreSQLGrammar() throws SQLException { - return false; - } - - public boolean supportsExtendedSQLGrammar() throws SQLException { - return false; - } - - public boolean supportsANSI92EntryLevelSQL() throws SQLException { - return false; - } - - public boolean supportsANSI92IntermediateSQL() throws SQLException { - return false; - } - - public boolean supportsANSI92FullSQL() throws SQLException { - return false; - } - - public boolean supportsIntegrityEnhancementFacility() throws SQLException { - return false; - } - - public boolean supportsOuterJoins() throws SQLException { - return false; - } - - public boolean supportsFullOuterJoins() throws SQLException { - return false; - } - - public boolean supportsLimitedOuterJoins() throws SQLException { - return false; - } - - public String getSchemaTerm() throws SQLException { - return null; - } - - public String getProcedureTerm() throws SQLException { - return null; - } - - public String getCatalogTerm() throws SQLException { - return "database"; - } - - public boolean isCatalogAtStart() throws SQLException { - return true; - } - - public String getCatalogSeparator() throws SQLException { - return "."; - } - - public boolean supportsSchemasInDataManipulation() throws SQLException { - return false; - } - - public boolean supportsSchemasInProcedureCalls() throws SQLException { - return false; - } - - public boolean supportsSchemasInTableDefinitions() throws SQLException { - return false; - } - - public boolean supportsSchemasInIndexDefinitions() throws SQLException { - return false; - } - - public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException { - return false; - } - - public boolean supportsCatalogsInDataManipulation() throws SQLException { - return true; - } - - public boolean supportsCatalogsInProcedureCalls() throws SQLException { - return false; - } - - public boolean supportsCatalogsInTableDefinitions() throws SQLException { - return false; - } - - public boolean supportsCatalogsInIndexDefinitions() throws SQLException { - return false; - } - - public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException { - return false; - } - - public boolean supportsPositionedDelete() throws SQLException { - return false; - } - - public boolean supportsPositionedUpdate() throws SQLException { - return false; - } - - public boolean supportsSelectForUpdate() throws SQLException { - return false; - } - - public boolean supportsStoredProcedures() throws SQLException { - return false; - } - - public boolean supportsSubqueriesInComparisons() throws SQLException { - return false; - } - - public boolean supportsSubqueriesInExists() throws SQLException { - return false; - } - - public boolean supportsSubqueriesInIns() throws SQLException { - return false; - } - - public boolean supportsSubqueriesInQuantifieds() throws SQLException { - return false; - } - - public boolean supportsCorrelatedSubqueries() throws SQLException { - return false; - } - - public boolean supportsUnion() throws SQLException { - return false; - } - - public boolean supportsUnionAll() throws SQLException { - return false; - } - - public boolean supportsOpenCursorsAcrossCommit() throws SQLException { - return false; - } - - public boolean supportsOpenCursorsAcrossRollback() throws SQLException { - return false; - } - - public boolean supportsOpenStatementsAcrossCommit() throws SQLException { - return false; - } - - public boolean supportsOpenStatementsAcrossRollback() throws SQLException { - return false; - } - - public int getMaxBinaryLiteralLength() throws SQLException { - return 0; - } - - public int getMaxCharLiteralLength() throws SQLException { - return 0; - } - - public int getMaxColumnNameLength() throws SQLException { - return 0; - } - - public int getMaxColumnsInGroupBy() throws SQLException { - return 0; - } - - public int getMaxColumnsInIndex() throws SQLException { - return 0; - } - - public int getMaxColumnsInOrderBy() throws SQLException { - return 0; - } - - public int getMaxColumnsInSelect() throws SQLException { - return 0; - } - - public int getMaxColumnsInTable() throws SQLException { - return 0; - } - - public int getMaxConnections() throws SQLException { - return 0; - } - - public int getMaxCursorNameLength() throws SQLException { - return 0; - } - - public int getMaxIndexLength() throws SQLException { - return 0; - } - - public int getMaxSchemaNameLength() throws SQLException { - return 0; - } - - public int getMaxProcedureNameLength() throws SQLException { - return 0; - } - - public int getMaxCatalogNameLength() throws SQLException { - return 0; - } - - public int getMaxRowSize() throws SQLException { - return 0; - } - - public boolean doesMaxRowSizeIncludeBlobs() throws SQLException { - return false; - } - - public int getMaxStatementLength() throws SQLException { - return 0; - } - - public int getMaxStatements() throws SQLException { - return 0; - } - - public int getMaxTableNameLength() throws SQLException { - return 0; - } - - public int getMaxTablesInSelect() throws SQLException { - return 0; - } - - public int getMaxUserNameLength() throws SQLException { - return 0; - } - - public int getDefaultTransactionIsolation() throws SQLException { - return Connection.TRANSACTION_NONE; - } - - public boolean supportsTransactions() throws SQLException { - return false; - } - - public boolean supportsTransactionIsolationLevel(int level) throws SQLException { - if (level == Connection.TRANSACTION_NONE) - return true; - return false; - } - - public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { - return false; - } - - public boolean supportsDataManipulationTransactionsOnly() throws SQLException { - return false; - } - - public boolean dataDefinitionCausesTransactionCommit() throws SQLException { - return false; - } - - public boolean dataDefinitionIgnoredInTransactions() throws SQLException { - return false; - } - - public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException { - return null; - } - - public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException { - return null; - } - - public abstract ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException; - - private List buildGetTablesColumnMetaDataList() { - List columnMetaDataList = new ArrayList<>(); - columnMetaDataList.add(buildTableCatalogMeta(1)); // 1. TABLE_CAT - columnMetaDataList.add(buildTableSchemaMeta(2)); // 2. TABLE_SCHEM - columnMetaDataList.add(buildTableNameMeta(3)); // 3. TABLE_NAME - columnMetaDataList.add(buildTableTypeMeta(4)); // 4. TABLE_TYPE - columnMetaDataList.add(buildRemarksMeta(5)); // 5. remarks - columnMetaDataList.add(buildTypeCatMeta(6)); // 6. TYPE_CAT - columnMetaDataList.add(buildTypeSchemaMeta(7)); // 7. TYPE_SCHEM - columnMetaDataList.add(buildTypeNameMeta(8)); // 8. TYPE_NAME - columnMetaDataList.add(buildSelfReferencingColName(9)); // 9. SELF_REFERENCING_COL_NAME - columnMetaDataList.add(buildRefGenerationMeta(10)); // 10. REF_GENERATION - return columnMetaDataList; - } - - private ColumnMetaData buildTypeCatMeta(int colIndex) { - ColumnMetaData col6 = new ColumnMetaData(); - col6.setColIndex(colIndex); - col6.setColName("TYPE_CAT"); - col6.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col6; - } - - private ColumnMetaData buildTypeSchemaMeta(int colIndex) { - ColumnMetaData col7 = new ColumnMetaData(); - col7.setColIndex(colIndex); - col7.setColName("TYPE_SCHEM"); - col7.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col7; - } - - private ColumnMetaData buildTypeNameMeta(int colIndex) { - ColumnMetaData col8 = new ColumnMetaData(); - col8.setColIndex(colIndex); - col8.setColName("TYPE_NAME"); - col8.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col8; - } - - private ColumnMetaData buildSelfReferencingColName(int colIndex) { - ColumnMetaData col9 = new ColumnMetaData(); - col9.setColIndex(colIndex); - col9.setColName("SELF_REFERENCING_COL_NAME"); - col9.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col9; - } - - private ColumnMetaData buildRefGenerationMeta(int colIndex) { - ColumnMetaData col10 = new ColumnMetaData(); - col10.setColIndex(colIndex); - col10.setColName("REF_GENERATION"); - col10.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col10; - } - - protected ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types, Connection connection) throws SQLException { - if (!StringUtils.isEmpty(catalog) && !isAvailableCatalog(connection, catalog)) - return new EmptyResultSet(); - - DatabaseMetaDataResultSet resultSet = new DatabaseMetaDataResultSet(); - // set column metadata list - resultSet.setColumnMetaDataList(buildGetTablesColumnMetaDataList()); - // set row data - List rowDataList = new ArrayList<>(); - try (Statement stmt = connection.createStatement()) { - List dbs = new ArrayList<>(); - if (!StringUtils.isEmpty(catalog)) { - dbs.add(catalog); - } else { - ResultSet dbRs = stmt.executeQuery("show databases"); - while (dbRs.next()) { - dbs.add(dbRs.getString("name")); - } - } - if (dbs.isEmpty()) { - return new EmptyResultSet(); - } - for (String db : dbs) { - StringBuilder sql = new StringBuilder().append("show ").append(db).append(".tables "); - StringBuilder Ssql = new StringBuilder().append("show ").append(db).append(".stables "); - if (!StringUtils.isEmpty(tableNamePattern)) { - sql.append("like '").append(tableNamePattern).append("'"); - Ssql.append("like '").append(tableNamePattern).append("'"); - } - ResultSet tables = stmt.executeQuery(sql.toString()); - while (tables.next()) { - TSDBResultSetRowData rowData = new TSDBResultSetRowData(10); - rowData.setStringValue(1, catalog); //TABLE_CAT - rowData.setStringValue(2, null); //TABLE_SCHEM - rowData.setStringValue(3, tables.getString("table_name")); //TABLE_NAME - rowData.setStringValue(4, "TABLE"); //TABLE_TYPE - rowData.setStringValue(5, ""); //REMARKS - rowDataList.add(rowData); - } - ResultSet stables = stmt.executeQuery(Ssql.toString()); - while (stables.next()) { - TSDBResultSetRowData rowData = new TSDBResultSetRowData(10); - rowData.setStringValue(1, catalog); //TABLE_CAT - rowData.setStringValue(2, null); //TABLE_SCHEM - rowData.setStringValue(3, stables.getString("name")); //TABLE_NAME - rowData.setStringValue(4, "TABLE"); //TABLE_TYPE - rowData.setStringValue(5, "STABLE"); //REMARKS - rowDataList.add(rowData); - } - } - resultSet.setRowDataList(rowDataList); - } - return resultSet; - } - - private ColumnMetaData buildTableTypeMeta(int colIndex) { - ColumnMetaData col4 = new ColumnMetaData(); - col4.setColIndex(colIndex); - col4.setColName("TABLE_TYPE"); - col4.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col4; - } - - public ResultSet getSchemas() { - return getEmptyResultSet(); - } - - public abstract ResultSet getCatalogs() throws SQLException; - - private List buildTableTypesColumnMetadataList() { - List columnMetaDataList = new ArrayList<>(); - columnMetaDataList.add(buildTableTypeMeta(1)); - return columnMetaDataList; - } - - public ResultSet getTableTypes() throws SQLException { - DatabaseMetaDataResultSet resultSet = new DatabaseMetaDataResultSet(); - // set up ColumnMetaDataList - resultSet.setColumnMetaDataList(buildTableTypesColumnMetadataList()); - - // set up rowDataList - List rowDataList = new ArrayList<>(); - TSDBResultSetRowData rowData = new TSDBResultSetRowData(1); - rowData.setStringValue(1, "TABLE"); - rowDataList.add(rowData); - rowData = new TSDBResultSetRowData(1); - rowData.setStringValue(1, "STABLE"); - rowDataList.add(rowData); - resultSet.setRowDataList(rowDataList); - - return resultSet; - } - - public abstract ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException; - - protected ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern, Connection conn) throws SQLException { - if (catalog == null || catalog.isEmpty()) - return null; - if (!isAvailableCatalog(conn, catalog)) - return new EmptyResultSet(); - - DatabaseMetaDataResultSet resultSet = new DatabaseMetaDataResultSet(); - // set up ColumnMetaDataList - resultSet.setColumnMetaDataList(buildGetColumnsColumnMetaDataList()); - // set up rowDataList - List rowDataList = new ArrayList<>(); - try (Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("describe " + catalog + "." + tableNamePattern)) { - - int rowIndex = 0; - while (rs.next()) { - TSDBResultSetRowData rowData = new TSDBResultSetRowData(24); - // set TABLE_CAT - rowData.setStringValue(1, catalog); - // set TABLE_SCHEM - rowData.setStringValue(2, null); - // set TABLE_NAME - rowData.setStringValue(3, tableNamePattern); - // set COLUMN_NAME - rowData.setStringValue(4, rs.getString("Field")); - // set DATA_TYPE - String typeName = rs.getString("Type"); - rowData.setIntValue(5, TSDBConstants.typeName2JdbcType(typeName)); - // set TYPE_NAME - rowData.setStringValue(6, typeName); - // set COLUMN_SIZE - int length = rs.getInt("Length"); - rowData.setIntValue(7, calculateColumnSize(typeName, precision, length)); - // set BUFFER LENGTH - rowData.setStringValue(8, null); - // set DECIMAL_DIGITS - Integer decimalDigits = calculateDecimalDigits(typeName); - if (decimalDigits != null) { - rowData.setIntValue(9, decimalDigits); - } else { - rowData.setStringValue(9, null); - } - // set NUM_PREC_RADIX - rowData.setIntValue(10, 10); - // set NULLABLE - rowData.setIntValue(11, isNullable(rowIndex, typeName)); - // set REMARKS - String note = rs.getString("Note"); - rowData.setStringValue(12, note.trim().isEmpty() ? null : note); - rowDataList.add(rowData); - rowIndex++; - } - resultSet.setRowDataList(rowDataList); - } - return resultSet; - } - - private int isNullable(int index, String typeName) { - if (index == 0 && "TIMESTAMP".equals(typeName)) - return DatabaseMetaData.columnNoNulls; - return DatabaseMetaData.columnNullable; - } - - private Integer calculateColumnSize(String typeName, String precisionType, int length) { - switch (typeName) { - case "TIMESTAMP": - return precisionType.equals("ms") ? TSDBConstants.TIMESTAMP_MS_PRECISION : TSDBConstants.TIMESTAMP_US_PRECISION; - case "BOOL": - return TSDBConstants.BOOLEAN_PRECISION; - case "TINYINT": - return TSDBConstants.TINYINT_PRECISION; - case "SMALLINT": - return TSDBConstants.SMALLINT_PRECISION; - case "INT": - return TSDBConstants.INT_PRECISION; - case "BIGINT": - return TSDBConstants.BIGINT_PRECISION; - case "FLOAT": - return TSDBConstants.FLOAT_PRECISION; - case "DOUBLE": - return TSDBConstants.DOUBLE_PRECISION; - case "NCHAR": - case "BINARY": - return length; - default: - return null; - } - } - - private Integer calculateDecimalDigits(String typeName) { - switch (typeName) { - case "TINYINT": - case "SMALLINT": - case "INT": - case "BIGINT": - return 0; - default: - return null; - } - } - - private ColumnMetaData buildTableCatalogMeta(int colIndex) { - ColumnMetaData col1 = new ColumnMetaData(); - col1.setColIndex(colIndex); - col1.setColName("TABLE_CAT"); - col1.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col1; - } - - private ColumnMetaData buildTableSchemaMeta(int colIndex) { - ColumnMetaData col2 = new ColumnMetaData(); - col2.setColIndex(colIndex); - col2.setColName("TABLE_SCHEM"); - col2.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col2; - } - - private ColumnMetaData buildTableNameMeta(int colIndex) { - ColumnMetaData col3 = new ColumnMetaData(); - col3.setColIndex(colIndex); - col3.setColName("TABLE_NAME"); - col3.setColSize(193); - col3.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col3; - } - - private ColumnMetaData buildColumnNameMeta(int colIndex) { - ColumnMetaData col4 = new ColumnMetaData(); - col4.setColIndex(colIndex); - col4.setColName("COLUMN_NAME"); - col4.setColSize(65); - col4.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col4; - } - - private ColumnMetaData buildDataTypeMeta(int colIndex) { - ColumnMetaData col5 = new ColumnMetaData(); - col5.setColIndex(colIndex); - col5.setColName("DATA_TYPE"); - col5.setColType(TSDBConstants.TSDB_DATA_TYPE_INT); - return col5; - } - - private ColumnMetaData buildColumnSizeMeta() { - ColumnMetaData col7 = new ColumnMetaData(); - col7.setColIndex(7); - col7.setColName("COLUMN_SIZE"); - col7.setColType(TSDBConstants.TSDB_DATA_TYPE_INT); - return col7; - } - - private ColumnMetaData buildBufferLengthMeta() { - ColumnMetaData col8 = new ColumnMetaData(); - col8.setColIndex(8); - col8.setColName("BUFFER_LENGTH"); - return col8; - } - - private ColumnMetaData buildDecimalDigitsMeta() { - ColumnMetaData col9 = new ColumnMetaData(); - col9.setColIndex(9); - col9.setColName("DECIMAL_DIGITS"); - col9.setColType(TSDBConstants.TSDB_DATA_TYPE_INT); - return col9; - } - - private ColumnMetaData buildNumPrecRadixMeta() { - ColumnMetaData col10 = new ColumnMetaData(); - col10.setColIndex(10); - col10.setColName("NUM_PREC_RADIX"); - col10.setColType(TSDBConstants.TSDB_DATA_TYPE_INT); - return col10; - } - - private ColumnMetaData buildNullableMeta() { - ColumnMetaData col11 = new ColumnMetaData(); - col11.setColIndex(11); - col11.setColName("NULLABLE"); - col11.setColType(TSDBConstants.TSDB_DATA_TYPE_INT); - return col11; - } - - private ColumnMetaData buildRemarksMeta(int colIndex) { - ColumnMetaData col12 = new ColumnMetaData(); - col12.setColIndex(colIndex); - col12.setColName("REMARKS"); - col12.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col12; - } - - private ColumnMetaData buildColumnDefMeta() { - ColumnMetaData col13 = new ColumnMetaData(); - col13.setColIndex(13); - col13.setColName("COLUMN_DEF"); - col13.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col13; - } - - private ColumnMetaData buildSqlDataTypeMeta() { - ColumnMetaData col14 = new ColumnMetaData(); - col14.setColIndex(14); - col14.setColName("SQL_DATA_TYPE"); - col14.setColType(TSDBConstants.TSDB_DATA_TYPE_INT); - return col14; - } - - private ColumnMetaData buildSqlDatetimeSubMeta() { - ColumnMetaData col15 = new ColumnMetaData(); - col15.setColIndex(15); - col15.setColName("SQL_DATETIME_SUB"); - col15.setColType(TSDBConstants.TSDB_DATA_TYPE_INT); - return col15; - } - - private ColumnMetaData buildCharOctetLengthMeta() { - ColumnMetaData col16 = new ColumnMetaData(); - col16.setColIndex(16); - col16.setColName("CHAR_OCTET_LENGTH"); - col16.setColType(TSDBConstants.TSDB_DATA_TYPE_INT); - return col16; - } - - private ColumnMetaData buildOrdinalPositionMeta() { - ColumnMetaData col17 = new ColumnMetaData(); - col17.setColIndex(17); - col17.setColName("ORDINAL_POSITION"); - col17.setColType(TSDBConstants.TSDB_DATA_TYPE_INT); - return col17; - } - - private ColumnMetaData buildIsNullableMeta() { - ColumnMetaData col18 = new ColumnMetaData(); - col18.setColIndex(18); - col18.setColName("IS_NULLABLE"); - col18.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col18; - } - - private ColumnMetaData buildScopeCatalogMeta() { - ColumnMetaData col19 = new ColumnMetaData(); - col19.setColIndex(19); - col19.setColName("SCOPE_CATALOG"); - col19.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col19; - } - - private ColumnMetaData buildScopeSchemaMeta() { - ColumnMetaData col20 = new ColumnMetaData(); - col20.setColIndex(20); - col20.setColName("SCOPE_SCHEMA"); - col20.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col20; - } - - private ColumnMetaData buildScopeTableMeta() { - ColumnMetaData col21 = new ColumnMetaData(); - col21.setColIndex(21); - col21.setColName("SCOPE_TABLE"); - col21.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col21; - } - - private ColumnMetaData buildSourceDataTypeMeta() { - ColumnMetaData col22 = new ColumnMetaData(); - col22.setColIndex(22); - col22.setColName("SOURCE_DATA_TYPE"); - col22.setColType(TSDBConstants.TSDB_DATA_TYPE_SMALLINT); - return col22; - } - - private ColumnMetaData buildIsAutoIncrementMeta() { - ColumnMetaData col23 = new ColumnMetaData(); - col23.setColIndex(23); - col23.setColName("IS_AUTOINCREMENT"); - col23.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col23; - } - - private ColumnMetaData buildIsGeneratedColumnMeta() { - ColumnMetaData col24 = new ColumnMetaData(); - col24.setColIndex(24); - col24.setColName("IS_GENERATEDCOLUMN"); - col24.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col24; - } - - private List buildGetColumnsColumnMetaDataList() { - List columnMetaDataList = new ArrayList<>(); - columnMetaDataList.add(buildTableCatalogMeta(1)); //1. TABLE_CAT - columnMetaDataList.add(buildTableSchemaMeta(2)); //2. TABLE_SCHEMA - columnMetaDataList.add(buildTableNameMeta(3)); //3. TABLE_NAME - columnMetaDataList.add(buildColumnNameMeta(4)); //4. COLUMN_NAME - columnMetaDataList.add(buildDataTypeMeta(5)); //5. DATA_TYPE - columnMetaDataList.add(buildTypeNameMeta(6)); //6. TYPE_NAME - columnMetaDataList.add(buildColumnSizeMeta()); //7. COLUMN_SIZE - columnMetaDataList.add(buildBufferLengthMeta()); //8. BUFFER_LENGTH, not used - columnMetaDataList.add(buildDecimalDigitsMeta()); //9. DECIMAL_DIGITS - columnMetaDataList.add(buildNumPrecRadixMeta()); //10. NUM_PREC_RADIX - columnMetaDataList.add(buildNullableMeta()); //11. NULLABLE - columnMetaDataList.add(buildRemarksMeta(12)); //12. REMARKS - columnMetaDataList.add(buildColumnDefMeta()); //13. COLUMN_DEF - columnMetaDataList.add(buildSqlDataTypeMeta()); //14. SQL_DATA_TYPE - columnMetaDataList.add(buildSqlDatetimeSubMeta()); //15. SQL_DATETIME_SUB - columnMetaDataList.add(buildCharOctetLengthMeta()); //16. CHAR_OCTET_LENGTH - columnMetaDataList.add(buildOrdinalPositionMeta()); //17. ORDINAL_POSITION - columnMetaDataList.add(buildIsNullableMeta()); //18. IS_NULLABLE - columnMetaDataList.add(buildScopeCatalogMeta()); //19. SCOPE_CATALOG - columnMetaDataList.add(buildScopeSchemaMeta()); //20. SCOPE_SCHEMA - columnMetaDataList.add(buildScopeTableMeta()); //21. SCOPE_TABLE - columnMetaDataList.add(buildSourceDataTypeMeta()); //22. SOURCE_DATA_TYPE - columnMetaDataList.add(buildIsAutoIncrementMeta()); //23. IS_AUTOINCREMENT - columnMetaDataList.add(buildIsGeneratedColumnMeta()); //24. IS_GENERATEDCOLUMN - return columnMetaDataList; - } - - public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) throws SQLException { - return getEmptyResultSet(); - } - - public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { - return getEmptyResultSet(); - } - - public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) throws SQLException { - return getEmptyResultSet(); - } - - public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException { - return getEmptyResultSet(); - } - - public abstract ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException; - - public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { - return getEmptyResultSet(); - } - - public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { - return getEmptyResultSet(); - } - - public ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException { - return getEmptyResultSet(); - } - - public ResultSet getTypeInfo() throws SQLException { - return getEmptyResultSet(); - } - - public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException { - return getEmptyResultSet(); - } - - public boolean supportsResultSetType(int type) throws SQLException { - return false; - } - - public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException { - return false; - } - - public boolean ownUpdatesAreVisible(int type) throws SQLException { - return false; - } - - public boolean ownDeletesAreVisible(int type) throws SQLException { - return false; - } - - public boolean ownInsertsAreVisible(int type) throws SQLException { - return false; - } - - public boolean othersUpdatesAreVisible(int type) throws SQLException { - return false; - } - - public boolean othersDeletesAreVisible(int type) throws SQLException { - return false; - } - - public boolean othersInsertsAreVisible(int type) throws SQLException { - return false; - } - - public boolean updatesAreDetected(int type) throws SQLException { - return false; - } - - public boolean deletesAreDetected(int type) throws SQLException { - return false; - } - - public boolean insertsAreDetected(int type) throws SQLException { - return false; - } - - public boolean supportsBatchUpdates() throws SQLException { - return false; - } - - public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types) throws SQLException { - return getEmptyResultSet(); - } - - public abstract Connection getConnection() throws SQLException; - - public boolean supportsSavepoints() throws SQLException { - return false; - } - - public boolean supportsNamedParameters() throws SQLException { - return false; - } - - public boolean supportsMultipleOpenResults() throws SQLException { - return false; - } - - public boolean supportsGetGeneratedKeys() throws SQLException { - return false; - } - - public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException { - return getEmptyResultSet(); - } - - public abstract ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException; - - public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern) throws SQLException { - return getEmptyResultSet(); - } - - public boolean supportsResultSetHoldability(int holdability) throws SQLException { - if (holdability == ResultSet.HOLD_CURSORS_OVER_COMMIT) - return true; - return false; - } - - public int getResultSetHoldability() throws SQLException { - return ResultSet.HOLD_CURSORS_OVER_COMMIT; - } - - public int getDatabaseMajorVersion() throws SQLException { - return 2; - } - - public int getDatabaseMinorVersion() throws SQLException { - return 0; - } - - public int getJDBCMajorVersion() throws SQLException { - return 2; - } - - public int getJDBCMinorVersion() throws SQLException { - return 0; - } - - public int getSQLStateType() throws SQLException { - return 0; - } - - public boolean locatorsUpdateCopy() throws SQLException { - return false; - } - - public boolean supportsStatementPooling() throws SQLException { - return false; - } - - public RowIdLifetime getRowIdLifetime() throws SQLException { - return null; - } - - public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException { - return getEmptyResultSet(); - } - - public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException { - return false; - } - - public boolean autoCommitFailureClosesAllResultSets() throws SQLException { - return false; - } - - public ResultSet getClientInfoProperties() throws SQLException { - //TODO: see https://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html#setClientInfo-java.lang.String-java.lang.String- - return getEmptyResultSet(); - } - - public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) throws SQLException { - return getEmptyResultSet(); - } - - public ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern, String columnNamePattern) throws SQLException { - return getEmptyResultSet(); - } - - public ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { - return getEmptyResultSet(); - } - - public boolean generatedKeyAlwaysReturned() throws SQLException { - return false; - } - - private ResultSet getEmptyResultSet() { - return new EmptyResultSet(); - } - - protected ResultSet getCatalogs(Connection conn) throws SQLException { - DatabaseMetaDataResultSet resultSet = new DatabaseMetaDataResultSet(); - // set up ColumnMetaDataList - List columnMetaDataList = new ArrayList<>(); - columnMetaDataList.add(buildTableCatalogMeta(1)); // 1. TABLE_CAT - resultSet.setColumnMetaDataList(columnMetaDataList); - - try (Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("show databases")) { - List rowDataList = new ArrayList<>(); - while (rs.next()) { - TSDBResultSetRowData rowData = new TSDBResultSetRowData(1); - rowData.setStringValue(1, rs.getString("name")); - rowDataList.add(rowData); - } - resultSet.setRowDataList(rowDataList); - } - return resultSet; - } - - - protected ResultSet getPrimaryKeys(String catalog, String schema, String table, Connection conn) throws SQLException { - if (catalog == null || catalog.isEmpty()) - return null; - if (!isAvailableCatalog(conn, catalog)) - return new EmptyResultSet(); - - DatabaseMetaDataResultSet resultSet = new DatabaseMetaDataResultSet(); - try (Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("describe " + catalog + "." + table)) { - // set up ColumnMetaDataList - resultSet.setColumnMetaDataList(buildGetPrimaryKeysMetadataList()); - // set rowData - List rowDataList = new ArrayList<>(); - - rs.next(); - TSDBResultSetRowData rowData = new TSDBResultSetRowData(6); - rowData.setStringValue(1, catalog); - rowData.setStringValue(2, null); - rowData.setStringValue(3, table); - String primaryKey = rs.getString("Field"); - rowData.setStringValue(4, primaryKey); - rowData.setShortValue(5, (short) 1); - rowData.setStringValue(6, primaryKey); - rowDataList.add(rowData); - resultSet.setRowDataList(rowDataList); - } - return resultSet; - } - - private List buildGetPrimaryKeysMetadataList() { - List columnMetaDataList = new ArrayList<>(); - columnMetaDataList.add(buildTableCatalogMeta(1)); // 1. TABLE_CAT - columnMetaDataList.add(buildTableSchemaMeta(2)); // 2. TABLE_SCHEM - columnMetaDataList.add(buildTableNameMeta(3)); // 3. TABLE_NAME - columnMetaDataList.add(buildColumnNameMeta(4)); // 4. COLUMN_NAME - columnMetaDataList.add(buildKeySeqMeta(5)); // 5. KEY_SEQ - columnMetaDataList.add(buildPrimaryKeyNameMeta(6)); // 6. PK_NAME - return columnMetaDataList; - } - - private ColumnMetaData buildKeySeqMeta(int colIndex) { - ColumnMetaData col5 = new ColumnMetaData(); - col5.setColIndex(colIndex); - col5.setColName("KEY_SEQ"); - col5.setColType(TSDBConstants.TSDB_DATA_TYPE_SMALLINT); - return col5; - } - - private ColumnMetaData buildPrimaryKeyNameMeta(int colIndex) { - ColumnMetaData col6 = new ColumnMetaData(); - col6.setColIndex(colIndex); - col6.setColName("PK_NAME"); - col6.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col6; - } - - private boolean isAvailableCatalog(Connection connection, String catalog) throws SQLException { - try (Statement stmt = connection.createStatement(); - ResultSet databases = stmt.executeQuery("show databases")) { - while (databases.next()) { - String dbname = databases.getString("name"); - this.precision = databases.getString("precision"); - if (dbname.equalsIgnoreCase(catalog)) - return true; - } - } - return false; - } - - protected ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern, Connection conn) throws SQLException { - if (catalog == null || catalog.isEmpty()) - return null; - - if (!isAvailableCatalog(conn, catalog)) { - return new EmptyResultSet(); - } - - DatabaseMetaDataResultSet resultSet = new DatabaseMetaDataResultSet(); - try (Statement stmt = conn.createStatement()) { - // set up ColumnMetaDataList - resultSet.setColumnMetaDataList(buildGetSuperTablesColumnMetaDataList()); - // set result set row data - stmt.execute("use " + catalog); - try (ResultSet rs = stmt.executeQuery("show tables like '" + tableNamePattern + "'")) { - List rowDataList = new ArrayList<>(); - while (rs.next()) { - TSDBResultSetRowData rowData = new TSDBResultSetRowData(4); - rowData.setStringValue(1, catalog); - rowData.setStringValue(2, null); - rowData.setStringValue(3, rs.getString("table_name")); - rowData.setStringValue(4, rs.getString("stable_name")); - rowDataList.add(rowData); - } - resultSet.setRowDataList(rowDataList); - } - } - return resultSet; - } - - private List buildGetSuperTablesColumnMetaDataList() { - List columnMetaDataList = new ArrayList<>(); - columnMetaDataList.add(buildTableCatalogMeta(1)); // 1. TABLE_CAT - columnMetaDataList.add(buildTableSchemaMeta(2)); // 2. TABLE_SCHEM - columnMetaDataList.add(buildTableNameMeta(3)); // 3. TABLE_NAME - columnMetaDataList.add(buildSuperTableNameMeta(4)); // 4. SUPERTABLE_NAME - return columnMetaDataList; - } - - private ColumnMetaData buildSuperTableNameMeta(int colIndex) { - ColumnMetaData col4 = new ColumnMetaData(); - col4.setColIndex(colIndex); - col4.setColName("SUPERTABLE_NAME"); - col4.setColType(TSDBConstants.TSDB_DATA_TYPE_NCHAR); - return col4; - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDriver.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDriver.java deleted file mode 100644 index 7d4a268391..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDriver.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.taosdata.jdbc; - -import java.sql.Driver; -import java.sql.DriverPropertyInfo; -import java.util.Properties; -import java.util.StringTokenizer; - -public abstract class AbstractDriver implements Driver { - - protected DriverPropertyInfo[] getPropertyInfo(Properties info) { - DriverPropertyInfo hostProp = new DriverPropertyInfo(TSDBDriver.PROPERTY_KEY_HOST, info.getProperty(TSDBDriver.PROPERTY_KEY_HOST)); - hostProp.required = false; - hostProp.description = "Hostname"; - - DriverPropertyInfo portProp = new DriverPropertyInfo(TSDBDriver.PROPERTY_KEY_PORT, info.getProperty(TSDBDriver.PROPERTY_KEY_PORT)); - portProp.required = false; - portProp.description = "Port"; - - DriverPropertyInfo dbProp = new DriverPropertyInfo(TSDBDriver.PROPERTY_KEY_DBNAME, info.getProperty(TSDBDriver.PROPERTY_KEY_DBNAME)); - dbProp.required = false; - dbProp.description = "Database name"; - - DriverPropertyInfo userProp = new DriverPropertyInfo(TSDBDriver.PROPERTY_KEY_USER, info.getProperty(TSDBDriver.PROPERTY_KEY_USER)); - userProp.required = true; - userProp.description = "User"; - - DriverPropertyInfo passwordProp = new DriverPropertyInfo(TSDBDriver.PROPERTY_KEY_PASSWORD, info.getProperty(TSDBDriver.PROPERTY_KEY_PASSWORD)); - passwordProp.required = true; - passwordProp.description = "Password"; - - DriverPropertyInfo[] propertyInfo = new DriverPropertyInfo[5]; - propertyInfo[0] = hostProp; - propertyInfo[1] = portProp; - propertyInfo[2] = dbProp; - propertyInfo[3] = userProp; - propertyInfo[4] = passwordProp; - return propertyInfo; - } - - protected Properties parseURL(String url, Properties defaults) { - Properties urlProps = (defaults != null) ? defaults : new Properties(); - - // parse properties in url - int beginningOfSlashes = url.indexOf("//"); - int index = url.indexOf("?"); - if (index != -1) { - String paramString = url.substring(index + 1); - url = url.substring(0, index); - StringTokenizer queryParams = new StringTokenizer(paramString, "&"); - while (queryParams.hasMoreElements()) { - String parameterValuePair = queryParams.nextToken(); - int indexOfEqual = parameterValuePair.indexOf("="); - String parameter = null; - String value = null; - if (indexOfEqual != -1) { - parameter = parameterValuePair.substring(0, indexOfEqual); - if (indexOfEqual + 1 < parameterValuePair.length()) { - value = parameterValuePair.substring(indexOfEqual + 1); - } - } - if (value != null && value.length() > 0 && parameter.length() > 0) { - urlProps.setProperty(parameter, value); - } - } - } - - // parse Product Name - String dbProductName = url.substring(0, beginningOfSlashes); - dbProductName = dbProductName.substring(dbProductName.indexOf(":") + 1); - dbProductName = dbProductName.substring(0, dbProductName.indexOf(":")); - urlProps.setProperty(TSDBDriver.PROPERTY_KEY_PRODUCT_NAME,dbProductName); - // parse dbname - url = url.substring(beginningOfSlashes + 2); - int indexOfSlash = url.indexOf("/"); - if (indexOfSlash != -1) { - if (indexOfSlash + 1 < url.length()) { - urlProps.setProperty(TSDBDriver.PROPERTY_KEY_DBNAME, url.substring(indexOfSlash + 1)); - } - url = url.substring(0, indexOfSlash); - } - // parse port - int indexOfColon = url.indexOf(":"); - if (indexOfColon != -1) { - if (indexOfColon + 1 < url.length()) { - urlProps.setProperty(TSDBDriver.PROPERTY_KEY_PORT, url.substring(indexOfColon + 1)); - } - url = url.substring(0, indexOfColon); - } - // parse host - if (url.length() > 0 && url.trim().length() > 0) { - urlProps.setProperty(TSDBDriver.PROPERTY_KEY_HOST, url); - } - return urlProps; - } - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractParameterMetaData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractParameterMetaData.java deleted file mode 100644 index 7d9d8ee515..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractParameterMetaData.java +++ /dev/null @@ -1,159 +0,0 @@ -package com.taosdata.jdbc; - -import java.sql.ParameterMetaData; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.sql.Types; - -public abstract class AbstractParameterMetaData extends WrapperImpl implements ParameterMetaData { - - private final Object[] parameters; - - public AbstractParameterMetaData(Object[] parameters) { - this.parameters = parameters; - } - - @Override - public int getParameterCount() throws SQLException { - return parameters == null ? 0 : parameters.length; - } - - @Override - public int isNullable(int param) throws SQLException { - return ParameterMetaData.parameterNullableUnknown; - } - - @Override - public boolean isSigned(int param) throws SQLException { - if (param < 1 && param >= parameters.length) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - if (parameters[param - 1] instanceof Byte) - return true; - if (parameters[param - 1] instanceof Short) - return true; - if (parameters[param - 1] instanceof Integer) - return true; - if (parameters[param - 1] instanceof Long) - return true; - if (parameters[param - 1] instanceof Float) - return true; - if (parameters[param - 1] instanceof Double) - return true; - - return false; - } - - @Override - public int getPrecision(int param) throws SQLException { - if (param < 1 && param >= parameters.length) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - if (parameters[param - 1] instanceof Boolean) - return TSDBConstants.BOOLEAN_PRECISION; - if (parameters[param - 1] instanceof Byte) - return TSDBConstants.TINYINT_PRECISION; - if (parameters[param - 1] instanceof Short) - return TSDBConstants.SMALLINT_PRECISION; - if (parameters[param - 1] instanceof Integer) - return TSDBConstants.INT_PRECISION; - if (parameters[param - 1] instanceof Long) - return TSDBConstants.BIGINT_PRECISION; - if (parameters[param - 1] instanceof Timestamp) - return TSDBConstants.TIMESTAMP_MS_PRECISION; - if (parameters[param - 1] instanceof Float) - return TSDBConstants.FLOAT_PRECISION; - if (parameters[param - 1] instanceof Double) - return TSDBConstants.DOUBLE_PRECISION; - if (parameters[param - 1] instanceof String) - return ((String) parameters[param - 1]).length(); - if (parameters[param - 1] instanceof byte[]) - return ((byte[]) parameters[param - 1]).length; - return 0; - } - - @Override - public int getScale(int param) throws SQLException { - if (param < 1 && param >= parameters.length) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - if (parameters[param - 1] instanceof Float) - return TSDBConstants.FLOAT_SCALE; - if (parameters[param - 1] instanceof Double) - return TSDBConstants.DOUBLE_SCALE; - return 0; - } - - @Override - public int getParameterType(int param) throws SQLException { - if (param < 1 && param >= parameters.length) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - if (parameters[param - 1] instanceof Timestamp) - return Types.TIMESTAMP; - if (parameters[param - 1] instanceof Byte) - return Types.TINYINT; - if (parameters[param - 1] instanceof Short) - return Types.SMALLINT; - if (parameters[param - 1] instanceof Integer) - return Types.INTEGER; - if (parameters[param - 1] instanceof Long) - return Types.BIGINT; - if (parameters[param - 1] instanceof Float) - return Types.FLOAT; - if (parameters[param - 1] instanceof Double) - return Types.DOUBLE; - if (parameters[param - 1] instanceof String) - return Types.NCHAR; - if (parameters[param - 1] instanceof byte[]) - return Types.BINARY; - if (parameters[param - 1] instanceof Boolean) - return Types.BOOLEAN; - return Types.OTHER; - } - - @Override - public String getParameterTypeName(int param) throws SQLException { - if (param < 1 && param >= parameters.length) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - if (parameters[param - 1] instanceof Timestamp) - return TSDBConstants.jdbcType2TaosTypeName(Types.TIMESTAMP); - if (parameters[param - 1] instanceof Byte) - return TSDBConstants.jdbcType2TaosTypeName(Types.TINYINT); - if (parameters[param - 1] instanceof Short) - return TSDBConstants.jdbcType2TaosTypeName(Types.SMALLINT); - if (parameters[param - 1] instanceof Integer) - return TSDBConstants.jdbcType2TaosTypeName(Types.INTEGER); - if (parameters[param - 1] instanceof Long) - return TSDBConstants.jdbcType2TaosTypeName(Types.BIGINT); - if (parameters[param - 1] instanceof Float) - return TSDBConstants.jdbcType2TaosTypeName(Types.FLOAT); - if (parameters[param - 1] instanceof Double) - return TSDBConstants.jdbcType2TaosTypeName(Types.DOUBLE); - if (parameters[param - 1] instanceof String) - return TSDBConstants.jdbcType2TaosTypeName(Types.NCHAR); - if (parameters[param - 1] instanceof byte[]) - return TSDBConstants.jdbcType2TaosTypeName(Types.BINARY); - if (parameters[param - 1] instanceof Boolean) - return TSDBConstants.jdbcType2TaosTypeName(Types.BOOLEAN); - - return parameters[param - 1].getClass().getName(); - } - - @Override - public String getParameterClassName(int param) throws SQLException { - if (param < 1 && param >= parameters.length) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - return parameters[param - 1].getClass().getName(); - } - - @Override - public int getParameterMode(int param) throws SQLException { - if (param < 1 && param >= parameters.length) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - return ParameterMetaData.parameterModeUnknown; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractResultSet.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractResultSet.java deleted file mode 100644 index 07553d7ef4..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractResultSet.java +++ /dev/null @@ -1,1189 +0,0 @@ -package com.taosdata.jdbc; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.net.URL; -import java.sql.*; -import java.util.Calendar; -import java.util.Map; - -public abstract class AbstractResultSet extends WrapperImpl implements ResultSet { - private int fetchSize; - protected boolean wasNull; - protected int timestampPrecision; - - public void setTimestampPrecision(int timestampPrecision) { - this.timestampPrecision = timestampPrecision; - } - - protected void checkAvailability(int columnIndex, int bounds) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - if (columnIndex < 1) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE, "Column Index out of range, " + columnIndex + " < 1"); - if (columnIndex > bounds) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE, "Column Index out of range, " + columnIndex + " > " + bounds); - } - - @Override - public abstract boolean next() throws SQLException; - - @Override - public abstract void close() throws SQLException; - - @Override - public boolean wasNull() throws SQLException { - return wasNull; - } - - @Override - public abstract String getString(int columnIndex) throws SQLException; - - @Override - public abstract boolean getBoolean(int columnIndex) throws SQLException; - - @Override - public abstract byte getByte(int columnIndex) throws SQLException; - - @Override - public abstract short getShort(int columnIndex) throws SQLException; - - @Override - public abstract int getInt(int columnIndex) throws SQLException; - - @Override - public abstract long getLong(int columnIndex) throws SQLException; - - @Override - public abstract float getFloat(int columnIndex) throws SQLException; - - @Override - public abstract double getDouble(int columnIndex) throws SQLException; - - @Deprecated - @Override - public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { - return getBigDecimal(columnIndex); - } - - @Override - public abstract byte[] getBytes(int columnIndex) throws SQLException; - - @Override - public Date getDate(int columnIndex) throws SQLException { - Timestamp timestamp = getTimestamp(columnIndex); - return timestamp == null ? null : new Date(timestamp.getTime()); - } - - @Override - public Time getTime(int columnIndex) throws SQLException { - Timestamp timestamp = getTimestamp(columnIndex); - return timestamp == null ? null : new Time(timestamp.getTime()); - } - - @Override - public abstract Timestamp getTimestamp(int columnIndex) throws SQLException; - - @Override - public InputStream getAsciiStream(int columnIndex) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - - } - - @Override - @Deprecated - public InputStream getUnicodeStream(int columnIndex) throws SQLException { - if (isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - } - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public InputStream getBinaryStream(int columnIndex) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public String getString(String columnLabel) throws SQLException { - return getString(findColumn(columnLabel)); - } - - @Override - public boolean getBoolean(String columnLabel) throws SQLException { - return getBoolean(findColumn(columnLabel)); - } - - @Override - public byte getByte(String columnLabel) throws SQLException { - return getByte(findColumn(columnLabel)); - } - - @Override - public short getShort(String columnLabel) throws SQLException { - return getShort(findColumn(columnLabel)); - } - - @Override - public int getInt(String columnLabel) throws SQLException { - return getInt(findColumn(columnLabel)); - } - - @Override - public long getLong(String columnLabel) throws SQLException { - return getLong(findColumn(columnLabel)); - } - - @Override - public float getFloat(String columnLabel) throws SQLException { - return getFloat(findColumn(columnLabel)); - } - - @Override - public double getDouble(String columnLabel) throws SQLException { - return getDouble(findColumn(columnLabel)); - } - - @Deprecated - @Override - public BigDecimal getBigDecimal(String columnLabel, int scale) throws SQLException { - return getBigDecimal(findColumn(columnLabel), scale); - } - - @Override - public byte[] getBytes(String columnLabel) throws SQLException { - return getBytes(findColumn(columnLabel)); - } - - @Override - public Date getDate(String columnLabel) throws SQLException { - return getDate(findColumn(columnLabel)); - } - - @Override - public Time getTime(String columnLabel) throws SQLException { - return getTime(findColumn(columnLabel)); - } - - @Override - public Timestamp getTimestamp(String columnLabel) throws SQLException { - return getTimestamp(findColumn(columnLabel)); - } - - @Override - public InputStream getAsciiStream(String columnLabel) throws SQLException { - return getAsciiStream(findColumn(columnLabel)); - } - - @Override - @Deprecated - public InputStream getUnicodeStream(String columnLabel) throws SQLException { - return getUnicodeStream(findColumn(columnLabel)); - } - - @Override - public InputStream getBinaryStream(String columnLabel) throws SQLException { - return getBinaryStream(findColumn(columnLabel)); - } - - @Override - public SQLWarning getWarnings() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - return null; - } - - @Override - public void clearWarnings() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - } - - @Override - public String getCursorName() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public abstract ResultSetMetaData getMetaData() throws SQLException; - - @Override - public abstract Object getObject(int columnIndex) throws SQLException; - - @Override - public Object getObject(String columnLabel) throws SQLException { - return getObject(findColumn(columnLabel)); - } - - @Override - public abstract int findColumn(String columnLabel) throws SQLException; - - @Override - public Reader getCharacterStream(int columnIndex) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Reader getCharacterStream(String columnLabel) throws SQLException { - return getCharacterStream(findColumn(columnLabel)); - } - - @Override - public abstract BigDecimal getBigDecimal(int columnIndex) throws SQLException; - - @Override - public BigDecimal getBigDecimal(String columnLabel) throws SQLException { - return getBigDecimal(findColumn(columnLabel)); - } - - @Override - public abstract boolean isBeforeFirst() throws SQLException; - - @Override - public abstract boolean isAfterLast() throws SQLException; - - @Override - public abstract boolean isFirst() throws SQLException; - - @Override - public abstract boolean isLast() throws SQLException; - - @Override - public abstract void beforeFirst() throws SQLException; - - @Override - public abstract void afterLast() throws SQLException; - - @Override - public abstract boolean first() throws SQLException; - - @Override - public abstract boolean last() throws SQLException; - - @Override - public abstract int getRow() throws SQLException; - - @Override - public abstract boolean absolute(int row) throws SQLException; - - @Override - public abstract boolean relative(int rows) throws SQLException; - - @Override - public abstract boolean previous() throws SQLException; - - @Override - public void setFetchDirection(int direction) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - //nothing to do - } - - @Override - public int getFetchDirection() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - return ResultSet.FETCH_FORWARD; - } - - @Override - public void setFetchSize(int rows) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - if (rows < 0) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - //nothing to do - this.fetchSize = rows; - } - - @Override - public int getFetchSize() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - return this.fetchSize; - } - - @Override - public int getType() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - return ResultSet.TYPE_FORWARD_ONLY; - } - - @Override - public int getConcurrency() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - return ResultSet.CONCUR_READ_ONLY; - } - - @Override - public boolean rowUpdated() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean rowInserted() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean rowDeleted() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateNull(int columnIndex) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBoolean(int columnIndex, boolean x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateByte(int columnIndex, byte x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateShort(int columnIndex, short x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateInt(int columnIndex, int x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateLong(int columnIndex, long x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateFloat(int columnIndex, float x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateDouble(int columnIndex, double x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateString(int columnIndex, String x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBytes(int columnIndex, byte[] x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateDate(int columnIndex, Date x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateTime(int columnIndex, Time x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateObject(int columnIndex, Object x, int scaleOrLength) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateObject(int columnIndex, Object x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateNull(String columnLabel) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBoolean(String columnLabel, boolean x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateByte(String columnLabel, byte x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateShort(String columnLabel, short x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateInt(String columnLabel, int x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateLong(String columnLabel, long x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateFloat(String columnLabel, float x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateDouble(String columnLabel, double x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBigDecimal(String columnLabel, BigDecimal x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateString(String columnLabel, String x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBytes(String columnLabel, byte[] x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateDate(String columnLabel, Date x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateTime(String columnLabel, Time x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateTimestamp(String columnLabel, Timestamp x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateAsciiStream(String columnLabel, InputStream x, int length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBinaryStream(String columnLabel, InputStream x, int length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateCharacterStream(String columnLabel, Reader reader, int length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateObject(String columnLabel, Object x, int scaleOrLength) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateObject(String columnLabel, Object x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void insertRow() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateRow() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void deleteRow() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void refreshRow() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void cancelRowUpdates() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void moveToInsertRow() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void moveToCurrentRow() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public abstract Statement getStatement() throws SQLException; - - @Override - public Object getObject(int columnIndex, Map> map) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Ref getRef(int columnIndex) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Blob getBlob(int columnIndex) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Clob getClob(int columnIndex) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Array getArray(int columnIndex) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Object getObject(String columnLabel, Map> map) throws SQLException { - return getObject(findColumn(columnLabel), map); - } - - @Override - public Ref getRef(String columnLabel) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Blob getBlob(String columnLabel) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Clob getClob(String columnLabel) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Array getArray(String columnLabel) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Date getDate(int columnIndex, Calendar cal) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Date getDate(String columnLabel, Calendar cal) throws SQLException { - return getDate(findColumn(columnLabel), cal); - } - - @Override - public Time getTime(int columnIndex, Calendar cal) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Time getTime(String columnLabel, Calendar cal) throws SQLException { - return getTime(findColumn(columnLabel), cal); - } - - @Override - public abstract Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException; - - @Override - public Timestamp getTimestamp(String columnLabel, Calendar cal) throws SQLException { - return getTimestamp(findColumn(columnLabel), cal); - } - - @Override - public URL getURL(int columnIndex) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public URL getURL(String columnLabel) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateRef(int columnIndex, Ref x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateRef(String columnLabel, Ref x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBlob(int columnIndex, Blob x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBlob(String columnLabel, Blob x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateClob(int columnIndex, Clob x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateClob(String columnLabel, Clob x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateArray(int columnIndex, Array x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateArray(String columnLabel, Array x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public RowId getRowId(int columnIndex) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public RowId getRowId(String columnLabel) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateRowId(int columnIndex, RowId x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateRowId(String columnLabel, RowId x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public int getHoldability() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - return ResultSet.HOLD_CURSORS_OVER_COMMIT; - } - - @Override - public abstract boolean isClosed() throws SQLException; - - @Override - public void updateNString(int columnIndex, String nString) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateNString(String columnLabel, String nString) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateNClob(int columnIndex, NClob nClob) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateNClob(String columnLabel, NClob nClob) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public NClob getNClob(int columnIndex) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public NClob getNClob(String columnLabel) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public SQLXML getSQLXML(int columnIndex) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public SQLXML getSQLXML(String columnLabel) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public abstract String getNString(int columnIndex) throws SQLException; - - @Override - public String getNString(String columnLabel) throws SQLException { - return getNString(findColumn(columnLabel)); - } - - @Override - public Reader getNCharacterStream(int columnIndex) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Reader getNCharacterStream(String columnLabel) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateNCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateAsciiStream(int columnIndex, InputStream x, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateClob(int columnIndex, Reader reader, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateClob(String columnLabel, Reader reader, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateCharacterStream(int columnIndex, Reader x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateClob(int columnIndex, Reader reader) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateClob(String columnLabel, Reader reader) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateNClob(int columnIndex, Reader reader) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void updateNClob(String columnLabel, Reader reader) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public T getObject(int columnIndex, Class type) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public T getObject(String columnLabel, Class type) throws SQLException { - return getObject(findColumn(columnLabel), type); - } - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractStatement.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractStatement.java deleted file mode 100644 index 12641087fb..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractStatement.java +++ /dev/null @@ -1,360 +0,0 @@ -package com.taosdata.jdbc; - -import java.sql.*; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public abstract class AbstractStatement extends WrapperImpl implements Statement { - - protected List batchedArgs; - private int fetchSize; - protected int affectedRows = -1; - - @Override - public abstract ResultSet executeQuery(String sql) throws SQLException; - - @Override - public abstract int executeUpdate(String sql) throws SQLException; - - @Override - public abstract void close() throws SQLException; - - @Override - public int getMaxFieldSize() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - return TSDBConstants.maxFieldSize; - } - - @Override - public void setMaxFieldSize(int max) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - if (max < 0) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - // nothing to do - } - - @Override - public int getMaxRows() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - return 0; - } - - @Override - public void setMaxRows(int max) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - if (max < 0) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - // do nothing - } - - @Override - public void setEscapeProcessing(boolean enable) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - // do nothing - } - - @Override - public int getQueryTimeout() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - return 0; - } - - @Override - public void setQueryTimeout(int seconds) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - if (seconds < 0) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - } - - @Override - public void cancel() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public SQLWarning getWarnings() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - return null; - } - - @Override - public void clearWarnings() throws SQLException { - // nothing to do - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - } - - @Override - public void setCursorName(String name) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public abstract boolean execute(String sql) throws SQLException; - - @Override - public abstract ResultSet getResultSet() throws SQLException; - - @Override - public abstract int getUpdateCount() throws SQLException; - - @Override - public boolean getMoreResults() throws SQLException { - return getMoreResults(CLOSE_CURRENT_RESULT); - } - - @Override - public void setFetchDirection(int direction) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - switch (direction) { - case ResultSet.FETCH_FORWARD: - case ResultSet.FETCH_REVERSE: - case ResultSet.FETCH_UNKNOWN: - break; - default: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - } - //nothing to do - } - - @Override - public int getFetchDirection() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - return ResultSet.FETCH_FORWARD; - } - - @Override - public void setFetchSize(int rows) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - if (rows < 0) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - //nothing to do - this.fetchSize = rows; - } - - @Override - public int getFetchSize() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - return this.fetchSize; - } - - @Override - public int getResultSetConcurrency() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - return ResultSet.CONCUR_READ_ONLY; - } - - @Override - public int getResultSetType() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - return ResultSet.TYPE_FORWARD_ONLY; - } - - @Override - public void addBatch(String sql) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - if (batchedArgs == null) { - batchedArgs = new ArrayList<>(); - } - batchedArgs.add(sql); - } - - @Override - public void clearBatch() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - if (batchedArgs != null) - batchedArgs.clear(); - } - - @Override - public int[] executeBatch() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - if (batchedArgs == null || batchedArgs.isEmpty()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_BATCH_IS_EMPTY); - - String clientInfo = getConnection().getClientInfo(TSDBDriver.PROPERTY_KEY_BATCH_ERROR_IGNORE); - boolean batchErrorIgnore = clientInfo == null ? TSDBConstants.DEFAULT_BATCH_ERROR_IGNORE : Boolean.parseBoolean(clientInfo); - - if (batchErrorIgnore) { - return executeBatchIgnoreException(); - } - return executeBatchThrowException(); - } - - private int[] executeBatchIgnoreException() { - return batchedArgs.stream().mapToInt(sql -> { - try { - boolean isSelect = execute(sql); - if (isSelect) { - return SUCCESS_NO_INFO; - } else { - return getUpdateCount(); - } - } catch (SQLException e) { - return EXECUTE_FAILED; - } - }).toArray(); - } - - private int[] executeBatchThrowException() throws BatchUpdateException { - int[] res = new int[batchedArgs.size()]; - for (int i = 0; i < batchedArgs.size(); i++) { - try { - boolean isSelect = execute(batchedArgs.get(i)); - if (isSelect) { - res[i] = SUCCESS_NO_INFO; - } else { - res[i] = getUpdateCount(); - } - } catch (SQLException e) { - String reason = e.getMessage(); - int[] updateCounts = Arrays.copyOfRange(res, 0, i); - throw new BatchUpdateException(reason, updateCounts, e); - } - } - return res; - } - - @Override - public abstract Connection getConnection() throws SQLException; - - @Override - public boolean getMoreResults(int current) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - this.affectedRows = -1; - switch (current) { - case Statement.CLOSE_CURRENT_RESULT: - return false; - case Statement.KEEP_CURRENT_RESULT: - case Statement.CLOSE_ALL_RESULTS: - break; - default: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - } - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public ResultSet getGeneratedKeys() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public int executeUpdate(String sql, String[] columnNames) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean execute(String sql, int[] columnIndexes) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean execute(String sql, String[] columnNames) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public int getResultSetHoldability() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - return ResultSet.HOLD_CURSORS_OVER_COMMIT; - } - - @Override - public abstract boolean isClosed() throws SQLException; - - @Override - public void setPoolable(boolean poolable) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - // do nothing - } - - @Override - public boolean isPoolable() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - return false; - } - - @Override - public void closeOnCompletion() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - // do nothing - } - - @Override - public boolean isCloseOnCompletion() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - return false; - } - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ColumnMetaData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ColumnMetaData.java deleted file mode 100644 index 8398c8f84b..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ColumnMetaData.java +++ /dev/null @@ -1,65 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2019 TAOS Data, Inc. - * - * This program is free software: you can use, redistribute, and/or modify - * it under the terms of the GNU Affero General Public License, version 3 - * or later ("AGPL"), as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - *****************************************************************************/ -package com.taosdata.jdbc; - -public class ColumnMetaData { - - private int colType = 0; //taosType - private String colName = null; - private int colSize = -1; - private int colIndex = 0; - - public int getColSize() { - return colSize; - } - - public void setColSize(int colSize) { - this.colSize = colSize; - } - - public int getColType() { - return colType; - } - - public void setColType(int colType) { - this.colType = colType; - } - - public String getColName() { - return colName; - } - - public void setColName(String colName) { - this.colName = colName; - } - - public int getColIndex() { - return colIndex; - } - - public void setColIndex(int colIndex) { - this.colIndex = colIndex; - } - - @Override - public String toString() { - return "ColumnMetaData{" + - "colType=" + colType + - ", colName='" + colName + '\'' + - ", colSize=" + colSize + - ", colIndex=" + colIndex + - '}'; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/DatabaseMetaDataResultSet.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/DatabaseMetaDataResultSet.java deleted file mode 100644 index 8a494f3a50..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/DatabaseMetaDataResultSet.java +++ /dev/null @@ -1,239 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2019 TAOS Data, Inc. - * - * This program is free software: you can use, redistribute, and/or modify - * it under the terms of the GNU Affero General Public License, version 3 - * or later ("AGPL"), as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - *****************************************************************************/ -package com.taosdata.jdbc; - -import java.math.BigDecimal; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; - -/* - * TDengine only supports a subset of the standard SQL, thus this implementation of the - * standard JDBC API contains more or less some adjustments customized for certain - * compatibility needs. - */ -public class DatabaseMetaDataResultSet extends AbstractResultSet { - - private List columnMetaDataList = new ArrayList<>(); - private List rowDataList = new ArrayList<>(); - private TSDBResultSetRowData rowCursor; - - // position of cursor, starts from 0 as beforeFirst, increases as next() is called - private int cursorRowNumber = 0; - - public void setRowDataList(List rowDataList) { - this.rowDataList = rowDataList; - } - - public void setColumnMetaDataList(List columnMetaDataList) { - this.columnMetaDataList = columnMetaDataList; - } - - @Override - public boolean next() throws SQLException { - boolean ret = false; - if (!rowDataList.isEmpty() && cursorRowNumber < rowDataList.size()) { - rowCursor = rowDataList.get(cursorRowNumber++); - ret = true; - } - return ret; - } - - @Override - public void close() throws SQLException { - - } - - @Override - public boolean wasNull() throws SQLException { - return false; - } - - @Override - public String getString(int columnIndex) throws SQLException { - int colType = columnMetaDataList.get(columnIndex - 1).getColType(); - return rowCursor.getString(columnIndex, colType); - } - - @Override - public boolean getBoolean(int columnIndex) throws SQLException { - int colType = columnMetaDataList.get(columnIndex - 1).getColType(); - return rowCursor.getBoolean(columnIndex, colType); - } - - @Override - public byte getByte(int columnIndex) throws SQLException { - int colType = columnMetaDataList.get(columnIndex - 1).getColType(); - return (byte) rowCursor.getInt(columnIndex, colType); - } - - @Override - public short getShort(int columnIndex) throws SQLException { - int colType = columnMetaDataList.get(columnIndex - 1).getColType(); - return (short) rowCursor.getInt(columnIndex, colType); - } - - @Override - public int getInt(int columnIndex) throws SQLException { - int colType = columnMetaDataList.get(columnIndex - 1).getColType(); - return rowCursor.getInt(columnIndex, colType); - } - - @Override - public long getLong(int columnIndex) throws SQLException { - int colType = columnMetaDataList.get(columnIndex - 1).getColType(); - return rowCursor.getLong(columnIndex, colType); - } - - @Override - public float getFloat(int columnIndex) throws SQLException { - int colType = columnMetaDataList.get(columnIndex - 1).getColType(); - return rowCursor.getFloat(columnIndex, colType); - } - - @Override - public double getDouble(int columnIndex) throws SQLException { - int colType = columnMetaDataList.get(columnIndex - 1).getColType(); - return rowCursor.getDouble(columnIndex, colType); - } - - @Override - public byte[] getBytes(int columnIndex) throws SQLException { - int colType = columnMetaDataList.get(columnIndex - 1).getColType(); - return (rowCursor.getString(columnIndex, colType)).getBytes(); - } - - @Override - public Timestamp getTimestamp(int columnIndex) throws SQLException { - int colType = columnMetaDataList.get(columnIndex - 1).getColType(); - return rowCursor.getTimestamp(columnIndex, colType); - } - - @Override - public ResultSetMetaData getMetaData() throws SQLException { - return new TSDBResultSetMetaData(this.columnMetaDataList); - } - - @Override - public Object getObject(int columnIndex) throws SQLException { - return rowCursor.getObject(columnIndex); - } - - @Override - public int findColumn(String columnLabel) throws SQLException { - for (ColumnMetaData colMetaData : this.columnMetaDataList) { - if (colMetaData.getColName() != null && colMetaData.getColName().equals(columnLabel)) { - return colMetaData.getColIndex(); - } - } - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - } - - @Override - public BigDecimal getBigDecimal(int columnIndex) throws SQLException { - int colType = columnMetaDataList.get(columnIndex - 1).getColType(); - double value = rowCursor.getDouble(columnIndex, colType); - return BigDecimal.valueOf(value); - } - - @Override - public boolean isBeforeFirst() throws SQLException { - return cursorRowNumber == 0; - } - - @Override - public boolean isAfterLast() throws SQLException { - return rowDataList.iterator().hasNext(); - } - - @Override - public boolean isFirst() throws SQLException { - return cursorRowNumber == 1; - } - - @Override - public boolean isLast() throws SQLException { - return cursorRowNumber == rowDataList.size(); - } - - @Override - public void beforeFirst() throws SQLException { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void afterLast() throws SQLException { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean first() throws SQLException { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean last() throws SQLException { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public int getRow() throws SQLException { - if (cursorRowNumber > 0 && cursorRowNumber <= rowDataList.size()) { - return cursorRowNumber; - } else { - return 0; - } - } - - @Override - public boolean absolute(int row) throws SQLException { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean relative(int rows) throws SQLException { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean previous() throws SQLException { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public Statement getStatement() throws SQLException { - return null; - } - - public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { - //TODO: calendar is not used - return getTimestamp(columnIndex); - } - - @Override - public boolean isClosed() throws SQLException { - return false; - } - - @Override - public String getNString(int columnIndex) throws SQLException { - return getString(columnIndex); - } - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/EmptyResultSet.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/EmptyResultSet.java deleted file mode 100644 index fa8bf9e7e9..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/EmptyResultSet.java +++ /dev/null @@ -1,986 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2019 TAOS Data, Inc. - * - * This program is free software: you can use, redistribute, and/or modify - * it under the terms of the GNU Affero General Public License, version 3 - * or later ("AGPL"), as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - *****************************************************************************/ -package com.taosdata.jdbc; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.net.URL; -import java.sql.*; -import java.util.Calendar; -import java.util.Map; - -/* - * TDengine only supports a subset of the standard SQL, thus this implementation of the - * standard JDBC API contains more or less some adjustments customized for certain - * compatibility needs. - */ -public class EmptyResultSet implements ResultSet { - - @Override - public boolean next() throws SQLException { - return false; - } - - @Override - public void close() throws SQLException { - - } - - @Override - public boolean wasNull() throws SQLException { - return false; - } - - @Override - public String getString(int columnIndex) throws SQLException { - return null; - } - - @Override - public boolean getBoolean(int columnIndex) throws SQLException { - return false; - } - - @Override - public byte getByte(int columnIndex) throws SQLException { - return 0; - } - - @Override - public short getShort(int columnIndex) throws SQLException { - return 0; - } - - @Override - public int getInt(int columnIndex) throws SQLException { - return 0; - } - - @Override - public long getLong(int columnIndex) throws SQLException { - return 0; - } - - @Override - public float getFloat(int columnIndex) throws SQLException { - return 0; - } - - @Override - public double getDouble(int columnIndex) throws SQLException { - return 0; - } - - @Override - public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { - return null; - } - - @Override - public byte[] getBytes(int columnIndex) throws SQLException { - return new byte[0]; - } - - @Override - public Date getDate(int columnIndex) throws SQLException { - return null; - } - - @Override - public Time getTime(int columnIndex) throws SQLException { - return null; - } - - @Override - public Timestamp getTimestamp(int columnIndex) throws SQLException { - return null; - } - - @Override - public InputStream getAsciiStream(int columnIndex) throws SQLException { - return null; - } - - @Override - public InputStream getUnicodeStream(int columnIndex) throws SQLException { - return null; - } - - @Override - public InputStream getBinaryStream(int columnIndex) throws SQLException { - return null; - } - - @Override - public String getString(String columnLabel) throws SQLException { - return null; - } - - @Override - public boolean getBoolean(String columnLabel) throws SQLException { - return false; - } - - @Override - public byte getByte(String columnLabel) throws SQLException { - return 0; - } - - @Override - public short getShort(String columnLabel) throws SQLException { - return 0; - } - - @Override - public int getInt(String columnLabel) throws SQLException { - return 0; - } - - @Override - public long getLong(String columnLabel) throws SQLException { - return 0; - } - - @Override - public float getFloat(String columnLabel) throws SQLException { - return 0; - } - - @Override - public double getDouble(String columnLabel) throws SQLException { - return 0; - } - - @Override - public BigDecimal getBigDecimal(String columnLabel, int scale) throws SQLException { - return null; - } - - @Override - public byte[] getBytes(String columnLabel) throws SQLException { - return new byte[0]; - } - - @Override - public Date getDate(String columnLabel) throws SQLException { - return null; - } - - @Override - public Time getTime(String columnLabel) throws SQLException { - return null; - } - - @Override - public Timestamp getTimestamp(String columnLabel) throws SQLException { - return null; - } - - @Override - public InputStream getAsciiStream(String columnLabel) throws SQLException { - return null; - } - - @Override - public InputStream getUnicodeStream(String columnLabel) throws SQLException { - return null; - } - - @Override - public InputStream getBinaryStream(String columnLabel) throws SQLException { - return null; - } - - @Override - public SQLWarning getWarnings() throws SQLException { - return null; - } - - @Override - public void clearWarnings() throws SQLException { - - } - - @Override - public String getCursorName() throws SQLException { - return null; - } - - @Override - public ResultSetMetaData getMetaData() throws SQLException { - return null; - } - - @Override - public Object getObject(int columnIndex) throws SQLException { - return null; - } - - @Override - public Object getObject(String columnLabel) throws SQLException { - return null; - } - - @Override - public int findColumn(String columnLabel) throws SQLException { - return 0; - } - - @Override - public Reader getCharacterStream(int columnIndex) throws SQLException { - return null; - } - - @Override - public Reader getCharacterStream(String columnLabel) throws SQLException { - return null; - } - - @Override - public BigDecimal getBigDecimal(int columnIndex) throws SQLException { - return null; - } - - @Override - public BigDecimal getBigDecimal(String columnLabel) throws SQLException { - return null; - } - - @Override - public boolean isBeforeFirst() throws SQLException { - return false; - } - - @Override - public boolean isAfterLast() throws SQLException { - return false; - } - - @Override - public boolean isFirst() throws SQLException { - return false; - } - - @Override - public boolean isLast() throws SQLException { - return false; - } - - @Override - public void beforeFirst() throws SQLException { - - } - - @Override - public void afterLast() throws SQLException { - - } - - @Override - public boolean first() throws SQLException { - return false; - } - - @Override - public boolean last() throws SQLException { - return false; - } - - @Override - public int getRow() throws SQLException { - return 0; - } - - @Override - public boolean absolute(int row) throws SQLException { - return false; - } - - @Override - public boolean relative(int rows) throws SQLException { - return false; - } - - @Override - public boolean previous() throws SQLException { - return false; - } - - @Override - public void setFetchDirection(int direction) throws SQLException { - - } - - @Override - public int getFetchDirection() throws SQLException { - return ResultSet.FETCH_FORWARD; - } - - @Override - public void setFetchSize(int rows) throws SQLException { - - } - - @Override - public int getFetchSize() throws SQLException { - return 0; - } - - @Override - public int getType() throws SQLException { - return ResultSet.TYPE_FORWARD_ONLY; - } - - @Override - public int getConcurrency() throws SQLException { - return ResultSet.CONCUR_READ_ONLY; - } - - @Override - public boolean rowUpdated() throws SQLException { - return false; - } - - @Override - public boolean rowInserted() throws SQLException { - return false; - } - - @Override - public boolean rowDeleted() throws SQLException { - return false; - } - - @Override - public void updateNull(int columnIndex) throws SQLException { - - } - - @Override - public void updateBoolean(int columnIndex, boolean x) throws SQLException { - - } - - @Override - public void updateByte(int columnIndex, byte x) throws SQLException { - - } - - @Override - public void updateShort(int columnIndex, short x) throws SQLException { - - } - - @Override - public void updateInt(int columnIndex, int x) throws SQLException { - - } - - @Override - public void updateLong(int columnIndex, long x) throws SQLException { - - } - - @Override - public void updateFloat(int columnIndex, float x) throws SQLException { - - } - - @Override - public void updateDouble(int columnIndex, double x) throws SQLException { - - } - - @Override - public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException { - - } - - @Override - public void updateString(int columnIndex, String x) throws SQLException { - - } - - @Override - public void updateBytes(int columnIndex, byte[] x) throws SQLException { - - } - - @Override - public void updateDate(int columnIndex, Date x) throws SQLException { - - } - - @Override - public void updateTime(int columnIndex, Time x) throws SQLException { - - } - - @Override - public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { - - } - - @Override - public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException { - - } - - @Override - public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException { - - } - - @Override - public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException { - - } - - @Override - public void updateObject(int columnIndex, Object x, int scaleOrLength) throws SQLException { - - } - - @Override - public void updateObject(int columnIndex, Object x) throws SQLException { - - } - - @Override - public void updateNull(String columnLabel) throws SQLException { - - } - - @Override - public void updateBoolean(String columnLabel, boolean x) throws SQLException { - - } - - @Override - public void updateByte(String columnLabel, byte x) throws SQLException { - - } - - @Override - public void updateShort(String columnLabel, short x) throws SQLException { - - } - - @Override - public void updateInt(String columnLabel, int x) throws SQLException { - - } - - @Override - public void updateLong(String columnLabel, long x) throws SQLException { - - } - - @Override - public void updateFloat(String columnLabel, float x) throws SQLException { - - } - - @Override - public void updateDouble(String columnLabel, double x) throws SQLException { - - } - - @Override - public void updateBigDecimal(String columnLabel, BigDecimal x) throws SQLException { - - } - - @Override - public void updateString(String columnLabel, String x) throws SQLException { - - } - - @Override - public void updateBytes(String columnLabel, byte[] x) throws SQLException { - - } - - @Override - public void updateDate(String columnLabel, Date x) throws SQLException { - - } - - @Override - public void updateTime(String columnLabel, Time x) throws SQLException { - - } - - @Override - public void updateTimestamp(String columnLabel, Timestamp x) throws SQLException { - - } - - @Override - public void updateAsciiStream(String columnLabel, InputStream x, int length) throws SQLException { - - } - - @Override - public void updateBinaryStream(String columnLabel, InputStream x, int length) throws SQLException { - - } - - @Override - public void updateCharacterStream(String columnLabel, Reader reader, int length) throws SQLException { - - } - - @Override - public void updateObject(String columnLabel, Object x, int scaleOrLength) throws SQLException { - - } - - @Override - public void updateObject(String columnLabel, Object x) throws SQLException { - - } - - @Override - public void insertRow() throws SQLException { - - } - - @Override - public void updateRow() throws SQLException { - - } - - @Override - public void deleteRow() throws SQLException { - - } - - @Override - public void refreshRow() throws SQLException { - - } - - @Override - public void cancelRowUpdates() throws SQLException { - - } - - @Override - public void moveToInsertRow() throws SQLException { - - } - - @Override - public void moveToCurrentRow() throws SQLException { - - } - - @Override - public Statement getStatement() throws SQLException { - return null; - } - - @Override - public Object getObject(int columnIndex, Map> map) throws SQLException { - return null; - } - - @Override - public Ref getRef(int columnIndex) throws SQLException { - return null; - } - - @Override - public Blob getBlob(int columnIndex) throws SQLException { - return null; - } - - @Override - public Clob getClob(int columnIndex) throws SQLException { - return null; - } - - @Override - public Array getArray(int columnIndex) throws SQLException { - return null; - } - - @Override - public Object getObject(String columnLabel, Map> map) throws SQLException { - return null; - } - - @Override - public Ref getRef(String columnLabel) throws SQLException { - return null; - } - - @Override - public Blob getBlob(String columnLabel) throws SQLException { - return null; - } - - @Override - public Clob getClob(String columnLabel) throws SQLException { - return null; - } - - @Override - public Array getArray(String columnLabel) throws SQLException { - return null; - } - - @Override - public Date getDate(int columnIndex, Calendar cal) throws SQLException { - return null; - } - - @Override - public Date getDate(String columnLabel, Calendar cal) throws SQLException { - return null; - } - - @Override - public Time getTime(int columnIndex, Calendar cal) throws SQLException { - return null; - } - - @Override - public Time getTime(String columnLabel, Calendar cal) throws SQLException { - return null; - } - - @Override - public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { - return null; - } - - @Override - public Timestamp getTimestamp(String columnLabel, Calendar cal) throws SQLException { - return null; - } - - @Override - public URL getURL(int columnIndex) throws SQLException { - return null; - } - - @Override - public URL getURL(String columnLabel) throws SQLException { - return null; - } - - @Override - public void updateRef(int columnIndex, Ref x) throws SQLException { - - } - - @Override - public void updateRef(String columnLabel, Ref x) throws SQLException { - - } - - @Override - public void updateBlob(int columnIndex, Blob x) throws SQLException { - - } - - @Override - public void updateBlob(String columnLabel, Blob x) throws SQLException { - - } - - @Override - public void updateClob(int columnIndex, Clob x) throws SQLException { - - } - - @Override - public void updateClob(String columnLabel, Clob x) throws SQLException { - - } - - @Override - public void updateArray(int columnIndex, Array x) throws SQLException { - - } - - @Override - public void updateArray(String columnLabel, Array x) throws SQLException { - - } - - @Override - public RowId getRowId(int columnIndex) throws SQLException { - return null; - } - - @Override - public RowId getRowId(String columnLabel) throws SQLException { - return null; - } - - @Override - public void updateRowId(int columnIndex, RowId x) throws SQLException { - - } - - @Override - public void updateRowId(String columnLabel, RowId x) throws SQLException { - - } - - @Override - public int getHoldability() throws SQLException { - return ResultSet.CLOSE_CURSORS_AT_COMMIT; - } - - @Override - public boolean isClosed() throws SQLException { - return false; - } - - @Override - public void updateNString(int columnIndex, String nString) throws SQLException { - - } - - @Override - public void updateNString(String columnLabel, String nString) throws SQLException { - - } - - @Override - public void updateNClob(int columnIndex, NClob nClob) throws SQLException { - - } - - @Override - public void updateNClob(String columnLabel, NClob nClob) throws SQLException { - - } - - @Override - public NClob getNClob(int columnIndex) throws SQLException { - return null; - } - - @Override - public NClob getNClob(String columnLabel) throws SQLException { - return null; - } - - @Override - public SQLXML getSQLXML(int columnIndex) throws SQLException { - return null; - } - - @Override - public SQLXML getSQLXML(String columnLabel) throws SQLException { - return null; - } - - @Override - public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException { - - } - - @Override - public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException { - - } - - @Override - public String getNString(int columnIndex) throws SQLException { - return null; - } - - @Override - public String getNString(String columnLabel) throws SQLException { - return null; - } - - @Override - public Reader getNCharacterStream(int columnIndex) throws SQLException { - return null; - } - - @Override - public Reader getNCharacterStream(String columnLabel) throws SQLException { - return null; - } - - @Override - public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException { - - } - - @Override - public void updateNCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { - - } - - @Override - public void updateAsciiStream(int columnIndex, InputStream x, long length) throws SQLException { - - } - - @Override - public void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException { - - } - - @Override - public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException { - - } - - @Override - public void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException { - - } - - @Override - public void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException { - - } - - @Override - public void updateCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { - - } - - @Override - public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException { - - } - - @Override - public void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException { - - } - - @Override - public void updateClob(int columnIndex, Reader reader, long length) throws SQLException { - - } - - @Override - public void updateClob(String columnLabel, Reader reader, long length) throws SQLException { - - } - - @Override - public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException { - - } - - @Override - public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException { - - } - - @Override - public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException { - - } - - @Override - public void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException { - - } - - @Override - public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException { - - } - - @Override - public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException { - - } - - @Override - public void updateCharacterStream(int columnIndex, Reader x) throws SQLException { - - } - - @Override - public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException { - - } - - @Override - public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException { - - } - - @Override - public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException { - - } - - @Override - public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException { - - } - - @Override - public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException { - - } - - @Override - public void updateClob(int columnIndex, Reader reader) throws SQLException { - - } - - @Override - public void updateClob(String columnLabel, Reader reader) throws SQLException { - - } - - @Override - public void updateNClob(int columnIndex, Reader reader) throws SQLException { - - } - - @Override - public void updateNClob(String columnLabel, Reader reader) throws SQLException { - - } - - @Override - public T getObject(int columnIndex, Class type) throws SQLException { - return null; - } - - @Override - public T getObject(String columnLabel, Class type) throws SQLException { - return null; - } - - @Override - public T unwrap(Class iface) throws SQLException { - return null; - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return false; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/SchemalessWriter.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/SchemalessWriter.java deleted file mode 100644 index d8cb5795f0..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/SchemalessWriter.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.taosdata.jdbc; - -import com.taosdata.jdbc.enums.SchemalessProtocolType; -import com.taosdata.jdbc.enums.SchemalessTimestampType; -import com.taosdata.jdbc.rs.RestfulConnection; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.List; - -/** - * This class is for schemaless lines(line/telnet/json) write to tdengine. - * e.g.: - * SchemalessWriter writer = new SchemalessWriter(connection); - * writer.write(lines, SchemalessProtocolType, SchemalessTimestampType); - */ -public class SchemalessWriter { - protected Connection connection; - - public SchemalessWriter(Connection connection) { - this.connection = connection; - } - - /** - * batch schemaless lines write to db - * - * @param lines schemaless lines - * @param protocolType schemaless type {@link SchemalessProtocolType} - * @param timestampType Time precision {@link SchemalessTimestampType} - * @throws SQLException execute exception - */ - public void write(String[] lines, SchemalessProtocolType protocolType, SchemalessTimestampType timestampType) throws SQLException { - if (connection instanceof TSDBConnection) { - TSDBConnection tsdbConnection = (TSDBConnection) connection; - tsdbConnection.getConnector().insertLines(lines, protocolType, timestampType); - } else if (connection instanceof RestfulConnection) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD, "restful connection is not supported currently"); - } else { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "unknown connection:" + connection.getMetaData().getURL()); - } - } - - /** - * only one line writes to db - * - * @param line schemaless line - * @param protocolType schemaless type {@link SchemalessProtocolType} - * @param timestampType Time precision {@link SchemalessTimestampType} - * @throws SQLException execute exception - */ - public void write(String line, SchemalessProtocolType protocolType, SchemalessTimestampType timestampType) throws SQLException { - write(new String[]{line}, protocolType, timestampType); - } - - /** - * batch schemaless lines write to db with list - * - * @param lines schemaless list - * @param protocolType schemaless type {@link SchemalessProtocolType} - * @param timestampType Time precision {@link SchemalessTimestampType} - * @throws SQLException execute exception - */ - public void write(List lines, SchemalessProtocolType protocolType, SchemalessTimestampType timestampType) throws SQLException { - String[] strings = lines.toArray(new String[0]); - write(strings, protocolType, timestampType); - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConnection.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConnection.java deleted file mode 100644 index c2687ba879..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConnection.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.taosdata.jdbc; - -import java.sql.*; -import java.util.*; -import java.util.concurrent.CopyOnWriteArrayList; - -public class TSDBConnection extends AbstractConnection { - - private TSDBJNIConnector connector; - private final TSDBDatabaseMetaData databaseMetaData; - private boolean batchFetch; - private CopyOnWriteArrayList statements = new CopyOnWriteArrayList<>(); - - public Boolean getBatchFetch() { - return this.batchFetch; - } - - public TSDBConnection(Properties info, TSDBDatabaseMetaData meta) throws SQLException { - super(info); - this.databaseMetaData = meta; - connect(info.getProperty(TSDBDriver.PROPERTY_KEY_HOST), - Integer.parseInt(info.getProperty(TSDBDriver.PROPERTY_KEY_PORT, "0")), - info.getProperty(TSDBDriver.PROPERTY_KEY_DBNAME), - info.getProperty(TSDBDriver.PROPERTY_KEY_USER), - info.getProperty(TSDBDriver.PROPERTY_KEY_PASSWORD)); - - String batchLoad = info.getProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD); - if (batchLoad != null) { - this.batchFetch = Boolean.parseBoolean(batchLoad); - } - } - - private void connect(String host, int port, String dbName, String user, String password) throws SQLException { - this.connector = new TSDBJNIConnector(); - this.connector.connect(host, port, dbName, user, password); - this.catalog = dbName; - this.databaseMetaData.setConnection(this); - } - - public TSDBJNIConnector getConnector() { - return this.connector; - } - - public Statement createStatement() throws SQLException { - if (isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - } - - return new TSDBStatement(this); - } - - public TSDBSubscribe subscribe(String topic, String sql, boolean restart) throws SQLException { - if (isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - } - - long id = this.connector.subscribe(topic, sql, restart); - if (id == 0) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_SUBSCRIBE_FAILED); - } - return new TSDBSubscribe(this.connector, id); - } - - public PreparedStatement prepareStatement(String sql) throws SQLException { - if (isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - } - return new TSDBPreparedStatement(this, sql); - } - - public void close() throws SQLException { - if (isClosed) - return; - synchronized (this) { - if (isClosed) { - return; - } - for (Statement statement : statements) { - statement.close(); - } - this.connector.closeConnection(); - this.isClosed = true; - } - } - - public void unregisterStatement(Statement stmt) { - this.statements.remove(stmt); - } - public void registerStatement(Statement stmt) { - this.statements.addIfAbsent(stmt); - } - - public boolean isClosed() throws SQLException { - return this.connector != null && this.connector.isClosed(); - } - - public DatabaseMetaData getMetaData() throws SQLException { - if (isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - } - return this.databaseMetaData; - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConstants.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConstants.java deleted file mode 100644 index 06113f2783..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConstants.java +++ /dev/null @@ -1,225 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2019 TAOS Data, Inc. - * - * This program is free software: you can use, redistribute, and/or modify - * it under the terms of the GNU Affero General Public License, version 3 - * or later ("AGPL"), as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - *****************************************************************************/ -package com.taosdata.jdbc; - -import java.sql.SQLException; -import java.sql.Types; - -public abstract class TSDBConstants { - - public static final long JNI_NULL_POINTER = 0L; - // JNI_ERROR_NUMBER - public static final int JNI_SUCCESS = 0; - public static final int JNI_TDENGINE_ERROR = -1; - public static final int JNI_CONNECTION_NULL = -2; - public static final int JNI_RESULT_SET_NULL = -3; - public static final int JNI_NUM_OF_FIELDS_0 = -4; - public static final int JNI_SQL_NULL = -5; - public static final int JNI_FETCH_END = -6; - public static final int JNI_OUT_OF_MEMORY = -7; - // TSDB Data Types - public static final int TSDB_DATA_TYPE_NULL = 0; - public static final int TSDB_DATA_TYPE_BOOL = 1; - public static final int TSDB_DATA_TYPE_TINYINT = 2; - public static final int TSDB_DATA_TYPE_SMALLINT = 3; - public static final int TSDB_DATA_TYPE_INT = 4; - public static final int TSDB_DATA_TYPE_BIGINT = 5; - public static final int TSDB_DATA_TYPE_FLOAT = 6; - public static final int TSDB_DATA_TYPE_DOUBLE = 7; - public static final int TSDB_DATA_TYPE_BINARY = 8; - public static final int TSDB_DATA_TYPE_TIMESTAMP = 9; - public static final int TSDB_DATA_TYPE_NCHAR = 10; - /** - * 系统增加新的无符号数据类型,分别是: - * unsigned tinyint, 数值范围:0-254, NULL 为255 - * unsigned smallint,数值范围: 0-65534, NULL 为65535 - * unsigned int,数值范围:0-4294967294,NULL 为4294967295u - * unsigned bigint,数值范围:0-18446744073709551614u,NULL 为18446744073709551615u。 - * example: - * create table tb(ts timestamp, a tinyint unsigned, b smallint unsigned, c int unsigned, d bigint unsigned); - */ - public static final int TSDB_DATA_TYPE_UTINYINT = 11; //unsigned tinyint - public static final int TSDB_DATA_TYPE_USMALLINT = 12; //unsigned smallint - public static final int TSDB_DATA_TYPE_UINT = 13; //unsigned int - public static final int TSDB_DATA_TYPE_UBIGINT = 14; //unsigned bigint - public static final int TSDB_DATA_TYPE_JSON = 15; //json - // nchar column max length - public static final int maxFieldSize = 16 * 1024; - - // precision for data types, this is used for metadata - public static final int BOOLEAN_PRECISION = 1; - public static final int TINYINT_PRECISION = 4; - public static final int SMALLINT_PRECISION = 6; - public static final int INT_PRECISION = 11; - public static final int BIGINT_PRECISION = 20; - public static final int FLOAT_PRECISION = 12; - public static final int DOUBLE_PRECISION = 22; - public static final int TIMESTAMP_MS_PRECISION = 23; - public static final int TIMESTAMP_US_PRECISION = 26; - // scale for data types, this is used for metadata - public static final int FLOAT_SCALE = 31; - public static final int DOUBLE_SCALE = 31; - - public static final String DEFAULT_PRECISION = "ms"; - - public static final boolean DEFAULT_BATCH_ERROR_IGNORE = false; - - public static int typeName2JdbcType(String type) { - switch (type.toUpperCase()) { - case "TIMESTAMP": - return Types.TIMESTAMP; - case "INT": - return Types.INTEGER; - case "BIGINT": - return Types.BIGINT; - case "FLOAT": - return Types.FLOAT; - case "DOUBLE": - return Types.DOUBLE; - case "BINARY": - return Types.BINARY; - case "SMALLINT": - return Types.SMALLINT; - case "TINYINT": - return Types.TINYINT; - case "BOOL": - return Types.BOOLEAN; - case "NCHAR": - return Types.NCHAR; - default: - return Types.NULL; - } - } - - public static int taosType2JdbcType(int taosType) throws SQLException { - switch (taosType) { - case TSDBConstants.TSDB_DATA_TYPE_BOOL: - return Types.BOOLEAN; - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: - case TSDBConstants.TSDB_DATA_TYPE_UTINYINT: - return Types.TINYINT; - case TSDBConstants.TSDB_DATA_TYPE_USMALLINT: - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: - return Types.SMALLINT; - case TSDBConstants.TSDB_DATA_TYPE_UINT: - case TSDBConstants.TSDB_DATA_TYPE_INT: - return Types.INTEGER; - case TSDBConstants.TSDB_DATA_TYPE_UBIGINT: - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - return Types.BIGINT; - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: - return Types.FLOAT; - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: - return Types.DOUBLE; - case TSDBConstants.TSDB_DATA_TYPE_BINARY: - return Types.BINARY; - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: - return Types.TIMESTAMP; - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: - return Types.NCHAR; - case TSDBConstants.TSDB_DATA_TYPE_JSON: - return Types.OTHER; - default: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN_TAOS_TYPE, "unknown taos type: " + taosType + " in tdengine"); - } - } - - public static String taosType2JdbcTypeName(int taosType) throws SQLException { - switch (taosType) { - case TSDBConstants.TSDB_DATA_TYPE_BOOL: - return "BOOL"; - case TSDBConstants.TSDB_DATA_TYPE_UTINYINT: - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: - return "TINYINT"; - case TSDBConstants.TSDB_DATA_TYPE_USMALLINT: - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: - return "SMALLINT"; - case TSDBConstants.TSDB_DATA_TYPE_UINT: - case TSDBConstants.TSDB_DATA_TYPE_INT: - return "INT"; - case TSDBConstants.TSDB_DATA_TYPE_UBIGINT: - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - return "BIGINT"; - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: - return "FLOAT"; - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: - return "DOUBLE"; - case TSDBConstants.TSDB_DATA_TYPE_BINARY: - return "BINARY"; - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: - return "TIMESTAMP"; - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: - return "NCHAR"; - case TSDBConstants.TSDB_DATA_TYPE_JSON: - return "JSON"; - default: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN_TAOS_TYPE, "unknown taos type: " + taosType + " in tdengine"); - } - } - - public static int jdbcType2TaosType(int jdbcType) throws SQLException { - switch (jdbcType) { - case Types.BOOLEAN: - return TSDBConstants.TSDB_DATA_TYPE_BOOL; - case Types.TINYINT: - return TSDBConstants.TSDB_DATA_TYPE_TINYINT; - case Types.SMALLINT: - return TSDBConstants.TSDB_DATA_TYPE_SMALLINT; - case Types.INTEGER: - return TSDBConstants.TSDB_DATA_TYPE_INT; - case Types.BIGINT: - return TSDBConstants.TSDB_DATA_TYPE_BIGINT; - case Types.FLOAT: - return TSDBConstants.TSDB_DATA_TYPE_FLOAT; - case Types.DOUBLE: - return TSDBConstants.TSDB_DATA_TYPE_DOUBLE; - case Types.BINARY: - return TSDBConstants.TSDB_DATA_TYPE_BINARY; - case Types.TIMESTAMP: - return TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP; - case Types.NCHAR: - return TSDBConstants.TSDB_DATA_TYPE_NCHAR; - } - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN_SQL_TYPE_IN_TDENGINE, "unknown sql type: " + jdbcType + " in tdengine"); - } - - public static String jdbcType2TaosTypeName(int jdbcType) throws SQLException { - switch (jdbcType) { - case Types.BOOLEAN: - return "BOOL"; - case Types.TINYINT: - return "TINYINT"; - case Types.SMALLINT: - return "SMALLINT"; - case Types.INTEGER: - return "INT"; - case Types.BIGINT: - return "BIGINT"; - case Types.FLOAT: - return "FLOAT"; - case Types.DOUBLE: - return "DOUBLE"; - case Types.BINARY: - return "BINARY"; - case Types.TIMESTAMP: - return "TIMESTAMP"; - case Types.NCHAR: - return "NCHAR"; - default: - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN_SQL_TYPE_IN_TDENGINE, "unknown sql type: " + jdbcType + " in tdengine"); - } - } - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBDatabaseMetaData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBDatabaseMetaData.java deleted file mode 100644 index 9a5eda4cd8..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBDatabaseMetaData.java +++ /dev/null @@ -1,95 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2019 TAOS Data, Inc. - * - * This program is free software: you can use, redistribute, and/or modify - * it under the terms of the GNU Affero General Public License, version 3 - * or later ("AGPL"), as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - *****************************************************************************/ -package com.taosdata.jdbc; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class TSDBDatabaseMetaData extends AbstractDatabaseMetaData { - - private final String url; - private final String userName; - private Connection conn; - - public TSDBDatabaseMetaData(String url, String userName) { - this.url = url; - this.userName = userName; - } - - public Connection getConnection() throws SQLException { - return this.conn; - } - - public void setConnection(Connection conn) { - this.conn = conn; - } - - public String getURL() throws SQLException { - return this.url; - } - - public String getUserName() throws SQLException { - return this.userName; - } - - public String getDriverName() throws SQLException { - return TSDBDriver.class.getName(); - } - - /** - * @Param catalog : database名称,"" 表示不属于任何database的table,null表示不使用database来缩小范围 - * @Param schemaPattern : schema名称,""表示 - * @Param tableNamePattern : 表名满足tableNamePattern的表, null表示返回所有表 - * @Param types : 表类型,null表示返回所有类型 - */ - public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException { - if (conn == null || conn.isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - } - return super.getTables(catalog, schemaPattern, tableNamePattern, types, conn); - } - - public ResultSet getCatalogs() throws SQLException { - if (conn == null || conn.isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - return super.getCatalogs(conn); - } - - public ResultSet getTableTypes() throws SQLException { - if (conn == null || conn.isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - return super.getTableTypes(); - } - - public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { - if (conn == null || conn.isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - return super.getColumns(catalog, schemaPattern, tableNamePattern, columnNamePattern, conn); - } - - public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException { - if (conn == null || conn.isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - return super.getPrimaryKeys(catalog, schema, table, conn); - } - - public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { - if (conn == null || conn.isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - return super.getSuperTables(catalog, schemaPattern, tableNamePattern, conn); - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBDriver.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBDriver.java deleted file mode 100755 index ac8f68d918..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBDriver.java +++ /dev/null @@ -1,254 +0,0 @@ -package com.taosdata.jdbc; - -import java.sql.*; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.logging.Logger; - -/** - * The Java SQL framework allows for multiple database drivers. Each driver - * should supply a class that implements the Driver interface - * - *

- * The DriverManager will try to load as many drivers as it can find and then - * for any given connection request, it will ask each driver in turn to try to - * connect to the target URL. - * - *

- * It is strongly recommended that each Driver class should be small and stand - * alone so that the Driver class can be loaded and queried without bringing in - * vast quantities of supporting code. - * - *

- * When a Driver class is loaded, it should create an instance of itself and - * register it with the DriverManager. This means that a user can load and - * register a driver by doing Class.forName("foo.bah.Driver") - */ -public class TSDBDriver extends AbstractDriver { - - @Deprecated - private static final String URL_PREFIX1 = "jdbc:TSDB://"; - - private static final String URL_PREFIX = "jdbc:TAOS://"; - - /** - * PRODUCT_NAME - */ - public static final String PROPERTY_KEY_PRODUCT_NAME = "productName"; - /** - * Key used to retrieve the host value from the properties instance passed to - * the driver. - */ - public static final String PROPERTY_KEY_HOST = "host"; - /** - * Key used to retrieve the port number value from the properties instance - * passed to the driver. - */ - public static final String PROPERTY_KEY_PORT = "port"; - /** - * Key used to retrieve the database value from the properties instance passed - * to the driver. - */ - public static final String PROPERTY_KEY_DBNAME = "dbname"; - /** - * Key used to retrieve the user value from the properties instance passed to - * the driver. - */ - public static final String PROPERTY_KEY_USER = "user"; - /** - * Key used to retrieve the password value from the properties instance passed - * to the driver. - */ - public static final String PROPERTY_KEY_PASSWORD = "password"; - /** - * Key used to retrieve the token value from the properties instance passed to - * the driver. - * Just for Cloud Service - */ - public static final String PROPERTY_KEY_TOKEN = "token"; - /** - * Use SSL (true/false) to communicate with the server. The default value is false. - * Just for Cloud Service - */ - public static final String PROPERTY_KEY_USE_SSL = "useSSL"; - /** - * Key for the configuration file directory of TSDB client in properties instance - */ - public static final String PROPERTY_KEY_CONFIG_DIR = "cfgdir"; - /** - * Key for the timezone used by the TSDB client in properties instance - */ - public static final String PROPERTY_KEY_TIME_ZONE = "timezone"; - /** - * Key for the locale used by the TSDB client in properties instance - */ - public static final String PROPERTY_KEY_LOCALE = "locale"; - /** - * Key for the char encoding used by the TSDB client in properties instance - */ - public static final String PROPERTY_KEY_CHARSET = "charset"; - - /** - * fetch data from native function in a batch model - */ - public static final String PROPERTY_KEY_BATCH_LOAD = "batchfetch"; - - /** - * timestamp format for JDBC-RESTful,should one of the options: string or timestamp or utc - */ - public static final String PROPERTY_KEY_TIMESTAMP_FORMAT = "timestampFormat"; - - /** - * continue process commands in executeBatch - */ - public static final String PROPERTY_KEY_BATCH_ERROR_IGNORE = "batchErrorIgnore"; - - /** - * message receive from server timeout. ms - */ - public static final String PROPERTY_KEY_MESSAGE_WAIT_TIMEOUT = "messageWaitTimeout"; - - /** - * max message number send to server concurrently - */ - public static final String PROPERTY_KEY_MAX_CONCURRENT_REQUEST = "maxConcurrentRequest"; - - private TSDBDatabaseMetaData dbMetaData = null; - - static { - try { - DriverManager.registerDriver(new TSDBDriver()); - } catch (SQLException e) { - throw TSDBError.createRuntimeException(TSDBErrorNumbers.ERROR_CANNOT_REGISTER_JNI_DRIVER, e); - } - } - - public Connection connect(String url, Properties info) throws SQLException { - if (!acceptsURL(url)) - return null; - - Properties props = parseURL(url, info); - if (props == null) { - return null; - } - - if (!props.containsKey(TSDBDriver.PROPERTY_KEY_USER)) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_USER_IS_REQUIRED); - if (!props.containsKey(TSDBDriver.PROPERTY_KEY_PASSWORD)) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PASSWORD_IS_REQUIRED); - - try { - TSDBJNIConnector.init(props); - return new TSDBConnection(props, this.dbMetaData); - } catch (SQLWarning sqlWarning) { - return new TSDBConnection(props, this.dbMetaData); - } catch (SQLException sqlEx) { - throw sqlEx; - } catch (Exception ex) { - throw new SQLException("SQLException:" + ex, ex); - } - } - - /** - * @param url the URL of the database - * @return true if this driver understands the given URL; - * false otherwise - * @throws SQLException if a database access error occurs or the url is {@code null} - */ - public boolean acceptsURL(String url) throws SQLException { - if (url == null) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_URL_NOT_SET); - return url.trim().length() > 0 && (url.startsWith(URL_PREFIX) || url.startsWith(URL_PREFIX1)); - } - - public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { - if (info == null) { - info = new Properties(); - } - - if (acceptsURL(url)) { - info = parseURL(url, info); - } - - return getPropertyInfo(info); - } - - /** - * example: jdbc:TAOS://127.0.0.1:0/db?user=root&password=your_password - */ - @Override - public Properties parseURL(String url, Properties defaults) { - Properties urlProps = (defaults != null) ? defaults : new Properties(); - if (url == null || url.length() <= 0 || url.trim().length() <= 0) - return null; - if (!url.startsWith(URL_PREFIX) && !url.startsWith(URL_PREFIX1)) - return null; - - // parse properties - String urlForMeta = url; - int beginningOfSlashes = url.indexOf("//"); - int index = url.indexOf("?"); - if (index != -1) { - String paramString = url.substring(index + 1); - url = url.substring(0, index); - StringTokenizer queryParams = new StringTokenizer(paramString, "&"); - while (queryParams.hasMoreElements()) { - String oneToken = queryParams.nextToken(); - String[] pair = oneToken.split("="); - - if ((pair[0] != null && pair[0].trim().length() > 0) && (pair[1] != null && pair[1].trim().length() > 0)) { - urlProps.setProperty(pair[0].trim(), pair[1].trim()); - } - } - } - - // parse Product Name - String dbProductName = url.substring(0, beginningOfSlashes); - dbProductName = dbProductName.substring(dbProductName.indexOf(":") + 1); - dbProductName = dbProductName.substring(0, dbProductName.indexOf(":")); - urlProps.setProperty(TSDBDriver.PROPERTY_KEY_PRODUCT_NAME, dbProductName); - - // parse database name - url = url.substring(beginningOfSlashes + 2); - int indexOfSlash = url.indexOf("/"); - if (indexOfSlash != -1) { - if (indexOfSlash + 1 < url.length()) { - urlProps.setProperty(TSDBDriver.PROPERTY_KEY_DBNAME, url.substring(indexOfSlash + 1)); - } - url = url.substring(0, indexOfSlash); - } - - // parse port - int indexOfColon = url.indexOf(":"); - if (indexOfColon != -1) { - if (indexOfColon + 1 < url.length()) { - urlProps.setProperty(TSDBDriver.PROPERTY_KEY_PORT, url.substring(indexOfColon + 1)); - } - url = url.substring(0, indexOfColon); - } - - if (url.length() > 0 && url.trim().length() > 0) { - urlProps.setProperty(TSDBDriver.PROPERTY_KEY_HOST, url); - } - - this.dbMetaData = new TSDBDatabaseMetaData(urlForMeta, urlProps.getProperty(TSDBDriver.PROPERTY_KEY_USER)); - return urlProps; - } - - public int getMajorVersion() { - return 2; - } - - public int getMinorVersion() { - return 0; - } - - public boolean jdbcCompliant() { - return false; - } - - public Logger getParentLogger() { - return null; - } - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBError.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBError.java deleted file mode 100644 index 0970148b1d..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBError.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.taosdata.jdbc; - -import java.sql.SQLClientInfoException; -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; -import java.sql.SQLWarning; -import java.util.HashMap; -import java.util.Map; - -public class TSDBError { - private static final Map TSDBErrorMap = new HashMap<>(); - - static { - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED, "connection already closed"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD, "this operation is NOT supported currently!"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_INVALID_VARIABLE, "invalid variables"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED, "statement is closed"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED, "resultSet is closed"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_BATCH_IS_EMPTY, "Batch is empty!"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEQUERY, "Can not issue data manipulation statements with executeQuery()"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEUPDATE, "Can not issue SELECT via executeUpdate()"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_INVALID_FOR_EXECUTE_QUERY, "invalid sql for executeQuery: (?)"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_DATABASE_NOT_SPECIFIED_OR_AVAILABLE, "Database not specified or available"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_INVALID_FOR_EXECUTE_UPDATE, "invalid sql for executeUpdate: (?)"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_INVALID_FOR_EXECUTE, "invalid sql for execute: (?)"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE, "parameter index out of range"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_SQLCLIENT_EXCEPTION_ON_CONNECTION_CLOSED, "connection already closed"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_UNKNOWN_SQL_TYPE_IN_TDENGINE, "unknown sql type in tdengine"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_CANNOT_REGISTER_JNI_DRIVER, "can't register JDBC-JNI driver"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_CANNOT_REGISTER_RESTFUL_DRIVER, "can't register JDBC-RESTful driver"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_URL_NOT_SET, "url is not set"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_INVALID_SQL, "invalid sql"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_NUMERIC_VALUE_OUT_OF_RANGE, "numeric value out of range"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_UNKNOWN_TAOS_TYPE, "unknown taos type in tdengine"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_UNKNOWN_TIMESTAMP_PRECISION, "unknown timestamp precision"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_USER_IS_REQUIRED, "user is required"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_PASSWORD_IS_REQUIRED, "password is required"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_INVALID_JSON_FORMAT, "invalid json format"); - - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_UNKNOWN, "unknown error"); - - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_SUBSCRIBE_FAILED, "failed to create subscription"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_UNSUPPORTED_ENCODING, "Unsupported encoding"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_JNI_TDENGINE_ERROR, "internal error of database, please see taoslog for more details"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL, "JNI connection is NULL"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_JNI_RESULT_SET_NULL, "JNI result set is NULL"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_JNI_NUM_OF_FIELDS_0, "invalid num of fields"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_JNI_SQL_NULL, "empty sql string"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_JNI_FETCH_END, "fetch to the end of resultSet"); - TSDBErrorMap.put(TSDBErrorNumbers.ERROR_JNI_OUT_OF_MEMORY, "JNI alloc memory failed, please see taoslog for more details"); - } - - public static SQLException createSQLException(int errorCode) { - String message; - if (TSDBErrorNumbers.contains(errorCode)) - message = TSDBErrorMap.get(errorCode); - else - message = TSDBErrorMap.get(TSDBErrorNumbers.ERROR_UNKNOWN); - return createSQLException(errorCode, message); - } - - public static SQLException createSQLException(int errorCode, String message) { - // throw SQLFeatureNotSupportedException - if (errorCode == TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD) - return new SQLFeatureNotSupportedException(message, "", errorCode); - // throw SQLClientInfoException - if (errorCode == TSDBErrorNumbers.ERROR_SQLCLIENT_EXCEPTION_ON_CONNECTION_CLOSED) - return new SQLClientInfoException(message, null); - - if (errorCode > 0x2300 && errorCode < 0x2350) - // JDBC exception's error number is less than 0x2350 - return new SQLException("ERROR (" + Integer.toHexString(errorCode) + "): " + message, "", errorCode); - if (errorCode > 0x2350 && errorCode < 0x2400) - // JNI exception's error number is large than 0x2350 - return new SQLException("JNI ERROR (" + Integer.toHexString(errorCode) + "): " + message, "", errorCode); - return new SQLException("TDengine ERROR (" + Integer.toHexString(errorCode) + "): " + message, "", errorCode); - } - - public static RuntimeException createRuntimeException(int errorCode, Throwable t) { - String message = TSDBErrorMap.get(errorCode); - return new RuntimeException("ERROR (" + Integer.toHexString(errorCode) + "): " + message, t); - } - - public static SQLWarning createSQLWarning(String message) { - return new SQLWarning(message); - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBErrorNumbers.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBErrorNumbers.java deleted file mode 100644 index 1c380fed7d..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBErrorNumbers.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.taosdata.jdbc; - -import java.util.HashSet; -import java.util.Set; - -public class TSDBErrorNumbers { - - public static final int ERROR_CONNECTION_CLOSED = 0x2301; // connection already closed - public static final int ERROR_UNSUPPORTED_METHOD = 0x2302; //this operation is NOT supported currently! - public static final int ERROR_INVALID_VARIABLE = 0x2303; //invalid variables - public static final int ERROR_STATEMENT_CLOSED = 0x2304; //statement already closed - public static final int ERROR_RESULTSET_CLOSED = 0x2305; //resultSet is closed - public static final int ERROR_BATCH_IS_EMPTY = 0x2306; //Batch is empty! - public static final int ERROR_INVALID_WITH_EXECUTEQUERY = 0x2307; //Can not issue data manipulation statements with executeQuery() - public static final int ERROR_INVALID_WITH_EXECUTEUPDATE = 0x2308; //Can not issue SELECT via executeUpdate() - public static final int ERROR_INVALID_FOR_EXECUTE_QUERY = 0x2309; //not a valid sql for executeQuery: (SQL) - public static final int ERROR_DATABASE_NOT_SPECIFIED_OR_AVAILABLE = 0x230a; //Database not specified or available - public static final int ERROR_INVALID_FOR_EXECUTE_UPDATE = 0x230b; //not a valid sql for executeUpdate: (SQL) - public static final int ERROR_INVALID_FOR_EXECUTE = 0x230c; //not a valid sql for execute: (SQL) - public static final int ERROR_PARAMETER_INDEX_OUT_RANGE = 0x230d; // parameter index out of range - public static final int ERROR_SQLCLIENT_EXCEPTION_ON_CONNECTION_CLOSED = 0x230e; // connection already closed - public static final int ERROR_UNKNOWN_SQL_TYPE_IN_TDENGINE = 0x230f; //unknown sql type in tdengine - public static final int ERROR_CANNOT_REGISTER_JNI_DRIVER = 0x2310; // can't register JDBC-JNI driver - public static final int ERROR_CANNOT_REGISTER_RESTFUL_DRIVER = 0x2311; // can't register JDBC-RESTful driver - public static final int ERROR_URL_NOT_SET = 0x2312; // url is not set - public static final int ERROR_INVALID_SQL = 0x2313; // invalid sql - public static final int ERROR_NUMERIC_VALUE_OUT_OF_RANGE = 0x2314; // numeric value out of range - public static final int ERROR_UNKNOWN_TAOS_TYPE = 0x2315; //unknown taos type in tdengine - public static final int ERROR_UNKNOWN_TIMESTAMP_PRECISION = 0x2316; // unknown timestamp precision - public static final int ERROR_RESTFul_Client_Protocol_Exception = 0x2317; - public static final int ERROR_RESTFul_Client_IOException = 0x2318; - public static final int ERROR_USER_IS_REQUIRED = 0x2319; // user is required - public static final int ERROR_PASSWORD_IS_REQUIRED = 0x231a; // password is required - public static final int ERROR_INVALID_JSON_FORMAT = 0x231b; - public static final int ERROR_HTTP_ENTITY_IS_NULL = 0x231c; //http entity is null - - - public static final int ERROR_UNKNOWN = 0x2350; //unknown error - - public static final int ERROR_SUBSCRIBE_FAILED = 0x2351; // failed to create subscription - public static final int ERROR_UNSUPPORTED_ENCODING = 0x2352; // Unsupported encoding - public static final int ERROR_JNI_TDENGINE_ERROR = 0x2353; // internal error of database - public static final int ERROR_JNI_CONNECTION_NULL = 0x2354; // JNI connection is NULL - public static final int ERROR_JNI_RESULT_SET_NULL = 0x2355; // invalid JNI result set - public static final int ERROR_JNI_NUM_OF_FIELDS_0 = 0x2356; // invalid num of fields - public static final int ERROR_JNI_SQL_NULL = 0x2357; // empty sql string - public static final int ERROR_JNI_FETCH_END = 0x2358; // fetch to the end of resultSet - public static final int ERROR_JNI_OUT_OF_MEMORY = 0x2359; // JNI alloc memory failed - - private static final Set errorNumbers = new HashSet<>(); - - static { - errorNumbers.add(ERROR_CONNECTION_CLOSED); - errorNumbers.add(ERROR_UNSUPPORTED_METHOD); - errorNumbers.add(ERROR_INVALID_VARIABLE); - errorNumbers.add(ERROR_STATEMENT_CLOSED); - errorNumbers.add(ERROR_RESULTSET_CLOSED); - errorNumbers.add(ERROR_INVALID_WITH_EXECUTEQUERY); - errorNumbers.add(ERROR_INVALID_WITH_EXECUTEUPDATE); - errorNumbers.add(ERROR_INVALID_FOR_EXECUTE_QUERY); - errorNumbers.add(ERROR_DATABASE_NOT_SPECIFIED_OR_AVAILABLE); - errorNumbers.add(ERROR_INVALID_FOR_EXECUTE_UPDATE); - errorNumbers.add(ERROR_INVALID_FOR_EXECUTE); - errorNumbers.add(ERROR_PARAMETER_INDEX_OUT_RANGE); - errorNumbers.add(ERROR_SQLCLIENT_EXCEPTION_ON_CONNECTION_CLOSED); - errorNumbers.add(ERROR_UNKNOWN_SQL_TYPE_IN_TDENGINE); - errorNumbers.add(ERROR_CANNOT_REGISTER_JNI_DRIVER); - errorNumbers.add(ERROR_CANNOT_REGISTER_RESTFUL_DRIVER); - errorNumbers.add(ERROR_URL_NOT_SET); - errorNumbers.add(ERROR_INVALID_SQL); - errorNumbers.add(ERROR_NUMERIC_VALUE_OUT_OF_RANGE); - errorNumbers.add(ERROR_UNKNOWN_TAOS_TYPE); - errorNumbers.add(ERROR_UNKNOWN_TIMESTAMP_PRECISION); - errorNumbers.add(ERROR_RESTFul_Client_IOException); - errorNumbers.add(ERROR_USER_IS_REQUIRED); - errorNumbers.add(ERROR_PASSWORD_IS_REQUIRED); - errorNumbers.add(ERROR_INVALID_JSON_FORMAT); - errorNumbers.add(ERROR_HTTP_ENTITY_IS_NULL); - - errorNumbers.add(ERROR_RESTFul_Client_Protocol_Exception); - - errorNumbers.add(ERROR_SUBSCRIBE_FAILED); - errorNumbers.add(ERROR_UNSUPPORTED_ENCODING); - errorNumbers.add(ERROR_JNI_TDENGINE_ERROR); - errorNumbers.add(ERROR_JNI_CONNECTION_NULL); - errorNumbers.add(ERROR_JNI_RESULT_SET_NULL); - errorNumbers.add(ERROR_JNI_NUM_OF_FIELDS_0); - errorNumbers.add(ERROR_JNI_SQL_NULL); - errorNumbers.add(ERROR_JNI_FETCH_END); - errorNumbers.add(ERROR_JNI_OUT_OF_MEMORY); - } - - private TSDBErrorNumbers() { - } - - public static boolean contains(int errorNumber) { - return errorNumbers.contains(errorNumber); - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBException.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBException.java deleted file mode 100644 index 31299a1c6f..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBException.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.taosdata.jdbc; - -public class TSDBException { - private int code; - private String message; - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBJNIConnector.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBJNIConnector.java deleted file mode 100755 index 3cc28b4de6..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBJNIConnector.java +++ /dev/null @@ -1,384 +0,0 @@ -package com.taosdata.jdbc; - -import com.alibaba.fastjson.JSONObject; -import com.taosdata.jdbc.enums.SchemalessProtocolType; -import com.taosdata.jdbc.enums.SchemalessTimestampType; -import com.taosdata.jdbc.utils.TaosInfo; - -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -import java.sql.SQLException; -import java.sql.SQLWarning; -import java.util.List; -import java.util.Properties; - -/** - * JNI connector - */ -public class TSDBJNIConnector { - private static final Object LOCK = new Object(); - private static volatile boolean isInitialized; - - private final TaosInfo taosInfo = TaosInfo.getInstance(); - private long taos = TSDBConstants.JNI_NULL_POINTER; // Connection pointer used in C - private boolean isResultsetClosed; // result set status in current connection - private int affectedRows = -1; - - static { - System.loadLibrary("taos"); - } - - /***********************************************************************/ - //NOTE: JDBC - public static void init(Properties props) throws SQLWarning { - synchronized (LOCK) { - if (!isInitialized) { - - JSONObject configJSON = new JSONObject(); - for (String key : props.stringPropertyNames()) { - configJSON.put(key, props.getProperty(key)); - } - setConfigImp(configJSON.toJSONString()); - - initImp(props.getProperty(TSDBDriver.PROPERTY_KEY_CONFIG_DIR, null)); - - String locale = props.getProperty(TSDBDriver.PROPERTY_KEY_LOCALE); - if (setOptions(0, locale) < 0) { - throw TSDBError.createSQLWarning("Failed to set locale: " + locale + ". System default will be used."); - } - String charset = props.getProperty(TSDBDriver.PROPERTY_KEY_CHARSET); - if (setOptions(1, charset) < 0) { - throw TSDBError.createSQLWarning("Failed to set charset: " + charset + ". System default will be used."); - } - String timezone = props.getProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE); - if (setOptions(2, timezone) < 0) { - throw TSDBError.createSQLWarning("Failed to set timezone: " + timezone + ". System default will be used."); - } - isInitialized = true; - TaosGlobalConfig.setCharset(getTsCharset()); - } - } - } - - private static native void initImp(String configDir); - - private static native int setOptions(int optionIndex, String optionValue); - - private static native String getTsCharset(); - - private static native TSDBException setConfigImp(String config); - - public boolean connect(String host, int port, String dbName, String user, String password) throws SQLException { - if (this.taos != TSDBConstants.JNI_NULL_POINTER) { - closeConnection(); - this.taos = TSDBConstants.JNI_NULL_POINTER; - } - - this.taos = this.connectImp(host, port, dbName, user, password); - if (this.taos == TSDBConstants.JNI_NULL_POINTER) { - String errMsg = this.getErrMsg(0); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL, errMsg); - } - // invoke connectImp only here - taosInfo.conn_open_increment(); - return true; - } - - private native long connectImp(String host, int port, String dbName, String user, String password); - - /** - * Execute DML/DDL operation - */ - public long executeQuery(String sql) throws SQLException { - long pSql = 0L; - try { - pSql = this.executeQueryImp(sql.getBytes(TaosGlobalConfig.getCharset()), this.taos); - taosInfo.stmt_count_increment(); - } catch (UnsupportedEncodingException e) { - this.freeResultSetImp(this.taos, pSql); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_ENCODING); - } - if (pSql == TSDBConstants.JNI_CONNECTION_NULL) { - this.freeResultSetImp(this.taos, pSql); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); - } - if (pSql == TSDBConstants.JNI_SQL_NULL) { - this.freeResultSetImp(this.taos, pSql); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_SQL_NULL); - } - if (pSql == TSDBConstants.JNI_OUT_OF_MEMORY) { - this.freeResultSetImp(this.taos, pSql); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_OUT_OF_MEMORY); - } - - int code = this.getErrCode(pSql); - if (code != TSDBConstants.JNI_SUCCESS) { - affectedRows = -1; - String msg = this.getErrMsg(pSql); - this.freeResultSetImp(this.taos, pSql); - throw TSDBError.createSQLException(code, msg); - } - - // Try retrieving result set for the executed SQL using the current connection pointer. - pSql = this.getResultSetImp(this.taos, pSql); - // if pSql == 0L that means resultset is closed - isResultsetClosed = (pSql == TSDBConstants.JNI_NULL_POINTER); - - return pSql; - } - - private native long executeQueryImp(byte[] sqlBytes, long connection); - - /** - * Get recent error code by connection - */ - public int getErrCode(long pSql) { - return this.getErrCodeImp(this.taos, pSql); - } - - private native int getErrCodeImp(long connection, long pSql); - - /** - * Get recent error message by connection - */ - public String getErrMsg(long pSql) { - return this.getErrMsgImp(pSql); - } - - private native String getErrMsgImp(long pSql); - - private native long getResultSetImp(long connection, long pSql); - - public boolean isUpdateQuery(long pSql) { - return isUpdateQueryImp(this.taos, pSql) == 1; - } - - private native long isUpdateQueryImp(long connection, long pSql); - - public boolean isClosed() { - return this.taos == TSDBConstants.JNI_NULL_POINTER; - } - - public boolean isResultsetClosed() { - return this.isResultsetClosed; - } - - /** - * Free result set operation from C to release result set pointer by JNI - */ - public int freeResultSet(long pSql) { - int res = this.freeResultSetImp(this.taos, pSql); - isResultsetClosed = true; - return res; - } - - private native int freeResultSetImp(long connection, long result); - - /** - * Get affected rows count - */ - public int getAffectedRows(long pSql) { - int affectedRows = this.affectedRows; - if (affectedRows < 0) { - affectedRows = this.getAffectedRowsImp(this.taos, pSql); - } - return affectedRows; - } - - private native int getAffectedRowsImp(long connection, long pSql); - - /** - * Get schema metadata - */ - public int getSchemaMetaData(long resultSet, List columnMetaData) { - int ret = this.getSchemaMetaDataImp(this.taos, resultSet, columnMetaData); - columnMetaData.forEach(column -> column.setColIndex(column.getColIndex() + 1)); - return ret; - } - - private native int getSchemaMetaDataImp(long connection, long resultSet, List columnMetaData); - - /** - * Get one row data - */ - public int fetchRow(long resultSet, TSDBResultSetRowData rowData) { - return this.fetchRowImp(this.taos, resultSet, rowData); - } - - private native int fetchRowImp(long connection, long resultSet, TSDBResultSetRowData rowData); - - public int fetchBlock(long resultSet, TSDBResultSetBlockData blockData) { - return this.fetchBlockImp(this.taos, resultSet, blockData); - } - - private native int fetchBlockImp(long connection, long resultSet, TSDBResultSetBlockData blockData); - - /** - * Get Result Time Precision. - * - * @return 0: ms, 1: us, 2: ns - */ - public int getResultTimePrecision(long sqlObj) { - return this.getResultTimePrecisionImp(this.taos, sqlObj); - } - - private native int getResultTimePrecisionImp(long connection, long result); - - /** - * Execute close operation from C to release connection pointer by JNI - */ - public void closeConnection() throws SQLException { - int code = this.closeConnectionImp(this.taos); - - if (code < 0) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); - } else if (code == 0) { - this.taos = TSDBConstants.JNI_NULL_POINTER; - } else { - throw new SQLException("Undefined error code returned by TDengine when closing a connection"); - } - - // invoke closeConnectionImpl only here - taosInfo.connect_close_increment(); - } - - private native int closeConnectionImp(long connection); - - /*****************************************************************************************/ - // NOTE: subscribe - - /** - * Create a subscription - */ - long subscribe(String topic, String sql, boolean restart) { - return subscribeImp(this.taos, restart, topic, sql, 0); - } - - private native long subscribeImp(long connection, boolean restart, String topic, String sql, int period); - - /** - * Consume a subscription - */ - long consume(long subscription) { - return this.consumeImp(subscription); - } - - private native long consumeImp(long subscription); - - /** - * Unsubscribe, close a subscription - */ - void unsubscribe(long subscription, boolean isKeep) { - unsubscribeImp(subscription, isKeep); - } - - private native void unsubscribeImp(long subscription, boolean isKeep); - - /******************************************************************************************************/ - // NOTE: parameter binding - public long prepareStmt(String sql) throws SQLException { - long stmt = prepareStmtImp(sql.getBytes(), this.taos); - - if (stmt == TSDBConstants.JNI_CONNECTION_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL, "connection already closed"); - } - if (stmt == TSDBConstants.JNI_SQL_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_SQL_NULL); - } - if (stmt == TSDBConstants.JNI_OUT_OF_MEMORY) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_OUT_OF_MEMORY); - } - if (stmt == TSDBConstants.JNI_TDENGINE_ERROR) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_TDENGINE_ERROR); - } - - return stmt; - } - - private native long prepareStmtImp(byte[] sql, long con); - - public void setBindTableName(long stmt, String tableName) throws SQLException { - int code = setBindTableNameImp(stmt, tableName, this.taos); - if (code != TSDBConstants.JNI_SUCCESS) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, - "failed to set table name, reason: " + stmtErrorMsgImp(stmt, this.taos)); - } - } - - private native int setBindTableNameImp(long stmt, String name, long conn); - - public void setBindTableNameAndTags(long stmt, String tableName, int numOfTags, ByteBuffer tags, - ByteBuffer typeList, ByteBuffer lengthList, ByteBuffer nullList) throws SQLException { - int code = setTableNameTagsImp(stmt, tableName, numOfTags, tags.array(), typeList.array(), lengthList.array(), nullList.array(), this.taos); - if (code != TSDBConstants.JNI_SUCCESS) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, - "failed to bind table name and corresponding tags, reason: " + stmtErrorMsgImp(stmt, this.taos)); - } - } - - private native int setTableNameTagsImp(long stmt, String name, int numOfTags, byte[] tags, byte[] typeList, byte[] lengthList, byte[] nullList, long conn); - - public void bindColumnDataArray(long stmt, ByteBuffer colDataList, ByteBuffer lengthList, ByteBuffer isNullList, int type, int bytes, int numOfRows, int columnIndex) throws SQLException { - int code = bindColDataImp(stmt, colDataList.array(), lengthList.array(), isNullList.array(), type, bytes, numOfRows, columnIndex, this.taos); - if (code != TSDBConstants.JNI_SUCCESS) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, - "failed to bind column data, reason: " + stmtErrorMsgImp(stmt, this.taos)); - } - } - - private native int bindColDataImp(long stmt, byte[] colDataList, byte[] lengthList, byte[] isNullList, int type, int bytes, int numOfRows, int columnIndex, long conn); - - public void executeBatch(long stmt) throws SQLException { - int code = executeBatchImp(stmt, this.taos); - if (code != TSDBConstants.JNI_SUCCESS) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, - "failed to execute batch bind, reason: " + stmtErrorMsgImp(stmt, this.taos)); - } - } - - public void addBatch(long stmt) throws SQLException { - int code = addBatchImp(stmt, this.taos); - if (code != TSDBConstants.JNI_SUCCESS) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, stmtErrorMsgImp(stmt, this.taos)); - } - } - - private native int addBatchImp(long stmt, long con); - - private native int executeBatchImp(long stmt, long con); - - public void closeBatch(long stmt) throws SQLException { - int code = closeStmt(stmt, this.taos); - if (code != TSDBConstants.JNI_SUCCESS) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "failed to close batch bind"); - } - } - - private native int closeStmt(long stmt, long con); - - private native String stmtErrorMsgImp(long stmt, long con); - - /*************************************************************************************************/ - // NOTE: schemaless-lines - public void insertLines(String[] lines, SchemalessProtocolType protocolType, SchemalessTimestampType timestampType) throws SQLException { - long pSql = schemalessInsertImp(lines, this.taos, protocolType.ordinal(), timestampType.ordinal()); - try { - if (pSql == TSDBConstants.JNI_CONNECTION_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); - } - if (pSql == TSDBConstants.JNI_OUT_OF_MEMORY) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_OUT_OF_MEMORY); - } - - int code = this.getErrCode(pSql); - if (code != TSDBConstants.JNI_SUCCESS) { - String msg = this.getErrMsg(pSql); - throw TSDBError.createSQLException(code, msg); - } - } finally { - this.freeResultSetImp(this.taos, pSql); - } - } - - private native long schemalessInsertImp(String[] lines, long conn, int type, int precision); -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBParameterMetaData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBParameterMetaData.java deleted file mode 100644 index 9ee23e3a26..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBParameterMetaData.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.taosdata.jdbc; - -public class TSDBParameterMetaData extends AbstractParameterMetaData { - - public TSDBParameterMetaData(Object[] parameters) { - super(parameters); - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBPreparedStatement.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBPreparedStatement.java deleted file mode 100644 index 7e02d80ae8..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBPreparedStatement.java +++ /dev/null @@ -1,971 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2019 TAOS Data, Inc. - * - * This program is free software: you can use, redistribute, and/or modify - * it under the terms of the GNU Affero General Public License, version 3 - * or later ("AGPL"), as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - *****************************************************************************/ -package com.taosdata.jdbc; - -import com.taosdata.jdbc.utils.Utils; - -import java.io.InputStream; -import java.io.Reader; -import java.io.UnsupportedEncodingException; -import java.math.BigDecimal; -import java.net.URL; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.sql.*; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/* - * TDengine only supports a subset of the standard SQL, thus this implementation of the - * standard JDBC API contains more or less some adjustments customized for certain - * compatibility needs. - */ -public class TSDBPreparedStatement extends TSDBStatement implements PreparedStatement { - // for jdbc preparedStatement interface - private String rawSql; - private Object[] parameters; - // for parameter binding - private long nativeStmtHandle; - private String tableName; - private ArrayList tableTags; - private int tagValueLength; - private ArrayList colData; - - TSDBPreparedStatement(TSDBConnection connection, String sql) throws SQLException { - super(connection); - init(sql); - int parameterCnt = 0; - if (!sql.contains("?")) - return; - for (int i = 0; i < sql.length(); i++) { - if ('?' == sql.charAt(i)) { - parameterCnt++; - } - } - parameters = new Object[parameterCnt]; - // for parameter-binding -// TSDBJNIConnector connector = ((TSDBConnection) this.getConnection()).getConnector(); -// this.nativeStmtHandle = connector.prepareStmt(rawSql); - - if (parameterCnt > 1) { - // the table name is also a parameter, so ignore it. - this.colData = new ArrayList<>(); - this.tableTags = new ArrayList<>(); - } - } - - private void init(String sql) { - this.rawSql = sql; - preprocessSql(); - } - - /** - * Some of the SQLs sent by other popular frameworks or tools like Spark, contains syntax that cannot be parsed by - * the TDengine client. Thus, some simple parsers/filters are intentionally added in this JDBC implementation in - * order to process those supported SQLs. - */ - private void preprocessSql() { - /***For processing some of Spark SQLs*/ - // SELECT * FROM db.tb WHERE 1=0 - this.rawSql = this.rawSql.replaceAll("WHERE 1=0", "WHERE _c0=1"); - this.rawSql = this.rawSql.replaceAll("WHERE 1=2", "WHERE _c0=1"); - - // SELECT "ts","val" FROM db.tb - this.rawSql = this.rawSql.replaceAll("\"", ""); - - /***** For processing inner subqueries *****/ - Pattern pattern = Pattern.compile("FROM\\s+((\\(.+\\))\\s+SUB_QRY)", Pattern.CASE_INSENSITIVE); - Matcher matcher = pattern.matcher(rawSql); - String tableFullName = ""; - if (matcher.find() && matcher.groupCount() == 2) { - String subQry = matcher.group(2); - Pattern pattern1 = Pattern.compile("FROM\\s+(\\w+\\.\\w+)", Pattern.CASE_INSENSITIVE); - Matcher matcher1 = pattern1.matcher(subQry); - if (matcher1.find() && matcher1.groupCount() == 1) { - tableFullName = matcher1.group(1); - } - rawSql = rawSql.replace(matcher.group(1), tableFullName); - } - } - - @Override - public ResultSet executeQuery() throws SQLException { - final String sql = Utils.getNativeSql(this.rawSql, this.parameters); - return executeQuery(sql); - } - - @Override - public int executeUpdate() throws SQLException { - String sql = Utils.getNativeSql(this.rawSql, this.parameters); - return executeUpdate(sql); - } - - @Override - public void setNull(int parameterIndex, int sqlType) throws SQLException { - setObject(parameterIndex, null); - } - - @Override - public void setBoolean(int parameterIndex, boolean x) throws SQLException { - setObject(parameterIndex, x); - } - - @Override - public void setByte(int parameterIndex, byte x) throws SQLException { - setObject(parameterIndex, x); - } - - @Override - public void setShort(int parameterIndex, short x) throws SQLException { - setObject(parameterIndex, x); - } - - @Override - public void setInt(int parameterIndex, int x) throws SQLException { - setObject(parameterIndex, x); - } - - @Override - public void setLong(int parameterIndex, long x) throws SQLException { - setObject(parameterIndex, x); - } - - @Override - public void setFloat(int parameterIndex, float x) throws SQLException { - setObject(parameterIndex, x); - } - - @Override - public void setDouble(int parameterIndex, double x) throws SQLException { - setObject(parameterIndex, x); - } - - @Override - public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { - setObject(parameterIndex, x.doubleValue()); - } - - @Override - public void setString(int parameterIndex, String x) throws SQLException { - setObject(parameterIndex, x); - } - - @Override - public void setBytes(int parameterIndex, byte[] x) throws SQLException { - setObject(parameterIndex, x); - } - - @Override - public void setDate(int parameterIndex, Date x) throws SQLException { - setObject(parameterIndex, new Timestamp(x.getTime())); - } - - @Override - public void setTime(int parameterIndex, Time x) throws SQLException { - setObject(parameterIndex, new Timestamp(x.getTime())); - } - - @Override - public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { - setObject(parameterIndex, x); - } - - @Override - public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void clearParameters() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - parameters = new Object[parameters.length]; - } - - @Override - public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - setObject(parameterIndex, x); - } - - @Override - public void setObject(int parameterIndex, Object x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - if (parameterIndex < 1 && parameterIndex >= parameters.length) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - parameters[parameterIndex - 1] = x; - } - - @Override - public boolean execute() throws SQLException { - final String sql = Utils.getNativeSql(this.rawSql, this.parameters); - return execute(sql); - } - - @Override - public void addBatch() throws SQLException { - String sql = Utils.getNativeSql(this.rawSql, this.parameters); - addBatch(sql); - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setRef(int parameterIndex, Ref x) throws SQLException { - if (isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - } - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setBlob(int parameterIndex, Blob x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setClob(int parameterIndex, Clob x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setArray(int parameterIndex, Array x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public ResultSetMetaData getMetaData() throws SQLException { - if (this.getResultSet() == null) - return null; - return getResultSet().getMetaData(); - } - - @Override - public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setURL(int parameterIndex, URL x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public ParameterMetaData getParameterMetaData() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - return new TSDBParameterMetaData(parameters); - } - - @Override - public void setRowId(int parameterIndex, RowId x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setNString(int parameterIndex, String value) throws SQLException { - setString(parameterIndex, value); - } - - @Override - public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setNClob(int parameterIndex, NClob value) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setClob(int parameterIndex, Reader reader) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setNClob(int parameterIndex, Reader reader) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - /////////////////////////////////////////////////////////////////////// - // NOTE: the following APIs are not JDBC compatible - // parameter binding - private static class ColumnInfo { - @SuppressWarnings("rawtypes") - private ArrayList data; - private int type; - private int bytes; - private boolean typeIsSet; - - public ColumnInfo() { - this.typeIsSet = false; - } - - public void setType(int type) throws SQLException { - if (this.isTypeSet()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "column data type has been set"); - } - - this.typeIsSet = true; - this.type = type; - } - - public boolean isTypeSet() { - return this.typeIsSet; - } - } - - private static class TableTagInfo { - private boolean isNull; - private final Object value; - private final int type; - - public TableTagInfo(Object value, int type) { - this.value = value; - this.type = type; - } - - public static TableTagInfo createNullTag(int type) { - TableTagInfo info = new TableTagInfo(null, type); - info.isNull = true; - return info; - } - } - - public void setTableName(String name) throws SQLException { - - if (this.nativeStmtHandle == 0) { - TSDBJNIConnector connector = ((TSDBConnection) this.getConnection()).getConnector(); - this.nativeStmtHandle = connector.prepareStmt(rawSql); - } - - if (this.tableName != null) { - this.columnDataAddBatch(); - this.columnDataClearBatchInternal(); - } - this.tableName = name; - } - - private void ensureTagCapacity(int index) { - if (this.tableTags.size() < index + 1) { - int delta = index + 1 - this.tableTags.size(); - this.tableTags.addAll(Collections.nCopies(delta, null)); - } - } - - public void setTagNull(int index, int type) { - ensureTagCapacity(index); - this.tableTags.set(index, TableTagInfo.createNullTag(type)); - } - - public void setTagBoolean(int index, boolean value) { - ensureTagCapacity(index); - this.tableTags.set(index, new TableTagInfo(value, TSDBConstants.TSDB_DATA_TYPE_BOOL)); - this.tagValueLength += Byte.BYTES; - } - - public void setTagInt(int index, int value) { - ensureTagCapacity(index); - this.tableTags.set(index, new TableTagInfo(value, TSDBConstants.TSDB_DATA_TYPE_INT)); - this.tagValueLength += Integer.BYTES; - } - - public void setTagByte(int index, byte value) { - ensureTagCapacity(index); - this.tableTags.set(index, new TableTagInfo(value, TSDBConstants.TSDB_DATA_TYPE_TINYINT)); - this.tagValueLength += Byte.BYTES; - } - - public void setTagShort(int index, short value) { - ensureTagCapacity(index); - this.tableTags.set(index, new TableTagInfo(value, TSDBConstants.TSDB_DATA_TYPE_SMALLINT)); - this.tagValueLength += Short.BYTES; - } - - public void setTagLong(int index, long value) { - ensureTagCapacity(index); - this.tableTags.set(index, new TableTagInfo(value, TSDBConstants.TSDB_DATA_TYPE_BIGINT)); - this.tagValueLength += Long.BYTES; - } - - public void setTagTimestamp(int index, long value) { - ensureTagCapacity(index); - this.tableTags.set(index, new TableTagInfo(value, TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP)); - this.tagValueLength += Long.BYTES; - } - - public void setTagFloat(int index, float value) { - ensureTagCapacity(index); - this.tableTags.set(index, new TableTagInfo(value, TSDBConstants.TSDB_DATA_TYPE_FLOAT)); - this.tagValueLength += Float.BYTES; - } - - public void setTagDouble(int index, double value) { - ensureTagCapacity(index); - this.tableTags.set(index, new TableTagInfo(value, TSDBConstants.TSDB_DATA_TYPE_DOUBLE)); - this.tagValueLength += Double.BYTES; - } - - public void setTagString(int index, String value) { - ensureTagCapacity(index); - this.tableTags.set(index, new TableTagInfo(value, TSDBConstants.TSDB_DATA_TYPE_BINARY)); - this.tagValueLength += value.getBytes().length; - } - - public void setTagNString(int index, String value) { - ensureTagCapacity(index); - this.tableTags.set(index, new TableTagInfo(value, TSDBConstants.TSDB_DATA_TYPE_NCHAR)); - - String charset = TaosGlobalConfig.getCharset(); - try { - this.tagValueLength += value.getBytes(charset).length; - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - } - - public void setTagJson(int index, String value) { - ensureTagCapacity(index); - this.tableTags.set(index, new TableTagInfo(value, TSDBConstants.TSDB_DATA_TYPE_JSON)); - - String charset = TaosGlobalConfig.getCharset(); - try { - this.tagValueLength += value.getBytes(charset).length; - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - } - - public void setValueImpl(int columnIndex, ArrayList list, int type, int bytes) throws SQLException { - if (this.colData.size() == 0) { - this.colData.addAll(Collections.nCopies(this.parameters.length - 1 - this.tableTags.size(), null)); - } - - ColumnInfo col = this.colData.get(columnIndex); - if (col == null) { - ColumnInfo p = new ColumnInfo(); - p.setType(type); - p.bytes = bytes; - p.data = (ArrayList) list.clone(); - this.colData.set(columnIndex, p); - } else { - if (col.type != type) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "column data type mismatch"); - } - col.data.addAll(list); - } - } - - public void setInt(int columnIndex, ArrayList list) throws SQLException { - setValueImpl(columnIndex, list, TSDBConstants.TSDB_DATA_TYPE_INT, Integer.BYTES); - } - - public void setFloat(int columnIndex, ArrayList list) throws SQLException { - setValueImpl(columnIndex, list, TSDBConstants.TSDB_DATA_TYPE_FLOAT, Float.BYTES); - } - - public void setTimestamp(int columnIndex, ArrayList list) throws SQLException { - setValueImpl(columnIndex, list, TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP, Long.BYTES); - } - - public void setLong(int columnIndex, ArrayList list) throws SQLException { - setValueImpl(columnIndex, list, TSDBConstants.TSDB_DATA_TYPE_BIGINT, Long.BYTES); - } - - public void setDouble(int columnIndex, ArrayList list) throws SQLException { - setValueImpl(columnIndex, list, TSDBConstants.TSDB_DATA_TYPE_DOUBLE, Double.BYTES); - } - - public void setBoolean(int columnIndex, ArrayList list) throws SQLException { - setValueImpl(columnIndex, list, TSDBConstants.TSDB_DATA_TYPE_BOOL, Byte.BYTES); - } - - public void setByte(int columnIndex, ArrayList list) throws SQLException { - setValueImpl(columnIndex, list, TSDBConstants.TSDB_DATA_TYPE_TINYINT, Byte.BYTES); - } - - public void setShort(int columnIndex, ArrayList list) throws SQLException { - setValueImpl(columnIndex, list, TSDBConstants.TSDB_DATA_TYPE_SMALLINT, Short.BYTES); - } - - public void setString(int columnIndex, ArrayList list, int size) throws SQLException { - setValueImpl(columnIndex, list, TSDBConstants.TSDB_DATA_TYPE_BINARY, size); - } - - // note: expand the required space for each NChar character - public void setNString(int columnIndex, ArrayList list, int size) throws SQLException { - setValueImpl(columnIndex, list, TSDBConstants.TSDB_DATA_TYPE_NCHAR, size * Integer.BYTES); - } - - public void columnDataAddBatch() throws SQLException { - // pass the data block to native code - if (rawSql == null) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "sql statement not set yet"); - } - // table name is not set yet, abort - if (this.tableName == null) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "table name not set yet"); - } - - int numOfCols = this.colData.size(); - if (numOfCols == 0) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "column data not bind"); - } - if (nativeStmtHandle == 0) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "stmt is null"); - } - - TSDBJNIConnector connector = ((TSDBConnection) this.getConnection()).getConnector(); - if (this.tableTags == null) { - connector.setBindTableName(this.nativeStmtHandle, this.tableName); - } else { - int tagSize = this.tableTags.size(); - ByteBuffer tagDataList = ByteBuffer.allocate(this.tagValueLength); - tagDataList.order(ByteOrder.LITTLE_ENDIAN); - - ByteBuffer typeList = ByteBuffer.allocate(tagSize); - typeList.order(ByteOrder.LITTLE_ENDIAN); - - ByteBuffer lengthList = ByteBuffer.allocate(tagSize * Long.BYTES); - lengthList.order(ByteOrder.LITTLE_ENDIAN); - - ByteBuffer isNullList = ByteBuffer.allocate(tagSize * Integer.BYTES); - isNullList.order(ByteOrder.LITTLE_ENDIAN); - - for (TableTagInfo tag : this.tableTags) { - if (tag.isNull) { - typeList.put((byte) tag.type); - isNullList.putInt(1); - lengthList.putLong(0); - continue; - } - - switch (tag.type) { - case TSDBConstants.TSDB_DATA_TYPE_INT: { - Integer val = (Integer) tag.value; - tagDataList.putInt(val); - lengthList.putLong(Integer.BYTES); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: { - Byte val = (Byte) tag.value; - tagDataList.put(val); - lengthList.putLong(Byte.BYTES); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_BOOL: { - Boolean val = (Boolean) tag.value; - tagDataList.put((byte) (val ? 1 : 0)); - lengthList.putLong(Byte.BYTES); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: { - Short val = (Short) tag.value; - tagDataList.putShort(val); - lengthList.putLong(Short.BYTES); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: { - Long val = (Long) tag.value; - tagDataList.putLong(val == null ? 0 : val); - lengthList.putLong(Long.BYTES); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: { - Float val = (Float) tag.value; - tagDataList.putFloat(val == null ? 0 : val); - lengthList.putLong(Float.BYTES); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: { - Double val = (Double) tag.value; - tagDataList.putDouble(val == null ? 0 : val); - lengthList.putLong(Double.BYTES); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: - case TSDBConstants.TSDB_DATA_TYPE_JSON: - case TSDBConstants.TSDB_DATA_TYPE_BINARY: { - String charset = TaosGlobalConfig.getCharset(); - String val = (String) tag.value; - byte[] b; - try { - if (tag.type == TSDBConstants.TSDB_DATA_TYPE_BINARY) { - b = val.getBytes(); - } else { - b = val.getBytes(charset); - } - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - tagDataList.put(b); - lengthList.putLong(b.length); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_UTINYINT: - case TSDBConstants.TSDB_DATA_TYPE_USMALLINT: - case TSDBConstants.TSDB_DATA_TYPE_UINT: - case TSDBConstants.TSDB_DATA_TYPE_UBIGINT: { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "not support data types"); - } - } - typeList.put((byte) tag.type); - isNullList.putInt(tag.isNull ? 1 : 0); - } - - connector.setBindTableNameAndTags(this.nativeStmtHandle, this.tableName, this.tableTags.size(), - tagDataList, typeList, lengthList, isNullList); - } - - ColumnInfo colInfo = this.colData.get(0); - if (colInfo == null) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "column data not bind"); - } - - int rows = colInfo.data.size(); - for (int i = 0; i < numOfCols; ++i) { - ColumnInfo col1 = this.colData.get(i); - if (col1 == null || !col1.isTypeSet()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "column data not bind"); - } - if (rows != col1.data.size()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "the rows in column data not identical"); - } - - ByteBuffer colDataList = ByteBuffer.allocate(rows * col1.bytes); - colDataList.order(ByteOrder.LITTLE_ENDIAN); - - ByteBuffer lengthList = ByteBuffer.allocate(rows * Integer.BYTES); - lengthList.order(ByteOrder.LITTLE_ENDIAN); - - ByteBuffer isNullList = ByteBuffer.allocate(rows * Byte.BYTES); - isNullList.order(ByteOrder.LITTLE_ENDIAN); - - switch (col1.type) { - case TSDBConstants.TSDB_DATA_TYPE_INT: { - for (int j = 0; j < rows; ++j) { - Integer val = (Integer) col1.data.get(j); - colDataList.putInt(val == null ? Integer.MIN_VALUE : val); - isNullList.put((byte) (val == null ? 1 : 0)); - } - break; - } - - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: { - for (int j = 0; j < rows; ++j) { - Byte val = (Byte) col1.data.get(j); - colDataList.put(val == null ? 0 : val); - isNullList.put((byte) (val == null ? 1 : 0)); - } - break; - } - - case TSDBConstants.TSDB_DATA_TYPE_BOOL: { - for (int j = 0; j < rows; ++j) { - Boolean val = (Boolean) col1.data.get(j); - if (val == null) { - colDataList.put((byte) 0); - } else { - colDataList.put((byte) (val ? 1 : 0)); - } - - isNullList.put((byte) (val == null ? 1 : 0)); - } - break; - } - - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: { - for (int j = 0; j < rows; ++j) { - Short val = (Short) col1.data.get(j); - colDataList.putShort(val == null ? 0 : val); - isNullList.put((byte) (val == null ? 1 : 0)); - } - break; - } - - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: { - for (int j = 0; j < rows; ++j) { - Long val = (Long) col1.data.get(j); - colDataList.putLong(val == null ? 0 : val); - isNullList.put((byte) (val == null ? 1 : 0)); - } - break; - } - - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: { - for (int j = 0; j < rows; ++j) { - Float val = (Float) col1.data.get(j); - colDataList.putFloat(val == null ? 0 : val); - isNullList.put((byte) (val == null ? 1 : 0)); - } - break; - } - - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: { - for (int j = 0; j < rows; ++j) { - Double val = (Double) col1.data.get(j); - colDataList.putDouble(val == null ? 0 : val); - isNullList.put((byte) (val == null ? 1 : 0)); - } - break; - } - - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: - case TSDBConstants.TSDB_DATA_TYPE_BINARY: { - String charset = TaosGlobalConfig.getCharset(); - for (int j = 0; j < rows; ++j) { - String val = (String) col1.data.get(j); - - colDataList.position(j * col1.bytes); // seek to the correct position - if (val != null) { - byte[] b = null; - try { - if (col1.type == TSDBConstants.TSDB_DATA_TYPE_BINARY) { - b = val.getBytes(); - } else { - b = val.getBytes(charset); - } - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - - if (val.length() > col1.bytes) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "string data too long"); - } - - colDataList.put(b); - lengthList.putInt(b.length); - isNullList.put((byte) 0); - } else { - lengthList.putInt(0); - isNullList.put((byte) 1); - } - } - break; - } - case TSDBConstants.TSDB_DATA_TYPE_UTINYINT: - case TSDBConstants.TSDB_DATA_TYPE_USMALLINT: - case TSDBConstants.TSDB_DATA_TYPE_UINT: - case TSDBConstants.TSDB_DATA_TYPE_UBIGINT: { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "not support data types"); - } - } - - connector.bindColumnDataArray(this.nativeStmtHandle, colDataList, lengthList, isNullList, col1.type, col1.bytes, rows, i); - } - connector.addBatch(this.nativeStmtHandle); - this.columnDataClearBatchInternal(); - } - - public void columnDataExecuteBatch() throws SQLException { - TSDBJNIConnector connector = ((TSDBConnection) this.getConnection()).getConnector(); - connector.executeBatch(this.nativeStmtHandle); - this.columnDataClearBatchInternal(); - } - - @Deprecated - public void columnDataClearBatch() { - columnDataClearBatchInternal(); - } - - private void columnDataClearBatchInternal() { - this.tableName = null; - if (this.tableTags != null) - this.tableTags.clear(); - tagValueLength = 0; - if (this.colData != null) - this.colData.clear(); - } - - public void columnDataCloseBatch() throws SQLException { - TSDBJNIConnector connector = ((TSDBConnection) this.getConnection()).getConnector(); - connector.closeBatch(this.nativeStmtHandle); - - this.nativeStmtHandle = 0L; - this.tableName = null; - } - - @Override - public void close() throws SQLException { - if (this.nativeStmtHandle != 0L) { - this.columnDataClearBatchInternal(); - this.columnDataCloseBatch(); - } - super.close(); - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSet.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSet.java deleted file mode 100644 index e1e15d0332..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSet.java +++ /dev/null @@ -1,490 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2019 TAOS Data, Inc. - * - * This program is free software: you can use, redistribute, and/or modify - * it under the terms of the GNU Affero General Public License, version 3 - * or later ("AGPL"), as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - *****************************************************************************/ -package com.taosdata.jdbc; - -import com.google.common.primitives.Ints; -import com.google.common.primitives.Longs; -import com.google.common.primitives.Shorts; - -import java.math.BigDecimal; -import java.sql.*; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; - -public class TSDBResultSet extends AbstractResultSet implements ResultSet { - private final TSDBJNIConnector jniConnector; - private final TSDBStatement statement; - private final long resultSetPointer; - private List columnMetaDataList = new ArrayList<>(); - private final TSDBResultSetRowData rowData; - private final TSDBResultSetBlockData blockData; - - private boolean batchFetch; - private boolean lastWasNull; - private boolean isClosed; - - public void setBatchFetch(boolean batchFetch) { - this.batchFetch = batchFetch; - } - - public Boolean getBatchFetch() { - return this.batchFetch; - } - - public void setColumnMetaDataList(List columnMetaDataList) { - this.columnMetaDataList = columnMetaDataList; - } - - public TSDBResultSetRowData getRowData() { - return rowData; - } - - public TSDBResultSet(TSDBStatement statement, TSDBJNIConnector connector, long resultSetPointer, int timestampPrecision) throws SQLException { - this.statement = statement; - this.jniConnector = connector; - this.resultSetPointer = resultSetPointer; - - int code = this.jniConnector.getSchemaMetaData(this.resultSetPointer, this.columnMetaDataList); - if (code == TSDBConstants.JNI_CONNECTION_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); - } - if (code == TSDBConstants.JNI_RESULT_SET_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_RESULT_SET_NULL); - } - if (code == TSDBConstants.JNI_NUM_OF_FIELDS_0) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_NUM_OF_FIELDS_0); - } - this.rowData = new TSDBResultSetRowData(this.columnMetaDataList.size()); - this.blockData = new TSDBResultSetBlockData(this.columnMetaDataList, this.columnMetaDataList.size(), timestampPrecision); - this.timestampPrecision = timestampPrecision; - } - - public boolean next() throws SQLException { - if (this.getBatchFetch()) { - if (this.blockData.forward()) - return true; - - int code = this.jniConnector.fetchBlock(this.resultSetPointer, this.blockData); - this.blockData.reset(); - - if (code == TSDBConstants.JNI_CONNECTION_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); - } else if (code == TSDBConstants.JNI_RESULT_SET_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_RESULT_SET_NULL); - } else if (code == TSDBConstants.JNI_NUM_OF_FIELDS_0) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_NUM_OF_FIELDS_0); - } else return code != TSDBConstants.JNI_FETCH_END; - } else { - if (rowData != null) { - this.rowData.clear(); - } - int code = this.jniConnector.fetchRow(this.resultSetPointer, this.rowData); - if (code == TSDBConstants.JNI_CONNECTION_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); - } else if (code == TSDBConstants.JNI_RESULT_SET_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_RESULT_SET_NULL); - } else if (code == TSDBConstants.JNI_NUM_OF_FIELDS_0) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_NUM_OF_FIELDS_0); - } else if (code == TSDBConstants.JNI_FETCH_END) { - return false; - } else { - return true; - } - } - } - - public void close() throws SQLException { - if (isClosed) - return; - if (this.statement == null) - return; - if (this.jniConnector != null) { - int code = this.jniConnector.freeResultSet(this.resultSetPointer); - if (code == TSDBConstants.JNI_CONNECTION_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); - } else if (code == TSDBConstants.JNI_RESULT_SET_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_RESULT_SET_NULL); - } - } - isClosed = true; - } - - public boolean wasNull() throws SQLException { - return this.lastWasNull; - } - - public String getString(int columnIndex) throws SQLException { - checkAvailability(columnIndex, this.columnMetaDataList.size()); - - String res = null; - if (this.getBatchFetch()) - return this.blockData.getString(columnIndex - 1); - - this.lastWasNull = this.rowData.wasNull(columnIndex); - if (!lastWasNull) { - int nativeType = this.columnMetaDataList.get(columnIndex - 1).getColType(); - res = this.rowData.getString(columnIndex, nativeType); - } - return res; - } - - public boolean getBoolean(int columnIndex) throws SQLException { - checkAvailability(columnIndex, this.columnMetaDataList.size()); - - boolean res = false; - if (this.getBatchFetch()) - return this.blockData.getBoolean(columnIndex - 1); - - this.lastWasNull = this.rowData.wasNull(columnIndex); - if (!lastWasNull) { - int nativeType = this.columnMetaDataList.get(columnIndex - 1).getColType(); - res = this.rowData.getBoolean(columnIndex, nativeType); - } - return res; - } - - public byte getByte(int columnIndex) throws SQLException { - checkAvailability(columnIndex, this.columnMetaDataList.size()); - - byte res = 0; - if (this.getBatchFetch()) - return (byte) this.blockData.getInt(columnIndex - 1); - - this.lastWasNull = this.rowData.wasNull(columnIndex); - if (!lastWasNull) { - int nativeType = this.columnMetaDataList.get(columnIndex - 1).getColType(); - res = (byte) this.rowData.getInt(columnIndex, nativeType); - } - return res; - } - - public short getShort(int columnIndex) throws SQLException { - checkAvailability(columnIndex, this.columnMetaDataList.size()); - - short res = 0; - if (this.getBatchFetch()) - return (short) this.blockData.getInt(columnIndex - 1); - - this.lastWasNull = this.rowData.wasNull(columnIndex); - if (!lastWasNull) { - int nativeType = this.columnMetaDataList.get(columnIndex - 1).getColType(); - res = (short) this.rowData.getInt(columnIndex, nativeType); - } - return res; - } - - public int getInt(int columnIndex) throws SQLException { - checkAvailability(columnIndex, this.columnMetaDataList.size()); - - int res = 0; - if (this.getBatchFetch()) - return this.blockData.getInt(columnIndex - 1); - - - this.lastWasNull = this.rowData.wasNull(columnIndex); - if (!lastWasNull) { - int nativeType = this.columnMetaDataList.get(columnIndex - 1).getColType(); - res = this.rowData.getInt(columnIndex, nativeType); - } - return res; - } - - public long getLong(int columnIndex) throws SQLException { - checkAvailability(columnIndex, this.columnMetaDataList.size()); - - long res = 0L; - if (this.getBatchFetch()) - return this.blockData.getLong(columnIndex - 1); - - this.lastWasNull = this.rowData.wasNull(columnIndex); - if (!lastWasNull) { - Object value = this.rowData.getObject(columnIndex); - if (value instanceof Timestamp) { - Timestamp ts = (Timestamp) value; - long epochSec = ts.getTime() / 1000; - long nanoAdjustment = ts.getNanos(); - switch (this.timestampPrecision) { - case 0: - default: // ms - return ts.getTime(); - case 1: // us - return epochSec * 1000_000L + nanoAdjustment / 1000L; - case 2: // ns - return epochSec * 1000_000_000L + nanoAdjustment; - } - } else { - int nativeType = this.columnMetaDataList.get(columnIndex - 1).getColType(); - res = this.rowData.getLong(columnIndex, nativeType); - } - } - return res; - } - - public float getFloat(int columnIndex) throws SQLException { - checkAvailability(columnIndex, this.columnMetaDataList.size()); - - float res = 0; - if (this.getBatchFetch()) - return (float) this.blockData.getDouble(columnIndex - 1); - - this.lastWasNull = this.rowData.wasNull(columnIndex); - if (!lastWasNull) { - int nativeType = this.columnMetaDataList.get(columnIndex - 1).getColType(); - res = this.rowData.getFloat(columnIndex, nativeType); - } - - return res; - } - - public double getDouble(int columnIndex) throws SQLException { - checkAvailability(columnIndex, this.columnMetaDataList.size()); - - double res = 0; - if (this.getBatchFetch()) - return this.blockData.getDouble(columnIndex - 1); - - this.lastWasNull = this.rowData.wasNull(columnIndex); - if (!lastWasNull) { - int nativeType = this.columnMetaDataList.get(columnIndex - 1).getColType(); - res = this.rowData.getDouble(columnIndex, nativeType); - } - return res; - } - - public byte[] getBytes(int columnIndex) throws SQLException { - checkAvailability(columnIndex, this.columnMetaDataList.size()); - - if (this.getBatchFetch()) - return this.blockData.getBytes(columnIndex -1); - - Object value = this.rowData.getObject(columnIndex); - this.lastWasNull = value == null; - if (value == null) - return null; - - int nativeType = this.columnMetaDataList.get(columnIndex - 1).getColType(); - switch (nativeType) { - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - return Longs.toByteArray((long) value); - case TSDBConstants.TSDB_DATA_TYPE_INT: - return Ints.toByteArray((int) value); - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: - return Shorts.toByteArray((short) value); - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: - return new byte[]{(byte) value}; - case TSDBConstants.TSDB_DATA_TYPE_BINARY: - return (byte[]) value; - case TSDBConstants.TSDB_DATA_TYPE_BOOL: - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: - default: - return value.toString().getBytes(); - } - } - - public Timestamp getTimestamp(int columnIndex) throws SQLException { - checkAvailability(columnIndex, this.columnMetaDataList.size()); - - Timestamp res = null; - if (this.getBatchFetch()) - return this.blockData.getTimestamp(columnIndex - 1); - - this.lastWasNull = this.rowData.wasNull(columnIndex); - if (!lastWasNull) { - int nativeType = this.columnMetaDataList.get(columnIndex - 1).getColType(); - res = this.rowData.getTimestamp(columnIndex, nativeType); - } - return res; - } - - public ResultSetMetaData getMetaData() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - return new TSDBResultSetMetaData(this.columnMetaDataList); - } - - @Override - public Object getObject(int columnIndex) throws SQLException { - checkAvailability(columnIndex, this.columnMetaDataList.size()); - - Object res = null; - if (this.getBatchFetch()) - return this.blockData.get(columnIndex - 1); - - this.lastWasNull = this.rowData.wasNull(columnIndex); - if (!lastWasNull) { - res = this.rowData.getObject(columnIndex); - } - return res; - } - - public int findColumn(String columnLabel) throws SQLException { - for (ColumnMetaData colMetaData : this.columnMetaDataList) { - if (colMetaData.getColName() != null && colMetaData.getColName().equalsIgnoreCase(columnLabel)) { - return colMetaData.getColIndex(); - } - } - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); - } - - @Override - public BigDecimal getBigDecimal(int columnIndex) throws SQLException { - if (this.getBatchFetch()) - return BigDecimal.valueOf(this.blockData.getDouble(columnIndex - 1)); - - this.lastWasNull = this.rowData.wasNull(columnIndex); - if (lastWasNull) - return null; - - BigDecimal res; - int nativeType = this.columnMetaDataList.get(columnIndex - 1).getColType(); - switch (nativeType) { - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: - case TSDBConstants.TSDB_DATA_TYPE_INT: - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - res = new BigDecimal(Long.parseLong(this.rowData.getObject(columnIndex).toString())); - break; - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: - res = BigDecimal.valueOf(Double.parseDouble(this.rowData.getObject(columnIndex).toString())); - break; - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: - return new BigDecimal(((Timestamp) this.rowData.getObject(columnIndex)).getTime()); - default: - res = new BigDecimal(this.rowData.getObject(columnIndex).toString()); - } - return res; - } - - @Override - public boolean isBeforeFirst() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean isAfterLast() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean isFirst() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean isLast() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void beforeFirst() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void afterLast() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean first() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean last() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public int getRow() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean absolute(int row) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean relative(int rows) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean previous() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - public Statement getStatement() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - return this.statement; - } - - @Override - public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { - //TODO:did not use the specified timezone in cal - return getTimestamp(columnIndex); - } - - public boolean isClosed() throws SQLException { - return isClosed; - } - - public String getNString(int columnIndex) throws SQLException { - return getString(columnIndex); - } - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetBlockData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetBlockData.java deleted file mode 100644 index 8dcd66ad47..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetBlockData.java +++ /dev/null @@ -1,552 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2019 TAOS Data, Inc. - * - * This program is free software: you can use, redistribute, and/or modify - * it under the terms of the GNU Affero General Public License, version 3 - * or later ("AGPL"), as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - *****************************************************************************/ -package com.taosdata.jdbc; - -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.DoubleBuffer; -import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.nio.LongBuffer; -import java.nio.ShortBuffer; -import java.sql.SQLDataException; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import com.google.common.primitives.Ints; -import com.google.common.primitives.Longs; -import com.google.common.primitives.Shorts; -import com.taosdata.jdbc.enums.TimestampPrecision; -import com.taosdata.jdbc.utils.NullType; - -public class TSDBResultSetBlockData { - private static final int BINARY_LENGTH_OFFSET = 2; - private int numOfRows = 0; - private int rowIndex = 0; - - private List columnMetaDataList; - private ArrayList colData; - - private int timestampPrecision; - - public TSDBResultSetBlockData(List colMeta, int numOfCols, int timestampPrecision) { - this.columnMetaDataList = colMeta; - this.colData = new ArrayList<>(numOfCols); - this.timestampPrecision = timestampPrecision; - } - - public TSDBResultSetBlockData() { - this.colData = new ArrayList<>(); - } - - public void clear() { - int size = this.colData.size(); - this.colData.clear(); - setNumOfCols(size); - } - - public int getNumOfRows() { - return this.numOfRows; - } - - public void setNumOfRows(int numOfRows) { - this.numOfRows = numOfRows; - } - - public int getNumOfCols() { - return this.colData.size(); - } - - public void setNumOfCols(int numOfCols) { - this.colData = new ArrayList<>(numOfCols); - this.colData.addAll(Collections.nCopies(numOfCols, null)); - } - - public boolean hasMore() { - return this.rowIndex < this.numOfRows; - } - - public boolean forward() { - if (this.rowIndex > this.numOfRows) { - return false; - } - - return ((++this.rowIndex) < this.numOfRows); - } - - public void reset() { - this.rowIndex = 0; - } - - public void setBoolean(int col, boolean value) { - colData.set(col, value); - } - - public void setByteArray(int col, int length, byte[] value) { - switch (this.columnMetaDataList.get(col).getColType()) { - case TSDBConstants.TSDB_DATA_TYPE_BOOL: { - ByteBuffer buf = ByteBuffer.wrap(value, 0, length); - buf.order(ByteOrder.LITTLE_ENDIAN).asCharBuffer(); - this.colData.set(col, buf); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_UTINYINT: - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: { - ByteBuffer buf = ByteBuffer.wrap(value, 0, length); - buf.order(ByteOrder.LITTLE_ENDIAN); - this.colData.set(col, buf); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_USMALLINT: - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: { - ByteBuffer buf = ByteBuffer.wrap(value, 0, length); - ShortBuffer sb = buf.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer(); - this.colData.set(col, sb); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_UINT: - case TSDBConstants.TSDB_DATA_TYPE_INT: { - ByteBuffer buf = ByteBuffer.wrap(value, 0, length); - IntBuffer ib = buf.order(ByteOrder.LITTLE_ENDIAN).asIntBuffer(); - this.colData.set(col, ib); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_UBIGINT: - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: { - ByteBuffer buf = ByteBuffer.wrap(value, 0, length); - LongBuffer lb = buf.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer(); - this.colData.set(col, lb); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: { - ByteBuffer buf = ByteBuffer.wrap(value, 0, length); - FloatBuffer fb = buf.order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer(); - this.colData.set(col, fb); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: { - ByteBuffer buf = ByteBuffer.wrap(value, 0, length); - DoubleBuffer db = buf.order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer(); - this.colData.set(col, db); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_BINARY: { - ByteBuffer buf = ByteBuffer.wrap(value, 0, length); - buf.order(ByteOrder.LITTLE_ENDIAN); - this.colData.set(col, buf); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { - ByteBuffer buf = ByteBuffer.wrap(value, 0, length); - LongBuffer lb = buf.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer(); - this.colData.set(col, lb); - break; - } - case TSDBConstants.TSDB_DATA_TYPE_JSON: - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: { - ByteBuffer buf = ByteBuffer.wrap(value, 0, length); - buf.order(ByteOrder.LITTLE_ENDIAN); - this.colData.set(col, buf); - break; - } - } - } - - - /** - * The original type may not be a string type, but will be converted to by - * calling this method - */ - public String getString(int col) throws SQLException { - Object obj = get(col); - if (obj == null) { -// return new NullType().toString(); - return null; - } - - if (obj instanceof String) - return (String) obj; - - if (obj instanceof byte[]) { - String charset = TaosGlobalConfig.getCharset(); - try { - return new String((byte[]) obj, charset); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - } - return obj.toString(); - } - - public byte[] getBytes(int col) throws SQLException { - - Object obj = get(col); - if (obj == null) { - return null; - } - if (obj instanceof byte[]) - return (byte[]) obj; - if (obj instanceof String) - return ((String) obj).getBytes(); - if (obj instanceof Long) - return Longs.toByteArray((long) obj); - if (obj instanceof Integer) - return Ints.toByteArray((int) obj); - if (obj instanceof Short) - return Shorts.toByteArray((short) obj); - if (obj instanceof Byte) - return new byte[]{(byte) obj}; - - return obj.toString().getBytes(); - } - - public int getInt(int col) { - Object obj = get(col); - if (obj == null) { - return 0; - } - - int type = this.columnMetaDataList.get(col).getColType(); - switch (type) { - case TSDBConstants.TSDB_DATA_TYPE_BOOL: - return (boolean) obj ? 1 : 0; - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: - return (byte) obj; - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: - return (short) obj; - case TSDBConstants.TSDB_DATA_TYPE_INT: { - return (int) obj; - } - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - return ((Long) obj).intValue(); - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { - return ((Long) ((Timestamp) obj).getTime()).intValue(); - } - - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: { - return ((Double) obj).intValue(); - } - - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: - case TSDBConstants.TSDB_DATA_TYPE_JSON: - case TSDBConstants.TSDB_DATA_TYPE_BINARY: { - return Integer.parseInt((String) obj); - } - } - - return 0; - } - - public boolean getBoolean(int col) throws SQLException { - Object obj = get(col); - if (obj == null) { - return Boolean.FALSE; - } - - int type = this.columnMetaDataList.get(col).getColType(); - switch (type) { - case TSDBConstants.TSDB_DATA_TYPE_BOOL: - return (boolean) obj; - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: - return ((byte) obj == 0) ? Boolean.FALSE : Boolean.TRUE; - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: - return ((short) obj == 0) ? Boolean.FALSE : Boolean.TRUE; - case TSDBConstants.TSDB_DATA_TYPE_INT: { - return ((int) obj == 0) ? Boolean.FALSE : Boolean.TRUE; - } - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - return (((long) obj) == 0L) ? Boolean.FALSE : Boolean.TRUE; - - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { - return ((Timestamp) obj).getTime() == 0L ? Boolean.FALSE : Boolean.TRUE; - } - - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: - return (((float) obj) == 0f) ? Boolean.FALSE : Boolean.TRUE; - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: { - return (((double) obj) == 0) ? Boolean.FALSE : Boolean.TRUE; - } - - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: - case TSDBConstants.TSDB_DATA_TYPE_JSON: - case TSDBConstants.TSDB_DATA_TYPE_BINARY: { - if ("TRUE".compareToIgnoreCase((String) obj) == 0) { - return Boolean.TRUE; - } else if ("FALSE".compareToIgnoreCase((String) obj) == 0) { - return Boolean.TRUE; - } else { - throw new SQLDataException(); - } - } - } - - return Boolean.FALSE; - } - - public long getLong(int col) throws SQLException { - Object obj = get(col); - if (obj == null) { - return 0; - } - - int type = this.columnMetaDataList.get(col).getColType(); - switch (type) { - case TSDBConstants.TSDB_DATA_TYPE_BOOL: - return (boolean) obj ? 1 : 0; - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: - return (byte) obj; - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: - return (short) obj; - case TSDBConstants.TSDB_DATA_TYPE_INT: { - return (int) obj; - } - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - return (long) obj; - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { - Timestamp ts = (Timestamp) obj; - switch (this.timestampPrecision) { - case TimestampPrecision.MS: - default: - return ts.getTime(); - case TimestampPrecision.US: - return ts.getTime() * 1000 + ts.getNanos() / 1000 % 1000; - case TimestampPrecision.NS: - return ts.getTime() * 1000_000 + ts.getNanos() % 1000_000; - } - } - - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: - return ((Float) obj).longValue(); - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: { - return ((Double) obj).longValue(); - } - - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: - case TSDBConstants.TSDB_DATA_TYPE_JSON: - case TSDBConstants.TSDB_DATA_TYPE_BINARY: { - return Long.parseLong((String) obj); - } - } - - return 0; - } - - public Timestamp getTimestamp(int col) throws SQLException { - Object obj = get(col); - if (obj == null) { - return null; - } - - int type = this.columnMetaDataList.get(col).getColType(); - if (type == TSDBConstants.TSDB_DATA_TYPE_BIGINT) - return parseTimestampColumnData((long) obj); - if (type == TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP) - return (Timestamp) obj; - - return new Timestamp(getLong(col)); - } - - public double getDouble(int col) { - Object obj = get(col); - if (obj == null) { - return 0; - } - - int type = this.columnMetaDataList.get(col).getColType(); - switch (type) { - case TSDBConstants.TSDB_DATA_TYPE_BOOL: - return (boolean) obj ? 1 : 0; - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: - return (byte) obj; - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: - return (short) obj; - case TSDBConstants.TSDB_DATA_TYPE_INT: { - return (int) obj; - } - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - return (long) obj; - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { - Timestamp ts = (Timestamp) obj; - switch (this.timestampPrecision) { - case TimestampPrecision.MS: - default: - return ts.getTime(); - case TimestampPrecision.US: - return ts.getTime() * 1000 + ts.getNanos() / 1000 % 1000; - case TimestampPrecision.NS: - return ts.getTime() * 1000_000 + ts.getNanos() % 1000_000; - } - } - - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: - return Double.parseDouble(String.valueOf(obj)); - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: { - return (double) obj; - } - - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: - case TSDBConstants.TSDB_DATA_TYPE_JSON: - case TSDBConstants.TSDB_DATA_TYPE_BINARY: { - return Double.parseDouble((String) obj); - } - } - - return 0; - } - - public Object get(int col) { - int fieldSize = this.columnMetaDataList.get(col).getColSize(); - - switch (this.columnMetaDataList.get(col).getColType()) { - case TSDBConstants.TSDB_DATA_TYPE_BOOL: { - ByteBuffer bb = (ByteBuffer) this.colData.get(col); - - byte val = bb.get(this.rowIndex); - if (NullType.isBooleanNull(val)) { - return null; - } - - return (val == 0x0) ? Boolean.FALSE : Boolean.TRUE; - } - - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: { - ByteBuffer bb = (ByteBuffer) this.colData.get(col); - - byte val = bb.get(this.rowIndex); - if (NullType.isTinyIntNull(val)) { - return null; - } - - return val; - } - - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: { - ShortBuffer sb = (ShortBuffer) this.colData.get(col); - short val = sb.get(this.rowIndex); - if (NullType.isSmallIntNull(val)) { - return null; - } - - return val; - } - - case TSDBConstants.TSDB_DATA_TYPE_INT: { - IntBuffer ib = (IntBuffer) this.colData.get(col); - int val = ib.get(this.rowIndex); - if (NullType.isIntNull(val)) { - return null; - } - - return val; - } - - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { - LongBuffer lb = (LongBuffer) this.colData.get(col); - long val = lb.get(this.rowIndex); - if (NullType.isBigIntNull(val)) { - return null; - } - - return parseTimestampColumnData(val); - } - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: { - LongBuffer lb = (LongBuffer) this.colData.get(col); - long val = lb.get(this.rowIndex); - if (NullType.isBigIntNull(val)) { - return null; - } - - return val; - } - - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: { - FloatBuffer fb = (FloatBuffer) this.colData.get(col); - float val = fb.get(this.rowIndex); - if (NullType.isFloatNull(val)) { - return null; - } - - return val; - } - - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: { - DoubleBuffer lb = (DoubleBuffer) this.colData.get(col); - double val = lb.get(this.rowIndex); - if (NullType.isDoubleNull(val)) { - return null; - } - - return val; - } - - case TSDBConstants.TSDB_DATA_TYPE_BINARY: { - ByteBuffer bb = (ByteBuffer) this.colData.get(col); - bb.position((fieldSize + BINARY_LENGTH_OFFSET) * this.rowIndex); - int length = bb.getShort(); - byte[] dest = new byte[length]; - bb.get(dest, 0, length); - if (NullType.isBinaryNull(dest, length)) { - return null; - } - - return dest; - } - - case TSDBConstants.TSDB_DATA_TYPE_JSON: - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: { - ByteBuffer bb = (ByteBuffer) this.colData.get(col); -// bb.position((fieldSize * 4 + 2 + 1) * this.rowIndex); - bb.position(bb.capacity() / numOfRows * this.rowIndex); - int length = bb.getShort(); - byte[] dest = new byte[length]; - bb.get(dest, 0, length); - if (NullType.isNcharNull(dest, length)) { - return null; - } - try { - String charset = TaosGlobalConfig.getCharset(); - return new String(dest, charset); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - } - } - - return 0; - } - - private Timestamp parseTimestampColumnData(long value) { - if (TimestampPrecision.MS == timestampPrecision) - return new Timestamp(value); - - if (TimestampPrecision.US == timestampPrecision) { - long epochSec = value / 1000_000L; - long nanoAdjustment = value % 1000_000L * 1000L; - return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); - } - if (TimestampPrecision.NS == timestampPrecision) { - long epochSec = value / 1000_000_000L; - long nanoAdjustment = value % 1000_000_000L; - return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); - } - return null; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetMetaData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetMetaData.java deleted file mode 100644 index f93384fcc7..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetMetaData.java +++ /dev/null @@ -1,205 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2019 TAOS Data, Inc. - * - * This program is free software: you can use, redistribute, and/or modify - * it under the terms of the GNU Affero General Public License, version 3 - * or later ("AGPL"), as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - *****************************************************************************/ -package com.taosdata.jdbc; - -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.sql.Types; -import java.util.List; - -public class TSDBResultSetMetaData extends WrapperImpl implements ResultSetMetaData { - - List colMetaDataList; - - public TSDBResultSetMetaData(List metaDataList) { - this.colMetaDataList = metaDataList; - } - - public int getColumnCount() throws SQLException { - return colMetaDataList.size(); - } - - public boolean isAutoIncrement(int column) throws SQLException { - return false; - } - - public boolean isCaseSensitive(int column) throws SQLException { - return false; - } - - public boolean isSearchable(int column) throws SQLException { - return column == 1; - } - - public boolean isCurrency(int column) throws SQLException { - return false; - } - - public int isNullable(int column) throws SQLException { - if (column < 1 && column >= colMetaDataList.size()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - if (column == 1) { - return columnNoNulls; - } - return columnNullable; - } - - public boolean isSigned(int column) throws SQLException { - if (column < 1 && column >= colMetaDataList.size()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - ColumnMetaData meta = this.colMetaDataList.get(column - 1); - switch (meta.getColType()) { - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: - case TSDBConstants.TSDB_DATA_TYPE_INT: - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: - return true; - default: - return false; - } - } - - public int getColumnDisplaySize(int column) throws SQLException { - if (column < 1 && column >= colMetaDataList.size()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - return colMetaDataList.get(column - 1).getColSize(); - } - - public String getColumnLabel(int column) throws SQLException { - if (column < 1 && column >= colMetaDataList.size()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - return colMetaDataList.get(column - 1).getColName(); - } - - public String getColumnName(int column) throws SQLException { - if (column < 1 && column >= colMetaDataList.size()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - return colMetaDataList.get(column - 1).getColName(); - } - - public String getSchemaName(int column) throws SQLException { - if (column < 1 && column >= colMetaDataList.size()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - public int getPrecision(int column) throws SQLException { - if (column < 1 && column >= colMetaDataList.size()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - ColumnMetaData columnMetaData = this.colMetaDataList.get(column - 1); - switch (columnMetaData.getColType()) { - - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: - return 5; - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: - return 9; - case TSDBConstants.TSDB_DATA_TYPE_BINARY: - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: - return columnMetaData.getColSize(); - default: - return 0; - } - } - - public int getScale(int column) throws SQLException { - if (column < 1 && column >= colMetaDataList.size()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - ColumnMetaData meta = this.colMetaDataList.get(column - 1); - switch (meta.getColType()) { - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: - return 5; - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: - return 9; - default: - return 0; - } - } - - public String getTableName(int column) throws SQLException { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - public String getCatalogName(int column) throws SQLException { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - public int getColumnType(int column) throws SQLException { - ColumnMetaData meta = this.colMetaDataList.get(column - 1); - return TSDBConstants.taosType2JdbcType(meta.getColType()); - } - - public String getColumnTypeName(int column) throws SQLException { - ColumnMetaData meta = this.colMetaDataList.get(column - 1); - return TSDBConstants.taosType2JdbcTypeName(meta.getColType()); - } - - public boolean isReadOnly(int column) throws SQLException { - return true; - } - - public boolean isWritable(int column) throws SQLException { - return false; - } - - public boolean isDefinitelyWritable(int column) throws SQLException { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - public String getColumnClassName(int column) throws SQLException { - int columnType = getColumnType(column); - String columnClassName = ""; - switch (columnType) { - case Types.TIMESTAMP: - columnClassName = Timestamp.class.getName(); - break; - case Types.CHAR: - columnClassName = String.class.getName(); - break; - case Types.DOUBLE: - columnClassName = Double.class.getName(); - break; - case Types.FLOAT: - columnClassName = Float.class.getName(); - break; - case Types.BIGINT: - columnClassName = Long.class.getName(); - break; - case Types.INTEGER: - columnClassName = Integer.class.getName(); - break; - case Types.SMALLINT: - columnClassName = Short.class.getName(); - break; - case Types.TINYINT: - columnClassName = Byte.class.getName(); - break; - case Types.BIT: - columnClassName = Boolean.class.getName(); - break; - } - return columnClassName; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java deleted file mode 100644 index 258a9ad614..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java +++ /dev/null @@ -1,516 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2019 TAOS Data, Inc. - * - * This program is free software: you can use, redistribute, and/or modify - * it under the terms of the GNU Affero General Public License, version 3 - * or later ("AGPL"), as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - *****************************************************************************/ -package com.taosdata.jdbc; - -import java.io.UnsupportedEncodingException; -import java.math.BigDecimal; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Collections; - -public class TSDBResultSetRowData { - - private ArrayList data; - private final int colSize; - - public TSDBResultSetRowData(int colSize) { - this.colSize = colSize; - this.clear(); - } - - public void clear() { - if (this.data != null) { - this.data.clear(); - } - if (this.colSize == 0) { - return; - } - this.data = new ArrayList<>(colSize); - this.data.addAll(Collections.nCopies(this.colSize, null)); - } - - public boolean wasNull(int col) { - return data.get(col - 1) == null; - } - - /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use an index start from 1 in JDBC api - */ - public void setBooleanValue(int col, boolean value) { - setBoolean(col - 1, value); - } - - /** - * !!! this method is invoked by JNI method and the index start from 0 in C implementations - */ - public void setBoolean(int col, boolean value) { - data.set(col, value); - } - - public boolean getBoolean(int col, int nativeType) throws SQLException { - Object obj = data.get(col - 1); - - switch (nativeType) { - case TSDBConstants.TSDB_DATA_TYPE_BOOL: - return (Boolean) obj; - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: - return ((Byte) obj) == 1 ? Boolean.TRUE : Boolean.FALSE; - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: - return ((Short) obj) == 1 ? Boolean.TRUE : Boolean.FALSE; - case TSDBConstants.TSDB_DATA_TYPE_INT: - return ((Integer) obj) == 1 ? Boolean.TRUE : Boolean.FALSE; - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - return ((Long) obj) == 1L ? Boolean.TRUE : Boolean.FALSE; - case TSDBConstants.TSDB_DATA_TYPE_BINARY: - case TSDBConstants.TSDB_DATA_TYPE_JSON: - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: { - return obj.toString().contains("1"); - } - default: - return false; - } - } - - /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use an index start from 1 in JDBC api - */ - public void setByteValue(int colIndex, byte value) { - setByte(colIndex - 1, value); - } - - /** - * !!! this method is invoked by JNI method and the index start from 0 in C implementations - */ - public void setByte(int col, byte value) { - data.set(col, value); - } - - /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use an index start from 1 in JDBC api - */ - public void setShortValue(int colIndex, short value) { - setShort(colIndex - 1, value); - } - - /** - * !!! this method is invoked by JNI method and the index start from 0 in C implementations - */ - public void setShort(int col, short value) { - data.set(col, value); - } - - /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use an index start from 1 in JDBC api - */ - public void setIntValue(int colIndex, int value) { - setInt(colIndex - 1, value); - } - - /** - * !!! this method is invoked by JNI method and the index start from 0 in C implementations - */ - public void setInt(int col, int value) { - data.set(col, value); - } - - public int getInt(int col, int nativeType) throws SQLException { - Object obj = data.get(col - 1); - if (obj == null) - return 0; - - switch (nativeType) { - case TSDBConstants.TSDB_DATA_TYPE_BOOL: - return Boolean.TRUE.equals(obj) ? 1 : 0; - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: - return (Byte) obj; - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: - return (Short) obj; - case TSDBConstants.TSDB_DATA_TYPE_INT: - return (Integer) obj; - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: - return ((Long) obj).intValue(); - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: - case TSDBConstants.TSDB_DATA_TYPE_BINARY: - case TSDBConstants.TSDB_DATA_TYPE_JSON: - return Integer.parseInt((String) obj); - case TSDBConstants.TSDB_DATA_TYPE_UTINYINT: - return parseUnsignedTinyIntToInt(obj); - case TSDBConstants.TSDB_DATA_TYPE_USMALLINT: - return parseUnsignedSmallIntToInt(obj); - case TSDBConstants.TSDB_DATA_TYPE_UINT: - return parseUnsignedIntegerToInt(obj); - case TSDBConstants.TSDB_DATA_TYPE_UBIGINT: - return parseUnsignedBigIntToInt(obj); - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: - return ((Float) obj).intValue(); - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: - return ((Double) obj).intValue(); - default: - return 0; - } - } - - private byte parseUnsignedTinyIntToInt(Object obj) throws SQLException { - byte value = (byte) obj; - if (value < 0) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_NUMERIC_VALUE_OUT_OF_RANGE); - return value; - } - - private short parseUnsignedSmallIntToInt(Object obj) throws SQLException { - short value = (short) obj; - if (value < 0) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_NUMERIC_VALUE_OUT_OF_RANGE); - return value; - } - - private int parseUnsignedIntegerToInt(Object obj) throws SQLException { - int value = (int) obj; - if (value < 0) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_NUMERIC_VALUE_OUT_OF_RANGE); - return value; - } - - private int parseUnsignedBigIntToInt(Object obj) throws SQLException { - long value = (long) obj; - if (value < 0) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_NUMERIC_VALUE_OUT_OF_RANGE); - return (int) value; - } - - - /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use an index start from 1 in JDBC api - */ - public void setLongValue(int colIndex, long value) { - setLong(colIndex - 1, value); - } - - /** - * !!! this method is invoked by JNI method and the index start from 0 in C implementations - */ - public void setLong(int col, long value) { - data.set(col, value); - } - - public long getLong(int col, int nativeType) throws SQLException { - Object obj = data.get(col - 1); - if (obj == null) { - return 0; - } - - switch (nativeType) { - case TSDBConstants.TSDB_DATA_TYPE_BOOL: - return Boolean.TRUE.equals(obj) ? 1 : 0; - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: - return (Byte) obj; - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: - return (Short) obj; - case TSDBConstants.TSDB_DATA_TYPE_INT: - return (Integer) obj; - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: - return (Long) obj; - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: - case TSDBConstants.TSDB_DATA_TYPE_BINARY: - case TSDBConstants.TSDB_DATA_TYPE_JSON: - return Long.parseLong((String) obj); - case TSDBConstants.TSDB_DATA_TYPE_UTINYINT: { - byte value = (byte) obj; - if (value < 0) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_NUMERIC_VALUE_OUT_OF_RANGE); - return value; - } - case TSDBConstants.TSDB_DATA_TYPE_USMALLINT: { - short value = (short) obj; - if (value < 0) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_NUMERIC_VALUE_OUT_OF_RANGE); - return value; - } - case TSDBConstants.TSDB_DATA_TYPE_UINT: { - int value = (int) obj; - if (value < 0) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_NUMERIC_VALUE_OUT_OF_RANGE); - return value; - } - case TSDBConstants.TSDB_DATA_TYPE_UBIGINT: { - long value = (long) obj; - if (value < 0) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_NUMERIC_VALUE_OUT_OF_RANGE); - return value; - } - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: - return ((Float) obj).longValue(); - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: - return ((Double) obj).longValue(); - default: - return 0; - } - } - - /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use an index start from 1 in JDBC api - */ - public void setFloatValue(int colIndex, float value) { - setFloat(colIndex - 1, value); - } - - /** - * !!! this method is invoked by JNI method and the index start from 0 in C implementations - */ - public void setFloat(int col, float value) { - data.set(col, value); - } - - public float getFloat(int col, int nativeType) { - Object obj = data.get(col - 1); - if (obj == null) - return 0; - - switch (nativeType) { - case TSDBConstants.TSDB_DATA_TYPE_BOOL: - return Boolean.TRUE.equals(obj) ? 1 : 0; - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: - return (Float) obj; - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: - return ((Double) obj).floatValue(); - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: - return (Byte) obj; - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: - return (Short) obj; - case TSDBConstants.TSDB_DATA_TYPE_INT: - return (Integer) obj; - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - return (Long) obj; - default: - return 0; - } - } - - /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use an index start from 1 in JDBC api - */ - public void setDoubleValue(int colIndex, double value) { - setDouble(colIndex - 1, value); - } - - /** - * !!! this method is invoked by JNI method and the index start from 0 in C implementations - */ - public void setDouble(int col, double value) { - data.set(col, value); - } - - public double getDouble(int col, int nativeType) { - Object obj = data.get(col - 1); - if (obj == null) - return 0; - - switch (nativeType) { - case TSDBConstants.TSDB_DATA_TYPE_BOOL: - return Boolean.TRUE.equals(obj) ? 1 : 0; - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: - return (Float) obj; - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: - return (Double) obj; - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: - return (Byte) obj; - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: - return (Short) obj; - case TSDBConstants.TSDB_DATA_TYPE_INT: - return (Integer) obj; - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - return (Long) obj; - default: - return 0; - } - } - - /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use an index start from 1 in JDBC api - */ - public void setStringValue(int colIndex, String value) { - data.set(colIndex - 1, value); - } - - /** - * !!! this method is invoked by JNI method and the index start from 0 in C implementations - */ - public void setString(int col, String value) { - // TODO: - // !!!NOTE!!! - // this is very confusing problem which related to JNI-method implementation, - // the JNI method return a String(encoded in UTF) for BINARY value, which means the JNI method will invoke - // this setString(int, String) to handle BINARY value, we need to build a byte[] with default charsetEncoding - data.set(col, value == null ? null : value.getBytes()); - } - - /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use an index start from 1 in JDBC api - */ - public void setByteArrayValue(int colIndex, byte[] value) { - setByteArray(colIndex - 1, value); - } - - /** - * !!! this method is invoked by JNI method and the index start from 0 in C implementations - */ - public void setByteArray(int col, byte[] value) { - // TODO: - // !!!NOTE!!! - // this is very confusing problem which related to JNI-method implementation, - // the JNI method return a byte[] for NCHAR value, which means the JNI method will invoke - // this setByteArr(int, byte[]) to handle NCHAR value, we need to build a String with charsetEncoding by TaosGlobalConfig - try { - data.set(col, new String(value, TaosGlobalConfig.getCharset())); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - } - - public String getString(int col, int nativeType) { - Object obj = data.get(col - 1); - if (obj == null) - return null; - - switch (nativeType) { - case TSDBConstants.TSDB_DATA_TYPE_UTINYINT: { - byte value = new Byte(String.valueOf(obj)); - if (value >= 0) - return Byte.toString(value); - return Integer.toString(value & 0xff); - } - case TSDBConstants.TSDB_DATA_TYPE_USMALLINT: { - short value = new Short(String.valueOf(obj)); - if (value >= 0) - return Short.toString(value); - return Integer.toString(value & 0xffff); - } - case TSDBConstants.TSDB_DATA_TYPE_UINT: { - int value = new Integer(String.valueOf(obj)); - if (value >= 0) - return Integer.toString(value); - return Long.toString(value & 0xffffffffL); - } - case TSDBConstants.TSDB_DATA_TYPE_UBIGINT: { - long value = new Long(String.valueOf(obj)); - if (value >= 0) - return Long.toString(value); - long lowValue = value & 0x7fffffffffffffffL; - return BigDecimal.valueOf(lowValue).add(BigDecimal.valueOf(Long.MAX_VALUE)).add(BigDecimal.valueOf(1)).toString(); - } - case TSDBConstants.TSDB_DATA_TYPE_BINARY: - return new String((byte[]) obj); - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: - case TSDBConstants.TSDB_DATA_TYPE_JSON: - return (String) obj; - default: - return String.valueOf(obj); - } - } - - /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use an index start from 1 in JDBC api - */ - public void setTimestampValue(int colIndex, long value) { - setTimestamp(colIndex - 1, value, 0); - } - - /** - * !!! this method is invoked by JNI method and the index start from 0 in C implementations - * - * @param precision 0 : ms, 1 : us, 2 : ns - */ - public void setTimestamp(int col, long ts, int precision) { - long milliseconds; - int fracNanoseconds; - switch (precision) { - case 0: { - milliseconds = ts; - fracNanoseconds = (int) (ts * 1_000_000 % 1_000_000_000); - fracNanoseconds = fracNanoseconds < 0 ? 1_000_000_000 + fracNanoseconds : fracNanoseconds; - break; - } - case 1: { - milliseconds = ts / 1_000; - fracNanoseconds = (int) (ts * 1_000 % 1_000_000_000); - if (fracNanoseconds < 0) { - if (milliseconds == 0) { - milliseconds = -1; - } - fracNanoseconds += 1_000_000_000; - } - break; - } - case 2: { - milliseconds = ts / 1_000_000; - fracNanoseconds = (int) (ts % 1_000_000_000); - if (fracNanoseconds < 0) { - if (milliseconds == 0) { - milliseconds = -1; - } - fracNanoseconds += 1_000_000_000; - } - break; - } - default: { - throw new IllegalArgumentException("precision is not valid. precision: " + precision); - } - } - - Timestamp tsObj = new Timestamp(milliseconds); - tsObj.setNanos(fracNanoseconds); - data.set(col, tsObj); - } - - /** - * this implementation is used for TDengine old version - */ - public void setTimestamp(int col, long ts) { - //TODO: this implementation contains logical error - // when precision is us the (long ts) is 16 digital number - // when precision is ms, the (long ts) is 13 digital number - // we need a JNI function like this: - // public void setTimestamp(int col, long epochSecond, long nanoAdjustment) - if (ts < 1_0000_0000_0000_0L) { - data.set(col, new Timestamp(ts)); - } else { - long epochSec = ts / 1000_000L; - long nanoAdjustment = ts % 1000_000L * 1000L; - Timestamp timestamp = Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); - data.set(col, timestamp); - } - } - - public Timestamp getTimestamp(int col, int nativeType) { - Object obj = data.get(col - 1); - if (obj == null) - return null; - if (nativeType == TSDBConstants.TSDB_DATA_TYPE_BIGINT) { - return new Timestamp((Long) obj); - } - return (Timestamp) obj; - } - - public Object getObject(int col) { - return data.get(col - 1); - } - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetWrapper.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetWrapper.java deleted file mode 100644 index 0a9f017cbb..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetWrapper.java +++ /dev/null @@ -1,1172 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2019 TAOS Data, Inc. - * - * This program is free software: you can use, redistribute, and/or modify - * it under the terms of the GNU Affero General Public License, version 3 - * or later ("AGPL"), as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - *****************************************************************************/ -package com.taosdata.jdbc; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.net.URL; -import java.sql.*; -import java.util.Calendar; -import java.util.Map; - -/* - * TDengine only supports a subset of the standard SQL, thus this implementation of the - * standard JDBC API contains more or less some adjustments customized for certain - * compatibility needs. - */ -public class TSDBResultSetWrapper implements ResultSet { - - private ResultSet originalResultSet; - - public ResultSet getOriginalResultSet() { - return originalResultSet; - } - - public void setOriginalResultSet(ResultSet originalResultSet) { - this.originalResultSet = originalResultSet; - } - - @Override - public boolean next() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.next(); - } - - @Override - public void close() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - this.originalResultSet.close(); - } - - @Override - public boolean wasNull() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.wasNull(); - } - - @Override - public String getString(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getString(columnIndex); - } - - @Override - public boolean getBoolean(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getBoolean(columnIndex); - } - - @Override - public byte getByte(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getByte(columnIndex); - } - - @Override - public short getShort(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getShort(columnIndex); - } - - @Override - public int getInt(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getInt(columnIndex); - } - - @Override - public long getLong(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getLong(columnIndex); - } - - @Override - public float getFloat(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getFloat(columnIndex); - } - - @Override - public double getDouble(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getDouble(columnIndex); - } - - @Override - public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getBigDecimal(columnIndex, scale); - } - - @Override - public byte[] getBytes(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - if (columnIndex <= 1) { - return this.originalResultSet.getBytes(columnIndex); - } else { - return null; - } - } - - @Override - public Date getDate(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getDate(columnIndex); - } - - @Override - public Time getTime(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getTime(columnIndex); - } - - @Override - public Timestamp getTimestamp(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getTimestamp(columnIndex); - } - - @Override - public InputStream getAsciiStream(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getAsciiStream(columnIndex); - } - - @Override - public InputStream getUnicodeStream(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getUnicodeStream(columnIndex); - } - - @Override - public InputStream getBinaryStream(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getBinaryStream(columnIndex); - } - - @Override - public String getString(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getString(columnLabel); - } - - @Override - public boolean getBoolean(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getBoolean(columnLabel); - } - - @Override - public byte getByte(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getByte(columnLabel); - } - - @Override - public short getShort(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getShort(columnLabel); - } - - @Override - public int getInt(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getInt(columnLabel); - } - - @Override - public long getLong(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getLong(columnLabel); - } - - @Override - public float getFloat(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getFloat(columnLabel); - } - - @Override - public double getDouble(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getDouble(columnLabel); - } - - @Override - public BigDecimal getBigDecimal(String columnLabel, int scale) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getBigDecimal(columnLabel, scale); - } - - @Override - public byte[] getBytes(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getBytes(columnLabel); - } - - @Override - public Date getDate(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getDate(columnLabel); - } - - @Override - public Time getTime(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getTime(columnLabel); - } - - @Override - public Timestamp getTimestamp(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getTimestamp(columnLabel); - } - - @Override - public InputStream getAsciiStream(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getAsciiStream(columnLabel); - } - - @Override - public InputStream getUnicodeStream(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getUnicodeStream(columnLabel); - } - - @Override - public InputStream getBinaryStream(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getBinaryStream(columnLabel); - } - - @Override - public SQLWarning getWarnings() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getWarnings(); - } - - @Override - public void clearWarnings() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - this.originalResultSet.clearWarnings(); - } - - @Override - public String getCursorName() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getCursorName(); - } - - @Override - public ResultSetMetaData getMetaData() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getMetaData(); - } - - @Override - public Object getObject(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getObject(columnIndex); - } - - @Override - public Object getObject(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getObject(columnLabel); - } - - @Override - public int findColumn(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.findColumn(columnLabel); - } - - @Override - public Reader getCharacterStream(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getCharacterStream(columnIndex); - } - - @Override - public Reader getCharacterStream(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getCharacterStream(columnLabel); - } - - @Override - public BigDecimal getBigDecimal(int columnIndex) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getBigDecimal(columnIndex); - } - - @Override - public BigDecimal getBigDecimal(String columnLabel) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getBigDecimal(columnLabel); - } - - @Override - public boolean isBeforeFirst() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.isBeforeFirst(); - } - - @Override - public boolean isAfterLast() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.isAfterLast(); - } - - @Override - public boolean isFirst() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.isFirst(); - } - - @Override - public boolean isLast() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.isLast(); - } - - @Override - public void beforeFirst() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - this.originalResultSet.beforeFirst(); - } - - @Override - public void afterLast() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - this.originalResultSet.afterLast(); - } - - @Override - public boolean first() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.first(); - } - - @Override - public boolean last() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.last(); - } - - @Override - public int getRow() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.getRow(); - } - - @Override - public boolean absolute(int row) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.absolute(row); - } - - @Override - public boolean relative(int rows) throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.relative(rows); - } - - @Override - public boolean previous() throws SQLException { - if (originalResultSet == null) { - throw new SQLException("No original result set is injected"); - } - return this.originalResultSet.previous(); - } - - @Override - public void setFetchDirection(int direction) throws SQLException { - this.originalResultSet.setFetchDirection(direction); - } - - @Override - public int getFetchDirection() throws SQLException { - return this.originalResultSet.getFetchDirection(); - } - - @Override - public void setFetchSize(int rows) throws SQLException { - this.originalResultSet.setFetchSize(rows); - } - - @Override - public int getFetchSize() throws SQLException { - return this.originalResultSet.getFetchSize(); - } - - @Override - public int getType() throws SQLException { - return this.originalResultSet.getType(); - } - - @Override - public int getConcurrency() throws SQLException { - return this.originalResultSet.getConcurrency(); - } - - @Override - public boolean rowUpdated() throws SQLException { - return this.originalResultSet.rowUpdated(); - } - - @Override - public boolean rowInserted() throws SQLException { - return this.originalResultSet.rowInserted(); - } - - @Override - public boolean rowDeleted() throws SQLException { - return this.originalResultSet.rowDeleted(); - } - - @Override - public void updateNull(int columnIndex) throws SQLException { - this.originalResultSet.updateNull(columnIndex); - } - - @Override - public void updateBoolean(int columnIndex, boolean x) throws SQLException { - this.originalResultSet.updateBoolean(columnIndex, x); - } - - @Override - public void updateByte(int columnIndex, byte x) throws SQLException { - this.originalResultSet.updateByte(columnIndex, x); - } - - @Override - public void updateShort(int columnIndex, short x) throws SQLException { - this.originalResultSet.updateShort(columnIndex, x); - } - - @Override - public void updateInt(int columnIndex, int x) throws SQLException { - this.originalResultSet.updateInt(columnIndex, x); - } - - @Override - public void updateLong(int columnIndex, long x) throws SQLException { - this.originalResultSet.updateLong(columnIndex, x); - } - - @Override - public void updateFloat(int columnIndex, float x) throws SQLException { - this.originalResultSet.updateFloat(columnIndex, x); - } - - @Override - public void updateDouble(int columnIndex, double x) throws SQLException { - this.originalResultSet.updateDouble(columnIndex, x); - } - - @Override - public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException { - this.originalResultSet.updateBigDecimal(columnIndex, x); - } - - @Override - public void updateString(int columnIndex, String x) throws SQLException { - this.originalResultSet.updateString(columnIndex, x); - } - - @Override - public void updateBytes(int columnIndex, byte[] x) throws SQLException { - this.originalResultSet.updateBytes(columnIndex, x); - } - - @Override - public void updateDate(int columnIndex, Date x) throws SQLException { - this.originalResultSet.updateDate(columnIndex, x); - } - - @Override - public void updateTime(int columnIndex, Time x) throws SQLException { - this.originalResultSet.updateTime(columnIndex, x); - } - - @Override - public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { - this.originalResultSet.updateTimestamp(columnIndex, x); - } - - @Override - public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException { - this.originalResultSet.updateAsciiStream(columnIndex, x, length); - } - - @Override - public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException { - this.originalResultSet.updateBinaryStream(columnIndex, x, length); - } - - @Override - public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException { - this.originalResultSet.updateCharacterStream(columnIndex, x, length); - } - - @Override - public void updateObject(int columnIndex, Object x, int scaleOrLength) throws SQLException { - this.originalResultSet.updateObject(columnIndex, x, scaleOrLength); - } - - @Override - public void updateObject(int columnIndex, Object x) throws SQLException { - this.originalResultSet.updateObject(columnIndex, x); - } - - @Override - public void updateNull(String columnLabel) throws SQLException { - this.originalResultSet.updateNull(columnLabel); - } - - @Override - public void updateBoolean(String columnLabel, boolean x) throws SQLException { - this.originalResultSet.updateBoolean(columnLabel, x); - } - - @Override - public void updateByte(String columnLabel, byte x) throws SQLException { - this.originalResultSet.updateByte(columnLabel, x); - } - - @Override - public void updateShort(String columnLabel, short x) throws SQLException { - this.originalResultSet.updateShort(columnLabel, x); - } - - @Override - public void updateInt(String columnLabel, int x) throws SQLException { - this.originalResultSet.updateInt(columnLabel, x); - } - - @Override - public void updateLong(String columnLabel, long x) throws SQLException { - this.originalResultSet.updateLong(columnLabel, x); - } - - @Override - public void updateFloat(String columnLabel, float x) throws SQLException { - this.originalResultSet.updateFloat(columnLabel, x); - } - - @Override - public void updateDouble(String columnLabel, double x) throws SQLException { - this.originalResultSet.updateDouble(columnLabel, x); - } - - @Override - public void updateBigDecimal(String columnLabel, BigDecimal x) throws SQLException { - this.originalResultSet.updateBigDecimal(columnLabel, x); - } - - @Override - public void updateString(String columnLabel, String x) throws SQLException { - this.originalResultSet.updateString(columnLabel, x); - } - - @Override - public void updateBytes(String columnLabel, byte[] x) throws SQLException { - this.originalResultSet.updateBytes(columnLabel, x); - } - - @Override - public void updateDate(String columnLabel, Date x) throws SQLException { - this.originalResultSet.updateDate(columnLabel, x); - } - - @Override - public void updateTime(String columnLabel, Time x) throws SQLException { - this.originalResultSet.updateTime(columnLabel, x); - } - - @Override - public void updateTimestamp(String columnLabel, Timestamp x) throws SQLException { - this.originalResultSet.updateTimestamp(columnLabel, x); - } - - @Override - public void updateAsciiStream(String columnLabel, InputStream x, int length) throws SQLException { - this.originalResultSet.updateAsciiStream(columnLabel, x, length); - } - - @Override - public void updateBinaryStream(String columnLabel, InputStream x, int length) throws SQLException { - this.originalResultSet.updateBinaryStream(columnLabel, x, length); - } - - @Override - public void updateCharacterStream(String columnLabel, Reader reader, int length) throws SQLException { - this.originalResultSet.updateCharacterStream(columnLabel, reader, length); - } - - @Override - public void updateObject(String columnLabel, Object x, int scaleOrLength) throws SQLException { - this.originalResultSet.updateObject(columnLabel, x, scaleOrLength); - } - - @Override - public void updateObject(String columnLabel, Object x) throws SQLException { - this.originalResultSet.updateObject(columnLabel, x); - } - - @Override - public void insertRow() throws SQLException { - this.originalResultSet.insertRow(); - } - - @Override - public void updateRow() throws SQLException { - this.originalResultSet.updateRow(); - } - - @Override - public void deleteRow() throws SQLException { - this.originalResultSet.deleteRow(); - } - - @Override - public void refreshRow() throws SQLException { - this.originalResultSet.refreshRow(); - } - - @Override - public void cancelRowUpdates() throws SQLException { - this.originalResultSet.cancelRowUpdates(); - } - - @Override - public void moveToInsertRow() throws SQLException { - this.originalResultSet.moveToInsertRow(); - } - - @Override - public void moveToCurrentRow() throws SQLException { - this.originalResultSet.moveToCurrentRow(); - } - - @Override - public Statement getStatement() throws SQLException { - return this.originalResultSet.getStatement(); - } - - @Override - public Object getObject(int columnIndex, Map> map) throws SQLException { - return this.originalResultSet.getObject(columnIndex, map); - } - - @Override - public Ref getRef(int columnIndex) throws SQLException { - return this.originalResultSet.getRef(columnIndex); - } - - @Override - public Blob getBlob(int columnIndex) throws SQLException { - return this.originalResultSet.getBlob(columnIndex); - } - - @Override - public Clob getClob(int columnIndex) throws SQLException { - return this.originalResultSet.getClob(columnIndex); - } - - @Override - public Array getArray(int columnIndex) throws SQLException { - return this.originalResultSet.getArray(columnIndex); - } - - @Override - public Object getObject(String columnLabel, Map> map) throws SQLException { - return this.originalResultSet.getObject(columnLabel, map); - } - - @Override - public Ref getRef(String columnLabel) throws SQLException { - return this.originalResultSet.getRef(columnLabel); - } - - @Override - public Blob getBlob(String columnLabel) throws SQLException { - return this.originalResultSet.getBlob(columnLabel); - } - - @Override - public Clob getClob(String columnLabel) throws SQLException { - return this.originalResultSet.getClob(columnLabel); - } - - @Override - public Array getArray(String columnLabel) throws SQLException { - return this.originalResultSet.getArray(columnLabel); - } - - @Override - public Date getDate(int columnIndex, Calendar cal) throws SQLException { - return this.originalResultSet.getDate(columnIndex, cal); - } - - @Override - public Date getDate(String columnLabel, Calendar cal) throws SQLException { - return this.originalResultSet.getDate(columnLabel, cal); - } - - @Override - public Time getTime(int columnIndex, Calendar cal) throws SQLException { - return this.originalResultSet.getTime(columnIndex, cal); - } - - @Override - public Time getTime(String columnLabel, Calendar cal) throws SQLException { - return this.originalResultSet.getTime(columnLabel, cal); - } - - @Override - public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { - return this.originalResultSet.getTimestamp(columnIndex, cal); - } - - @Override - public Timestamp getTimestamp(String columnLabel, Calendar cal) throws SQLException { - return this.originalResultSet.getTimestamp(columnLabel, cal); - } - - @Override - public URL getURL(int columnIndex) throws SQLException { - return this.originalResultSet.getURL(columnIndex); - } - - @Override - public URL getURL(String columnLabel) throws SQLException { - return this.originalResultSet.getURL(columnLabel); - } - - @Override - public void updateRef(int columnIndex, Ref x) throws SQLException { - this.originalResultSet.updateRef(columnIndex, x); - } - - @Override - public void updateRef(String columnLabel, Ref x) throws SQLException { - this.originalResultSet.updateRef(columnLabel, x); - } - - @Override - public void updateBlob(int columnIndex, Blob x) throws SQLException { - this.originalResultSet.updateBlob(columnIndex, x); - } - - @Override - public void updateBlob(String columnLabel, Blob x) throws SQLException { - this.originalResultSet.updateBlob(columnLabel, x); - } - - @Override - public void updateClob(int columnIndex, Clob x) throws SQLException { - this.originalResultSet.updateClob(columnIndex, x); - } - - @Override - public void updateClob(String columnLabel, Clob x) throws SQLException { - this.originalResultSet.updateClob(columnLabel, x); - } - - @Override - public void updateArray(int columnIndex, Array x) throws SQLException { - this.originalResultSet.updateArray(columnIndex, x); - } - - @Override - public void updateArray(String columnLabel, Array x) throws SQLException { - this.originalResultSet.updateArray(columnLabel, x); - } - - @Override - public RowId getRowId(int columnIndex) throws SQLException { - return this.originalResultSet.getRowId(columnIndex); - } - - @Override - public RowId getRowId(String columnLabel) throws SQLException { - return this.originalResultSet.getRowId(columnLabel); - } - - @Override - public void updateRowId(int columnIndex, RowId x) throws SQLException { - this.originalResultSet.updateRowId(columnIndex, x); - } - - @Override - public void updateRowId(String columnLabel, RowId x) throws SQLException { - this.originalResultSet.updateRowId(columnLabel, x); - } - - @Override - public int getHoldability() throws SQLException { - return this.originalResultSet.getHoldability(); - } - - @Override - public boolean isClosed() throws SQLException { - return this.originalResultSet.isClosed(); - } - - @Override - public void updateNString(int columnIndex, String nString) throws SQLException { - this.originalResultSet.updateNString(columnIndex, nString); - } - - @Override - public void updateNString(String columnLabel, String nString) throws SQLException { - this.originalResultSet.updateNString(columnLabel, nString); - } - - @Override - public void updateNClob(int columnIndex, NClob nClob) throws SQLException { - this.originalResultSet.updateNClob(columnIndex, nClob); - } - - @Override - public void updateNClob(String columnLabel, NClob nClob) throws SQLException { - this.originalResultSet.updateNClob(columnLabel, nClob); - } - - @Override - public NClob getNClob(int columnIndex) throws SQLException { - return this.originalResultSet.getNClob(columnIndex); - } - - @Override - public NClob getNClob(String columnLabel) throws SQLException { - return this.originalResultSet.getNClob(columnLabel); - } - - @Override - public SQLXML getSQLXML(int columnIndex) throws SQLException { - return this.originalResultSet.getSQLXML(columnIndex); - } - - @Override - public SQLXML getSQLXML(String columnLabel) throws SQLException { - return this.originalResultSet.getSQLXML(columnLabel); - } - - @Override - public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException { - this.originalResultSet.updateSQLXML(columnIndex, xmlObject); - } - - @Override - public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException { - this.originalResultSet.updateSQLXML(columnLabel, xmlObject); - } - - @Override - public String getNString(int columnIndex) throws SQLException { - return this.originalResultSet.getNString(columnIndex); - } - - @Override - public String getNString(String columnLabel) throws SQLException { - return this.originalResultSet.getNString(columnLabel); - } - - @Override - public Reader getNCharacterStream(int columnIndex) throws SQLException { - return this.originalResultSet.getNCharacterStream(columnIndex); - } - - @Override - public Reader getNCharacterStream(String columnLabel) throws SQLException { - return this.originalResultSet.getNCharacterStream(columnLabel); - } - - @Override - public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException { - this.originalResultSet.updateNCharacterStream(columnIndex, x, length); - } - - @Override - public void updateNCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { - this.originalResultSet.updateNCharacterStream(columnLabel, reader, length); - } - - @Override - public void updateAsciiStream(int columnIndex, InputStream x, long length) throws SQLException { - this.originalResultSet.updateAsciiStream(columnIndex, x, length); - } - - @Override - public void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException { - this.originalResultSet.updateBinaryStream(columnIndex, x, length); - } - - @Override - public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException { - this.originalResultSet.updateCharacterStream(columnIndex, x, length); - } - - @Override - public void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException { - this.originalResultSet.updateAsciiStream(columnLabel, x, length); - } - - @Override - public void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException { - this.originalResultSet.updateBinaryStream(columnLabel, x, length); - } - - @Override - public void updateCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { - this.originalResultSet.updateCharacterStream(columnLabel, reader, length); - } - - @Override - public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException { - this.originalResultSet.updateBlob(columnIndex, inputStream, length); - } - - @Override - public void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException { - this.originalResultSet.updateBlob(columnLabel, inputStream, length); - } - - @Override - public void updateClob(int columnIndex, Reader reader, long length) throws SQLException { - this.originalResultSet.updateClob(columnIndex, reader, length); - } - - @Override - public void updateClob(String columnLabel, Reader reader, long length) throws SQLException { - this.originalResultSet.updateClob(columnLabel, reader, length); - } - - @Override - public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException { - this.originalResultSet.updateNClob(columnIndex, reader, length); - } - - @Override - public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException { - this.originalResultSet.updateNClob(columnLabel, reader, length); - } - - @Override - public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException { - this.originalResultSet.updateNCharacterStream(columnIndex, x); - } - - @Override - public void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException { - this.originalResultSet.updateNCharacterStream(columnLabel, reader); - } - - @Override - public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException { - this.originalResultSet.updateAsciiStream(columnIndex, x); - } - - @Override - public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException { - this.originalResultSet.updateBinaryStream(columnIndex, x); - } - - @Override - public void updateCharacterStream(int columnIndex, Reader x) throws SQLException { - this.originalResultSet.updateCharacterStream(columnIndex, x); - } - - @Override - public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException { - this.originalResultSet.updateAsciiStream(columnLabel, x); - } - - @Override - public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException { - this.originalResultSet.updateBinaryStream(columnLabel, x); - } - - @Override - public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException { - this.originalResultSet.updateCharacterStream(columnLabel, reader); - } - - @Override - public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException { - this.originalResultSet.updateBlob(columnIndex, inputStream); - } - - @Override - public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException { - this.originalResultSet.updateBlob(columnLabel, inputStream); - } - - @Override - public void updateClob(int columnIndex, Reader reader) throws SQLException { - this.originalResultSet.updateClob(columnIndex, reader); - } - - @Override - public void updateClob(String columnLabel, Reader reader) throws SQLException { - this.originalResultSet.updateClob(columnLabel, reader); - } - - @Override - public void updateNClob(int columnIndex, Reader reader) throws SQLException { - this.originalResultSet.updateNClob(columnIndex, reader); - } - - @Override - public void updateNClob(String columnLabel, Reader reader) throws SQLException { - this.originalResultSet.updateNClob(columnLabel, reader); - } - - public T getObject(int columnIndex, Class type) throws SQLException { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - public T getObject(String columnLabel, Class type) throws SQLException { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public T unwrap(Class iface) throws SQLException { - return this.originalResultSet.unwrap(iface); - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return this.originalResultSet.isWrapperFor(iface); - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBStatement.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBStatement.java deleted file mode 100644 index c4cf2bafbf..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBStatement.java +++ /dev/null @@ -1,148 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2019 TAOS Data, Inc. - * - * This program is free software: you can use, redistribute, and/or modify - * it under the terms of the GNU Affero General Public License, version 3 - * or later ("AGPL"), as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - *****************************************************************************/ -package com.taosdata.jdbc; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class TSDBStatement extends AbstractStatement { - /** - * Status of current statement - */ - private boolean isClosed; - private TSDBConnection connection; - private TSDBResultSet resultSet; - - TSDBStatement(TSDBConnection connection) { - this.connection = connection; - connection.registerStatement(this); - } - - public ResultSet executeQuery(String sql) throws SQLException { - synchronized (this) { - if (isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - } - if (this.resultSet != null && !this.resultSet.isClosed()) - this.resultSet.close(); - //TODO: - // this is an unreasonable implementation, if the paratemer is a insert statement, - // the JNI connector will execute the sql at first and return a pointer: pSql, - // we use this pSql and invoke the isUpdateQuery(long pSql) method to decide . - // but the insert sql is already executed in database. - //execute query - long pSql = this.connection.getConnector().executeQuery(sql); - // if pSql is create/insert/update/delete/alter SQL - if (this.connection.getConnector().isUpdateQuery(pSql)) { - this.connection.getConnector().freeResultSet(pSql); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEQUERY); - } - int timestampPrecision = this.connection.getConnector().getResultTimePrecision(pSql); - resultSet = new TSDBResultSet(this, this.connection.getConnector(), pSql, timestampPrecision); - resultSet.setBatchFetch(this.connection.getBatchFetch()); - return resultSet; - } - } - - public int executeUpdate(String sql) throws SQLException { - synchronized (this) { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - if (this.resultSet != null && !this.resultSet.isClosed()) - this.resultSet.close(); - - long pSql = this.connection.getConnector().executeQuery(sql); - // if pSql is create/insert/update/delete/alter SQL - if (!this.connection.getConnector().isUpdateQuery(pSql)) { - this.connection.getConnector().freeResultSet(pSql); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEUPDATE); - } - int affectedRows = this.connection.getConnector().getAffectedRows(pSql); - this.connection.getConnector().freeResultSet(pSql); - return affectedRows; - } - } - - public void close() throws SQLException { - if (isClosed) - return; - connection.unregisterStatement(this); - if (this.resultSet != null && !this.resultSet.isClosed()) - this.resultSet.close(); - isClosed = true; - } - - public boolean execute(String sql) throws SQLException { - synchronized (this) { - // check if closed - if (isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - } - if (this.resultSet != null && !this.resultSet.isClosed()) - this.resultSet.close(); - - // execute query - long pSql = this.connection.getConnector().executeQuery(sql); - // if pSql is create/insert/update/delete/alter SQL - if (this.connection.getConnector().isUpdateQuery(pSql)) { - this.affectedRows = this.connection.getConnector().getAffectedRows(pSql); - this.connection.getConnector().freeResultSet(pSql); - return false; - } - - int timestampPrecision = this.connection.getConnector().getResultTimePrecision(pSql); - this.resultSet = new TSDBResultSet(this, this.connection.getConnector(), pSql, timestampPrecision); - this.resultSet.setBatchFetch(this.connection.getBatchFetch()); - return true; - } - } - - public ResultSet getResultSet() throws SQLException { - if (isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - } - - return this.resultSet; - } - - public int getUpdateCount() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - return this.affectedRows; - } - - public Connection getConnection() throws SQLException { - if (isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - } - - if (this.connection.getConnector() == null) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); - } - - return this.connection; - } - - public void setConnection(TSDBConnection connection) { - this.connection = connection; - } - - public boolean isClosed() throws SQLException { - return isClosed; - } - - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBSubscribe.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBSubscribe.java deleted file mode 100644 index 2a535fc8fa..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBSubscribe.java +++ /dev/null @@ -1,60 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2019 TAOS Data, Inc. - * - * This program is free software: you can use, redistribute, and/or modify - * it under the terms of the GNU Affero General Public License, version 3 - * or later ("AGPL"), as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - *****************************************************************************/ -package com.taosdata.jdbc; - -import com.taosdata.jdbc.enums.TimestampPrecision; - -import java.sql.SQLException; - -public class TSDBSubscribe { - private final TSDBJNIConnector connecter; - private final long id; - - TSDBSubscribe(TSDBJNIConnector connecter, long id) throws SQLException { - if (connecter == null) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); - - this.connecter = connecter; - this.id = id; - } - - /** - * consume - */ - public TSDBResultSet consume() throws SQLException { - if (this.connecter.isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); - - long resultSetPointer = this.connecter.consume(this.id); - if (resultSetPointer == TSDBConstants.JNI_CONNECTION_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); - } else if (resultSetPointer == TSDBConstants.JNI_NULL_POINTER) { - return null; - } else { - return new TSDBResultSet(null, this.connecter, resultSetPointer, TimestampPrecision.UNKNOWN); - } - } - - /** - * close subscription - */ - public void close(boolean keepProgress) throws SQLException { - if (this.connecter.isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); - - this.connecter.unsubscribe(this.id, keepProgress); - } -} - diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TaosGlobalConfig.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TaosGlobalConfig.java deleted file mode 100644 index 171189763b..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TaosGlobalConfig.java +++ /dev/null @@ -1,30 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2019 TAOS Data, Inc. - * - * This program is free software: you can use, redistribute, and/or modify - * it under the terms of the GNU Affero General Public License, version 3 - * or later ("AGPL"), as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - *****************************************************************************/ -package com.taosdata.jdbc; - -public class TaosGlobalConfig { - static String charset = ""; - - public static String getCharset() { - if (charset == null || charset.isEmpty()) { - charset = System.getProperty("file.encoding"); - } - return charset; - } - - public static void setCharset(String tsCharset) { - TaosGlobalConfig.charset = tsCharset; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/WrapperImpl.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/WrapperImpl.java deleted file mode 100644 index 5b7539d434..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/WrapperImpl.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.taosdata.jdbc; - -import java.sql.SQLException; -import java.sql.Wrapper; - -public class WrapperImpl implements Wrapper { - - @Override - public T unwrap(Class iface) throws SQLException { - try { - return iface.cast(this); - } catch (ClassCastException cce) { - throw new SQLException("Unable to unwrap to " + iface.toString()); - } - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return iface.isInstance(this); - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/SchemalessProtocolType.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/SchemalessProtocolType.java deleted file mode 100644 index 2a0bea1570..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/SchemalessProtocolType.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.taosdata.jdbc.enums; - -import java.util.Arrays; - -public enum SchemalessProtocolType { - UNKNOWN, - LINE, - TELNET, - JSON, - ; - - public static SchemalessProtocolType parse(String type) { - return Arrays.stream(SchemalessProtocolType.values()) - .filter(protocol -> type.equalsIgnoreCase(protocol.name())) - .findFirst().orElse(UNKNOWN); - } - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/SchemalessTimestampType.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/SchemalessTimestampType.java deleted file mode 100644 index fa10a23634..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/SchemalessTimestampType.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.taosdata.jdbc.enums; - -public enum SchemalessTimestampType { - // Let the database decide - NOT_CONFIGURED, - HOURS, - MINUTES, - SECONDS, - MILLI_SECONDS, - MICRO_SECONDS, - NANO_SECONDS, - ; -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/TimestampFormat.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/TimestampFormat.java deleted file mode 100644 index 5ff0774639..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/TimestampFormat.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.taosdata.jdbc.enums; - -public enum TimestampFormat { - STRING, - TIMESTAMP, - UTC -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/TimestampPrecision.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/TimestampPrecision.java deleted file mode 100644 index aee575b266..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/TimestampPrecision.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.taosdata.jdbc.enums; - -public class TimestampPrecision { - public static final int MS = 0; - public static final int US = 1; - public static final int NS = 2; - public static final int UNKNOWN = 9999; -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulConnection.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulConnection.java deleted file mode 100644 index f3ce3a742e..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulConnection.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.taosdata.jdbc.rs; - -import com.taosdata.jdbc.AbstractConnection; -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.TSDBError; -import com.taosdata.jdbc.TSDBErrorNumbers; - -import java.sql.DatabaseMetaData; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Properties; - -public class RestfulConnection extends AbstractConnection { - - private final String host; - private final int port; - private final String url; - private final String database; - private final String auth; - private final boolean useSsl; - private final String token; - - private boolean isClosed; - private final DatabaseMetaData metadata; - - public RestfulConnection(String host, String port, Properties props, String database, String url, String auth, boolean useSsl, String token) { - super(props); - this.host = host; - this.port = Integer.parseInt(port); - this.database = database; - this.url = url; - this.auth = "Basic " + auth; - this.useSsl = useSsl; - this.token = token; - this.metadata = new RestfulDatabaseMetaData(url, props.getProperty(TSDBDriver.PROPERTY_KEY_USER), this); - } - - @Override - public Statement createStatement() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - return new RestfulStatement(this, database); - } - - @Override - public PreparedStatement prepareStatement(String sql) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - return new RestfulPreparedStatement(this, database, sql); - } - - @Override - public void close() throws SQLException { - if (isClosed) - return; - //TODO: release all resources - isClosed = true; - } - - @Override - public boolean isClosed() throws SQLException { - return isClosed; - } - - @Override - public DatabaseMetaData getMetaData() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - return this.metadata; - } - - // getters - public String getHost() { - return host; - } - - public int getPort() { - return port; - } - - public String getDatabase() { - return database; - } - - public String getUrl() { - return url; - } - - public String getToken() { - return token; - } - - public String getAuth() { - return auth; - } - - public boolean isUseSsl() { - return useSsl; - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDatabaseMetaData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDatabaseMetaData.java deleted file mode 100644 index d108f46a79..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDatabaseMetaData.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.taosdata.jdbc.rs; - -import com.taosdata.jdbc.AbstractDatabaseMetaData; -import com.taosdata.jdbc.TSDBError; -import com.taosdata.jdbc.TSDBErrorNumbers; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class RestfulDatabaseMetaData extends AbstractDatabaseMetaData { - - private final String url; - private final String userName; - private final Connection connection; - - public RestfulDatabaseMetaData(String url, String userName, Connection connection) { - this.url = url; - this.userName = userName; - this.connection = connection; - } - - @Override - public String getURL() throws SQLException { - return this.url; - } - - @Override - public String getUserName() throws SQLException { - return this.userName; - } - - @Override - public String getDriverName() throws SQLException { - return RestfulDriver.class.getName(); - } - - @Override - public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException { - if (connection == null || connection.isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - } - return super.getTables(catalog, schemaPattern, tableNamePattern, types, connection); - } - - @Override - public ResultSet getCatalogs() throws SQLException { - if (connection == null || connection.isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - return super.getCatalogs(connection); - } - - @Override - public ResultSet getTableTypes() throws SQLException { - if (connection == null || connection.isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - } - return super.getTableTypes(); - } - - @Override - public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { - if (connection == null || connection.isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - return super.getColumns(catalog, schemaPattern, tableNamePattern, columnNamePattern, connection); - } - - @Override - public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException { - if (connection == null || connection.isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - return super.getPrimaryKeys(catalog, schema, table, connection); - } - - @Override - public Connection getConnection() throws SQLException { - return this.connection; - } - - @Override - public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { - if (connection == null || connection.isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - return super.getSuperTables(catalog, schemaPattern, tableNamePattern, connection); - } - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDriver.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDriver.java deleted file mode 100644 index 3cb4749335..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDriver.java +++ /dev/null @@ -1,173 +0,0 @@ -package com.taosdata.jdbc.rs; - -import com.taosdata.jdbc.AbstractDriver; -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.TSDBError; -import com.taosdata.jdbc.TSDBErrorNumbers; -import com.taosdata.jdbc.enums.TimestampFormat; -import com.taosdata.jdbc.utils.HttpClientPoolUtil; -import com.taosdata.jdbc.ws.InFlightRequest; -import com.taosdata.jdbc.ws.Transport; -import com.taosdata.jdbc.ws.WSClient; -import com.taosdata.jdbc.ws.WSConnection; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.sql.*; -import java.util.Base64; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.logging.Logger; - -public class RestfulDriver extends AbstractDriver { - - private static final String URL_PREFIX = "jdbc:TAOS-RS://"; - - static { - try { - DriverManager.registerDriver(new RestfulDriver()); - } catch (SQLException e) { - throw TSDBError.createRuntimeException(TSDBErrorNumbers.ERROR_URL_NOT_SET, e); - } - } - - @Override - public Connection connect(String url, Properties info) throws SQLException { - // throw SQLException if url is null - if (url == null || url.trim().isEmpty() || url.trim().replaceAll("\\s", "").isEmpty()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_URL_NOT_SET); - - // return null if url is not be accepted - if (!acceptsURL(url)) - return null; - - Properties props = parseURL(url, info); - String host = props.getProperty(TSDBDriver.PROPERTY_KEY_HOST); - String port = props.getProperty(TSDBDriver.PROPERTY_KEY_PORT, "6041"); - String database = props.containsKey(TSDBDriver.PROPERTY_KEY_DBNAME) ? props.getProperty(TSDBDriver.PROPERTY_KEY_DBNAME) : null; - - String user; - String password; - try { - if (!props.containsKey(TSDBDriver.PROPERTY_KEY_USER)) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_USER_IS_REQUIRED); - if (!props.containsKey(TSDBDriver.PROPERTY_KEY_PASSWORD)) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PASSWORD_IS_REQUIRED); - - user = URLEncoder.encode(props.getProperty(TSDBDriver.PROPERTY_KEY_USER), StandardCharsets.UTF_8.displayName()); - password = URLEncoder.encode(props.getProperty(TSDBDriver.PROPERTY_KEY_PASSWORD), StandardCharsets.UTF_8.displayName()); - } catch (UnsupportedEncodingException e) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE, "unsupported UTF-8 concoding, user: " + props.getProperty(TSDBDriver.PROPERTY_KEY_USER) + ", password: " + props.getProperty(TSDBDriver.PROPERTY_KEY_PASSWORD)); - } - - String cloudToken = null; - if (props.containsKey(TSDBDriver.PROPERTY_KEY_TOKEN)) { - cloudToken = props.getProperty(TSDBDriver.PROPERTY_KEY_TOKEN); - } - - boolean useSsl = Boolean.parseBoolean(props.getProperty(TSDBDriver.PROPERTY_KEY_USE_SSL, "false")); - String loginUrl; - String batchLoad = info.getProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD); - if (Boolean.parseBoolean(batchLoad)) { - String protocol = "ws"; - if (useSsl) { - protocol = "wss"; - } - loginUrl = protocol + "://" + props.getProperty(TSDBDriver.PROPERTY_KEY_HOST) - + ":" + props.getProperty(TSDBDriver.PROPERTY_KEY_PORT) + "/rest/ws"; - if (null != cloudToken) { - loginUrl = loginUrl + "?token=" + cloudToken; - } - WSClient client; - Transport transport; - try { - int timeout = props.containsKey(TSDBDriver.PROPERTY_KEY_MESSAGE_WAIT_TIMEOUT) - ? Integer.parseInt(props.getProperty(TSDBDriver.PROPERTY_KEY_MESSAGE_WAIT_TIMEOUT)) - : Transport.DEFAULT_MESSAGE_WAIT_TIMEOUT; - int maxRequest = props.containsKey(TSDBDriver.PROPERTY_KEY_MAX_CONCURRENT_REQUEST) - ? Integer.parseInt(props.getProperty(TSDBDriver.PROPERTY_KEY_MAX_CONCURRENT_REQUEST)) - : Transport.DEFAULT_MAX_REQUEST; - - InFlightRequest inFlightRequest = new InFlightRequest(timeout, maxRequest); - CountDownLatch latch = new CountDownLatch(1); - Map httpHeaders = new HashMap<>(); - client = new WSClient(new URI(loginUrl), user, password, database, - inFlightRequest, httpHeaders, latch, maxRequest); - transport = new Transport(client, inFlightRequest); - if (!client.connectBlocking(timeout, TimeUnit.MILLISECONDS)) { - throw new SQLException("can't create connection with server"); - } - if (!latch.await(timeout, TimeUnit.MILLISECONDS)) { - throw new SQLException("auth timeout"); - } - if (!client.isAuth()) { - throw new SQLException("auth failure"); - } - } catch (URISyntaxException e) { - throw new SQLException("Websocket url parse error: " + loginUrl, e); - } catch (InterruptedException e) { - throw new SQLException("creat websocket connection has been Interrupted ", e); - } - props.setProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, String.valueOf(TimestampFormat.TIMESTAMP)); - return new WSConnection(url, props, transport, database); - } - int poolSize = Integer.parseInt(props.getProperty("httpPoolSize", HttpClientPoolUtil.DEFAULT_MAX_PER_ROUTE)); - boolean keepAlive = Boolean.parseBoolean(props.getProperty("httpKeepAlive", HttpClientPoolUtil.DEFAULT_HTTP_KEEP_ALIVE)); - HttpClientPoolUtil.init(poolSize, keepAlive); - - String auth = Base64.getEncoder().encodeToString( - (user + ":" + password).getBytes(StandardCharsets.UTF_8)); - RestfulConnection conn = new RestfulConnection(host, port, props, database, url, auth, useSsl, cloudToken); - if (database != null && !database.trim().replaceAll("\\s", "").isEmpty()) { - try (Statement stmt = conn.createStatement()) { - stmt.execute("use " + database); - } - } - return conn; - } - - @Override - public boolean acceptsURL(String url) throws SQLException { - if (url == null) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_URL_NOT_SET); - return url.trim().length() > 0 && url.startsWith(URL_PREFIX); - } - - @Override - public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { - if (info == null) { - info = new Properties(); - } - if (acceptsURL(url)) { - info = parseURL(url, info); - } - return getPropertyInfo(info); - } - - @Override - public int getMajorVersion() { - return 2; - } - - @Override - public int getMinorVersion() { - return 0; - } - - @Override - public boolean jdbcCompliant() { - return false; - } - - @Override - public Logger getParentLogger() throws SQLFeatureNotSupportedException { - //TODO SQLFeatureNotSupportedException - throw new SQLFeatureNotSupportedException(); - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulParameterMetaData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulParameterMetaData.java deleted file mode 100644 index 7a130eb72b..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulParameterMetaData.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.taosdata.jdbc.rs; - -import com.taosdata.jdbc.AbstractParameterMetaData; - -public class RestfulParameterMetaData extends AbstractParameterMetaData { - - RestfulParameterMetaData(Object[] parameters) { - super(parameters); - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulPreparedStatement.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulPreparedStatement.java deleted file mode 100644 index 9b0155d791..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulPreparedStatement.java +++ /dev/null @@ -1,445 +0,0 @@ -package com.taosdata.jdbc.rs; - -import com.taosdata.jdbc.TSDBError; -import com.taosdata.jdbc.TSDBErrorNumbers; -import com.taosdata.jdbc.utils.Utils; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.net.URL; -import java.sql.*; -import java.util.Calendar; - -public class RestfulPreparedStatement extends RestfulStatement implements PreparedStatement { - - private final ParameterMetaData parameterMetaData; - private final String rawSql; - private Object[] parameters; - private boolean isPrepared; - - public RestfulPreparedStatement(RestfulConnection conn, String database, String sql) { - super(conn, database); - this.rawSql = sql; - - int parameterCnt = 0; - if (sql.contains("?")) { - for (int i = 0; i < sql.length(); i++) { - if ('?' == sql.charAt(i)) { - parameterCnt++; - } - } - this.isPrepared = true; - } - parameters = new Object[parameterCnt]; - - // build parameterMetaData - this.parameterMetaData = new RestfulParameterMetaData(parameters); - } - - @Override - public ResultSet executeQuery() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - if (!isPrepared) - return executeQuery(this.rawSql); - - final String sql = Utils.getNativeSql(this.rawSql, this.parameters); - return executeQuery(sql); - } - - @Override - public int executeUpdate() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - if (!isPrepared) - return executeUpdate(this.rawSql); - - final String sql = Utils.getNativeSql(rawSql, this.parameters); - return executeUpdate(sql); - } - - @Override - public void setNull(int parameterIndex, int sqlType) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - setObject(parameterIndex, null); - } - - @Override - public void setBoolean(int parameterIndex, boolean x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - setObject(parameterIndex, x); - } - - @Override - public void setByte(int parameterIndex, byte x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - setObject(parameterIndex, x); - } - - @Override - public void setShort(int parameterIndex, short x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - setObject(parameterIndex, x); - } - - @Override - public void setInt(int parameterIndex, int x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - setObject(parameterIndex, x); - } - - @Override - public void setLong(int parameterIndex, long x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - setObject(parameterIndex, x); - } - - @Override - public void setFloat(int parameterIndex, float x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - setObject(parameterIndex, x); - } - - @Override - public void setDouble(int parameterIndex, double x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - setObject(parameterIndex, x); - } - - @Override - public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setString(int parameterIndex, String x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - setObject(parameterIndex, x); - } - - @Override - public void setBytes(int parameterIndex, byte[] x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - setObject(parameterIndex, x); - } - - @Override - public void setDate(int parameterIndex, Date x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setTime(int parameterIndex, Time x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - setObject(parameterIndex, x); - } - - @Override - public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void clearParameters() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - this.parameters = new Object[parameters.length]; - } - - @Override - public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - setObject(parameterIndex, x); - } - - @Override - public void setObject(int parameterIndex, Object x) throws SQLException { - if (parameterIndex < 1 && parameterIndex >= parameters.length) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - - parameters[parameterIndex - 1] = x; - } - - @Override - public boolean execute() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - if (!isPrepared) - return execute(this.rawSql); - final String sql = Utils.getNativeSql(rawSql, this.parameters); - return execute(sql); - } - - @Override - public void addBatch() throws SQLException { - final String sql = Utils.getNativeSql(rawSql, this.parameters); - addBatch(sql); - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setRef(int parameterIndex, Ref x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setBlob(int parameterIndex, Blob x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setClob(int parameterIndex, Clob x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setArray(int parameterIndex, Array x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public ResultSetMetaData getMetaData() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setURL(int parameterIndex, URL x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public ParameterMetaData getParameterMetaData() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); -// throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - - return this.parameterMetaData; - } - - @Override - public void setRowId(int parameterIndex, RowId x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setNString(int parameterIndex, String value) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setNClob(int parameterIndex, NClob value) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setClob(int parameterIndex, Reader reader) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public void setNClob(int parameterIndex, Reader reader) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSet.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSet.java deleted file mode 100644 index 2819173da8..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSet.java +++ /dev/null @@ -1,738 +0,0 @@ -package com.taosdata.jdbc.rs; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.alibaba.fastjson.serializer.SerializerFeature; -import com.google.common.primitives.Ints; -import com.google.common.primitives.Longs; -import com.google.common.primitives.Shorts; -import com.taosdata.jdbc.*; -import com.taosdata.jdbc.enums.TimestampPrecision; -import com.taosdata.jdbc.enums.TimestampFormat; -import com.taosdata.jdbc.utils.Utils; - -import java.math.BigDecimal; -import java.sql.*; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.chrono.IsoChronology; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.time.format.DateTimeParseException; -import java.time.format.ResolverStyle; -import java.time.temporal.ChronoField; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; - -public class RestfulResultSet extends AbstractResultSet implements ResultSet { - - public static DateTimeFormatter rfc3339Parser = null; - - { - rfc3339Parser = new DateTimeFormatterBuilder() - .parseCaseInsensitive() - .appendValue(ChronoField.YEAR, 4) - .appendLiteral('-') - .appendValue(ChronoField.MONTH_OF_YEAR, 2) - .appendLiteral('-') - .appendValue(ChronoField.DAY_OF_MONTH, 2) - .appendLiteral('T') - .appendValue(ChronoField.HOUR_OF_DAY, 2) - .appendLiteral(':') - .appendValue(ChronoField.MINUTE_OF_HOUR, 2) - .appendLiteral(':') - .appendValue(ChronoField.SECOND_OF_MINUTE, 2) - .optionalStart() - .appendFraction(ChronoField.NANO_OF_SECOND, 2, 9, true) - .optionalEnd() - .appendOffset("+HH:MM", "Z").toFormatter() - .withResolverStyle(ResolverStyle.STRICT) - .withChronology(IsoChronology.INSTANCE); - } - - private final Statement statement; - // data - private final List> resultSet = new ArrayList<>(); - // meta - private final List columnNames = new ArrayList<>(); - private final List columns = new ArrayList<>(); - private final RestfulResultSetMetaData metaData; - - private volatile boolean isClosed; - private int pos = -1; - - /** - * 由一个result的Json构造结果集,对应执行show databases, show tables等这些语句,返回结果集,但无法获取结果集对应的meta,统一当成String处理 - * - * @param resultJson: 包含data信息的结果集,有sql返回的结果集 - ***/ - public RestfulResultSet(String database, Statement statement, JSONObject resultJson) throws SQLException { - this.statement = statement; - - // get head - JSONArray head = resultJson.getJSONArray("head"); - // get column metadata - JSONArray columnMeta = resultJson.getJSONArray("column_meta"); - // get row data - JSONArray data = resultJson.getJSONArray("data"); - // get rows - Integer rows = resultJson.getInteger("rows"); - - // parse column_meta - if (columnMeta != null) { - parseColumnMeta_new(columnMeta); - } else { - parseColumnMeta_old(head, data, rows); - } - this.metaData = new RestfulResultSetMetaData(database, columns, this); - - if (data == null || data.isEmpty()) - return; - // parse row data - for (int rowIndex = 0; rowIndex < data.size(); rowIndex++) { - List row = new ArrayList<>(); - JSONArray jsonRow = data.getJSONArray(rowIndex); - for (int colIndex = 0; colIndex < this.metaData.getColumnCount(); colIndex++) { - row.add(parseColumnData(jsonRow, colIndex, columns.get(colIndex).taos_type)); - } - resultSet.add(row); - } - } - - /*** - * use this method after TDengine-2.0.18.0 to parse column meta, restful add column_meta in resultSet - * @Param columnMeta - */ - private void parseColumnMeta_new(JSONArray columnMeta) throws SQLException { - columnNames.clear(); - columns.clear(); - for (int colIndex = 0; colIndex < columnMeta.size(); colIndex++) { - JSONArray col = columnMeta.getJSONArray(colIndex); - String col_name = col.getString(0); - int taos_type = col.getInteger(1); - int col_type = TSDBConstants.taosType2JdbcType(taos_type); - int col_length = col.getInteger(2); - columnNames.add(col_name); - columns.add(new Field(col_name, col_type, col_length, "", taos_type)); - } - } - - /** - * use this method before TDengine-2.0.18.0 to parse column meta - */ - private void parseColumnMeta_old(JSONArray head, JSONArray data, int rows) { - columnNames.clear(); - columns.clear(); - for (int colIndex = 0; colIndex < head.size(); colIndex++) { - String col_name = head.getString(colIndex); - columnNames.add(col_name); - - int col_type = Types.NULL; - int col_length = 0; - int taos_type = TSDBConstants.TSDB_DATA_TYPE_NULL; - - JSONArray row0Json = data.getJSONArray(0); - if (colIndex < row0Json.size()) { - Object value = row0Json.get(colIndex); - if (value instanceof Boolean) { - col_type = Types.BOOLEAN; - col_length = 1; - taos_type = TSDBConstants.TSDB_DATA_TYPE_BOOL; - } - if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long) { - col_type = Types.BIGINT; - col_length = 8; - taos_type = TSDBConstants.TSDB_DATA_TYPE_BIGINT; - } - if (value instanceof Float || value instanceof Double || value instanceof BigDecimal) { - col_type = Types.DOUBLE; - col_length = 8; - taos_type = TSDBConstants.TSDB_DATA_TYPE_DOUBLE; - } - if (value instanceof String) { - col_type = Types.NCHAR; - col_length = ((String) value).length(); - taos_type = TSDBConstants.TSDB_DATA_TYPE_NCHAR; - } - } - columns.add(new Field(col_name, col_type, col_length, "", taos_type)); - } - } - - private Object parseColumnData(JSONArray row, int colIndex, int taosType) throws SQLException { - switch (taosType) { - case TSDBConstants.TSDB_DATA_TYPE_NULL: - return null; - case TSDBConstants.TSDB_DATA_TYPE_BOOL: - return row.getBoolean(colIndex); - case TSDBConstants.TSDB_DATA_TYPE_TINYINT: - return row.getByte(colIndex); - case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: - return row.getShort(colIndex); - case TSDBConstants.TSDB_DATA_TYPE_INT: - return row.getInteger(colIndex); - case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - return row.getLong(colIndex); - case TSDBConstants.TSDB_DATA_TYPE_FLOAT: - return row.getFloat(colIndex); - case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: - return row.getDouble(colIndex); - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: - return parseTimestampColumnData(row, colIndex); - case TSDBConstants.TSDB_DATA_TYPE_BINARY: - return row.getString(colIndex) == null ? null : row.getString(colIndex).getBytes(); - case TSDBConstants.TSDB_DATA_TYPE_NCHAR: - return row.getString(colIndex) == null ? null : row.getString(colIndex); - case TSDBConstants.TSDB_DATA_TYPE_JSON: - // all json tag or just a json tag value - return row.get(colIndex) != null && (row.get(colIndex) instanceof String || row.get(colIndex) instanceof JSONObject) - ? JSON.toJSONString(row.get(colIndex), SerializerFeature.WriteMapNullValue) - : row.get(colIndex); - default: - return row.get(colIndex); - } - } - - private Timestamp parseTimestampColumnData(JSONArray row, int colIndex) throws SQLException { - if (row.get(colIndex) == null) - return null; - String tsFormatUpperCase = this.statement.getConnection().getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT).toUpperCase(); - TimestampFormat timestampFormat = TimestampFormat.valueOf(tsFormatUpperCase); - switch (timestampFormat) { - case TIMESTAMP: { - Long value = row.getLong(colIndex); - //TODO: this implementation has bug if the timestamp bigger than 9999_9999_9999_9 - if (value < 1_0000_0000_0000_0L) { - this.timestampPrecision = TimestampPrecision.MS; - return new Timestamp(value); - } - if (value >= 1_0000_0000_0000_0L && value < 1_000_000_000_000_000_0l) { - this.timestampPrecision = TimestampPrecision.US; - long epochSec = value / 1000_000L; - long nanoAdjustment = value % 1000_000L * 1000L; - return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); - } - if (value >= 1_000_000_000_000_000_0l) { - this.timestampPrecision = TimestampPrecision.NS; - long epochSec = value / 1000_000_000L; - long nanoAdjustment = value % 1000_000_000L; - return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); - } - } - case UTC: { - String value = row.getString(colIndex); - if (value.lastIndexOf(":") > 19) { - ZonedDateTime parse = ZonedDateTime.parse(value, rfc3339Parser); - long nanoAdjustment; - if (value.length() > 32) { - // ns timestamp: yyyy-MM-ddTHH:mm:ss.SSSSSSSSS+0x:00 - this.timestampPrecision = TimestampPrecision.NS; - } else if (value.length() > 29) { - // ms timestamp: yyyy-MM-ddTHH:mm:ss.SSSSSS+0x:00 - this.timestampPrecision = TimestampPrecision.US; - } else { - // ms timestamp: yyyy-MM-ddTHH:mm:ss.SSS+0x:00 - this.timestampPrecision = TimestampPrecision.MS; - } - return Timestamp.from(parse.toInstant()); - } else { - long epochSec = Timestamp.valueOf(value.substring(0, 19).replace("T", " ")).getTime() / 1000; - int fractionalSec = Integer.parseInt(value.substring(20, value.length() - 5)); - long nanoAdjustment; - if (value.length() > 32) { - // ns timestamp: yyyy-MM-ddTHH:mm:ss.SSSSSSSSS+0x00 - nanoAdjustment = fractionalSec; - this.timestampPrecision = TimestampPrecision.NS; - } else if (value.length() > 29) { - // ms timestamp: yyyy-MM-ddTHH:mm:ss.SSSSSS+0x00 - nanoAdjustment = fractionalSec * 1000L; - this.timestampPrecision = TimestampPrecision.US; - } else { - // ms timestamp: yyyy-MM-ddTHH:mm:ss.SSS+0x00 - nanoAdjustment = fractionalSec * 1000_000L; - this.timestampPrecision = TimestampPrecision.MS; - } - ZoneOffset zoneOffset = ZoneOffset.of(value.substring(value.length() - 5)); - Instant instant = Instant.ofEpochSecond(epochSec, nanoAdjustment).atOffset(zoneOffset).toInstant(); - return Timestamp.from(instant); - } - } - case STRING: - default: { - String value = row.getString(colIndex); - int precision = Utils.guessTimestampPrecision(value); - this.timestampPrecision = precision; - - if (precision == TimestampPrecision.MS) { - // ms timestamp: yyyy-MM-dd HH:mm:ss.SSS - return (Timestamp) row.getTimestamp(colIndex); - } - if (precision == TimestampPrecision.US) { - // us timestamp: yyyy-MM-dd HH:mm:ss.SSSSSS - long epochSec = Timestamp.valueOf(value.substring(0, 19)).getTime() / 1000; - long nanoAdjustment = Integer.parseInt(value.substring(20)) * 1000L; - return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); - } - if (precision == TimestampPrecision.NS) { - // ms timestamp: yyyy-MM-dd HH:mm:ss.SSSSSSSSS - long epochSec = Timestamp.valueOf(value.substring(0, 19)).getTime() / 1000; - long nanoAdjustment = Integer.parseInt(value.substring(20)); - return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); - } - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN_TIMESTAMP_PRECISION); - } - } - } - - public static class Field { - String name; - int type; - int length; - String note; - int taos_type; - - public Field(String name, int type, int length, String note, int taos_type) { - this.name = name; - this.type = type; - this.length = length; - this.note = note; - this.taos_type = taos_type; - } - - public int getTaosType() { - return taos_type; - } - } - - @Override - public boolean next() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - pos++; - return pos <= resultSet.size() - 1; - } - - @Override - public void close() throws SQLException { - synchronized (RestfulResultSet.class) { - this.isClosed = true; - } - } - - @Override - public String getString(int columnIndex) throws SQLException { - checkAvailability(columnIndex, resultSet.get(pos).size()); - - Object value = resultSet.get(pos).get(columnIndex - 1); - wasNull = value == null; - if (value == null) - return null; - if (value instanceof byte[]) - return new String((byte[]) value); - return value.toString(); - } - - @Override - public boolean getBoolean(int columnIndex) throws SQLException { - checkAvailability(columnIndex, resultSet.get(pos).size()); - - Object value = resultSet.get(pos).get(columnIndex - 1); - wasNull = value == null; - if (value == null) - return false; - if (value instanceof Boolean) - return (boolean) value; - return Boolean.parseBoolean(value.toString()); - } - - @Override - public byte getByte(int columnIndex) throws SQLException { - checkAvailability(columnIndex, resultSet.get(pos).size()); - - Object value = resultSet.get(pos).get(columnIndex - 1); - wasNull = value == null; - if (value == null) - return 0; - long valueAsLong = Long.parseLong(value.toString()); - if (valueAsLong == Byte.MIN_VALUE) - return 0; - if (valueAsLong < Byte.MIN_VALUE || valueAsLong > Byte.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.TINYINT); - - return (byte) valueAsLong; - } - - private void throwRangeException(String valueAsString, int columnIndex, int jdbcType) throws SQLException { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_NUMERIC_VALUE_OUT_OF_RANGE, - "'" + valueAsString + "' in column '" + columnIndex + "' is outside valid range for the jdbcType " + TSDBConstants.jdbcType2TaosTypeName(jdbcType)); - } - - @Override - public short getShort(int columnIndex) throws SQLException { - checkAvailability(columnIndex, resultSet.get(pos).size()); - - Object value = resultSet.get(pos).get(columnIndex - 1); - wasNull = value == null; - if (value == null) - return 0; - long valueAsLong = Long.parseLong(value.toString()); - if (valueAsLong == Short.MIN_VALUE) - return 0; - if (valueAsLong < Short.MIN_VALUE || valueAsLong > Short.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.SMALLINT); - return (short) valueAsLong; - } - - @Override - public int getInt(int columnIndex) throws SQLException { - checkAvailability(columnIndex, resultSet.get(pos).size()); - - Object value = resultSet.get(pos).get(columnIndex - 1); - wasNull = value == null; - if (value == null) - return 0; - long valueAsLong = Long.parseLong(value.toString()); - if (valueAsLong == Integer.MIN_VALUE) - return 0; - if (valueAsLong < Integer.MIN_VALUE || valueAsLong > Integer.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.INTEGER); - return (int) valueAsLong; - } - - @Override - public long getLong(int columnIndex) throws SQLException { - checkAvailability(columnIndex, resultSet.get(pos).size()); - - Object value = resultSet.get(pos).get(columnIndex - 1); - wasNull = value == null; - if (value == null) - return 0; - if (value instanceof Timestamp) { - Timestamp ts = (Timestamp) value; - switch (this.timestampPrecision) { - case TimestampPrecision.MS: - default: - return ts.getTime(); - case TimestampPrecision.US: - return ts.getTime() * 1000 + ts.getNanos() / 1000 % 1000; - case TimestampPrecision.NS: - return ts.getTime() * 1000_000 + ts.getNanos() % 1000_000; - } - } - long valueAsLong = 0; - try { - valueAsLong = Long.parseLong(value.toString()); - if (valueAsLong == Long.MIN_VALUE) - return 0; - } catch (NumberFormatException e) { - throwRangeException(value.toString(), columnIndex, Types.BIGINT); - } - return valueAsLong; - } - - @Override - public float getFloat(int columnIndex) throws SQLException { - checkAvailability(columnIndex, resultSet.get(pos).size()); - - Object value = resultSet.get(pos).get(columnIndex - 1); - wasNull = value == null; - if (value == null) - return 0; - if (value instanceof Float) - return (float) value; - if (value instanceof Double) - return new Float((Double) value); - return Float.parseFloat(value.toString()); - } - - @Override - public double getDouble(int columnIndex) throws SQLException { - checkAvailability(columnIndex, resultSet.get(pos).size()); - - Object value = resultSet.get(pos).get(columnIndex - 1); - wasNull = value == null; - if (value == null) { - return 0; - } - if (value instanceof Double || value instanceof Float) - return (double) value; - return Double.parseDouble(value.toString()); - } - - @Override - public byte[] getBytes(int columnIndex) throws SQLException { - checkAvailability(columnIndex, resultSet.get(pos).size()); - - Object value = resultSet.get(pos).get(columnIndex - 1); - wasNull = value == null; - if (value == null) - return null; - if (value instanceof byte[]) - return (byte[]) value; - if (value instanceof String) - return ((String) value).getBytes(); - if (value instanceof Long) - return Longs.toByteArray((long) value); - if (value instanceof Integer) - return Ints.toByteArray((int) value); - if (value instanceof Short) - return Shorts.toByteArray((short) value); - if (value instanceof Byte) - return new byte[]{(byte) value}; - - return value.toString().getBytes(); - } - - @Override - public Date getDate(int columnIndex) throws SQLException { - checkAvailability(columnIndex, resultSet.get(pos).size()); - - Object value = resultSet.get(pos).get(columnIndex - 1); - wasNull = value == null; - if (value == null) - return null; - if (value instanceof Timestamp) - return new Date(((Timestamp) value).getTime()); - return Utils.parseDate(value.toString()); - } - - @Override - public Time getTime(int columnIndex) throws SQLException { - checkAvailability(columnIndex, resultSet.get(pos).size()); - - Object value = resultSet.get(pos).get(columnIndex - 1); - wasNull = value == null; - if (value == null) - return null; - if (value instanceof Timestamp) - return new Time(((Timestamp) value).getTime()); - Time time = null; - try { - time = Utils.parseTime(value.toString()); - } catch (DateTimeParseException ignored) { - } - return time; - } - - @Override - public Timestamp getTimestamp(int columnIndex) throws SQLException { - checkAvailability(columnIndex, resultSet.get(pos).size()); - - Object value = resultSet.get(pos).get(columnIndex - 1); - wasNull = value == null; - if (value == null) - return null; - if (value instanceof Timestamp) - return (Timestamp) value; - if (value instanceof Long) { - if (1_0000_0000_0000_0L > (long) value) - return Timestamp.from(Instant.ofEpochMilli((long) value)); - long epochSec = (long) value / 1000_000L; - long nanoAdjustment = (long) value % 1000_000L * 1000; - return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); - } - Timestamp ret; - try { - ret = Utils.parseTimestamp(value.toString()); - } catch (Exception e) { - ret = null; - wasNull = true; - } - return ret; - } - - @Override - public ResultSetMetaData getMetaData() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - return this.metaData; - } - - @Override - public Object getObject(int columnIndex) throws SQLException { - checkAvailability(columnIndex, resultSet.get(pos).size()); - - Object value = resultSet.get(pos).get(columnIndex - 1); - wasNull = value == null; - return value; - } - - @Override - public int findColumn(String columnLabel) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - int columnIndex = columnNames.indexOf(columnLabel); - if (columnIndex == -1) - throw new SQLException("cannot find Column in resultSet"); - return columnIndex + 1; - } - - @Override - public BigDecimal getBigDecimal(int columnIndex) throws SQLException { - checkAvailability(columnIndex, resultSet.get(pos).size()); - - Object value = resultSet.get(pos).get(columnIndex - 1); - wasNull = value == null; - if (value == null) - return null; - if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte) - return new BigDecimal(Long.parseLong(value.toString())); - if (value instanceof Double || value instanceof Float) - return BigDecimal.valueOf(Double.parseDouble(value.toString())); - if (value instanceof Timestamp) - return new BigDecimal(((Timestamp) value).getTime()); - BigDecimal ret; - try { - ret = new BigDecimal(value.toString()); - } catch (Exception e) { - ret = null; - } - return ret; - } - - @Override - public boolean isBeforeFirst() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - return this.pos == -1 && this.resultSet.size() != 0; - } - - @Override - public boolean isAfterLast() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - return this.pos >= resultSet.size() && this.resultSet.size() != 0; - } - - @Override - public boolean isFirst() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - return this.pos == 0; - } - - @Override - public boolean isLast() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - if (this.resultSet.size() == 0) - return false; - return this.pos == (this.resultSet.size() - 1); - } - - @Override - public void beforeFirst() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - synchronized (this) { - if (this.resultSet.size() > 0) { - this.pos = -1; - } - } - } - - @Override - public void afterLast() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - synchronized (this) { - if (this.resultSet.size() > 0) { - this.pos = this.resultSet.size(); - } - } - } - - @Override - public boolean first() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - if (this.resultSet.size() == 0) - return false; - - synchronized (this) { - this.pos = 0; - } - return true; - } - - @Override - public boolean last() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - if (this.resultSet.size() == 0) - return false; - synchronized (this) { - this.pos = this.resultSet.size() - 1; - } - return true; - } - - @Override - public int getRow() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - int row; - synchronized (this) { - if (this.pos < 0 || this.pos >= this.resultSet.size()) - return 0; - row = this.pos + 1; - } - return row; - } - - @Override - public boolean absolute(int row) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean relative(int rows) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean previous() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public String getNString(int columnIndex) throws SQLException { - return getString(columnIndex); - } - - @Override - public Statement getStatement() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - return this.statement; - } - - @Override - public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { - //TODO:did not use the specified timezone in cal - return getTimestamp(columnIndex); - } - - @Override - public boolean isClosed() throws SQLException { - return isClosed; - } - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSetMetaData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSetMetaData.java deleted file mode 100644 index 148f77974f..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSetMetaData.java +++ /dev/null @@ -1,187 +0,0 @@ -package com.taosdata.jdbc.rs; - -import com.taosdata.jdbc.TSDBConstants; -import com.taosdata.jdbc.WrapperImpl; - -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.sql.Types; -import java.util.Collections; -import java.util.List; - -public class RestfulResultSetMetaData extends WrapperImpl implements ResultSetMetaData { - - private final String database; - private final List fields; - - public RestfulResultSetMetaData(String database, List fields, RestfulResultSet resultSet) { - this.database = database; - this.fields = fields == null ? Collections.emptyList() : fields; - } - - public List getFields() { - return fields; - } - - @Override - public int getColumnCount() throws SQLException { - return fields.size(); - } - - @Override - public boolean isAutoIncrement(int column) throws SQLException { - return false; - } - - @Override - public boolean isCaseSensitive(int column) throws SQLException { - return false; - } - - @Override - public boolean isSearchable(int column) throws SQLException { - return true; - } - - @Override - public boolean isCurrency(int column) throws SQLException { - return false; - } - - @Override - public int isNullable(int column) throws SQLException { - if (column == 1) - return ResultSetMetaData.columnNoNulls; - return ResultSetMetaData.columnNullable; - } - - @Override - public boolean isSigned(int column) throws SQLException { - int type = this.fields.get(column - 1).type; - switch (type) { - case Types.TINYINT: - case Types.SMALLINT: - case Types.INTEGER: - case Types.BIGINT: - case Types.FLOAT: - case Types.DOUBLE: - return true; - default: - return false; - } - } - - @Override - public int getColumnDisplaySize(int column) throws SQLException { - return this.fields.get(column - 1).length; - } - - @Override - public String getColumnLabel(int column) throws SQLException { - return fields.get(column - 1).name; - } - - @Override - public String getColumnName(int column) throws SQLException { - return fields.get(column - 1).name; - } - - @Override - public String getSchemaName(int column) throws SQLException { - return ""; - } - - @Override - public int getPrecision(int column) throws SQLException { - int type = this.fields.get(column - 1).type; - switch (type) { - case Types.FLOAT: - return 5; - case Types.DOUBLE: - return 9; - case Types.BINARY: - case Types.NCHAR: - return this.fields.get(column - 1).length; - default: - return 0; - } - } - - @Override - public int getScale(int column) throws SQLException { - int type = this.fields.get(column - 1).type; - switch (type) { - case Types.FLOAT: - return 5; - case Types.DOUBLE: - return 9; - default: - return 0; - } - } - - @Override - public String getTableName(int column) throws SQLException { - return ""; - } - - @Override - public String getCatalogName(int column) throws SQLException { - return this.database; - } - - @Override - public int getColumnType(int column) throws SQLException { - return this.fields.get(column - 1).type; - } - - @Override - public String getColumnTypeName(int column) throws SQLException { - int taosType = fields.get(column - 1).taos_type; - return TSDBConstants.taosType2JdbcTypeName(taosType); - } - - @Override - public boolean isReadOnly(int column) throws SQLException { - return true; - } - - @Override - public boolean isWritable(int column) throws SQLException { - return false; - } - - @Override - public boolean isDefinitelyWritable(int column) throws SQLException { - return false; - } - - @Override - public String getColumnClassName(int column) throws SQLException { - int type = this.fields.get(column - 1).type; - String columnClassName = ""; - switch (type) { - case Types.BOOLEAN: - return Boolean.class.getName(); - case Types.TINYINT: - case Types.SMALLINT: - return Short.class.getName(); - case Types.INTEGER: - return Integer.class.getName(); - case Types.BIGINT: - return Long.class.getName(); - case Types.FLOAT: - return Float.class.getName(); - case Types.DOUBLE: - return Double.class.getName(); - case Types.TIMESTAMP: - return Timestamp.class.getName(); - case Types.BINARY: - case Types.NCHAR: - return String.class.getName(); - } - return columnClassName; - } - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulStatement.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulStatement.java deleted file mode 100644 index 7befd0007f..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulStatement.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.taosdata.jdbc.rs; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.taosdata.jdbc.AbstractStatement; -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.TSDBError; -import com.taosdata.jdbc.TSDBErrorNumbers; -import com.taosdata.jdbc.enums.TimestampFormat; -import com.taosdata.jdbc.utils.HttpClientPoolUtil; -import com.taosdata.jdbc.utils.SqlSyntaxValidator; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class RestfulStatement extends AbstractStatement { - - private boolean closed; - private String database; - private final RestfulConnection conn; - private static final String ROW_NAME = "affected_rows"; - - private volatile RestfulResultSet resultSet; - - public RestfulStatement(RestfulConnection conn, String database) { - this.conn = conn; - this.database = database; - } - - @Override - public ResultSet executeQuery(String sql) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - execute(sql); - return resultSet; - } - - @Override - public int executeUpdate(String sql) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - execute(sql); - return affectedRows; - } - - @Override - public void close() throws SQLException { - synchronized (RestfulStatement.class) { - if (!isClosed()) - this.closed = true; - } - } - - @Override - public boolean execute(String sql) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - //如果执行了use操作应该将当前Statement的catalog设置为新的database - boolean result = true; - - String response = HttpClientPoolUtil.execute(getUrl(), sql, this.conn.getAuth()); - JSONObject jsonObject = JSON.parseObject(response); - if (null == jsonObject) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "sql: " + sql); - } - if (jsonObject.getString("status").equals("error")) { - throw TSDBError.createSQLException(jsonObject.getInteger("code"), "sql: " + sql + ", desc: " + jsonObject.getString("desc")); - } - - if (SqlSyntaxValidator.isUseSql(sql)) { - this.database = sql.trim().replace("use", "").trim(); - this.conn.setCatalog(this.database); - this.conn.setClientInfo(TSDBDriver.PROPERTY_KEY_DBNAME, this.database); - result = false; - } else { - JSONArray head = jsonObject.getJSONArray("head"); - Integer rows = jsonObject.getInteger("rows"); - if (head.size() == 1 && ROW_NAME.equals(head.getString(0)) && rows == 1) { - this.resultSet = null; - this.affectedRows = getAffectedRows(jsonObject); - return false; - } else { - this.resultSet = new RestfulResultSet(database, this, jsonObject); - this.affectedRows = -1; - } - } - return result; - } - - - private String getUrl() throws SQLException { - String dbname = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_DBNAME); - String protocol = "http"; -// if (conn.isUseSsl()) { -// protocol = "https"; -// } - if (dbname == null || dbname.trim().isEmpty()) { - dbname = ""; - } else { - dbname = "/" + dbname.toLowerCase(); - } - TimestampFormat timestampFormat = TimestampFormat.valueOf(conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT).trim().toUpperCase()); - String url; - - switch (timestampFormat) { - case TIMESTAMP: - url = protocol + "://" + conn.getHost() + ":" + conn.getPort() + "/rest/sqlt" + dbname; - break; - case UTC: - url = protocol + "://" + conn.getHost() + ":" + conn.getPort() + "/rest/sqlutc" + dbname; - break; - default: - url = protocol + "://" + conn.getHost() + ":" + conn.getPort() + "/rest/sql" + dbname; - } - if (this.conn.getToken() != null && !"".equals(this.conn.getToken().trim())) { - url = url + "?token=" + this.conn.getToken(); - } - return url; - } - - private int getAffectedRows(JSONObject jsonObject) throws SQLException { - JSONArray head = jsonObject.getJSONArray("head"); - if (head.size() != 1 || !"affected_rows".equals(head.getString(0))) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE, "invalid variable: [" + head.toJSONString() + "]"); - JSONArray data = jsonObject.getJSONArray("data"); - if (data != null) { - return data.getJSONArray(0).getInteger(0); - } - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE, "invalid variable: [" + jsonObject.toJSONString() + "]"); - } - - @Override - public ResultSet getResultSet() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - return resultSet; - } - - @Override - public int getUpdateCount() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - return this.affectedRows; - } - - @Override - public Connection getConnection() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - return this.conn; - } - - @Override - public boolean isClosed() throws SQLException { - return closed; - } - - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/HttpClientPoolUtil.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/HttpClientPoolUtil.java deleted file mode 100644 index 2923ad76aa..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/HttpClientPoolUtil.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.taosdata.jdbc.utils; - -import com.taosdata.jdbc.TSDBError; -import com.taosdata.jdbc.TSDBErrorNumbers; -import org.apache.http.HeaderElement; -import org.apache.http.HeaderElementIterator; -import org.apache.http.HttpEntity; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.*; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.ConnectionKeepAliveStrategy; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.BasicHeaderElementIterator; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.EntityUtils; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.sql.SQLException; -import java.util.concurrent.TimeUnit; - -public class HttpClientPoolUtil { - - private static final String DEFAULT_CONTENT_TYPE = "application/json"; - private static final int DEFAULT_MAX_RETRY_COUNT = 5; - - public static final String DEFAULT_HTTP_KEEP_ALIVE = "true"; - public static final String DEFAULT_MAX_PER_ROUTE = "20"; - private static final int DEFAULT_HTTP_KEEP_TIME = -1; - private static String isKeepAlive; - - private static final ConnectionKeepAliveStrategy DEFAULT_KEEP_ALIVE_STRATEGY = (response, context) -> { - HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); - while (it.hasNext()) { - HeaderElement headerElement = it.nextElement(); - String param = headerElement.getName(); - String value = headerElement.getValue(); - if (value != null && param.equalsIgnoreCase("timeout")) { - try { - return Long.parseLong(value) * 1000; - } catch (NumberFormatException ignore) { - } - } - } - return DEFAULT_HTTP_KEEP_TIME * 1000; - }; - - private static CloseableHttpClient httpClient; - - public static void init(Integer connPoolSize, boolean keepAlive) { - if (httpClient == null) { - synchronized (HttpClientPoolUtil.class) { - if (httpClient == null) { - isKeepAlive = keepAlive ? HTTP.CONN_KEEP_ALIVE : HTTP.CONN_CLOSE; - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); - connectionManager.setMaxTotal(connPoolSize * 10); - connectionManager.setDefaultMaxPerRoute(connPoolSize); - httpClient = HttpClients.custom() - .setKeepAliveStrategy(DEFAULT_KEEP_ALIVE_STRATEGY) - .setConnectionManager(connectionManager) - .setRetryHandler((exception, executionCount, httpContext) -> executionCount < DEFAULT_MAX_RETRY_COUNT) - .build(); - } - } - } - } - - /*** execute GET request ***/ - public static String execute(String uri) throws SQLException { - HttpEntity httpEntity = null; - String responseBody = ""; - HttpRequestBase method = getRequest(uri, HttpGet.METHOD_NAME); - HttpContext context = HttpClientContext.create(); - - try (CloseableHttpResponse httpResponse = httpClient.execute(method, context)) { - httpEntity = httpResponse.getEntity(); - if (httpEntity != null) { - responseBody = EntityUtils.toString(httpEntity, StandardCharsets.UTF_8); - } - } catch (ClientProtocolException e) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_Protocol_Exception, e.getMessage()); - } catch (IOException exception) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_IOException, exception.getMessage()); - } finally { - if (httpEntity != null) { - EntityUtils.consumeQuietly(httpEntity); - } - } - return responseBody; - } - - /*** execute POST request ***/ - public static String execute(String uri, String data, String auth) throws SQLException { - - HttpEntityEnclosingRequestBase method = (HttpEntityEnclosingRequestBase) getRequest(uri, HttpPost.METHOD_NAME); - method.setHeader(HTTP.CONTENT_TYPE, "text/plain"); - method.setHeader(HTTP.CONN_DIRECTIVE, isKeepAlive); - method.setHeader("Authorization", auth); - method.setEntity(new StringEntity(data, StandardCharsets.UTF_8)); - HttpContext context = HttpClientContext.create(); - - HttpEntity httpEntity = null; - String responseBody = ""; - try (CloseableHttpResponse httpResponse = httpClient.execute(method, context)) { - httpEntity = httpResponse.getEntity(); - if (httpEntity == null) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_HTTP_ENTITY_IS_NULL, "httpEntity is null, sql: " + data); - } - responseBody = EntityUtils.toString(httpEntity, StandardCharsets.UTF_8); - } catch (ClientProtocolException e) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_Protocol_Exception, e.getMessage()); - } catch (IOException exception) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_IOException, exception.getMessage()); - } finally { - if (httpEntity != null) { - EntityUtils.consumeQuietly(httpEntity); - } - } - return responseBody; - } - - /*** create http request ***/ - private static HttpRequestBase getRequest(String uri, String methodName) { - HttpRequestBase method; - RequestConfig requestConfig = RequestConfig.custom() - .setExpectContinueEnabled(false) - .build(); - if (HttpPut.METHOD_NAME.equalsIgnoreCase(methodName)) { - method = new HttpPut(uri); - } else if (HttpPost.METHOD_NAME.equalsIgnoreCase(methodName)) { - method = new HttpPost(uri); - } else if (HttpGet.METHOD_NAME.equalsIgnoreCase(methodName)) { - method = new HttpGet(uri); - } else { - method = new HttpPost(uri); - } - method.addHeader(HTTP.CONTENT_TYPE, DEFAULT_CONTENT_TYPE); - method.addHeader("Accept", DEFAULT_CONTENT_TYPE); - method.setConfig(requestConfig); - return method; - } - - - public static void reset() { - synchronized (HttpClientPoolUtil.class) { - ClientConnectionManager cm = httpClient.getConnectionManager(); - cm.closeExpiredConnections(); - cm.closeIdleConnections(100, TimeUnit.MILLISECONDS); - } - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/NullType.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/NullType.java deleted file mode 100755 index 4ab1bc419f..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/NullType.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.taosdata.jdbc.utils; - -public class NullType { - private static final byte NULL_BOOL_VAL = 0x2; - private static final String NULL_STR = "null"; - - public String toString() { - return NullType.NULL_STR; - } - - public static boolean isBooleanNull(byte val) { - return val == NullType.NULL_BOOL_VAL; - } - - public static boolean isTinyIntNull(byte val) { - return val == Byte.MIN_VALUE; - } - - public static boolean isUnsignedTinyIntNull(byte val) { - return val == (byte) 0xFF; - } - - public static boolean isSmallIntNull(short val) { - return val == Short.MIN_VALUE; - } - - public static boolean isUnsignedSmallIntNull(short val) { - return val == (short) 0xFFFF; - } - - public static boolean isIntNull(int val) { - return val == Integer.MIN_VALUE; - } - - public static boolean isUnsignedIntNull(int val) { - return val == 0xFFFFFFFF; - } - - public static boolean isBigIntNull(long val) { - return val == Long.MIN_VALUE; - } - - public static boolean isUnsignedBigIntNull(long val) { - return val == 0xFFFFFFFFFFFFFFFFL; - } - - public static boolean isFloatNull(float val) { - return Float.isNaN(val); - } - - public static boolean isDoubleNull(double val) { - return Double.isNaN(val); - } - - public static boolean isBinaryNull(byte[] val, int length) { - if (length != Byte.BYTES) { - return false; - } - - return val[0] == (byte) 0xFF; - } - - public static boolean isNcharNull(byte[] val, int length) { - if (length != Integer.BYTES) { - return false; - } - - return (val[0] & val[1] & val[2] & val[3] & 0xFF) == 0xFF; - } - - public static byte getBooleanNull() { - return NullType.NULL_BOOL_VAL; - } - - public static byte getTinyintNull() { - return Byte.MIN_VALUE; - } - - public static int getIntNull() { - return Integer.MIN_VALUE; - } - - public static short getSmallIntNull() { - return Short.MIN_VALUE; - } - - public static long getBigIntNull() { - return Long.MIN_VALUE; - } - - public static int getFloatNull() { - return 0x7FF00000; - } - - public static long getDoubleNull() { - return 0x7FFFFF0000000000L; - } - - public static byte getBinaryNull() { - return (byte) 0xFF; - } - - public static byte[] getNcharNull() { - return new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}; - } - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/OSUtils.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/OSUtils.java deleted file mode 100644 index 1af3e9666c..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/OSUtils.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.taosdata.jdbc.utils; - -public class OSUtils { - private static final String OS = System.getProperty("os.name").toLowerCase(); - - public static boolean isWindows() { - return OS.contains("win"); - } - - public static boolean isMac() { - return OS.contains("mac"); - } - - public static boolean isLinux() { - return OS.contains("nux"); - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/SqlSyntaxValidator.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/SqlSyntaxValidator.java deleted file mode 100644 index e258b79fee..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/SqlSyntaxValidator.java +++ /dev/null @@ -1,22 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2019 TAOS Data, Inc. - * - * This program is free software: you can use, redistribute, and/or modify - * it under the terms of the GNU Affero General Public License, version 3 - * or later ("AGPL"), as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - *****************************************************************************/ -package com.taosdata.jdbc.utils; - -public class SqlSyntaxValidator { - - public static boolean isUseSql(String sql) { - return sql.trim().toLowerCase().startsWith("use"); - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/StringUtils.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/StringUtils.java deleted file mode 100644 index 5cd7091c33..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/StringUtils.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.taosdata.jdbc.utils; - -public class StringUtils { - public static boolean isEmpty(final CharSequence cs) { - return cs == null || cs.length() == 0; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/TaosInfo.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/TaosInfo.java deleted file mode 100644 index 583c2c3236..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/TaosInfo.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.taosdata.jdbc.utils; - -import javax.management.*; -import java.lang.management.ManagementFactory; -import java.util.concurrent.atomic.AtomicLong; - -public class TaosInfo implements TaosInfoMBean { - - private static volatile TaosInfo instance; - private final AtomicLong connect_open = new AtomicLong(); - private final AtomicLong connect_close = new AtomicLong(); - private final AtomicLong statement_count = new AtomicLong(); - - static { - try { - MBeanServer server = ManagementFactory.getPlatformMBeanServer(); - ObjectName name = new ObjectName("TaosInfoMBean:name=TaosInfo"); - server.registerMBean(TaosInfo.getInstance(), name); - } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException ignored) { - throw new RuntimeException("registerMBean failed"); - } - } - - @Override - public long getConnect_open() { - return connect_open.get(); - } - - @Override - public long getConnect_close() { - return connect_close.get(); - } - - @Override - public long getConnect_active() { - return connect_open.get() - connect_close.get(); - } - - @Override - public long getStatement_count() { - return statement_count.get(); - } - - /*******************************************************/ - - public void conn_open_increment() { - connect_open.incrementAndGet(); - } - - public void connect_close_increment() { - connect_close.incrementAndGet(); - } - - public void stmt_count_increment() { - statement_count.incrementAndGet(); - } - - /********************************************************************************/ - private TaosInfo() { - } - - public static TaosInfo getInstance() { - if (instance == null) { - synchronized (TaosInfo.class) { - if (instance == null) { - instance = new TaosInfo(); - } - } - } - return instance; - } - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/TaosInfoMBean.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/TaosInfoMBean.java deleted file mode 100644 index e16f41b2f5..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/TaosInfoMBean.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.taosdata.jdbc.utils; - -public interface TaosInfoMBean { - - long getConnect_open(); - - long getConnect_close(); - - long getConnect_active(); - - long getStatement_count(); - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/Utils.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/Utils.java deleted file mode 100644 index 6ec76fffd9..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/Utils.java +++ /dev/null @@ -1,233 +0,0 @@ -package com.taosdata.jdbc.utils; - -import com.google.common.collect.Range; -import com.google.common.collect.RangeSet; -import com.google.common.collect.TreeRangeSet; -import com.taosdata.jdbc.enums.TimestampPrecision; - -import java.nio.charset.StandardCharsets; -import java.sql.Date; -import java.sql.Time; -import java.sql.Timestamp; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.time.format.DateTimeParseException; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -public class Utils { - - private static final Pattern ptn = Pattern.compile(".*?'"); - private static final DateTimeFormatter milliSecFormatter = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd HH:mm:ss.SSS").toFormatter(); - private static final DateTimeFormatter microSecFormatter = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd HH:mm:ss.SSSSSS").toFormatter(); - private static final DateTimeFormatter nanoSecFormatter = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd HH:mm:ss.SSSSSSSSS").toFormatter(); - - public static Time parseTime(String timestampStr) throws DateTimeParseException { - LocalDateTime dateTime = parseLocalDateTime(timestampStr); - return dateTime != null ? Time.valueOf(dateTime.toLocalTime()) : null; - } - - public static Date parseDate(String timestampStr) { - LocalDateTime dateTime = parseLocalDateTime(timestampStr); - return dateTime != null ? Date.valueOf(String.valueOf(dateTime)) : null; - } - - public static Timestamp parseTimestamp(String timeStampStr) { - LocalDateTime dateTime = parseLocalDateTime(timeStampStr); - return dateTime != null ? Timestamp.valueOf(dateTime) : null; - } - - private static LocalDateTime parseLocalDateTime(String timeStampStr) { - try { - return parseMilliSecTimestamp(timeStampStr); - } catch (DateTimeParseException e) { - try { - return parseMicroSecTimestamp(timeStampStr); - } catch (DateTimeParseException ee) { - return parseNanoSecTimestamp(timeStampStr); - } - } - } - - private static LocalDateTime parseMilliSecTimestamp(String timeStampStr) throws DateTimeParseException { - return LocalDateTime.parse(timeStampStr, milliSecFormatter); - } - - private static LocalDateTime parseMicroSecTimestamp(String timeStampStr) throws DateTimeParseException { - return LocalDateTime.parse(timeStampStr, microSecFormatter); - } - - private static LocalDateTime parseNanoSecTimestamp(String timeStampStr) throws DateTimeParseException { - return LocalDateTime.parse(timeStampStr, nanoSecFormatter); - } - - public static String escapeSingleQuota(String origin) { - Matcher m = ptn.matcher(origin); - StringBuilder sb = new StringBuilder(); - int end = 0; - while (m.find()) { - end = m.end(); - String seg = origin.substring(m.start(), end); - int len = seg.length(); - if (len == 1) { - if ('\'' == seg.charAt(0)) { - sb.append("\\'"); - } else { - sb.append(seg); - } - } else { // len > 1 - sb.append(seg, 0, seg.length() - 2); - char lastcSec = seg.charAt(seg.length() - 2); - if (lastcSec == '\\') { - sb.append("\\'"); - } else { - sb.append(lastcSec); - sb.append("\\'"); - } - } - } - - if (end < origin.length()) { - sb.append(origin.substring(end)); - } - return sb.toString(); - } - - public static String getNativeSql(String rawSql, Object[] parameters) { - if (parameters == null || !rawSql.contains("?")) - return rawSql; - // toLowerCase - String preparedSql = rawSql.trim().toLowerCase(); - String[] clause = new String[]{"tags\\s*\\([\\s\\S]*?\\)", "where[\\s\\S]*"}; - Map placeholderPositions = new HashMap<>(); - RangeSet clauseRangeSet = TreeRangeSet.create(); - findPlaceholderPosition(preparedSql, placeholderPositions); - // find tags and where clause's position - findClauseRangeSet(preparedSql, clause, clauseRangeSet); - // find values clause's position - findValuesClauseRangeSet(preparedSql, clauseRangeSet); - - return transformSql(rawSql, parameters, placeholderPositions, clauseRangeSet); - } - - private static void findValuesClauseRangeSet(String preparedSql, RangeSet clauseRangeSet) { - Matcher matcher = Pattern.compile("(values||,)\\s*(\\([^)]*\\))").matcher(preparedSql); - while (matcher.find()) { - int start = matcher.start(2); - int end = matcher.end(2); - clauseRangeSet.add(Range.closedOpen(start, end)); - } - } - - private static void findClauseRangeSet(String preparedSql, String[] regexArr, RangeSet clauseRangeSet) { - clauseRangeSet.clear(); - for (String regex : regexArr) { - Matcher matcher = Pattern.compile(regex).matcher(preparedSql); - while (matcher.find()) { - int start = matcher.start(); - int end = matcher.end(); - clauseRangeSet.add(Range.closedOpen(start, end)); - } - } - } - - private static void findPlaceholderPosition(String preparedSql, Map placeholderPosition) { - placeholderPosition.clear(); - Matcher matcher = Pattern.compile("\\?").matcher(preparedSql); - int index = 0; - while (matcher.find()) { - int pos = matcher.start(); - placeholderPosition.put(index, pos); - index++; - } - } - - /*** - * - * @param rawSql - * @param paramArr - * @param placeholderPosition - * @param clauseRangeSet - * @return - */ - private static String transformSql(String rawSql, Object[] paramArr, Map placeholderPosition, RangeSet clauseRangeSet) { - String[] sqlArr = rawSql.split("\\?"); - - return IntStream.range(0, sqlArr.length).mapToObj(index -> { - if (index == paramArr.length) - return sqlArr[index]; - - Object para = paramArr[index]; - String paraStr; - if (para != null) { - if (para instanceof byte[]) { - paraStr = new String((byte[]) para, StandardCharsets.UTF_8); - } else { - paraStr = para.toString(); - } - // if para is timestamp or String or byte[] need to translate ' character - if (para instanceof Timestamp || para instanceof String || para instanceof byte[]) { - paraStr = Utils.escapeSingleQuota(paraStr); - - Integer pos = placeholderPosition.get(index); - boolean contains = clauseRangeSet.contains(pos); - if (contains) { - paraStr = "'" + paraStr + "'"; - } - } - } else { - paraStr = "NULL"; - } - return sqlArr[index] + paraStr; - }).collect(Collectors.joining()); - } - - public static String formatTimestamp(Timestamp timestamp) { - int nanos = timestamp.getNanos(); - if (nanos % 1000000L != 0) - return timestamp.toLocalDateTime().format(microSecFormatter); - return timestamp.toLocalDateTime().format(milliSecFormatter); - } - - public static int guessTimestampPrecision(String value) { - if (isMilliSecFormat(value)) - return TimestampPrecision.MS; - if (isMicroSecFormat(value)) - return TimestampPrecision.US; - if (isNanoSecFormat(value)) - return TimestampPrecision.NS; - return TimestampPrecision.MS; - } - - private static boolean isMilliSecFormat(String timestampStr) { - try { - milliSecFormatter.parse(timestampStr); - } catch (DateTimeParseException e) { - return false; - } - return true; - } - - private static boolean isMicroSecFormat(String timestampStr) { - try { - microSecFormatter.parse(timestampStr); - } catch (DateTimeParseException e) { - return false; - } - return true; - } - - private static boolean isNanoSecFormat(String timestampStr) { - try { - nanoSecFormatter.parse(timestampStr); - } catch (DateTimeParseException e) { - return false; - } - return true; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/AbstractWSResultSet.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/AbstractWSResultSet.java deleted file mode 100644 index 7df84c740c..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/AbstractWSResultSet.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.taosdata.jdbc.ws; - -import com.taosdata.jdbc.*; -import com.taosdata.jdbc.rs.RestfulResultSet; -import com.taosdata.jdbc.rs.RestfulResultSetMetaData; -import com.taosdata.jdbc.ws.entity.*; - -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; -import java.time.chrono.IsoChronology; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.time.format.ResolverStyle; -import java.time.temporal.ChronoField; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -public abstract class AbstractWSResultSet extends AbstractResultSet { - protected final Statement statement; - protected final Transport transport; - protected final RequestFactory factory; - protected final long queryId; - - protected volatile boolean isClosed; - // meta - protected final ResultSetMetaData metaData; - protected final List fields = new ArrayList<>(); - protected final List columnNames; - protected List fieldLength; - // data - protected List> result = new ArrayList<>(); - - protected int numOfRows = 0; - protected int rowIndex = 0; - private boolean isCompleted; - - public AbstractWSResultSet(Statement statement, Transport transport, RequestFactory factory, - QueryResp response, String database) throws SQLException { - this.statement = statement; - this.transport = transport; - this.factory = factory; - this.queryId = response.getId(); - columnNames = Arrays.asList(response.getFieldsNames()); - for (int i = 0; i < response.getFieldsCount(); i++) { - String colName = response.getFieldsNames()[i]; - int taosType = response.getFieldsTypes()[i]; - int jdbcType = TSDBConstants.taosType2JdbcType(taosType); - int length = response.getFieldsLengths()[i]; - fields.add(new RestfulResultSet.Field(colName, jdbcType, length, "", taosType)); - } - this.metaData = new RestfulResultSetMetaData(database, fields, null); - this.timestampPrecision = response.getPrecision(); - } - - private boolean forward() { - if (this.rowIndex > this.numOfRows) { - return false; - } - - return ((++this.rowIndex) < this.numOfRows); - } - - public void reset() { - this.rowIndex = 0; - } - - @Override - public boolean next() throws SQLException { - if (isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - } - - if (this.forward()) { - return true; - } - - Request request = factory.generateFetch(queryId); - CompletableFuture send = transport.send(request); - try { - Response response = send.get(); - FetchResp fetchResp = (FetchResp) response; - if (Code.SUCCESS.getCode() != fetchResp.getCode()) { -// TODO reWrite error type - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, fetchResp.getMessage()); - } - this.reset(); - if (fetchResp.isCompleted() || fetchResp.getRows() == 0) { - this.isCompleted = true; - return false; - } - fieldLength = Arrays.asList(fetchResp.getLengths()); - this.numOfRows = fetchResp.getRows(); - this.result = fetchJsonData(); - return true; - } catch (InterruptedException | ExecutionException e) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_IOException, e.getMessage()); - } - } - - public abstract List> fetchJsonData() throws SQLException, ExecutionException, InterruptedException; - - @Override - public void close() throws SQLException { - synchronized (this) { - if (!this.isClosed) { - this.isClosed = true; - if (result != null && !result.isEmpty() && !isCompleted) { - FetchReq fetchReq = new FetchReq(queryId, queryId); - transport.sendWithoutRep(new Request(Action.FREE_RESULT.getAction(), fetchReq)); - } - } - } - } - - @Override - public ResultSetMetaData getMetaData() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - return this.metaData; - } - - @Override - public boolean isClosed() throws SQLException { - return isClosed; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/BlockResultSet.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/BlockResultSet.java deleted file mode 100644 index 6cf2d06df4..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/BlockResultSet.java +++ /dev/null @@ -1,1040 +0,0 @@ -package com.taosdata.jdbc.ws; - -import com.google.common.primitives.Ints; -import com.google.common.primitives.Longs; -import com.google.common.primitives.Shorts; -import com.taosdata.jdbc.*; -import com.taosdata.jdbc.enums.TimestampPrecision; -import com.taosdata.jdbc.utils.NullType; -import com.taosdata.jdbc.utils.Utils; -import com.taosdata.jdbc.ws.entity.*; - -import java.io.UnsupportedEncodingException; -import java.math.BigDecimal; -import java.nio.ByteBuffer; -import java.sql.*; -import java.time.Instant; -import java.time.format.DateTimeParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -import static com.taosdata.jdbc.TSDBConstants.*; - -public class BlockResultSet extends AbstractWSResultSet { - - public BlockResultSet(Statement statement, Transport transport, RequestFactory factory, - QueryResp response, String database) throws SQLException { - super(statement, transport, factory, response, database); - } - - @Override - public List> fetchJsonData() throws ExecutionException, InterruptedException { - Request blockRequest = factory.generateFetchBlock(queryId); - CompletableFuture fetchFuture = transport.send(blockRequest); - FetchBlockResp resp = (FetchBlockResp) fetchFuture.get(); - ByteBuffer buffer = resp.getBuffer(); - List> list = new ArrayList<>(); - if (resp.getBuffer() != null) { - for (int i = 0; i < fields.size(); i++) { - List col = new ArrayList<>(numOfRows); - int type = fields.get(i).getTaosType(); - switch (type) { - case TSDB_DATA_TYPE_BOOL: - case TSDB_DATA_TYPE_TINYINT: - case TSDB_DATA_TYPE_UTINYINT: - for (int j = 0; j < numOfRows; j++) { - col.add(buffer.get()); - } - break; - case TSDB_DATA_TYPE_SMALLINT: - case TSDB_DATA_TYPE_USMALLINT: - for (int j = 0; j < numOfRows; j++) { - col.add(buffer.getShort()); - } - break; - case TSDB_DATA_TYPE_INT: - case TSDB_DATA_TYPE_UINT: - for (int j = 0; j < numOfRows; j++) { - col.add(buffer.getInt()); - } - break; - case TSDB_DATA_TYPE_BIGINT: - case TSDB_DATA_TYPE_UBIGINT: - case TSDB_DATA_TYPE_TIMESTAMP: - for (int j = 0; j < numOfRows; j++) { - col.add(buffer.getLong()); - } - break; - case TSDB_DATA_TYPE_FLOAT: - for (int j = 0; j < numOfRows; j++) { - col.add(buffer.getFloat()); - } - break; - case TSDB_DATA_TYPE_DOUBLE: - for (int j = 0; j < numOfRows; j++) { - col.add(buffer.getDouble()); - } - break; - case TSDB_DATA_TYPE_BINARY: { - byte[] bytes = new byte[fieldLength.get(i) - 2]; - for (int j = 0; j < numOfRows; j++) { - short s = buffer.getShort(); - buffer.get(bytes); - - byte[] tmp = Arrays.copyOf(bytes, s); - if (NullType.isBinaryNull(tmp, s)) { - col.add(null); - continue; - } - col.add(tmp); - } - break; - } - case TSDB_DATA_TYPE_NCHAR: - case TSDB_DATA_TYPE_JSON: { - byte[] bytes = new byte[fieldLength.get(i) - 2]; - for (int j = 0; j < numOfRows; j++) { - short s = buffer.getShort(); - buffer.get(bytes); - - byte[] tmp = Arrays.copyOf(bytes, s); - if (NullType.isNcharNull(tmp, s)) { - col.add(null); - continue; - } - col.add(tmp); - } - break; - } - default: - // unknown type, do nothing - col.add(null); - break; - } - list.add(col); - } - } - return list; - } - - private Timestamp parseTimestampColumnData(long value) { - if (TimestampPrecision.MS == this.timestampPrecision) - return new Timestamp(value); - - if (TimestampPrecision.US == this.timestampPrecision) { - long epochSec = value / 1000_000L; - long nanoAdjustment = value % 1000_000L * 1000L; - return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); - } - if (TimestampPrecision.NS == this.timestampPrecision) { - long epochSec = value / 1000_000_000L; - long nanoAdjustment = value % 1000_000_000L; - return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); - } - return null; - } - - public Object parseValue(int columnIndex) { - Object source = result.get(columnIndex - 1).get(rowIndex); - if (null == source) - return null; - - int type = fields.get(columnIndex - 1).getTaosType(); - switch (type) { - case TSDB_DATA_TYPE_BOOL: { - byte val = (byte) source; - if (NullType.isBooleanNull(val)) { - return null; - } - return (val == 0x0) ? Boolean.FALSE : Boolean.TRUE; - } - case TSDB_DATA_TYPE_TINYINT: { - byte val = (byte) source; - if (NullType.isTinyIntNull(val)) { - return null; - } - return val; - } - case TSDB_DATA_TYPE_UTINYINT: { - byte val = (byte) source; - if (NullType.isUnsignedTinyIntNull(val)) { - return null; - } - return (short) val & 0xFF; - } - case TSDB_DATA_TYPE_SMALLINT: { - short val = (short) source; - if (NullType.isSmallIntNull(val)) { - return null; - } - return val; - } - case TSDB_DATA_TYPE_USMALLINT: { - short val = (short) source; - if (NullType.isUnsignedSmallIntNull(val)) { - return null; - } - return val & 0xFFFF; - } - case TSDB_DATA_TYPE_INT: { - int val = (int) source; - if (NullType.isIntNull(val)) { - return null; - } - return val; - } - case TSDB_DATA_TYPE_UINT: { - int val = (int) source; - if (NullType.isUnsignedIntNull(val)) { - return null; - } - return val & 0xFFFFFFFFL; - } - case TSDB_DATA_TYPE_BIGINT: { - long val = (long) source; - if (NullType.isBigIntNull(val)) { - return null; - } - return val; - } - case TSDB_DATA_TYPE_TIMESTAMP: { - long val = (long) source; - if (NullType.isBigIntNull(val)) { - return null; - } - return parseTimestampColumnData(val); - } - case TSDB_DATA_TYPE_UBIGINT: { - long val = (long) source; - if (NullType.isUnsignedBigIntNull(val)) { - return null; - } - BigDecimal tmp = new BigDecimal(val >>> 1).multiply(new BigDecimal(2)); - return (val & 0x1) == 0x1 ? tmp.add(new BigDecimal(1)) : tmp; - } - case TSDB_DATA_TYPE_FLOAT: { - float val = (float) source; - if (NullType.isFloatNull(val)) { - return null; - } - return val; - } - case TSDB_DATA_TYPE_DOUBLE: { - double val = (double) source; - if (NullType.isDoubleNull(val)) { - return null; - } - return val; - } - case TSDB_DATA_TYPE_BINARY: { - return source; - } - case TSDB_DATA_TYPE_NCHAR: - case TSDB_DATA_TYPE_JSON: { - String charset = TaosGlobalConfig.getCharset(); - try { - return new String((byte[]) source, charset); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - } - default: - // unknown type, do nothing - return null; - } - } - - @Override - public String getString(int columnIndex) throws SQLException { - checkAvailability(columnIndex, fields.size()); - - Object value = parseValue(columnIndex); - if (value == null) { - wasNull = true; -// return new NullType().toString(); - return null; - } - if (value instanceof String) - return (String) value; - - if (value instanceof byte[]) { - String charset = TaosGlobalConfig.getCharset(); - try { - return new String((byte[]) value, charset); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - } - return value.toString(); - } - - @Override - public boolean getBoolean(int columnIndex) throws SQLException { - checkAvailability(columnIndex, fields.size()); - - Object value = parseValue(columnIndex); - if (value == null) { - wasNull = true; - return false; - } - if (value instanceof Boolean) - return (boolean) value; - - int taosType = fields.get(columnIndex - 1).getTaosType(); - switch (taosType) { - case TSDB_DATA_TYPE_TINYINT: - return ((byte) value == 0) ? Boolean.FALSE : Boolean.TRUE; - case TSDB_DATA_TYPE_UTINYINT: - case TSDB_DATA_TYPE_SMALLINT: - return ((short) value == 0) ? Boolean.FALSE : Boolean.TRUE; - case TSDB_DATA_TYPE_USMALLINT: - case TSDB_DATA_TYPE_INT: - return ((int) value == 0) ? Boolean.FALSE : Boolean.TRUE; - case TSDB_DATA_TYPE_UINT: - case TSDB_DATA_TYPE_BIGINT: - case TSDB_DATA_TYPE_TIMESTAMP: - return (((long) value) == 0L) ? Boolean.FALSE : Boolean.TRUE; - case TSDB_DATA_TYPE_UBIGINT: - return value.equals(new BigDecimal(0)) ? Boolean.FALSE : Boolean.TRUE; - - case TSDB_DATA_TYPE_FLOAT: - return (((float) value) == 0) ? Boolean.FALSE : Boolean.TRUE; - case TSDB_DATA_TYPE_DOUBLE: { - return (((double) value) == 0) ? Boolean.FALSE : Boolean.TRUE; - } - - case TSDB_DATA_TYPE_NCHAR: - case TSDB_DATA_TYPE_JSON: { - if ("TRUE".compareToIgnoreCase((String) value) == 0) { - return Boolean.TRUE; - } else if ("FALSE".compareToIgnoreCase((String) value) == 0) { - return Boolean.TRUE; - } else { - throw new SQLDataException(); - } - } - case TSDB_DATA_TYPE_BINARY: { - String charset = TaosGlobalConfig.getCharset(); - String tmp; - try { - tmp = new String((byte[]) value, charset); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - if ("TRUE".compareToIgnoreCase(tmp) == 0) { - return Boolean.TRUE; - } else if ("FALSE".compareToIgnoreCase(tmp) == 0) { - return Boolean.TRUE; - } else { - throw new SQLDataException(); - } - } - } - - return Boolean.FALSE; - } - - @Override - public byte getByte(int columnIndex) throws SQLException { - checkAvailability(columnIndex, fields.size()); - - Object value = parseValue(columnIndex); - if (value == null) { - wasNull = true; - return 0; - } - if (value instanceof Byte) - return (byte) value; - - int taosType = fields.get(columnIndex - 1).getTaosType(); - switch (taosType) { - case TSDB_DATA_TYPE_BOOL: - return (boolean) value ? (byte) 1 : (byte) 0; - case TSDB_DATA_TYPE_UTINYINT: - case TSDB_DATA_TYPE_SMALLINT: { - short tmp = (short) value; - if (tmp < Byte.MIN_VALUE || tmp > Byte.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.TINYINT); - return (byte) tmp; - } - case TSDB_DATA_TYPE_USMALLINT: - case TSDB_DATA_TYPE_INT: { - int tmp = (int) value; - if (tmp < Byte.MIN_VALUE || tmp > Byte.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.TINYINT); - return (byte) tmp; - } - - case TSDB_DATA_TYPE_BIGINT: - case TSDB_DATA_TYPE_UINT: { - long tmp = (long) value; - if (tmp < Byte.MIN_VALUE || tmp > Byte.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.TINYINT); - return (byte) tmp; - } - case TSDB_DATA_TYPE_UBIGINT: { - BigDecimal tmp = (BigDecimal) value; - if (tmp.compareTo(new BigDecimal(Byte.MIN_VALUE)) < 0 || tmp.compareTo(new BigDecimal(Byte.MAX_VALUE)) > 0) - throwRangeException(value.toString(), columnIndex, Types.TINYINT); - - return tmp.byteValue(); - } - case TSDB_DATA_TYPE_FLOAT: { - float tmp = (float) value; - if (tmp < Byte.MIN_VALUE || tmp > Byte.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.TINYINT); - return (byte) tmp; - } - case TSDB_DATA_TYPE_DOUBLE: { - double tmp = (double) value; - if (tmp < Byte.MIN_VALUE || tmp > Byte.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.TINYINT); - return (byte) tmp; - } - - case TSDB_DATA_TYPE_NCHAR: - case TSDB_DATA_TYPE_JSON: - return Byte.parseByte((String) value); - case TSDB_DATA_TYPE_BINARY: { - String charset = TaosGlobalConfig.getCharset(); - String tmp; - try { - tmp = new String((byte[]) value, charset); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - return Byte.parseByte(tmp); - } - } - - return 0; - } - - private void throwRangeException(String valueAsString, int columnIndex, int jdbcType) throws SQLException { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_NUMERIC_VALUE_OUT_OF_RANGE, - "'" + valueAsString + "' in column '" + columnIndex + "' is outside valid range for the jdbcType " + jdbcType2TaosTypeName(jdbcType)); - } - - @Override - public short getShort(int columnIndex) throws SQLException { - checkAvailability(columnIndex, fields.size()); - - Object value = parseValue(columnIndex); - if (value == null) { - wasNull = true; - return 0; - } - if (value instanceof Short) - return (short) value; - - int taosType = fields.get(columnIndex - 1).getTaosType(); - switch (taosType) { - case TSDB_DATA_TYPE_BOOL: - return (boolean) value ? (short) 1 : (short) 0; - case TSDB_DATA_TYPE_TINYINT: - return (byte) value; - case TSDB_DATA_TYPE_USMALLINT: - case TSDB_DATA_TYPE_INT: { - int tmp = (int) value; - if (tmp < Short.MIN_VALUE || tmp > Short.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.SMALLINT); - return (short) tmp; - } - - case TSDB_DATA_TYPE_BIGINT: - case TSDB_DATA_TYPE_UINT: { - long tmp = (long) value; - if (tmp < Short.MIN_VALUE || tmp > Short.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.SMALLINT); - return (short) tmp; - } - case TSDB_DATA_TYPE_UBIGINT: { - BigDecimal tmp = (BigDecimal) value; - if (tmp.compareTo(new BigDecimal(Short.MIN_VALUE)) < 0 || tmp.compareTo(new BigDecimal(Short.MAX_VALUE)) > 0) - throwRangeException(value.toString(), columnIndex, Types.SMALLINT); - return tmp.shortValue(); - } - case TSDB_DATA_TYPE_FLOAT: { - float tmp = (float) value; - if (tmp < Short.MIN_VALUE || tmp > Short.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.SMALLINT); - return (short) tmp; - } - case TSDB_DATA_TYPE_DOUBLE: { - double tmp = (double) value; - if (tmp < Short.MIN_VALUE || tmp > Short.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.SMALLINT); - return (short) tmp; - } - - case TSDB_DATA_TYPE_NCHAR: - case TSDB_DATA_TYPE_JSON: - return Short.parseShort((String) value); - case TSDB_DATA_TYPE_BINARY: { - String charset = TaosGlobalConfig.getCharset(); - String tmp; - try { - tmp = new String((byte[]) value, charset); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - return Short.parseShort(tmp); - } - } - return 0; - } - - @Override - public int getInt(int columnIndex) throws SQLException { - checkAvailability(columnIndex, fields.size()); - - Object value = parseValue(columnIndex); - if (value == null) { - wasNull = true; - return 0; - } - if (value instanceof Integer) - return (int) value; - - int taosType = fields.get(columnIndex - 1).getTaosType(); - switch (taosType) { - case TSDB_DATA_TYPE_BOOL: - return (boolean) value ? 1 : 0; - case TSDB_DATA_TYPE_TINYINT: - return (byte) value; - case TSDB_DATA_TYPE_UTINYINT: - case TSDB_DATA_TYPE_SMALLINT: - return (short) value; - case TSDB_DATA_TYPE_USMALLINT: - case TSDB_DATA_TYPE_INT: - return (int) value; - - case TSDB_DATA_TYPE_BIGINT: - case TSDB_DATA_TYPE_UINT: { - long tmp = (long) value; - if (tmp < Integer.MIN_VALUE || tmp > Integer.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.INTEGER); - return (int) tmp; - } - case TSDB_DATA_TYPE_UBIGINT: { - BigDecimal tmp = (BigDecimal) value; - if (tmp.compareTo(new BigDecimal(Integer.MIN_VALUE)) < 0 || tmp.compareTo(new BigDecimal(Integer.MAX_VALUE)) > 0) - throwRangeException(value.toString(), columnIndex, Types.INTEGER); - return tmp.intValue(); - } - case TSDB_DATA_TYPE_FLOAT: { - float tmp = (float) value; - if (tmp < Integer.MIN_VALUE || tmp > Integer.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.INTEGER); - return (int) tmp; - } - case TSDB_DATA_TYPE_DOUBLE: { - double tmp = (double) value; - if (tmp < Integer.MIN_VALUE || tmp > Integer.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.INTEGER); - return (int) tmp; - } - - case TSDB_DATA_TYPE_NCHAR: - case TSDB_DATA_TYPE_JSON: - return Integer.parseInt((String) value); - case TSDB_DATA_TYPE_BINARY: { - String charset = TaosGlobalConfig.getCharset(); - String tmp; - try { - tmp = new String((byte[]) value, charset); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - return Integer.parseInt(tmp); - } - } - return 0; - } - - @Override - public long getLong(int columnIndex) throws SQLException { - checkAvailability(columnIndex, fields.size()); - - Object value = parseValue(columnIndex); - if (value == null) { - wasNull = true; - return 0; - } - if (value instanceof Long) - return (long) value; - if (value instanceof Timestamp) { - Timestamp ts = (Timestamp) value; - switch (this.timestampPrecision) { - case TimestampPrecision.MS: - default: - return ts.getTime(); - case TimestampPrecision.US: - return ts.getTime() * 1000 + ts.getNanos() / 1000 % 1000; - case TimestampPrecision.NS: - return ts.getTime() * 1000_000 + ts.getNanos() % 1000_000; - } - } - - int taosType = fields.get(columnIndex - 1).getTaosType(); - switch (taosType) { - case TSDB_DATA_TYPE_BOOL: - return (boolean) value ? 1 : 0; - case TSDB_DATA_TYPE_TINYINT: - return (byte) value; - case TSDB_DATA_TYPE_UTINYINT: - case TSDB_DATA_TYPE_SMALLINT: - return (short) value; - case TSDB_DATA_TYPE_USMALLINT: - case TSDB_DATA_TYPE_INT: - return (int) value; - case TSDB_DATA_TYPE_BIGINT: - case TSDB_DATA_TYPE_UINT: - return (long) value; - - case TSDB_DATA_TYPE_UBIGINT: { - BigDecimal tmp = (BigDecimal) value; - if (tmp.compareTo(new BigDecimal(Long.MIN_VALUE)) < 0 || tmp.compareTo(new BigDecimal(Long.MAX_VALUE)) > 0) - throwRangeException(value.toString(), columnIndex, Types.BIGINT); - return tmp.longValue(); - } - case TSDB_DATA_TYPE_TIMESTAMP: - return ((Timestamp) value).getTime(); - case TSDB_DATA_TYPE_FLOAT: { - float tmp = (float) value; - if (tmp < Long.MIN_VALUE || tmp > Long.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.BIGINT); - return (long) tmp; - } - case TSDB_DATA_TYPE_DOUBLE: { - double tmp = (Double) value; - if (tmp < Long.MIN_VALUE || tmp > Long.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.BIGINT); - return (long) tmp; - } - - case TSDB_DATA_TYPE_NCHAR: - case TSDB_DATA_TYPE_JSON: - return Long.parseLong((String) value); - case TSDB_DATA_TYPE_BINARY: { - String charset = TaosGlobalConfig.getCharset(); - String tmp; - try { - tmp = new String((byte[]) value, charset); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - return Long.parseLong(tmp); - } - } - return 0; - } - - @Override - public float getFloat(int columnIndex) throws SQLException { - checkAvailability(columnIndex, fields.size()); - - Object value = parseValue(columnIndex); - if (value == null) { - wasNull = true; - return 0; - } - if (value instanceof Float) - return (float) value; - - int taosType = fields.get(columnIndex - 1).getTaosType(); - switch (taosType) { - case TSDB_DATA_TYPE_BOOL: - return (boolean) value ? (float) 1 : (float) 0; - case TSDB_DATA_TYPE_TINYINT: - return (byte) value; - case TSDB_DATA_TYPE_UTINYINT: - case TSDB_DATA_TYPE_SMALLINT: - return (short) value; - case TSDB_DATA_TYPE_USMALLINT: - case TSDB_DATA_TYPE_INT: - return (int) value; - case TSDB_DATA_TYPE_BIGINT: - case TSDB_DATA_TYPE_UINT: - return (long) value; - - case TSDB_DATA_TYPE_UBIGINT: { - BigDecimal tmp = (BigDecimal) value; - if (tmp.compareTo(new BigDecimal(Float.MIN_VALUE)) < 0 || tmp.compareTo(new BigDecimal(Float.MAX_VALUE)) > 0) - throwRangeException(value.toString(), columnIndex, Types.FLOAT); - return tmp.floatValue(); - } - case TSDB_DATA_TYPE_DOUBLE:{ - Double tmp = (double) value; - if (tmp < Float.MIN_VALUE || tmp > Float.MAX_VALUE) - throwRangeException(value.toString(), columnIndex, Types.FLOAT); - return Float.parseFloat(String.valueOf(tmp)); - } - - case TSDB_DATA_TYPE_NCHAR: - case TSDB_DATA_TYPE_JSON: - return Float.parseFloat(value.toString()); - case TSDB_DATA_TYPE_BINARY: { - String charset = TaosGlobalConfig.getCharset(); - String tmp; - try { - tmp = new String((byte[]) value, charset); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - return Float.parseFloat(tmp); - } - } - return 0; - } - - @Override - public double getDouble(int columnIndex) throws SQLException { - checkAvailability(columnIndex, fields.size()); - - Object value = parseValue(columnIndex); - if (value == null) { - wasNull = true; - return 0; - } - if (value instanceof Double) - return (double) value; - if (value instanceof Float) - return Double.parseDouble(String.valueOf(value)); - - int taosType = fields.get(columnIndex - 1).getTaosType(); - switch (taosType) { - case TSDB_DATA_TYPE_BOOL: - return (boolean) value ? 1 : 0; - case TSDB_DATA_TYPE_TINYINT: - return (byte) value; - case TSDB_DATA_TYPE_UTINYINT: - case TSDB_DATA_TYPE_SMALLINT: - return (short) value; - case TSDB_DATA_TYPE_USMALLINT: - case TSDB_DATA_TYPE_INT: - return (int) value; - case TSDB_DATA_TYPE_BIGINT: - case TSDB_DATA_TYPE_UINT: - return (long) value; - - case TSDB_DATA_TYPE_UBIGINT: { - BigDecimal tmp = (BigDecimal) value; - if (tmp.compareTo(new BigDecimal(Double.MIN_VALUE)) < 0 || tmp.compareTo(new BigDecimal(Double.MAX_VALUE)) > 0) - throwRangeException(value.toString(), columnIndex, Types.DOUBLE); - return tmp.floatValue(); - } - - case TSDB_DATA_TYPE_NCHAR: - case TSDB_DATA_TYPE_JSON: - return Double.parseDouble(value.toString()); - case TSDB_DATA_TYPE_BINARY: { - String charset = TaosGlobalConfig.getCharset(); - String tmp; - try { - tmp = new String((byte[]) value, charset); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - return Double.parseDouble(tmp); - } - } - return 0; - } - - @Override - public byte[] getBytes(int columnIndex) throws SQLException { - checkAvailability(columnIndex, fields.size()); - - Object value = parseValue(columnIndex); - if (value == null) { - wasNull = true; - return null; - } - if (value instanceof byte[]) - return (byte[]) value; - if (value instanceof String) - return ((String) value).getBytes(); - if (value instanceof Long) - return Longs.toByteArray((long) value); - if (value instanceof Integer) - return Ints.toByteArray((int) value); - if (value instanceof Short) - return Shorts.toByteArray((short) value); - if (value instanceof Byte) - return new byte[]{(byte) value}; - - return value.toString().getBytes(); - } - - @Override - public Date getDate(int columnIndex) throws SQLException { - checkAvailability(columnIndex, fields.size()); - - Object value = parseValue(columnIndex); - if (value == null) { - wasNull = true; - return null; - } - if (value instanceof Timestamp) - return new Date(((Timestamp) value).getTime()); - return Utils.parseDate(value.toString()); - } - - @Override - public Time getTime(int columnIndex) throws SQLException { - checkAvailability(columnIndex, fields.size()); - - Object value = parseValue(columnIndex); - if (value == null) { - wasNull = true; - return null; - } - if (value instanceof Timestamp) - return new Time(((Timestamp) value).getTime()); - Time time = null; - try { - time = Utils.parseTime(value.toString()); - } catch (DateTimeParseException e) { - throw new RuntimeException(e.getMessage()); - } - return time; - } - - @Override - public Timestamp getTimestamp(int columnIndex) throws SQLException { - checkAvailability(columnIndex, fields.size()); - - Object value = parseValue(columnIndex); - if (value == null) { - wasNull = true; - return null; - } - if (value instanceof Timestamp) - return (Timestamp) value; - if (value instanceof Long) { - return parseTimestampColumnData((long) value); - } - Timestamp ret; - try { - ret = Utils.parseTimestamp(value.toString()); - } catch (Exception e) { - ret = null; - wasNull = true; - } - return ret; - } - - @Override - public Object getObject(int columnIndex) throws SQLException { - checkAvailability(columnIndex, fields.size()); - - Object value = parseValue(columnIndex); - wasNull = value == null; - return value; - } - - @Override - public int findColumn(String columnLabel) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - int columnIndex = columnNames.indexOf(columnLabel); - if (columnIndex == -1) - throw new SQLException("cannot find Column in result"); - return columnIndex + 1; - } - - @Override - public BigDecimal getBigDecimal(int columnIndex) throws SQLException { - checkAvailability(columnIndex, fields.size()); - - Object value = parseValue(columnIndex); - if (value == null) { - wasNull = true; - return null; - } - if (value instanceof BigDecimal) - return (BigDecimal) value; - - - int taosType = fields.get(columnIndex - 1).getTaosType(); - switch (taosType) { - case TSDB_DATA_TYPE_BOOL: - return (boolean) value ? new BigDecimal(1) : new BigDecimal(0); - case TSDB_DATA_TYPE_TINYINT: - return new BigDecimal((byte) value); - case TSDB_DATA_TYPE_UTINYINT: - case TSDB_DATA_TYPE_SMALLINT: - return new BigDecimal((short) value); - case TSDB_DATA_TYPE_USMALLINT: - case TSDB_DATA_TYPE_INT: - return new BigDecimal((int) value); - case TSDB_DATA_TYPE_BIGINT: - case TSDB_DATA_TYPE_UINT: - return new BigDecimal((long) value); - - case TSDB_DATA_TYPE_FLOAT: - return BigDecimal.valueOf((float) value); - case TSDB_DATA_TYPE_DOUBLE: - return BigDecimal.valueOf((double) value); - - case TSDB_DATA_TYPE_TIMESTAMP: - return new BigDecimal(((Timestamp) value).getTime()); - case TSDB_DATA_TYPE_NCHAR: - case TSDB_DATA_TYPE_JSON: - return new BigDecimal(value.toString()); - case TSDB_DATA_TYPE_BINARY: { - String charset = TaosGlobalConfig.getCharset(); - String tmp; - try { - tmp = new String((byte[]) value, charset); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage()); - } - return new BigDecimal(tmp); - } - } - - return new BigDecimal(0); - } - - @Override - public boolean isBeforeFirst() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - return this.rowIndex == -1 && this.numOfRows != 0; - } - - @Override - public boolean isAfterLast() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - return this.rowIndex >= numOfRows && this.numOfRows != 0; - } - - @Override - public boolean isFirst() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - return this.rowIndex == 0; - } - - @Override - public boolean isLast() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - if (this.numOfRows == 0) - return false; - return this.rowIndex == (this.numOfRows - 1); - } - - @Override - public void beforeFirst() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - synchronized (this) { - if (this.numOfRows > 0) { - this.rowIndex = -1; - } - } - } - - @Override - public void afterLast() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - synchronized (this) { - if (this.numOfRows > 0) { - this.rowIndex = this.numOfRows; - } - } - } - - @Override - public boolean first() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - if (this.numOfRows == 0) - return false; - - synchronized (this) { - this.rowIndex = 0; - } - return true; - } - - @Override - public boolean last() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - if (this.numOfRows == 0) - return false; - synchronized (this) { - this.rowIndex = this.numOfRows - 1; - } - return true; - } - - @Override - public int getRow() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - int row; - synchronized (this) { - if (this.rowIndex < 0 || this.rowIndex >= this.numOfRows) - return 0; - row = this.rowIndex + 1; - } - return row; - } - - @Override - public boolean absolute(int row) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean relative(int rows) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public boolean previous() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } - - @Override - public String getNString(int columnIndex) throws SQLException { - return getString(columnIndex); - } - - @Override - public Statement getStatement() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - - return this.statement; - } - - @Override - public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { - return getTimestamp(columnIndex); - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/InFlightRequest.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/InFlightRequest.java deleted file mode 100644 index 37349c4332..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/InFlightRequest.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.taosdata.jdbc.ws; - -import com.taosdata.jdbc.ws.entity.Action; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.*; - -/** - * Unfinished execution - */ -public class InFlightRequest { - private final int timeoutSec; - private final Semaphore semaphore; - private final Map> futureMap = new HashMap<>(); - private final Map> expireMap = new HashMap<>(); - private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(r -> { - Thread t = new Thread(r); - t.setName("timer-" + t.getId()); - return t; - }); - - public InFlightRequest(int timeoutSec, int concurrentNum) { - this.timeoutSec = timeoutSec; - this.semaphore = new Semaphore(concurrentNum); - scheduledExecutorService.scheduleWithFixedDelay(this::removeTimeoutFuture, - timeoutSec, timeoutSec, TimeUnit.MILLISECONDS); - Runtime.getRuntime().addShutdownHook(new Thread(scheduledExecutorService::shutdown)); - for (Action value : Action.values()) { - String action = value.getAction(); - if (Action.CONN.getAction().equals(action)) - continue; - futureMap.put(action, new ConcurrentHashMap<>()); - expireMap.put(action, new PriorityBlockingQueue<>()); - } - } - - public void put(ResponseFuture rf) throws InterruptedException, TimeoutException { - if (semaphore.tryAcquire(timeoutSec, TimeUnit.MILLISECONDS)) { - futureMap.get(rf.getAction()).put(rf.getId(), rf); - expireMap.get(rf.getAction()).put(rf); - } else { - throw new TimeoutException(); - } - } - - public ResponseFuture remove(String action, Long id) { - ResponseFuture future = futureMap.get(action).remove(id); - if (null != future) { - expireMap.get(action).remove(future); - semaphore.release(); - } - return future; - } - - private void removeTimeoutFuture() { - expireMap.forEach((k, v) -> { - while (true) { - ResponseFuture response = v.peek(); - if (null == response || (System.nanoTime() - response.getTimestamp()) < timeoutSec * 1_000_000L) - break; - - try { - v.poll(); - futureMap.get(k).remove(response.getId()); - response.getFuture().completeExceptionally(new TimeoutException()); - } finally { - semaphore.release(); - } - } - }); - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/ResponseFuture.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/ResponseFuture.java deleted file mode 100644 index 5ce7e86572..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/ResponseFuture.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.taosdata.jdbc.ws; - -import com.taosdata.jdbc.ws.entity.Response; - -import java.util.concurrent.CompletableFuture; - -public class ResponseFuture implements Comparable { - private final String action; - private final Long id; - private final CompletableFuture future; - private final long timestamp; - - public ResponseFuture(String action, Long id, CompletableFuture future) { - this.action = action; - this.id = id; - this.future = future; - timestamp = System.nanoTime(); - } - - public String getAction() { - return action; - } - - public Long getId() { - return id; - } - - public CompletableFuture getFuture() { - return future; - } - - long getTimestamp() { - return timestamp; - } - - @Override - public int compareTo(ResponseFuture rf) { - long r = this.timestamp - rf.timestamp; - if (r > 0) return 1; - if (r < 0) return -1; - return 0; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/Transport.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/Transport.java deleted file mode 100644 index 94b5d9b6c8..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/Transport.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.taosdata.jdbc.ws; - -import com.taosdata.jdbc.ws.entity.Request; -import com.taosdata.jdbc.ws.entity.Response; - -import java.sql.SQLException; -import java.util.concurrent.CompletableFuture; - -/** - * send message - */ -public class Transport implements AutoCloseable { - - public static final int DEFAULT_MAX_REQUEST = 100; - public static final int DEFAULT_MESSAGE_WAIT_TIMEOUT = 3_000; - - private final WSClient client; - private final InFlightRequest inFlightRequest; - - public Transport(WSClient client, InFlightRequest inFlightRequest) { - this.client = client; - this.inFlightRequest = inFlightRequest; - } - - public CompletableFuture send(Request request) { - CompletableFuture completableFuture = new CompletableFuture<>(); - try { - inFlightRequest.put(new ResponseFuture(request.getAction(), request.id(), completableFuture)); - client.send(request.toString()); - } catch (Throwable t) { - inFlightRequest.remove(request.getAction(), request.id()); - completableFuture.completeExceptionally(t); - } - return completableFuture; - } - - public void sendWithoutRep(Request request) { - client.send(request.toString()); - } - - public boolean isClosed() throws SQLException { - return client.isClosed(); - } - - @Override - public void close() throws SQLException { - client.close(); - } - -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSClient.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSClient.java deleted file mode 100644 index a24998cbf1..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSClient.java +++ /dev/null @@ -1,159 +0,0 @@ -package com.taosdata.jdbc.ws; - -import com.alibaba.fastjson.JSONObject; -import com.taosdata.jdbc.ws.entity.*; -import org.java_websocket.client.WebSocketClient; -import org.java_websocket.handshake.ServerHandshake; - -import java.net.URI; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.charset.StandardCharsets; -import java.util.Map; -import java.util.concurrent.*; - -public class WSClient extends WebSocketClient implements AutoCloseable { - private final String user; - private final String password; - private final String database; - private final CountDownLatch latch; - - private final InFlightRequest inFlightRequest; - ThreadPoolExecutor executor; - - private boolean auth; - private int reqId; - - public boolean isAuth() { - return auth; - } - - /** - * create websocket connection client - * - * @param serverUri connection url - * @param user database user - * @param password database password - * @param database connection database - */ - public WSClient(URI serverUri, String user, String password, String database, InFlightRequest inFlightRequest, Map httpHeaders, CountDownLatch latch, int maxRequest) { - super(serverUri, httpHeaders); - this.user = user; - this.password = password; - this.database = database; - this.inFlightRequest = inFlightRequest; - this.latch = latch; - executor = new ThreadPoolExecutor(1, 1, - 0L, TimeUnit.MILLISECONDS, - new ArrayBlockingQueue<>(maxRequest), - r -> { - Thread t = new Thread(r); - t.setName("parse-message-" + t.getId()); - return t; - }, - new ThreadPoolExecutor.CallerRunsPolicy()); - } - - @Override - public void onOpen(ServerHandshake serverHandshake) { - // certification - ConnectReq connectReq = new ConnectReq(++reqId, user, password, database); - this.send(new Request(Action.CONN.getAction(), connectReq).toString()); - } - - @Override - public void onMessage(String message) { - if (!"".equals(message)) { - executor.submit(() -> { - JSONObject jsonObject = JSONObject.parseObject(message); - if (Action.CONN.getAction().equals(jsonObject.getString("action"))) { - if (Code.SUCCESS.getCode() != jsonObject.getInteger("code")) { - this.close(); - } else { - auth = true; - } - latch.countDown(); - } else { - Response response = parseMessage(jsonObject); - ResponseFuture remove = inFlightRequest.remove(response.getAction(), response.getReqId()); - if (null != remove) { - remove.getFuture().complete(response); - } - } - }); - } - } - - private Response parseMessage(JSONObject message) { - Action action = Action.of(message.getString("action")); - return message.toJavaObject(action.getResponseClazz()); - } - - @Override - public void onMessage(ByteBuffer bytes) { - bytes.order(ByteOrder.LITTLE_ENDIAN); - long id = bytes.getLong(); - ResponseFuture remove = inFlightRequest.remove(Action.FETCH_BLOCK.getAction(), id); - if (null != remove) { - FetchBlockResp fetchBlockResp = new FetchBlockResp(id, bytes); - remove.getFuture().complete(fetchBlockResp); - } - } - - @Override - public void onClose(int code, String reason, boolean remote) { - if (remote) { - throw new RuntimeException("The remote server closed the connection: " + reason); - } else { - throw new RuntimeException("close connection: " + reason); - } - } - - @Override - public void onError(Exception e) { - this.close(); - } - - @Override - public void close() { - super.close(); - executor.shutdown(); - } - - static class ConnectReq extends Payload { - private String user; - private String password; - private String db; - - public ConnectReq(long reqId, String user, String password, String db) { - super(reqId); - this.user = user; - this.password = password; - this.db = db; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getDb() { - return db; - } - - public void setDb(String db) { - this.db = db; - } - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSConnection.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSConnection.java deleted file mode 100644 index 4b3c54d3a6..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSConnection.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.taosdata.jdbc.ws; - -import com.taosdata.jdbc.AbstractConnection; -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.TSDBError; -import com.taosdata.jdbc.TSDBErrorNumbers; -import com.taosdata.jdbc.rs.RestfulDatabaseMetaData; -import com.taosdata.jdbc.ws.entity.RequestFactory; - -import java.sql.DatabaseMetaData; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Properties; - -public class WSConnection extends AbstractConnection { - private final Transport transport; - private final DatabaseMetaData metaData; - private final String database; - private final RequestFactory factory; - - public WSConnection(String url, Properties properties, Transport transport, String database) { - super(properties); - this.transport = transport; - this.database = database; - this.metaData = new RestfulDatabaseMetaData(url, properties.getProperty(TSDBDriver.PROPERTY_KEY_USER), this); - this.factory = new RequestFactory(); - } - - @Override - public Statement createStatement() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - - return new WSStatement(transport, database, this, factory); - } - - @Override - public PreparedStatement prepareStatement(String sql) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - //TODO - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); -// return new WSPreparedStatement(transport, database, this, factory, sql); - } - - @Override - public void close() throws SQLException { - transport.close(); - } - - @Override - public boolean isClosed() throws SQLException { - return transport.isClosed(); - } - - @Override - public DatabaseMetaData getMetaData() throws SQLException { - if (isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - } - return this.metaData; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSPreparedStatement.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSPreparedStatement.java deleted file mode 100644 index 96c22f87aa..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSPreparedStatement.java +++ /dev/null @@ -1,575 +0,0 @@ -package com.taosdata.jdbc.ws; - -import com.taosdata.jdbc.TSDBError; -import com.taosdata.jdbc.TSDBErrorNumbers; -import com.taosdata.jdbc.utils.Utils; -import com.taosdata.jdbc.ws.entity.RequestFactory; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.net.URL; -import java.sql.*; -import java.util.ArrayList; -import java.util.Calendar; - -public class WSPreparedStatement extends WSStatement implements PreparedStatement { - private final String rawSql; - private Object[] parameters; - private ArrayList tableTags; - private ArrayList colData; - - public WSPreparedStatement(Transport transport, String database, Connection connection, RequestFactory factory, String rawSql) { - super(transport, database, connection, factory); - this.rawSql = rawSql; - int parameterCnt = 0; - if (rawSql.contains("?")) { - for (int i = 0; i < rawSql.length(); i++) { - if ('?' == rawSql.charAt(i)) { - parameterCnt++; - } - } - this.parameters = new Object[parameterCnt]; - this.colData = new ArrayList<>(); - this.tableTags = new ArrayList<>(); - } - } - - @Override - public ResultSet executeQuery() throws SQLException { - final String sql = Utils.getNativeSql(this.rawSql, this.parameters); - return executeQuery(sql); - } - - @Override - public int executeUpdate() throws SQLException { - return 0; - } - - @Override - public void setNull(int parameterIndex, int sqlType) throws SQLException { - - } - - @Override - public void setBoolean(int parameterIndex, boolean x) throws SQLException { - - } - - @Override - public void setByte(int parameterIndex, byte x) throws SQLException { - - } - - @Override - public void setShort(int parameterIndex, short x) throws SQLException { - - } - - @Override - public void setInt(int parameterIndex, int x) throws SQLException { - - } - - @Override - public void setLong(int parameterIndex, long x) throws SQLException { - - } - - @Override - public void setFloat(int parameterIndex, float x) throws SQLException { - - } - - @Override - public void setDouble(int parameterIndex, double x) throws SQLException { - - } - - @Override - public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { - - } - - @Override - public void setString(int parameterIndex, String x) throws SQLException { - - } - - @Override - public void setBytes(int parameterIndex, byte[] x) throws SQLException { - - } - - @Override - public void setDate(int parameterIndex, Date x) throws SQLException { - - } - - @Override - public void setTime(int parameterIndex, Time x) throws SQLException { - - } - - @Override - public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { - - } - - @Override - public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { - - } - - @Override - public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { - - } - - @Override - public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { - - } - - @Override - public void clearParameters() throws SQLException { - - } - - @Override - public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { - - } - - @Override - public void setObject(int parameterIndex, Object x) throws SQLException { - - } - - @Override - public boolean execute() throws SQLException { - return false; - } - - @Override - public void addBatch() throws SQLException { - - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { - - } - - @Override - public void setRef(int parameterIndex, Ref x) throws SQLException { - - } - - @Override - public void setBlob(int parameterIndex, Blob x) throws SQLException { - - } - - @Override - public void setClob(int parameterIndex, Clob x) throws SQLException { - - } - - @Override - public void setArray(int parameterIndex, Array x) throws SQLException { - - } - - @Override - public ResultSetMetaData getMetaData() throws SQLException { - return null; - } - - @Override - public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { - - } - - @Override - public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { - - } - - @Override - public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { - - } - - @Override - public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { - - } - - @Override - public void setURL(int parameterIndex, URL x) throws SQLException { - - } - - @Override - public ParameterMetaData getParameterMetaData() throws SQLException { - return null; - } - - @Override - public void setRowId(int parameterIndex, RowId x) throws SQLException { - - } - - @Override - public void setNString(int parameterIndex, String value) throws SQLException { - - } - - @Override - public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { - - } - - @Override - public void setNClob(int parameterIndex, NClob value) throws SQLException { - - } - - @Override - public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { - - } - - @Override - public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { - - } - - @Override - public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { - - } - - @Override - public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { - - } - - @Override - public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { - - } - - @Override - public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { - - } - - @Override - public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { - - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { - - } - - @Override - public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { - - } - - @Override - public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { - - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { - - } - - @Override - public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { - - } - - @Override - public void setClob(int parameterIndex, Reader reader) throws SQLException { - - } - - @Override - public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { - - } - - @Override - public void setNClob(int parameterIndex, Reader reader) throws SQLException { - - } - - @Override - public ResultSet executeQuery(String sql) throws SQLException { - return null; - } - - @Override - public int executeUpdate(String sql) throws SQLException { - return 0; - } - - @Override - public void close() throws SQLException { - - } - - @Override - public int getMaxFieldSize() throws SQLException { - return 0; - } - - @Override - public void setMaxFieldSize(int max) throws SQLException { - - } - - @Override - public int getMaxRows() throws SQLException { - return 0; - } - - @Override - public void setMaxRows(int max) throws SQLException { - - } - - @Override - public void setEscapeProcessing(boolean enable) throws SQLException { - - } - - @Override - public int getQueryTimeout() throws SQLException { - return 0; - } - - @Override - public void setQueryTimeout(int seconds) throws SQLException { - - } - - @Override - public void cancel() throws SQLException { - - } - - @Override - public SQLWarning getWarnings() throws SQLException { - return null; - } - - @Override - public void clearWarnings() throws SQLException { - - } - - @Override - public void setCursorName(String name) throws SQLException { - - } - - @Override - public boolean execute(String sql) throws SQLException { - return false; - } - - @Override - public ResultSet getResultSet() throws SQLException { - return null; - } - - @Override - public int getUpdateCount() throws SQLException { - return 0; - } - - @Override - public boolean getMoreResults() throws SQLException { - return false; - } - - @Override - public void setFetchDirection(int direction) throws SQLException { - - } - - @Override - public int getFetchDirection() throws SQLException { - return 0; - } - - @Override - public void setFetchSize(int rows) throws SQLException { - - } - - @Override - public int getFetchSize() throws SQLException { - return 0; - } - - @Override - public int getResultSetConcurrency() throws SQLException { - return 0; - } - - @Override - public int getResultSetType() throws SQLException { - return 0; - } - - @Override - public void addBatch(String sql) throws SQLException { - - } - - @Override - public void clearBatch() throws SQLException { - - } - - @Override - public int[] executeBatch() throws SQLException { - return new int[0]; - } - - @Override - public Connection getConnection() throws SQLException { - return null; - } - - @Override - public boolean getMoreResults(int current) throws SQLException { - return false; - } - - @Override - public ResultSet getGeneratedKeys() throws SQLException { - return null; - } - - @Override - public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { - return 0; - } - - @Override - public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { - return 0; - } - - @Override - public int executeUpdate(String sql, String[] columnNames) throws SQLException { - return 0; - } - - @Override - public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { - return false; - } - - @Override - public boolean execute(String sql, int[] columnIndexes) throws SQLException { - return false; - } - - @Override - public boolean execute(String sql, String[] columnNames) throws SQLException { - return false; - } - - @Override - public int getResultSetHoldability() throws SQLException { - return 0; - } - - @Override - public boolean isClosed() throws SQLException { - return false; - } - - @Override - public void setPoolable(boolean poolable) throws SQLException { - - } - - @Override - public boolean isPoolable() throws SQLException { - return false; - } - - @Override - public void closeOnCompletion() throws SQLException { - - } - - @Override - public boolean isCloseOnCompletion() throws SQLException { - return false; - } - - @Override - public T unwrap(Class iface) throws SQLException { - return null; - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return false; - } - - private static class ColumnInfo { - @SuppressWarnings("rawtypes") - private ArrayList data; - private int type; - private int bytes; - private boolean typeIsSet; - - public ColumnInfo() { - this.typeIsSet = false; - } - - public void setType(int type) throws SQLException { - if (this.isTypeSet()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "column data type has been set"); - } - - this.typeIsSet = true; - this.type = type; - } - - public boolean isTypeSet() { - return this.typeIsSet; - } - } - - private static class TableTagInfo { - private boolean isNull; - private final Object value; - private final int type; - - public TableTagInfo(Object value, int type) { - this.value = value; - this.type = type; - } - - public static TableTagInfo createNullTag(int type) { - TableTagInfo info = new TableTagInfo(null, type); - info.isNull = true; - return info; - } - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSStatement.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSStatement.java deleted file mode 100644 index a984d7f988..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/WSStatement.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.taosdata.jdbc.ws; - -import com.taosdata.jdbc.AbstractStatement; -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.TSDBError; -import com.taosdata.jdbc.TSDBErrorNumbers; -import com.taosdata.jdbc.utils.SqlSyntaxValidator; -import com.taosdata.jdbc.ws.entity.*; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -public class WSStatement extends AbstractStatement { - private final Transport transport; - private String database; - private final Connection connection; - private final RequestFactory factory; - - private boolean closed; - private ResultSet resultSet; - - public WSStatement(Transport transport, String database, Connection connection, RequestFactory factory) { - this.transport = transport; - this.database = database; - this.connection = connection; - this.factory = factory; - } - - @Override - public ResultSet executeQuery(String sql) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - this.execute(sql); - return this.resultSet; - } - - @Override - public int executeUpdate(String sql) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - this.execute(sql); - return affectedRows; - } - - @Override - public void close() throws SQLException { - if (!isClosed()) { - this.closed = true; - if (resultSet != null && !resultSet.isClosed()) { - resultSet.close(); - } - } - } - - @Override - public boolean execute(String sql) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - Request request = factory.generateQuery(sql); - CompletableFuture send = transport.send(request); - - Response response; - try { - response = send.get(); - QueryResp queryResp = (QueryResp) response; - if (Code.SUCCESS.getCode() != queryResp.getCode()) { - throw TSDBError.createSQLException(queryResp.getCode(), queryResp.getMessage()); - } - if (SqlSyntaxValidator.isUseSql(sql)) { - this.database = sql.trim().replace("use", "").trim(); - this.connection.setCatalog(this.database); - this.connection.setClientInfo(TSDBDriver.PROPERTY_KEY_DBNAME, this.database); - } - if (queryResp.isUpdate()) { - this.resultSet = null; - this.affectedRows = queryResp.getAffectedRows(); - return false; - } else { - this.resultSet = new BlockResultSet(this, this.transport, this.factory, queryResp, this.database); - this.affectedRows = -1; - return true; - } - } catch (InterruptedException | ExecutionException e) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEQUERY, e.getMessage()); - } - } - - @Override - public ResultSet getResultSet() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - return this.resultSet; - } - - @Override - public int getUpdateCount() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - return affectedRows; - } - - @Override - public Connection getConnection() throws SQLException { - return this.connection; - } - - @Override - public boolean isClosed() throws SQLException { - return closed; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Action.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Action.java deleted file mode 100644 index 9d44282df7..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Action.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.taosdata.jdbc.ws.entity; - -import java.util.HashMap; -import java.util.Map; - -/** - * request type - */ -public enum Action { - CONN("conn", ConnectResp.class), - QUERY("query", QueryResp.class), - FETCH("fetch", FetchResp.class), - FETCH_JSON("fetch_json", FetchJsonResp.class), - FETCH_BLOCK("fetch_block", FetchBlockResp.class), - // free_result's class is meaningless - FREE_RESULT("free_result", Response.class), - ; - private final String action; - private final Class clazz; - - Action(String action, Class clazz) { - this.action = action; - this.clazz = clazz; - } - - public String getAction() { - return action; - } - - public Class getResponseClazz() { - return clazz; - } - - private static final Map actions = new HashMap<>(); - - static { - for (Action value : Action.values()) { - actions.put(value.action, value); - } - } - - public static Action of(String action) { - if (null == action || action.equals("")) { - return null; - } - return actions.get(action); - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Code.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Code.java deleted file mode 100644 index 13a2b852e0..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Code.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.taosdata.jdbc.ws.entity; - -/** - * response message info - */ -public enum Code { - SUCCESS(0, "success"), - ; - - private final int code; - private final String message; - - Code(int code, String message) { - this.code = code; - this.message = message; - } - - public int getCode() { - return code; - } - - public String getMessage() { - return message; - } - - public static Code of(int code) { - for (Code value : Code.values()) { - if (value.code == code) { - return value; - } - } - return null; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/ConnectResp.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/ConnectResp.java deleted file mode 100644 index f1071ef74c..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/ConnectResp.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.taosdata.jdbc.ws.entity; - -/** - * connection result pojo - */ -public class ConnectResp extends Response { - private int code; - private String message; - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchBlockResp.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchBlockResp.java deleted file mode 100644 index 2dbcffb40f..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchBlockResp.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.taosdata.jdbc.ws.entity; - -import java.nio.ByteBuffer; - -public class FetchBlockResp extends Response { - private ByteBuffer buffer; - - public FetchBlockResp(long id, ByteBuffer buffer) { - this.setAction(Action.FETCH_BLOCK.getAction()); - this.setReqId(id); - this.buffer = buffer; - } - - public ByteBuffer getBuffer() { - return buffer; - } - - public void setBuffer(ByteBuffer buffer) { - this.buffer = buffer; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchJsonResp.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchJsonResp.java deleted file mode 100644 index 74c2f46d54..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchJsonResp.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.taosdata.jdbc.ws.entity; - -import com.alibaba.fastjson.JSONArray; - -public class FetchJsonResp extends Response{ - private long id; - private JSONArray data; - - public JSONArray getData() { - return data; - } - - public void setData(JSONArray data) { - this.data = data; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchReq.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchReq.java deleted file mode 100644 index 25cd9dc472..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchReq.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.taosdata.jdbc.ws.entity; - -public class FetchReq extends Payload { - private long id; - - public FetchReq(long reqId, long id) { - super(reqId); - this.id = id; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchResp.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchResp.java deleted file mode 100644 index 08229c00b1..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/FetchResp.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.taosdata.jdbc.ws.entity; - -/** - * fetch result pojo - */ -public class FetchResp extends Response{ - private int code; - private String message; - private long id; - private boolean completed; - private Integer[] lengths; - private int rows; - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public boolean isCompleted() { - return completed; - } - - public void setCompleted(boolean completed) { - this.completed = completed; - } - - public Integer[] getLengths() { - return lengths; - } - - public void setLengths(Integer[] lengths) { - this.lengths = lengths; - } - - public int getRows() { - return rows; - } - - public void setRows(int rows) { - this.rows = rows; - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Payload.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Payload.java deleted file mode 100644 index 1821a5fc1f..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Payload.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.taosdata.jdbc.ws.entity; - -import com.alibaba.fastjson.annotation.JSONField; - -public class Payload { - @JSONField(name = "req_id") - private final long reqId; - - public Payload(long reqId) { - this.reqId = reqId; - } - - public long getReqId() { - return reqId; - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/QueryReq.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/QueryReq.java deleted file mode 100644 index 8e6d197bc6..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/QueryReq.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.taosdata.jdbc.ws.entity; - -public class QueryReq extends Payload { - private String sql; - - public QueryReq(long reqId, String sql) { - super(reqId); - this.sql = sql; - } - - public String getSql() { - return sql; - } - - public void setSql(String sql) { - this.sql = sql; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/QueryResp.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/QueryResp.java deleted file mode 100644 index 22e1418b68..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/QueryResp.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.taosdata.jdbc.ws.entity; - -import com.alibaba.fastjson.annotation.JSONField; - -/** - * query result pojo - */ -public class QueryResp extends Response { - private int code; - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - private String message; - - private long id; - - @JSONField(name = "is_update") - private boolean isUpdate; - - @JSONField(name = "affected_rows") - private int affectedRows; - - @JSONField(name = "fields_count") - private int fieldsCount; - - @JSONField(name = "fields_names") - private String[] fieldsNames; - - @JSONField(name = "fields_types") - private int[] fieldsTypes; - - @JSONField(name = "fields_lengths") - private int[] fieldsLengths; - - private int precision; - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public boolean isUpdate() { - return isUpdate; - } - - public void setUpdate(boolean update) { - isUpdate = update; - } - - public int getAffectedRows() { - return affectedRows; - } - - public void setAffectedRows(int affectedRows) { - this.affectedRows = affectedRows; - } - - public int getFieldsCount() { - return fieldsCount; - } - - public void setFieldsCount(int fieldsCount) { - this.fieldsCount = fieldsCount; - } - - public String[] getFieldsNames() { - return fieldsNames; - } - - public void setFieldsNames(String[] fieldsNames) { - this.fieldsNames = fieldsNames; - } - - public int[] getFieldsTypes() { - return fieldsTypes; - } - - public void setFieldsTypes(int[] fieldsTypes) { - this.fieldsTypes = fieldsTypes; - } - - public int[] getFieldsLengths() { - return fieldsLengths; - } - - public void setFieldsLengths(int[] fieldsLengths) { - this.fieldsLengths = fieldsLengths; - } - - public int getPrecision() { - return precision; - } - - public void setPrecision(int precision) { - this.precision = precision; - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Request.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Request.java deleted file mode 100644 index 6462664309..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Request.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.taosdata.jdbc.ws.entity; - -import com.alibaba.fastjson.JSON; - -/** - * send to taosadapter - */ -public class Request { - private String action; - private Payload args; - - public Request(String action, Payload args) { - this.action = action; - this.args = args; - } - - public String getAction() { - return action; - } - - public Long id(){ - return args.getReqId(); - } - - public void setAction(String action) { - this.action = action; - } - - public Payload getArgs() { - return args; - } - - public void setArgs(Payload args) { - this.args = args; - } - - @Override - public String toString() { - return JSON.toJSONString(this); - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/RequestFactory.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/RequestFactory.java deleted file mode 100644 index f033d0d8ba..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/RequestFactory.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.taosdata.jdbc.ws.entity; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; - -/** - * generate id for request - */ -public class RequestFactory { - private final Map ids = new HashMap<>(); - - public long getId(String action) { - return ids.get(action).incrementAndGet(); - } - - public RequestFactory() { - for (Action value : Action.values()) { - String action = value.getAction(); - if (Action.CONN.getAction().equals(action) || Action.FETCH_BLOCK.getAction().equals(action)) - continue; - ids.put(action, new AtomicLong(0)); - } - } - - public Request generateQuery(String sql) { - long reqId = this.getId(Action.QUERY.getAction()); - QueryReq queryReq = new QueryReq(reqId, sql); - return new Request(Action.QUERY.getAction(), queryReq); - } - - public Request generateFetch(long id) { - long reqId = this.getId(Action.FETCH.getAction()); - FetchReq fetchReq = new FetchReq(reqId, id); - return new Request(Action.FETCH.getAction(), fetchReq); - } - - public Request generateFetchJson(long id) { - long reqId = this.getId(Action.FETCH_JSON.getAction()); - FetchReq fetchReq = new FetchReq(reqId, id); - return new Request(Action.FETCH_JSON.getAction(), fetchReq); - } - - public Request generateFetchBlock(long id) { - FetchReq fetchReq = new FetchReq(id, id); - return new Request(Action.FETCH_BLOCK.getAction(), fetchReq); - } -} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Response.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Response.java deleted file mode 100644 index 604317acaf..0000000000 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/entity/Response.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.taosdata.jdbc.ws.entity; - -import com.alibaba.fastjson.annotation.JSONField; - -/** - * return from taosadapter - */ -public class Response { - private String action; - - @JSONField(name = "req_id") - private long reqId; - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public long getReqId() { - return reqId; - } - - public void setReqId(long reqId) { - this.reqId = reqId; - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/main/resources/META-INF/services/java.sql.Driver b/src/connector/jdbc/src/main/resources/META-INF/services/java.sql.Driver deleted file mode 100644 index 893f7cdf34..0000000000 --- a/src/connector/jdbc/src/main/resources/META-INF/services/java.sql.Driver +++ /dev/null @@ -1,2 +0,0 @@ -com.taosdata.jdbc.TSDBDriver -com.taosdata.jdbc.rs.RestfulDriver diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/JsonTagTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/JsonTagTest.java deleted file mode 100644 index 75480356e0..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/JsonTagTest.java +++ /dev/null @@ -1,1330 +0,0 @@ -package com.taosdata.jdbc; - -import com.taosdata.jdbc.annotation.CatalogRunner; -import com.taosdata.jdbc.annotation.Description; -import com.taosdata.jdbc.annotation.TestTarget; -import org.junit.*; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; - -import java.sql.*; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Random; -import java.util.Set; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(CatalogRunner.class) -@TestTarget(alias = "JsonTag", author = "huolibo", version = "2.0.36") -public class JsonTagTest { - private static final String dbName = "json_tag_test"; - private static Connection connection; - private static Statement statement; - private static final String superSql = "create table if not exists jsons1(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"; - private static final String[] sql = { - "insert into jsons1_1 using jsons1 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(now, 1, false, 'json1', '你是') (1591060608000, 23, true, '等等', 'json')", - "insert into jsons1_2 using jsons1 tags('{\"tag1\":5,\"tag2\":\"beijing\"}') values (1591060628000, 2, true, 'json2', 'sss')", - "insert into jsons1_3 using jsons1 tags('{\"tag1\":false,\"tag2\":\"beijing\"}') values (1591060668000, 3, false, 'json3', 'efwe')", - "insert into jsons1_4 using jsons1 tags('{\"tag1\":null,\"tag2\":\"shanghai\",\"tag3\":\"hello\"}') values (1591060728000, 4, true, 'json4', '323sd')", - "insert into jsons1_5 using jsons1 tags('{\"tag1\":1.232, \"tag2\":null}') values(1591060928000, 1, false, '你就会', 'ewe')", - "insert into jsons1_6 using jsons1 tags('{\"tag1\":11,\"tag2\":\"\",\"tag2\":null}') values(1591061628000, 11, false, '你就会','')", - "insert into jsons1_7 using jsons1 tags('{\"tag1\":\"收到货\",\"tag2\":\"\",\"tag3\":null}') values(1591062628000, 2, NULL, '你就会', 'dws')", - // test duplicate key using the first one. - "CREATE TABLE if not exists jsons1_8 using jsons1 tags('{\"tag1\":null, \"tag1\":true, \"tag1\":45, \"1tag$\":2, \" \":90}')", - - }; - - private static final String[] invalidJsonInsertSql = { - // test empty json string, save as tag is NULL - "insert into jsons1_9 using jsons1 tags('\t') values (1591062328000, 24, NULL, '你就会', '2sdw')", - }; - - private static final String[] invalidJsonCreateSql = { - "CREATE TABLE if not exists jsons1_10 using jsons1 tags('')", - "CREATE TABLE if not exists jsons1_11 using jsons1 tags(' ')", - "CREATE TABLE if not exists jsons1_12 using jsons1 tags('{}')", - "CREATE TABLE if not exists jsons1_13 using jsons1 tags('null')", - }; - - // test invalidate json - private static final String[] errorJsonInsertSql = { - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('\"efwewf\"')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('3333')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('33.33')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('false')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('[1,true]')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{222}')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"fe\"}')", - }; - - private static final String[] errorSelectSql = { - "select * from jsons1 where jtag->tag1='beijing'", - "select * from jsons1 where jtag->'location'", - "select * from jsons1 where jtag->''", - "select * from jsons1 where jtag->''=9", - "select -> from jsons1", - "select ? from jsons1", - "select * from jsons1 where contains", - "select * from jsons1 where jtag->", - "select jtag->location from jsons1", - "select jtag contains location from jsons1", - "select * from jsons1 where jtag contains location", - "select * from jsons1 where jtag contains ''", - "select * from jsons1 where jtag contains 'location'='beijing'", - // test where with json tag - "select * from jsons1_1 where jtag is not null", - "select * from jsons1 where jtag='{\"tag1\":11,\"tag2\":\"\"}'", - "select * from jsons1 where jtag->'tag1'={}" - }; - - @Test - @Description("insert json tag") - public void case01_InsertTest() throws SQLException { - for (String sql : sql) { - statement.execute(sql); - } - for (String sql : invalidJsonInsertSql) { - statement.execute(sql); - } - for (String sql : invalidJsonCreateSql) { - statement.execute(sql); - } - } - - @Test - @Description("error json tag insert") - public void case02_ErrorJsonInsertTest() { - int count = 0; - for (String sql : errorJsonInsertSql) { - try { - statement.execute(sql); - } catch (SQLException e) { - count++; - } - } - Assert.assertEquals(errorJsonInsertSql.length, count); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json value is array") - public void case02_ArrayErrorTest() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"tag1\":[1,true]}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json value is empty") - public void case02_EmptyValueErrorTest() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"tag1\":{}}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json key is not ASCII") - public void case02_AbnormalKeyErrorTest1() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"。loc\":\"fff\"}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json key is '\\t'") - public void case02_AbnormalKeyErrorTest2() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"\t\":\"fff\"}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json key is chinese") - public void case02_AbnormalKeyErrorTest3() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"试试\":\"fff\"}')"); - } - - @Test - @Description("alter json tag") - public void case03_AlterTag() throws SQLException { - statement.execute("ALTER TABLE jsons1_1 SET TAG jtag='{\"tag1\":\"femail\",\"tag2\":35,\"tag3\":true}'"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when add json tag") - public void case03_AddTagErrorTest() throws SQLException { - statement.execute("ALTER STABLE jsons1 add tag tag2 nchar(20)"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when delete json tag") - public void case03_dropTagErrorTest() throws SQLException { - statement.execute("ALTER STABLE jsons1 drop tag jtag"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when set some json tag value") - public void case03_AlterTagErrorTest() throws SQLException { - statement.execute("ALTER TABLE jsons1_1 SET TAG jtag=4"); - } - - @Test - @Description("exception will throw when select syntax error") - public void case04_SelectErrorTest() { - int count = 0; - for (String sql : errorSelectSql) { - try { - statement.execute(sql); - } catch (SQLException e) { - count++; - } - } - Assert.assertEquals(errorSelectSql.length, count); - } - - @Test - @Description("normal select stable") - public void case04_select01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select dataint from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("select all column from stable") - public void case04_select02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("select json tag from stable") - public void case04_select03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1"); - ResultSetMetaData metaData = resultSet.getMetaData(); - metaData.getColumnTypeName(1); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonInsertSql.length + invalidJsonCreateSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition tag is null") - public void case04_select04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1 where jtag is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(invalidJsonInsertSql.length + invalidJsonCreateSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition tag is not null") - public void case04_select05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1 where jtag is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length, count); - close(resultSet); - } - - @Test - @Description("select json tag") - public void case04_select06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1_8"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("{\"tag1\":null,\"1tag$\":2,\" \":90}", result); - close(resultSet); - } - - @Test - @Description("select json tag") - public void case04_select07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1_1"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("{\"tag1\":\"femail\",\"tag2\":35,\"tag3\":true}", result); - close(resultSet); - } - - @Test - @Description("select not exist json tag") - public void case04_select08() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1_9"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertNull(result); - close(resultSet); - } - - @Test - @Description("select a json tag") - public void case04_select09() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_1"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("\"femail\"", result); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is empty") - public void case04_select10() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag2' from jsons1_6"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("\"\"", result); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is int") - public void case04_select11() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag2' from jsons1_1"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("35", string); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is boolean") - public void case04_select12() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag3' from jsons1_1"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("true", string); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is null") - public void case04_select13() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_4"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("null", string); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is double") - public void case04_select14() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_5"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("1.232000000", string); - close(resultSet); - } - - @Test - @Description("select a json tag, the key is not exist") - public void case04_select15() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag10' from jsons1_4"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertNull(string); - close(resultSet); - } - - @Test - @Description("select a json tag, the result number equals tables number") - public void case04_select16() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonCreateSql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition '=' for string") - public void case04_select19() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("select and where conditon '=' for string") - public void case04_select20() throws SQLException { - ResultSet resultSet = statement.executeQuery("select dataint,tbname,jtag->'tag1',jtag from jsons1 where jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition result is null") - public void case04_select21() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition equation has chinese") - public void case04_select23() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'='收到货'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '>' for character") - public void case05_symbolOperation01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'>'beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '>=' for character") - public void case05_symbolOperation02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'>='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '<' for character") - public void case05_symbolOperation03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'<'beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition support '<=' in character") - public void case05_symbolOperation04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'<='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' in character") - public void case05_symbolOperation05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'!='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '=' empty") - public void case05_symbolOperation06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'=''"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - // where json value is int - @Test - @Description("where condition support '=' for int") - public void case06_selectValue01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=5"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where conditional support '<' for int") - public void case06_selectValue02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<54"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '<=' for int") - public void case06_selectValue03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<=11"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where conditional support '>' for int") - public void case06_selectValue04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>4"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition support '>=' for int") - public void case06_selectValue05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>=5"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where conditional support '!=' for int") - public void case06_selectValue06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=5"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where conditional support '!=' for int") - public void case06_selectValue07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=55"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where conditional support '!=' for int and result is nothing") - public void case06_selectValue08() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=10"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support '=' for double") - public void case07_selectValue01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '<' for double") - public void case07_doubleOperation01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support '<=' for double") - public void case07_doubleOperation02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '>' for double") - public void case07_doubleOperation03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>1.23"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '>=' for double") - public void case07_doubleOperation04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' for double") - public void case07_doubleOperation05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' for double") - public void case07_doubleOperation06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=3.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when denominator is zero") - public void case07_doubleOperation07() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1'/0=3"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when invalid operation") - public void case07_doubleOperation08() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1'/5=1"); - } - - @Test - @Description("where condition support '=' for boolean") - public void case08_boolOperation01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=true"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support '=' for boolean") - public void case08_boolOperation02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' for boolean") - public void case08_boolOperation03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=false"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when '>' operation for boolean") - public void case08_boolOperation04() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1'>false"); - } - - @Test - @Description("where conditional support '=null'") - public void case09_select01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where conditional support 'is null'") - public void case09_select02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support 'is not null'") - public void case09_select03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag '='") - public void case09_select04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag_no_exist'=3"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag 'is null'") - public void case09_select05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag 'is null'") - public void case09_select06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag4' is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag 'is not null'") - public void case09_select07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag3' is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("contains") - public void case09_select10() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag contains 'tag1'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("contains") - public void case09_select11() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("contains with no exist tag") - public void case09_select12() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag contains 'tag_no_exist'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition with and") - public void case10_selectAndOr01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false and jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition with 'or'") - public void case10_selectAndOr02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false or jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition with 'and'") - public void case10_selectAndOr03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false and jtag->'tag2'='shanghai'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition with 'or'") - public void case10_selectAndOr04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=13 or jtag->'tag2'>35"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition with 'or' and contains") - public void case10_selectAndOr05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' is not null and jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("where condition with 'and' and contains") - public void case10_selectAndOr06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'='femail' and jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3' and dataint=3"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3' and dataint=23"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition like") - public void case12_selectWhere01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,tbname from jsons1 where jtag->'tag2' like 'bei%'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition like") - public void case12_selectWhere02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,tbname from jsons1 where jtag->'tag1' like 'fe%' and jtag->'tag2' is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test(expected = SQLException.class) - @Description("where condition in no support in") - public void case12_selectWhere03() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1' in ('beijing')"); - } - - @Test - @Description("where condition match") - public void case12_selectWhere04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' match 'ma'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition match") - public void case12_selectWhere05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' match 'ma$'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition match") - public void case12_selectWhere06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2' match 'jing$'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition match") - public void case12_selectWhere07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' match '收到'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("insert distinct") - public void case13_selectDistinct01() throws SQLException { - statement.execute("insert into jsons1_14 using jsons1 tags('{\"tag1\":\"收到货\",\"tag2\":\"\",\"tag3\":null}') values(1591062628000, 2, NULL, '你就会', 'dws')"); - } - - @Test - @Description("distinct json tag") - public void case13_selectDistinct02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select distinct jtag->'tag1' from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("distinct json tag") - public void case13_selectDistinct03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select distinct jtag from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(9, count); - close(resultSet); - } - - @Test - @Description("insert json tag") - public void case14_selectDump01() throws SQLException { - statement.execute("INSERT INTO jsons1_15 using jsons1 tags('{\"tbname\":\"tt\",\"databool\":true,\"datastr\":\"是是是\"}') values(1591060828000, 4, false, 'jjsf', \"你就会\")"); - } - - @Test - @Description("test duplicate key with normal column") - public void case14_selectDump02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,tbname,jtag from jsons1 where jtag->'datastr' match '是' and datastr match 'js'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("test duplicate key with normal column") - public void case14_selectDump03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select tbname,jtag->'tbname' from jsons1 where jtag->'tbname'='tt' and tbname='jsons1_14'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("insert json tag for join test") - public void case15_selectJoin01() throws SQLException { - statement.execute("create table if not exists jsons2(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"); - statement.execute("insert into jsons2_1 using jsons2 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(1591060618000, 2, false, 'json2', '你是2')"); - statement.execute("insert into jsons2_2 using jsons2 tags('{\"tag1\":5,\"tag2\":null}') values (1591060628000, 2, true, 'json2', 'sss')"); - - statement.execute("create table if not exists jsons3(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"); - statement.execute("insert into jsons3_1 using jsons3 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(1591060618000, 3, false, 'json3', '你是3')"); - statement.execute("insert into jsons3_2 using jsons3 tags('{\"tag1\":5,\"tag2\":\"beijing\"}') values (1591060638000, 2, true, 'json3', 'sss')"); - } - - @Test - @Description("select json tag from join") - public void case15_selectJoin02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select 'sss',33,a.jtag->'tag3' from jsons2 a,jsons3 b where a.ts=b.ts and a.jtag->'tag1'=b.jtag->'tag1'"); - resultSet.next(); - Assert.assertEquals("sss", resultSet.getString(1)); - close(resultSet); - } - - @Test - @Description("group by and order by json tag desc") - public void case16_selectGroupOrder01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select count(*) from jsons1 group by jtag->'tag1' order by jtag->'tag1' desc"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("group by and order by json tag asc") - public void case16_selectGroupOrder02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select count(*) from jsons1 group by jtag->'tag1' order by jtag->'tag1' asc"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("stddev with group by json tag") - public void case17_selectStddev01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select stddev(dataint) from jsons1 group by jtag->'tag1'"); - String s = ""; - int count = 0; - Set set = new HashSet<>(); - while (resultSet.next()) { - count++; - set.add(resultSet.getString(2)); - } - Assert.assertEquals(8, count); - Assert.assertTrue(set.contains("\"femail\"")); - Assert.assertTrue(set.contains("\"收到货\"")); - } - - @Test - @Description("subquery json tag") - public void case18_selectSubquery01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from (select jtag, dataint from jsons1)"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(11, count); - close(resultSet); - } - - @Test - @Description("subquery some json tags") - public void case18_selectSubquery02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from (select jtag->'tag1', dataint from jsons1)"); - - ResultSetMetaData metaData = resultSet.getMetaData(); - String columnName = metaData.getColumnName(1); - Assert.assertEquals("jtag->'tag1'", columnName); - - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(11, count); - close(resultSet); - } - - @Test - @Description("query some json tags from subquery") - public void case18_selectSubquery04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select ts,tbname,jtag->'tag1' from (select jtag->'tag1',tbname,ts from jsons1 order by ts)"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(11, count); - close(resultSet); - } - - @Test - @Description("query metadata for json") - public void case19_selectMetadata01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1"); - ResultSetMetaData metaData = resultSet.getMetaData(); - int columnType = metaData.getColumnType(1); - String columnTypeName = metaData.getColumnTypeName(1); - Assert.assertEquals(Types.OTHER, columnType); - Assert.assertEquals("JSON", columnTypeName); - close(resultSet); - } - - @Test - @Description("query metadata for json") - public void case19_selectMetadata02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,jtag from jsons1"); - ResultSetMetaData metaData = resultSet.getMetaData(); - int columnType = metaData.getColumnType(6); - String columnTypeName = metaData.getColumnTypeName(6); - Assert.assertEquals(Types.OTHER, columnType); - Assert.assertEquals("JSON", columnTypeName); - close(resultSet); - } - - @Test - @Description("query metadata for one json result") - public void case19_selectMetadata03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_6"); - ResultSetMetaData metaData = resultSet.getMetaData(); - int columnType = metaData.getColumnType(1); - String columnTypeName = metaData.getColumnTypeName(1); - Assert.assertEquals(Types.OTHER, columnType); - Assert.assertEquals("JSON", columnTypeName); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("11", string); - close(resultSet); - } - - @Test - @Description("stmt batch insert with json tag") - public void case20_batchInsert() throws SQLException { - String jsonTag = "{\"tag1\":\"fff\",\"tag2\":5,\"tag3\":true}"; - statement.execute("drop table if exists jsons5"); - statement.execute("CREATE STABLE IF NOT EXISTS jsons5 (ts timestamp, dataInt int, dataStr nchar(20)) TAGS(jtag json)"); - - String sql = "INSERT INTO ? USING jsons5 TAGS (?) VALUES ( ?,?,? )"; - - try (PreparedStatement pst = connection.prepareStatement(sql)) { - TSDBPreparedStatement ps = pst.unwrap(TSDBPreparedStatement.class); - // 设定数据表名: - ps.setTableName("batch_test"); - // 设定 TAGS 取值 setTagNString or setTagJson: -// ps.setTagNString(0, jsonTag); - ps.setTagJson(0, jsonTag); - - // VALUES 部分以逐列的方式进行设置: - int numOfRows = 4; - ArrayList ts = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - ts.add(System.currentTimeMillis() + i); - } - ps.setTimestamp(0, ts); - - Random r = new Random(); - int random = 10 + r.nextInt(5); - ArrayList c1 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - if (i % random == 0) { - c1.add(null); - } else { - c1.add(r.nextInt()); - } - } - ps.setInt(1, c1); - - ArrayList c2 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - c2.add("分支" + i % 4); - } - ps.setNString(2, c2, 10); - - // AddBatch 之后,缓存并未清空。为避免混乱,并不推荐在 ExecuteBatch 之前再次绑定新一批的数据: - ps.columnDataAddBatch(); - // 执行绑定数据后的语句: - ps.columnDataExecuteBatch(); - } - - ResultSet resultSet = statement.executeQuery("select jtag from batch_test"); - ResultSetMetaData metaData = resultSet.getMetaData(); - String columnName = metaData.getColumnName(1); - Assert.assertEquals("jtag", columnName); - Assert.assertEquals("JSON", metaData.getColumnTypeName(1)); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals(jsonTag, string); - resultSet.close(); - resultSet = statement.executeQuery("select jtag->'tag2' from batch_test"); - resultSet.next(); - long l = resultSet.getLong(1); - Assert.assertEquals(5, l); - resultSet.close(); - } - - private void close(ResultSet resultSet) { - try { - if (null != resultSet) { - resultSet.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @BeforeClass - public static void beforeClass() { - String host = "127.0.0.1"; - final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - try { - connection = DriverManager.getConnection(url); - statement = connection.createStatement(); - statement.execute("drop database if exists " + dbName); - statement.execute("create database if not exists " + dbName); - statement.execute("use " + dbName); - statement.execute(superSql); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @AfterClass - public static void afterClass() { - try { - if (null != statement) { - statement.execute("drop database " + dbName); - statement.close(); - } - if (null != connection) { - connection.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ParameterBindTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ParameterBindTest.java deleted file mode 100644 index f06480bc68..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ParameterBindTest.java +++ /dev/null @@ -1,190 +0,0 @@ -package com.taosdata.jdbc; - -import org.junit.*; - -import java.sql.*; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Random; -import java.util.stream.Collectors; - -public class ParameterBindTest { - - private static final String host = "127.0.0.1"; - private static final String stable = "weather"; - - private Connection conn; - private final Random random = new Random(System.currentTimeMillis()); - - @Test - public void one_batch_multi_table() throws SQLException { - // given - String[] tbnames = {"t1", "t2", "t3"}; - int rows = 10; - - // when - String sql = "insert into ? using " + stable + " tags(?, ?) values(?, ?, ?)"; - try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { - long current = System.currentTimeMillis(); - insertIntoTables(pstmt, tbnames, current, 10); - } - - // then - assertRows(stable, tbnames.length * rows); - for (String t : tbnames) { - assertRows(t, rows); - } - } - - @Test - public void multi_batch_multi_table() throws SQLException { - // given - int rows = 10; - int batchSize = 10; - String[] tbnames = {"t1", "t2", "t3"}; - - // when - String sql = "insert into ? using " + stable + " tags(?, ?) values(?, ?, ?)"; - try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { - - long current = System.currentTimeMillis(); - - for (int i = 0; i < batchSize; i++) { - insertIntoTables(pstmt, tbnames, current + 1000 * i * rows, rows); - } - } - - // then - assertRows(stable, tbnames.length * batchSize * rows); - for (String t : tbnames) { - assertRows(t, rows * batchSize); - } - } - - @Test - public void multiThreads() { - // given - String[][] tables = {{"t1", "t2", "t3"}, {"t4", "t5", "t6"}, {"t7", "t8", "t9"}, {"t10"}}; - int rows = 10; - - // when - List threads = Arrays.stream(tables).map(tbnames -> new Thread(() -> { - - String sql = "insert into ? using " + stable + " tags(?, ?) values(?, ?, ?)"; - try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { - long current = System.currentTimeMillis(); - insertIntoTables(pstmt, tbnames, current, 10); - } catch (SQLException throwables) { - throwables.printStackTrace(); - } - - })).collect(Collectors.toList()); - threads.forEach(Thread::start); - for (Thread thread : threads) { - try { - thread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - // then - for (String[] table : tables) { - for (String t : table) { - assertRows(t, rows); - } - } - } - - @Ignore - @Test - public void testOOM() throws SQLException { - String[] tbnames = {"t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9", "t10"}; - String sql = "insert into ? using " + stable + " tags(?, ?) values(?, ?, ?)"; - int rows = 1000; - - try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { - - long ts = Instant.now().minus(5 * 365, ChronoUnit.DAYS).getEpochSecond() * 1000; - while (true) { - insertIntoTables(pstmt, tbnames, ts, rows); - ts += 1000 * rows; - } - } - } - - - private void assertRows(String tbname, int rows) { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + tbname); - while (rs.next()) { - int count = rs.getInt(1); - Assert.assertEquals(rows, count); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private void insertIntoTables(TSDBPreparedStatement pstmt, String[] tbnames, long ts_start, int rowsEachTable) throws SQLException { - for (int i = 0; i < tbnames.length; i++) { - // set table name - pstmt.setTableName(tbnames[i]); - // set tags - pstmt.setTagInt(0, random.nextInt(100)); - pstmt.setTagInt(1, random.nextInt(100)); - // set column: ts - ArrayList timestampList = new ArrayList<>(); - for (int j = 0; j < rowsEachTable; j++) { - timestampList.add(ts_start + j * 1000L); - } - pstmt.setTimestamp(0, timestampList); - // set column: f1 - ArrayList f1List = new ArrayList<>(); - for (int j = 0; j < rowsEachTable; j++) { - f1List.add(random.nextInt(100)); - } - pstmt.setInt(1, f1List); - // set column: f2 - ArrayList f2List = new ArrayList<>(); - for (int j = 0; j < rowsEachTable; j++) { - f2List.add(random.nextInt(100)); - } - pstmt.setInt(2, f2List); - // add batch - pstmt.columnDataAddBatch(); - } - // execute batch - pstmt.columnDataExecuteBatch(); - } - - @Before - public void before() { - String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - try { - conn = DriverManager.getConnection(url); - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists test_pd"); - stmt.execute("create database if not exists test_pd"); - stmt.execute("use test_pd"); - stmt.execute("create table " + stable + "(ts timestamp, f1 int, f2 int) tags(t1 int, t2 int)"); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @After - public void after() { - try { - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists test_pd"); - if (conn != null) - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SchemalessInsertTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SchemalessInsertTest.java deleted file mode 100644 index cc47a47f1c..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SchemalessInsertTest.java +++ /dev/null @@ -1,195 +0,0 @@ -package com.taosdata.jdbc; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.taosdata.jdbc.annotation.CatalogRunner; -import com.taosdata.jdbc.annotation.Description; -import com.taosdata.jdbc.annotation.TestTarget; -import com.taosdata.jdbc.enums.SchemalessProtocolType; -import com.taosdata.jdbc.enums.SchemalessTimestampType; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.sql.*; -import java.util.ArrayList; -import java.util.List; - -@RunWith(CatalogRunner.class) -@TestTarget(alias = "Schemaless",author = "huolibo", version = "2.0.36") -public class SchemalessInsertTest { - private final String dbname = "test_schemaless_insert"; - private Connection conn; - - /** - * schemaless insert compatible with influxdb - * - * @throws SQLException execute error - */ - @Test - @Description("line insert") - public void schemalessInsert() throws SQLException { - // given - String[] lines = new String[]{ - "st,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", - "st,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64 1626006833640000000"}; - // when - SchemalessWriter writer = new SchemalessWriter(conn); - writer.write(lines, SchemalessProtocolType.LINE, SchemalessTimestampType.NANO_SECONDS); - - // then - Statement statement = conn.createStatement(); - ResultSet rs = statement.executeQuery("show tables"); - Assert.assertNotNull(rs); - ResultSetMetaData metaData = rs.getMetaData(); - Assert.assertTrue(metaData.getColumnCount() > 0); - int rowCnt = 0; - while (rs.next()) { - rowCnt++; - } - Assert.assertEquals(lines.length, rowCnt); - rs.close(); - statement.close(); - } - - /** - * telnet insert compatible with opentsdb - * - * @throws SQLException execute error - */ - @Test - @Description("telnet insert") - public void telnetInsert() throws SQLException { - // given - String[] lines = new String[]{ - "stb0_0 1626006833 4 host=host0 interface=eth0", - "stb0_1 1626006833 4 host=host0 interface=eth0", - "stb0_2 1626006833 4 host=host0 interface=eth0 id=\"special_name\"", - }; - - // when - - SchemalessWriter writer = new SchemalessWriter(conn); - writer.write(lines, SchemalessProtocolType.TELNET, SchemalessTimestampType.NOT_CONFIGURED); - - // then - Statement statement = conn.createStatement(); - ResultSet rs = statement.executeQuery("show tables"); - Assert.assertNotNull(rs); - ResultSetMetaData metaData = rs.getMetaData(); - Assert.assertTrue(metaData.getColumnCount() > 0); - int rowCnt = 0; - while (rs.next()) { - rowCnt++; - } - Assert.assertEquals(lines.length, rowCnt); - rs.close(); - statement.close(); - } - - /** - * json insert compatible with opentsdb json format - * - * @throws SQLException execute error - */ - @Test - @Description("json insert") - public void jsonInsert() throws SQLException { - // given - String json = "[\n" + - " {\n" + - " \"metric\": \"cpu_load_1\",\n" + - " \"timestamp\": 1626006833,\n" + - " \"value\": 55.5,\n" + - " \"tags\": {\n" + - " \"host\": \"ubuntu\",\n" + - " \"interface\": \"eth1\",\n" + - " \"Id\": \"tb1\"\n" + - " }\n" + - " },\n" + - " {\n" + - " \"metric\": \"cpu_load_2\",\n" + - " \"timestamp\": 1626006834,\n" + - " \"value\": 55.5,\n" + - " \"tags\": {\n" + - " \"host\": \"ubuntu\",\n" + - " \"interface\": \"eth2\",\n" + - " \"Id\": \"tb2\"\n" + - " }\n" + - " }\n" + - "]"; - - // when - SchemalessWriter writer = new SchemalessWriter(conn); - writer.write(json, SchemalessProtocolType.JSON, SchemalessTimestampType.NOT_CONFIGURED); - - // then - Statement statement = conn.createStatement(); - ResultSet rs = statement.executeQuery("show tables"); - Assert.assertNotNull(rs); - ResultSetMetaData metaData = rs.getMetaData(); - Assert.assertTrue(metaData.getColumnCount() > 0); - int rowCnt = 0; - while (rs.next()) { - rowCnt++; - } - - Assert.assertEquals(((JSONArray) JSONObject.parse(json)).size(), rowCnt); - rs.close(); - statement.close(); - } - - @Test - public void telnetListInsert() throws SQLException { - // given - List list = new ArrayList<>(); - list.add("stb0_0 1626006833 4 host=host0 interface=eth0"); - list.add("stb0_1 1626006833 4 host=host0 interface=eth0"); - list.add("stb0_2 1626006833 4 host=host0 interface=eth0 id=\"special_name\""); - // when - - SchemalessWriter writer = new SchemalessWriter(conn); - writer.write(list, SchemalessProtocolType.TELNET, SchemalessTimestampType.NOT_CONFIGURED); - - // then - Statement statement = conn.createStatement(); - ResultSet rs = statement.executeQuery("show tables"); - Assert.assertNotNull(rs); - ResultSetMetaData metaData = rs.getMetaData(); - Assert.assertTrue(metaData.getColumnCount() > 0); - int rowCnt = 0; - while (rs.next()) { - rowCnt++; - } - Assert.assertEquals(list.size(), rowCnt); - rs.close(); - statement.close(); - } - - @Before - public void before() { - String host = "127.0.0.1"; - final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - try { - conn = DriverManager.getConnection(url); - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname + " precision 'ns'"); - stmt.execute("use " + dbname); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @After - public void after() { - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists " + dbname); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SetConfigurationInJNITest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SetConfigurationInJNITest.java deleted file mode 100644 index 6a983cd5bd..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SetConfigurationInJNITest.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.taosdata.jdbc; - -import org.junit.Test; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Properties; - - -public class SetConfigurationInJNITest { - - private String host = "127.0.0.1"; - private String dbname = "test_set_config"; - - @Test - public void setConfigInUrl() { - try { - Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?user=root&password=taosdata&debugFlag=143&rpcTimer=500"); - Statement stmt = conn.createStatement(); - - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))"); - stmt.execute("drop database if exists " + dbname); - - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void setConfigInProperties() { - try { - Properties props = new Properties(); - props.setProperty("debugFlag", "143"); - props.setProperty("r pcTimer", "500"); - Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?user=root&password=taosdata", props); - - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))"); - stmt.execute("drop database if exists " + dbname); - - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - //test case1:set debugFlag=135 - //expect:debugFlag:135 - //result:pass - public void setConfigfordebugFlag() { - try { - Properties props = new Properties(); - //set debugFlag=135 - props.setProperty("debugFlag", "135"); - Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?user=root&password=taosdata", props); - - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))"); - stmt.execute("drop database if exists " + dbname); - - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - @Test - //test case2:set debugFlag=abc (wrong type) - //expect:debugFlag:135 - //result:pass - public void setConfigforwrongtype() { - try { - Properties props = new Properties(); - //set debugFlag=135 - props.setProperty("debugFlag", "abc"); - Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?user=root&password=taosdata", props); - - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))"); - stmt.execute("drop database if exists " + dbname); - - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - @Test - //test case3:set rpcTimer=0 (smaller than the boundary conditions) - //expect:rpcTimer:300 - //result:pass - public void setConfigrpcTimer() { - try { - Properties props = new Properties(); - //set rpcTimer=0 - props.setProperty("rpcTimer", "0"); - Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?user=root&password=taosdata", props); - - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))"); - stmt.execute("drop database if exists " + dbname); - - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - @Test - //test case4:set rpcMaxTime=10000 (bigger than the boundary conditions) - //expect:rpcMaxTime:600 - //result:pass - public void setConfigforrpcMaxTime() { - try { - Properties props = new Properties(); - //set rpcMaxTime=10000 - props.setProperty("rpcMaxTime", "10000"); - Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?user=root&password=taosdata", props); - - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))"); - stmt.execute("drop database if exists " + dbname); - - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - @Test - //test case5:set numOfThreadsPerCore=aaa (wrong type) - //expect:numOfThreadsPerCore:1.0 - //result:pass - public void setConfigfornumOfThreadsPerCore() { - try { - Properties props = new Properties(); - //set numOfThreadsPerCore=aaa - props.setProperty("numOfThreadsPerCore", "aaa"); - Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?user=root&password=taosdata", props); - - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))"); - stmt.execute("drop database if exists " + dbname); - - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - @Test - //test case6:set numOfThreadsPerCore=100000 (bigger than the boundary conditions) - //expect:numOfThreadsPerCore:1.0 - //result:pass - public void setConfignumOfThreadsPerCore() { - try { - Properties props = new Properties(); - //set numOfThreadsPerCore=100000 - props.setProperty("numOfThreadsPerCore", "100000"); - Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?user=root&password=taosdata", props); - - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))"); - stmt.execute("drop database if exists " + dbname); - - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - @Test - // test case7:set both true and wrong config(debugFlag=0,rpcDebugFlag=143,cDebugFlag=143,rpcTimer=100000) - // expect:rpcDebugFlag:143,cDebugFlag:143,rpcTimer:300 - // result:pass - public void setConfigformaxTmrCtrl() { - try { - Properties props = new Properties(); - props.setProperty("debugFlag", "0"); - props.setProperty("rpcDebugFlag", "143"); - props.setProperty("cDebugFlag", "143"); - props.setProperty("rpcTimer", "100000"); - Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?user=root&password=taosdata", props); - - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))"); - stmt.execute("drop database if exists " + dbname); - - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - @Test - //test case 8:use url to set with wrong type(debugFlag=abc,rpcTimer=abc) - //expect:default value - //result:pass - public void setConfigInUrlwithwrongtype() { - try { - Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?user=root&password=taosdata&debugFlag=abc&rpcTimer=abc"); - Statement stmt = conn.createStatement(); - - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))"); - stmt.execute("drop database if exists " + dbname); - - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SubscribeTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SubscribeTest.java deleted file mode 100644 index 95307071e1..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SubscribeTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.taosdata.jdbc; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -public class SubscribeTest { - - Connection connection; - Statement statement; - String dbName = "test"; - String tName = "t0"; - String host = "127.0.0.1"; - String topic = "test"; - private long ts; - - @Test - public void subscribe() { - try { - String rawSql = "select * from " + dbName + "." + tName + ";"; - TSDBConnection conn = connection.unwrap(TSDBConnection.class); - TSDBSubscribe subscribe = conn.subscribe(topic, rawSql, false); - - for (int j = 0; j < 10; j++) { - TimeUnit.SECONDS.sleep(1); - TSDBResultSet resSet = subscribe.consume(); - - int rowCnt = 0; - while (resSet.next()) { - if (rowCnt == 0) { - long cur_ts = resSet.getTimestamp(1).getTime(); - int k = resSet.getInt(2); - int v = resSet.getInt(3); - Assert.assertEquals(ts, cur_ts); - Assert.assertEquals(100, k); - Assert.assertEquals(1, v); - } - if (rowCnt == 1) { - long cur_ts = resSet.getTimestamp(1).getTime(); - int k = resSet.getInt(2); - int v = resSet.getInt(3); - Assert.assertEquals(ts + 1, cur_ts); - Assert.assertEquals(101, k); - Assert.assertEquals(2, v); - - } - rowCnt++; - } - if (j == 0) - Assert.assertEquals(2, rowCnt); - resSet.close(); - } - subscribe.close(true); - - - } catch (SQLException | InterruptedException throwables) { - throwables.printStackTrace(); - } - } - - @Before - public void createDatabase() throws SQLException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties); - - statement = connection.createStatement(); - statement.execute("drop database if exists " + dbName); - statement.execute("create database if not exists " + dbName); - statement.execute("create table if not exists " + dbName + "." + tName + " (ts timestamp, k int, v int)"); - ts = System.currentTimeMillis(); - statement.executeUpdate("insert into " + dbName + "." + tName + " values (" + ts + ", 100, 1)"); - statement.executeUpdate("insert into " + dbName + "." + tName + " values (" + (ts + 1) + ", 101, 2)"); - } - - @After - public void close() { - try { - statement.execute("drop database " + dbName); - if (statement != null) - statement.close(); - if (connection != null) - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBConnectionTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBConnectionTest.java deleted file mode 100644 index c69a556ae4..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBConnectionTest.java +++ /dev/null @@ -1,391 +0,0 @@ -package com.taosdata.jdbc; - -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; - -public class TSDBConnectionTest { - - private static final String host = "127.0.0.1"; - private static Connection conn; - - @Test - public void getConnection() { - // already test in beforeClass method - } - - @Test - public void createStatement() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select server_status()"); - rs.next(); - int status = rs.getInt("server_status()"); - Assert.assertEquals(1, status); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void prepareStatement() throws SQLException { - PreparedStatement pstmt = conn.prepareStatement("select server_status()"); - ResultSet rs = pstmt.executeQuery(); - rs.next(); - int status = rs.getInt("server_status()"); - Assert.assertEquals(1, status); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void prepareCall() throws SQLException { - conn.prepareCall("select server_status()"); - } - - @Test - public void nativeSQL() throws SQLException { - String nativeSQL = conn.nativeSQL("select * from log.log"); - Assert.assertEquals("select * from log.log", nativeSQL); - } - - @Test - public void setAutoCommit() throws SQLException { - conn.setAutoCommit(true); - conn.setAutoCommit(false); - } - - @Test - public void getAutoCommit() throws SQLException { - Assert.assertTrue(conn.getAutoCommit()); - } - - @Test - public void commit() throws SQLException { - conn.commit(); - } - - @Test - public void rollback() throws SQLException { - conn.rollback(); - } - - @Test - public void close() { - // connection will close in afterClass method - } - - @Test - public void isClosed() throws SQLException { - Assert.assertFalse(conn.isClosed()); - } - - @Test - public void getMetaData() throws SQLException { - DatabaseMetaData meta = conn.getMetaData(); - Assert.assertNotNull(meta); - Assert.assertEquals("com.taosdata.jdbc.TSDBDriver", meta.getDriverName()); - } - - @Test - public void setReadOnly() throws SQLException { - conn.setReadOnly(true); - } - - @Test - public void isReadOnly() throws SQLException { - Assert.assertTrue(conn.isReadOnly()); - } - - @Test - public void setCatalog() throws SQLException { - conn.setCatalog("test"); - Assert.assertEquals("test", conn.getCatalog()); - } - - @Test - public void getCatalog() throws SQLException { - conn.setCatalog("log"); - Assert.assertEquals("log", conn.getCatalog()); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setTransactionIsolation() throws SQLException { - conn.setTransactionIsolation(Connection.TRANSACTION_NONE); - Assert.assertEquals(Connection.TRANSACTION_NONE, conn.getTransactionIsolation()); - conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); - } - - @Test - public void getTransactionIsolation() throws SQLException { - Assert.assertEquals(Connection.TRANSACTION_NONE, conn.getTransactionIsolation()); - } - - @Test - public void getWarnings() throws SQLException { - Assert.assertNull(conn.getWarnings()); - } - - @Test - public void clearWarnings() throws SQLException { - conn.clearWarnings(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testCreateStatement() throws SQLException { - Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - ResultSet rs = stmt.executeQuery("select server_status()"); - rs.next(); - int status = rs.getInt("server_status()"); - Assert.assertEquals(1, status); - - conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testPrepareStatement() throws SQLException { - PreparedStatement pstmt = conn.prepareStatement("select server_status()", - ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - ResultSet rs = pstmt.executeQuery(); - rs.next(); - int status = rs.getInt("server_status()"); - Assert.assertEquals(1, status); - - conn.prepareStatement("select server_status", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testPrepareCall() throws SQLException { - conn.prepareCall("", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getTypeMap() throws SQLException { - conn.getTypeMap(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setTypeMap() throws SQLException { - conn.setTypeMap(null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setHoldability() throws SQLException { - conn.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); - Assert.assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, conn.getHoldability()); - conn.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); - } - - @Test - public void getHoldability() throws SQLException { - Assert.assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, conn.getHoldability()); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setSavepoint() throws SQLException { - conn.setSavepoint(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testSetSavepoint() throws SQLException { - conn.setSavepoint(null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testRollback() throws SQLException { - conn.rollback(null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void releaseSavepoint() throws SQLException { - conn.releaseSavepoint(null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testCreateStatement1() throws SQLException { - Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); - ResultSet rs = stmt.executeQuery("select server_status()"); - rs.next(); - int status = rs.getInt("server_status()"); - Assert.assertEquals(1, status); - - conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testPrepareStatement1() throws SQLException { - PreparedStatement pstmt = conn.prepareStatement("select server_status()", - ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); - ResultSet rs = pstmt.executeQuery(); - rs.next(); - int status = rs.getInt("server_status()"); - Assert.assertEquals(1, status); - - conn.prepareStatement("select server_status", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testPrepareCall1() throws SQLException { - conn.prepareCall("", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testPrepareStatement2() throws SQLException { - Assert.assertNotNull("", Statement.NO_GENERATED_KEYS); - conn.prepareStatement("", Statement.RETURN_GENERATED_KEYS); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testPrepareStatement3() throws SQLException { - conn.prepareStatement("", new int[]{}); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testPrepareStatement4() throws SQLException { - conn.prepareStatement("", new String[]{}); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void createClob() throws SQLException { - conn.createClob(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void createBlob() throws SQLException { - conn.createBlob(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void createNClob() throws SQLException { - conn.createNClob(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void createSQLXML() throws SQLException { - conn.createSQLXML(); - } - - @Test(expected = SQLException.class) - public void isValid() throws SQLException { - Assert.assertTrue(conn.isValid(10)); - Assert.assertTrue(conn.isValid(0)); - conn.isValid(-1); - } - - @Test - public void setClientInfo() throws SQLClientInfoException { - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_CHARSET, "en_US.UTF-8"); - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_CHARSET, "UTC-8"); - } - - @Test - public void testSetClientInfo() throws SQLClientInfoException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - conn.setClientInfo(properties); - } - - @Test - public void getClientInfo() throws SQLException { - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - - Properties info = conn.getClientInfo(); - String charset = info.getProperty(TSDBDriver.PROPERTY_KEY_CHARSET); - Assert.assertEquals("UTF-8", charset); - String locale = info.getProperty(TSDBDriver.PROPERTY_KEY_LOCALE); - Assert.assertEquals("en_US.UTF-8", locale); - String timezone = info.getProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE); - Assert.assertEquals("UTC-8", timezone); - } - - @Test - public void testGetClientInfo() throws SQLException { - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - - String charset = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_CHARSET); - Assert.assertEquals("UTF-8", charset); - String locale = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_LOCALE); - Assert.assertEquals("en_US.UTF-8", locale); - String timezone = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIME_ZONE); - Assert.assertEquals("UTC-8", timezone); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void createArrayOf() throws SQLException { - conn.createArrayOf("", null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void createStruct() throws SQLException { - conn.createStruct("", null); - } - - @Test - public void setSchema() throws SQLException { - conn.setSchema("test"); - } - - @Test - public void getSchema() throws SQLException { - Assert.assertNull(conn.getSchema()); - } - - @Test - public void abort() throws SQLException { - conn.abort(null); - } - - @Test - public void setNetworkTimeout() throws SQLException { - conn.setNetworkTimeout(null, 1000); - } - - @Test - public void getNetworkTimeout() throws SQLException { - int networkTimeout = conn.getNetworkTimeout(); - Assert.assertEquals(0, networkTimeout); - } - - @Test - public void unwrap() throws SQLException { - TSDBConnection tsdbConnection = conn.unwrap(TSDBConnection.class); - Assert.assertNotNull(tsdbConnection); - } - - @Test - public void isWrapperFor() throws SQLException { - Assert.assertTrue(conn.isWrapperFor(TSDBConnection.class)); - } - - @BeforeClass - public static void beforeClass() throws SQLException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/log?user=root&password=taosdata", properties); - // create test database for test cases - try (Statement stmt = conn.createStatement()) { - stmt.execute("create database if not exists test"); - } - } - - @AfterClass - public static void afterClass() throws SQLException { - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists test"); - statement.close(); - conn.close(); - } - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBDatabaseMetaDataTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBDatabaseMetaDataTest.java deleted file mode 100644 index d620168c80..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBDatabaseMetaDataTest.java +++ /dev/null @@ -1,1107 +0,0 @@ -package com.taosdata.jdbc; - -import org.junit.*; - -import java.sql.*; -import java.util.Properties; - -public class TSDBDatabaseMetaDataTest { - private static final String host = "127.0.0.1"; - private static final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - private static Connection connection; - private static TSDBDatabaseMetaData metaData; - - - @Test - public void unwrap() throws SQLException { - TSDBDatabaseMetaData unwrap = metaData.unwrap(TSDBDatabaseMetaData.class); - Assert.assertNotNull(unwrap); - } - - @Test - public void isWrapperFor() throws SQLException { - Assert.assertTrue(metaData.isWrapperFor(TSDBDatabaseMetaData.class)); - } - - @Test - public void allProceduresAreCallable() throws SQLException { - Assert.assertFalse(metaData.allProceduresAreCallable()); - } - - @Test - public void allTablesAreSelectable() throws SQLException { - Assert.assertFalse(metaData.allTablesAreSelectable()); - } - - @Test - public void getURL() throws SQLException { - Assert.assertEquals(url, metaData.getURL()); - } - - @Test - public void getUserName() throws SQLException { - Assert.assertEquals("root", metaData.getUserName()); - } - - @Test - public void isReadOnly() throws SQLException { - Assert.assertFalse(metaData.isReadOnly()); - } - - @Test - public void nullsAreSortedHigh() throws SQLException { - Assert.assertFalse(metaData.nullsAreSortedHigh()); - } - - @Test - public void nullsAreSortedLow() throws SQLException { - Assert.assertTrue(metaData.nullsAreSortedLow()); - } - - @Test - public void nullsAreSortedAtStart() throws SQLException { - Assert.assertTrue(metaData.nullsAreSortedAtStart()); - } - - @Test - public void nullsAreSortedAtEnd() throws SQLException { - Assert.assertFalse(metaData.nullsAreSortedAtEnd()); - } - - @Test - public void getDatabaseProductName() throws SQLException { - Assert.assertEquals("TDengine", metaData.getDatabaseProductName()); - } - - @Test - public void getDatabaseProductVersion() throws SQLException { - Assert.assertEquals("2.0.x.x", metaData.getDatabaseProductVersion()); - } - - @Test - public void getDriverName() throws SQLException { - Assert.assertEquals("com.taosdata.jdbc.TSDBDriver", metaData.getDriverName()); - } - - @Test - public void getDriverVersion() throws SQLException { - Assert.assertEquals("2.0.x", metaData.getDriverVersion()); - } - - @Test - public void getDriverMajorVersion() { - Assert.assertEquals(2, metaData.getDriverMajorVersion()); - } - - @Test - public void getDriverMinorVersion() { - Assert.assertEquals(0, metaData.getDriverMinorVersion()); - } - - @Test - public void usesLocalFiles() throws SQLException { - Assert.assertFalse(metaData.usesLocalFiles()); - } - - @Test - public void usesLocalFilePerTable() throws SQLException { - Assert.assertFalse(metaData.usesLocalFilePerTable()); - } - - @Test - public void supportsMixedCaseIdentifiers() throws SQLException { - Assert.assertFalse(metaData.supportsMixedCaseIdentifiers()); - } - - @Test - public void storesUpperCaseIdentifiers() throws SQLException { - Assert.assertFalse(metaData.storesUpperCaseIdentifiers()); - } - - @Test - public void storesLowerCaseIdentifiers() throws SQLException { - Assert.assertTrue(metaData.storesLowerCaseIdentifiers()); - } - - @Test - public void storesMixedCaseIdentifiers() throws SQLException { - Assert.assertFalse(metaData.storesMixedCaseIdentifiers()); - } - - @Test - public void supportsMixedCaseQuotedIdentifiers() throws SQLException { - Assert.assertFalse(metaData.supportsMixedCaseQuotedIdentifiers()); - } - - @Test - public void storesUpperCaseQuotedIdentifiers() throws SQLException { - Assert.assertFalse(metaData.storesUpperCaseQuotedIdentifiers()); - } - - @Test - public void storesLowerCaseQuotedIdentifiers() throws SQLException { - Assert.assertFalse(metaData.storesLowerCaseQuotedIdentifiers()); - } - - @Test - public void storesMixedCaseQuotedIdentifiers() throws SQLException { - Assert.assertFalse(metaData.storesMixedCaseQuotedIdentifiers()); - } - - @Test - public void getIdentifierQuoteString() throws SQLException { - Assert.assertEquals(" ", metaData.getIdentifierQuoteString()); - } - - @Test - public void getSQLKeywords() throws SQLException { - Assert.assertEquals(null, metaData.getSQLKeywords()); - } - - @Test - public void getNumericFunctions() throws SQLException { - Assert.assertEquals(null, metaData.getNumericFunctions()); - } - - @Test - public void getStringFunctions() throws SQLException { - Assert.assertEquals(null, metaData.getStringFunctions()); - } - - @Test - public void getSystemFunctions() throws SQLException { - Assert.assertEquals(null, metaData.getSystemFunctions()); - } - - @Test - public void getTimeDateFunctions() throws SQLException { - Assert.assertEquals(null, metaData.getTimeDateFunctions()); - } - - @Test - public void getSearchStringEscape() throws SQLException { - Assert.assertEquals(null, metaData.getSearchStringEscape()); - } - - @Test - public void getExtraNameCharacters() throws SQLException { - Assert.assertEquals(null, metaData.getExtraNameCharacters()); - } - - @Test - public void supportsAlterTableWithAddColumn() throws SQLException { - Assert.assertTrue(metaData.supportsAlterTableWithAddColumn()); - } - - @Test - public void supportsAlterTableWithDropColumn() throws SQLException { - Assert.assertTrue(metaData.supportsAlterTableWithDropColumn()); - } - - @Test - public void supportsColumnAliasing() throws SQLException { - Assert.assertTrue(metaData.supportsColumnAliasing()); - } - - @Test - public void nullPlusNonNullIsNull() throws SQLException { - Assert.assertFalse(metaData.nullPlusNonNullIsNull()); - } - - @Test - public void supportsConvert() throws SQLException { - Assert.assertFalse(metaData.supportsConvert()); - } - - @Test - public void testSupportsConvert() throws SQLException { - Assert.assertFalse(metaData.supportsConvert(1, 1)); - } - - @Test - public void supportsTableCorrelationNames() throws SQLException { - Assert.assertFalse(metaData.supportsTableCorrelationNames()); - } - - @Test - public void supportsDifferentTableCorrelationNames() throws SQLException { - Assert.assertFalse(metaData.supportsDifferentTableCorrelationNames()); - } - - @Test - public void supportsExpressionsInOrderBy() throws SQLException { - Assert.assertFalse(metaData.supportsExpressionsInOrderBy()); - } - - @Test - public void supportsOrderByUnrelated() throws SQLException { - Assert.assertFalse(metaData.supportsOrderByUnrelated()); - } - - @Test - public void supportsGroupBy() throws SQLException { - Assert.assertTrue(metaData.supportsGroupBy()); - } - - @Test - public void supportsGroupByUnrelated() throws SQLException { - Assert.assertFalse(metaData.supportsGroupByUnrelated()); - } - - @Test - public void supportsGroupByBeyondSelect() throws SQLException { - Assert.assertFalse(metaData.supportsGroupByBeyondSelect()); - } - - @Test - public void supportsLikeEscapeClause() throws SQLException { - Assert.assertFalse(metaData.supportsLikeEscapeClause()); - } - - @Test - public void supportsMultipleResultSets() throws SQLException { - Assert.assertFalse(metaData.supportsMultipleResultSets()); - } - - @Test - public void supportsMultipleTransactions() throws SQLException { - Assert.assertFalse(metaData.supportsMultipleTransactions()); - } - - @Test - public void supportsNonNullableColumns() throws SQLException { - Assert.assertFalse(metaData.supportsNonNullableColumns()); - } - - @Test - public void supportsMinimumSQLGrammar() throws SQLException { - Assert.assertFalse(metaData.supportsMinimumSQLGrammar()); - } - - @Test - public void supportsCoreSQLGrammar() throws SQLException { - Assert.assertFalse(metaData.supportsCoreSQLGrammar()); - } - - @Test - public void supportsExtendedSQLGrammar() throws SQLException { - Assert.assertFalse(metaData.supportsExtendedSQLGrammar()); - } - - @Test - public void supportsANSI92EntryLevelSQL() throws SQLException { - Assert.assertFalse(metaData.supportsANSI92EntryLevelSQL()); - } - - @Test - public void supportsANSI92IntermediateSQL() throws SQLException { - Assert.assertFalse(metaData.supportsANSI92IntermediateSQL()); - } - - @Test - public void supportsANSI92FullSQL() throws SQLException { - Assert.assertFalse(metaData.supportsANSI92FullSQL()); - } - - @Test - public void supportsIntegrityEnhancementFacility() throws SQLException { - Assert.assertFalse(metaData.supportsIntegrityEnhancementFacility()); - } - - @Test - public void supportsOuterJoins() throws SQLException { - Assert.assertFalse(metaData.supportsOuterJoins()); - } - - @Test - public void supportsFullOuterJoins() throws SQLException { - Assert.assertFalse(metaData.supportsFullOuterJoins()); - } - - @Test - public void supportsLimitedOuterJoins() throws SQLException { - Assert.assertFalse(metaData.supportsLimitedOuterJoins()); - } - - @Test - public void getSchemaTerm() throws SQLException { - Assert.assertNull(metaData.getSchemaTerm()); - } - - @Test - public void getProcedureTerm() throws SQLException { - Assert.assertNull(metaData.getProcedureTerm()); - } - - @Test - public void getCatalogTerm() throws SQLException { - Assert.assertEquals("database", metaData.getCatalogTerm()); - } - - @Test - public void isCatalogAtStart() throws SQLException { - Assert.assertTrue(metaData.isCatalogAtStart()); - } - - @Test - public void getCatalogSeparator() throws SQLException { - Assert.assertEquals(".", metaData.getCatalogSeparator()); - } - - @Test - public void supportsSchemasInDataManipulation() throws SQLException { - Assert.assertFalse(metaData.supportsSchemasInDataManipulation()); - } - - @Test - public void supportsSchemasInProcedureCalls() throws SQLException { - Assert.assertFalse(metaData.supportsSchemasInProcedureCalls()); - } - - @Test - public void supportsSchemasInTableDefinitions() throws SQLException { - Assert.assertFalse(metaData.supportsSchemasInTableDefinitions()); - } - - @Test - public void supportsSchemasInIndexDefinitions() throws SQLException { - Assert.assertFalse(metaData.supportsSchemasInIndexDefinitions()); - } - - @Test - public void supportsSchemasInPrivilegeDefinitions() throws SQLException { - Assert.assertFalse(metaData.supportsSchemasInPrivilegeDefinitions()); - } - - @Test - public void supportsCatalogsInDataManipulation() throws SQLException { - Assert.assertTrue(metaData.supportsCatalogsInDataManipulation()); - } - - @Test - public void supportsCatalogsInProcedureCalls() throws SQLException { - Assert.assertFalse(metaData.supportsCatalogsInProcedureCalls()); - } - - @Test - public void supportsCatalogsInTableDefinitions() throws SQLException { - Assert.assertFalse(metaData.supportsCatalogsInTableDefinitions()); - } - - @Test - public void supportsCatalogsInIndexDefinitions() throws SQLException { - Assert.assertFalse(metaData.supportsCatalogsInIndexDefinitions()); - } - - @Test - public void supportsCatalogsInPrivilegeDefinitions() throws SQLException { - Assert.assertFalse(metaData.supportsCatalogsInPrivilegeDefinitions()); - } - - @Test - public void supportsPositionedDelete() throws SQLException { - Assert.assertFalse(metaData.supportsPositionedDelete()); - } - - @Test - public void supportsPositionedUpdate() throws SQLException { - Assert.assertFalse(metaData.supportsPositionedUpdate()); - } - - @Test - public void supportsSelectForUpdate() throws SQLException { - Assert.assertFalse(metaData.supportsSelectForUpdate()); - } - - @Test - public void supportsStoredProcedures() throws SQLException { - Assert.assertFalse(metaData.supportsStoredProcedures()); - } - - @Test - public void supportsSubqueriesInComparisons() throws SQLException { - Assert.assertFalse(metaData.supportsSubqueriesInComparisons()); - } - - @Test - public void supportsSubqueriesInExists() throws SQLException { - Assert.assertFalse(metaData.supportsSubqueriesInExists()); - } - - @Test - public void supportsSubqueriesInIns() throws SQLException { - Assert.assertFalse(metaData.supportsSubqueriesInIns()); - } - - @Test - public void supportsSubqueriesInQuantifieds() throws SQLException { - Assert.assertFalse(metaData.supportsSubqueriesInQuantifieds()); - } - - @Test - public void supportsCorrelatedSubqueries() throws SQLException { - Assert.assertFalse(metaData.supportsCorrelatedSubqueries()); - } - - @Test - public void supportsUnion() throws SQLException { - Assert.assertFalse(metaData.supportsUnion()); - } - - @Test - public void supportsUnionAll() throws SQLException { - Assert.assertFalse(metaData.supportsUnionAll()); - } - - @Test - public void supportsOpenCursorsAcrossCommit() throws SQLException { - Assert.assertFalse(metaData.supportsOpenCursorsAcrossCommit()); - } - - @Test - public void supportsOpenCursorsAcrossRollback() throws SQLException { - Assert.assertFalse(metaData.supportsOpenCursorsAcrossRollback()); - } - - @Test - public void supportsOpenStatementsAcrossCommit() throws SQLException { - Assert.assertFalse(metaData.supportsOpenStatementsAcrossCommit()); - } - - @Test - public void supportsOpenStatementsAcrossRollback() throws SQLException { - Assert.assertFalse(metaData.supportsOpenStatementsAcrossRollback()); - } - - @Test - public void getMaxBinaryLiteralLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxBinaryLiteralLength()); - } - - @Test - public void getMaxCharLiteralLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxCharLiteralLength()); - } - - @Test - public void getMaxColumnNameLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxColumnNameLength()); - } - - @Test - public void getMaxColumnsInGroupBy() throws SQLException { - Assert.assertEquals(0, metaData.getMaxColumnsInGroupBy()); - } - - @Test - public void getMaxColumnsInIndex() throws SQLException { - Assert.assertEquals(0, metaData.getMaxColumnsInIndex()); - } - - @Test - public void getMaxColumnsInOrderBy() throws SQLException { - Assert.assertEquals(0, metaData.getMaxColumnsInOrderBy()); - } - - @Test - public void getMaxColumnsInSelect() throws SQLException { - Assert.assertEquals(0, metaData.getMaxColumnsInSelect()); - } - - @Test - public void getMaxColumnsInTable() throws SQLException { - Assert.assertEquals(0, metaData.getMaxColumnsInTable()); - } - - @Test - public void getMaxConnections() throws SQLException { - Assert.assertEquals(0, metaData.getMaxConnections()); - } - - @Test - public void getMaxCursorNameLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxCursorNameLength()); - } - - @Test - public void getMaxIndexLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxIndexLength()); - } - - @Test - public void getMaxSchemaNameLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxSchemaNameLength()); - } - - @Test - public void getMaxProcedureNameLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxProcedureNameLength()); - } - - @Test - public void getMaxCatalogNameLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxCatalogNameLength()); - } - - @Test - public void getMaxRowSize() throws SQLException { - Assert.assertEquals(0, metaData.getMaxRowSize()); - } - - @Test - public void doesMaxRowSizeIncludeBlobs() throws SQLException { - Assert.assertFalse(metaData.doesMaxRowSizeIncludeBlobs()); - } - - @Test - public void getMaxStatementLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxStatementLength()); - } - - @Test - public void getMaxStatements() throws SQLException { - Assert.assertEquals(0, metaData.getMaxStatements()); - } - - @Test - public void getMaxTableNameLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxTableNameLength()); - } - - @Test - public void getMaxTablesInSelect() throws SQLException { - Assert.assertEquals(0, metaData.getMaxTablesInSelect()); - } - - @Test - public void getMaxUserNameLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxUserNameLength()); - } - - @Test - public void getDefaultTransactionIsolation() throws SQLException { - Assert.assertEquals(Connection.TRANSACTION_NONE, metaData.getDefaultTransactionIsolation()); - } - - @Test - public void supportsTransactions() throws SQLException { - Assert.assertFalse(metaData.supportsTransactions()); - } - - @Test - public void supportsTransactionIsolationLevel() throws SQLException { - Assert.assertTrue(metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_NONE)); - Assert.assertFalse(metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED)); - Assert.assertFalse(metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED)); - Assert.assertFalse(metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ)); - Assert.assertFalse(metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE)); - } - - @Test - public void supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { - Assert.assertFalse(metaData.supportsDataDefinitionAndDataManipulationTransactions()); - } - - @Test - public void supportsDataManipulationTransactionsOnly() throws SQLException { - Assert.assertFalse(metaData.supportsDataManipulationTransactionsOnly()); - } - - @Test - public void dataDefinitionCausesTransactionCommit() throws SQLException { - Assert.assertFalse(metaData.dataDefinitionCausesTransactionCommit()); - } - - @Test - public void dataDefinitionIgnoredInTransactions() throws SQLException { - Assert.assertFalse(metaData.dataDefinitionIgnoredInTransactions()); - } - - @Test - public void getProcedures() throws SQLException { - Assert.assertNull(metaData.getProcedures("*", "*", "*")); - } - - @Test - public void getProcedureColumns() throws SQLException { - Assert.assertNull(metaData.getProcedureColumns("*", "*", "*", "*")); - } - - @Test - public void getTables() throws SQLException { - ResultSet rs = metaData.getTables("log", "", null, null); - ResultSetMetaData meta = rs.getMetaData(); - Assert.assertNotNull(rs); - rs.next(); - { - // TABLE_CAT - Assert.assertEquals("TABLE_CAT", meta.getColumnLabel(1)); - Assert.assertEquals("log", rs.getString(1)); - Assert.assertEquals("log", rs.getString("TABLE_CAT")); - // TABLE_SCHEM - Assert.assertEquals("TABLE_SCHEM", meta.getColumnLabel(2)); - Assert.assertEquals(null, rs.getString(2)); - Assert.assertEquals(null, rs.getString("TABLE_SCHEM")); - // TABLE_NAME - Assert.assertEquals("TABLE_NAME", meta.getColumnLabel(3)); - Assert.assertNotNull(rs.getString(3)); - Assert.assertNotNull(rs.getString("TABLE_NAME")); - // TABLE_TYPE - Assert.assertEquals("TABLE_TYPE", meta.getColumnLabel(4)); - Assert.assertEquals("TABLE", rs.getString(4)); - Assert.assertEquals("TABLE", rs.getString("TABLE_TYPE")); - // REMARKS - Assert.assertEquals("REMARKS", meta.getColumnLabel(5)); - Assert.assertEquals("", rs.getString(5)); - Assert.assertEquals("", rs.getString("REMARKS")); - } - } - - @Test - public void getSchemas() throws SQLException { - Assert.assertNotNull(metaData.getSchemas()); - } - - @Test - public void getCatalogs() throws SQLException { - ResultSet rs = metaData.getCatalogs(); - ResultSetMetaData meta = rs.getMetaData(); - rs.next(); - { - // TABLE_CAT - Assert.assertEquals("TABLE_CAT", meta.getColumnLabel(1)); - Assert.assertNotNull(rs.getString(1)); - Assert.assertNotNull(rs.getString("TABLE_CAT")); - } - } - - @Test - public void getTableTypes() throws SQLException { - ResultSet tableTypes = metaData.getTableTypes(); - tableTypes.next(); - // tableTypes: table - { - Assert.assertEquals("TABLE", tableTypes.getString(1)); - Assert.assertEquals("TABLE", tableTypes.getString("TABLE_TYPE")); - } - tableTypes.next(); - // tableTypes: stable - { - Assert.assertEquals("STABLE", tableTypes.getString(1)); - Assert.assertEquals("STABLE", tableTypes.getString("TABLE_TYPE")); - } - } - - @Test - public void getColumns() throws SQLException { - // when - ResultSet columns = metaData.getColumns("log", "", "dn", ""); - // then - ResultSetMetaData meta = columns.getMetaData(); - columns.next(); - // column: 1 - { - // TABLE_CAT - Assert.assertEquals("TABLE_CAT", meta.getColumnLabel(1)); - Assert.assertEquals("log", columns.getString(1)); - Assert.assertEquals("log", columns.getString("TABLE_CAT")); - // TABLE_NAME - Assert.assertEquals("TABLE_NAME", meta.getColumnLabel(3)); - Assert.assertEquals("dn", columns.getString(3)); - Assert.assertEquals("dn", columns.getString("TABLE_NAME")); - // COLUMN_NAME - Assert.assertEquals("COLUMN_NAME", meta.getColumnLabel(4)); - Assert.assertEquals("ts", columns.getString(4)); - Assert.assertEquals("ts", columns.getString("COLUMN_NAME")); - // DATA_TYPE - Assert.assertEquals("DATA_TYPE", meta.getColumnLabel(5)); - Assert.assertEquals(Types.TIMESTAMP, columns.getInt(5)); - Assert.assertEquals(Types.TIMESTAMP, columns.getInt("DATA_TYPE")); - // TYPE_NAME - Assert.assertEquals("TYPE_NAME", meta.getColumnLabel(6)); - Assert.assertEquals("TIMESTAMP", columns.getString(6)); - Assert.assertEquals("TIMESTAMP", columns.getString("TYPE_NAME")); - // COLUMN_SIZE - Assert.assertEquals("COLUMN_SIZE", meta.getColumnLabel(7)); - Assert.assertEquals(26, columns.getInt(7)); - Assert.assertEquals(26, columns.getInt("COLUMN_SIZE")); - // DECIMAL_DIGITS - Assert.assertEquals("DECIMAL_DIGITS", meta.getColumnLabel(9)); - Assert.assertEquals(0, columns.getInt(9)); - Assert.assertEquals(0, columns.getInt("DECIMAL_DIGITS")); - Assert.assertEquals(null, columns.getString(9)); - Assert.assertEquals(null, columns.getString("DECIMAL_DIGITS")); - // NUM_PREC_RADIX - Assert.assertEquals("NUM_PREC_RADIX", meta.getColumnLabel(10)); - Assert.assertEquals(10, columns.getInt(10)); - Assert.assertEquals(10, columns.getInt("NUM_PREC_RADIX")); - // NULLABLE - Assert.assertEquals("NULLABLE", meta.getColumnLabel(11)); - Assert.assertEquals(DatabaseMetaData.columnNoNulls, columns.getInt(11)); - Assert.assertEquals(DatabaseMetaData.columnNoNulls, columns.getInt("NULLABLE")); - // REMARKS - Assert.assertEquals("REMARKS", meta.getColumnLabel(12)); - Assert.assertEquals(null, columns.getString(12)); - Assert.assertEquals(null, columns.getString("REMARKS")); - } - columns.next(); - // column: 2 - { - // TABLE_CAT - Assert.assertEquals("TABLE_CAT", meta.getColumnLabel(1)); - Assert.assertEquals("log", columns.getString(1)); - Assert.assertEquals("log", columns.getString("TABLE_CAT")); - // TABLE_NAME - Assert.assertEquals("TABLE_NAME", meta.getColumnLabel(3)); - Assert.assertEquals("dn", columns.getString(3)); - Assert.assertEquals("dn", columns.getString("TABLE_NAME")); - // COLUMN_NAME - Assert.assertEquals("COLUMN_NAME", meta.getColumnLabel(4)); - Assert.assertEquals("cpu_taosd", columns.getString(4)); - Assert.assertEquals("cpu_taosd", columns.getString("COLUMN_NAME")); - // DATA_TYPE - Assert.assertEquals("DATA_TYPE", meta.getColumnLabel(5)); - Assert.assertEquals(Types.FLOAT, columns.getInt(5)); - Assert.assertEquals(Types.FLOAT, columns.getInt("DATA_TYPE")); - // TYPE_NAME - Assert.assertEquals("TYPE_NAME", meta.getColumnLabel(6)); - Assert.assertEquals("FLOAT", columns.getString(6)); - Assert.assertEquals("FLOAT", columns.getString("TYPE_NAME")); - // COLUMN_SIZE - Assert.assertEquals("COLUMN_SIZE", meta.getColumnLabel(7)); - Assert.assertEquals(12, columns.getInt(7)); - Assert.assertEquals(12, columns.getInt("COLUMN_SIZE")); - // DECIMAL_DIGITS - Assert.assertEquals("DECIMAL_DIGITS", meta.getColumnLabel(9)); - Assert.assertEquals(0, columns.getInt(9)); - Assert.assertEquals(0, columns.getInt("DECIMAL_DIGITS")); - Assert.assertEquals(null, columns.getString(9)); - Assert.assertEquals(null, columns.getString("DECIMAL_DIGITS")); - // NUM_PREC_RADIX - Assert.assertEquals("NUM_PREC_RADIX", meta.getColumnLabel(10)); - Assert.assertEquals(10, columns.getInt(10)); - Assert.assertEquals(10, columns.getInt("NUM_PREC_RADIX")); - // NULLABLE - Assert.assertEquals("NULLABLE", meta.getColumnLabel(11)); - Assert.assertEquals(DatabaseMetaData.columnNullable, columns.getInt(11)); - Assert.assertEquals(DatabaseMetaData.columnNullable, columns.getInt("NULLABLE")); - // REMARKS - Assert.assertEquals("REMARKS", meta.getColumnLabel(12)); - Assert.assertEquals(null, columns.getString(12)); - } - } - - @Test - public void getColumnPrivileges() throws SQLException { - Assert.assertNotNull(metaData.getColumnPrivileges("", "", "", "")); - } - - @Test - public void getTablePrivileges() throws SQLException { - Assert.assertNotNull(metaData.getTablePrivileges("", "", "")); - } - - @Test - public void getBestRowIdentifier() throws SQLException { - Assert.assertNotNull(metaData.getBestRowIdentifier("", "", "", 0, false)); - } - - @Test - public void getVersionColumns() throws SQLException { - Assert.assertNotNull(metaData.getVersionColumns("", "", "")); - } - - @Test - public void getPrimaryKeys() throws SQLException { - ResultSet rs = metaData.getPrimaryKeys("log", "", "dn1"); - ResultSetMetaData meta = rs.getMetaData(); - rs.next(); - { - // TABLE_CAT - Assert.assertEquals("TABLE_CAT", meta.getColumnLabel(1)); - Assert.assertEquals("log", rs.getString(1)); - Assert.assertEquals("log", rs.getString("TABLE_CAT")); - // TABLE_SCHEM - Assert.assertEquals("TABLE_SCHEM", meta.getColumnLabel(2)); - Assert.assertEquals(null, rs.getString(2)); - Assert.assertEquals(null, rs.getString("TABLE_SCHEM")); - // TABLE_NAME - Assert.assertEquals("TABLE_NAME", meta.getColumnLabel(3)); - Assert.assertEquals("dn1", rs.getString(3)); - Assert.assertEquals("dn1", rs.getString("TABLE_NAME")); - // COLUMN_NAME - Assert.assertEquals("COLUMN_NAME", meta.getColumnLabel(4)); - Assert.assertEquals("ts", rs.getString(4)); - Assert.assertEquals("ts", rs.getString("COLUMN_NAME")); - // KEY_SEQ - Assert.assertEquals("KEY_SEQ", meta.getColumnLabel(5)); - Assert.assertEquals(1, rs.getShort(5)); - Assert.assertEquals(1, rs.getShort("KEY_SEQ")); - // DATA_TYPE - Assert.assertEquals("PK_NAME", meta.getColumnLabel(6)); - Assert.assertEquals("ts", rs.getString(6)); - Assert.assertEquals("ts", rs.getString("PK_NAME")); - } - } - - @Test - public void getImportedKeys() throws SQLException { - Assert.assertNotNull(metaData.getImportedKeys("", "", "")); - } - - @Test - public void getExportedKeys() throws SQLException { - Assert.assertNotNull(metaData.getExportedKeys("", "", "")); - } - - @Test - public void getCrossReference() throws SQLException { - Assert.assertNotNull(metaData.getCrossReference("", "", "", "", "", "")); - } - - @Test - public void getTypeInfo() throws SQLException { - Assert.assertNotNull(metaData.getTypeInfo()); - } - - @Test - public void getIndexInfo() throws SQLException { - Assert.assertNotNull(metaData.getIndexInfo("", "", "", false, false)); - } - - @Test - public void supportsResultSetType() throws SQLException { - Assert.assertFalse(metaData.supportsResultSetType(0)); - } - - @Test - public void supportsResultSetConcurrency() throws SQLException { - Assert.assertFalse(metaData.supportsResultSetConcurrency(0, 0)); - } - - @Test - public void ownUpdatesAreVisible() throws SQLException { - Assert.assertFalse(metaData.ownUpdatesAreVisible(0)); - } - - @Test - public void ownDeletesAreVisible() throws SQLException { - Assert.assertFalse(metaData.ownDeletesAreVisible(0)); - } - - @Test - public void ownInsertsAreVisible() throws SQLException { - Assert.assertFalse(metaData.ownInsertsAreVisible(0)); - } - - @Test - public void othersUpdatesAreVisible() throws SQLException { - Assert.assertFalse(metaData.othersUpdatesAreVisible(0)); - } - - @Test - public void othersDeletesAreVisible() throws SQLException { - Assert.assertFalse(metaData.othersDeletesAreVisible(0)); - } - - @Test - public void othersInsertsAreVisible() throws SQLException { - Assert.assertFalse(metaData.othersInsertsAreVisible(0)); - } - - @Test - public void updatesAreDetected() throws SQLException { - Assert.assertFalse(metaData.updatesAreDetected(0)); - } - - @Test - public void deletesAreDetected() throws SQLException { - Assert.assertFalse(metaData.deletesAreDetected(0)); - } - - @Test - public void insertsAreDetected() throws SQLException { - Assert.assertFalse(metaData.insertsAreDetected(0)); - } - - @Test - public void supportsBatchUpdates() throws SQLException { - Assert.assertFalse(metaData.supportsBatchUpdates()); - } - - @Test - public void getUDTs() throws SQLException { - Assert.assertNotNull(metaData.getUDTs("", "", "", null)); - } - - @Test - public void getConnection() throws SQLException { - Assert.assertNotNull(metaData.getConnection()); - } - - @Test - public void supportsSavepoints() throws SQLException { - Assert.assertFalse(metaData.supportsSavepoints()); - } - - @Test - public void supportsNamedParameters() throws SQLException { - Assert.assertFalse(metaData.supportsNamedParameters()); - } - - @Test - public void supportsMultipleOpenResults() throws SQLException { - Assert.assertFalse(metaData.supportsMultipleOpenResults()); - } - - @Test - public void supportsGetGeneratedKeys() throws SQLException { - Assert.assertFalse(metaData.supportsGetGeneratedKeys()); - } - - @Test - public void getSuperTypes() throws SQLException { - Assert.assertNotNull(metaData.getSuperTypes("", "", "")); - } - - @Test - public void getSuperTables() throws SQLException { - ResultSet rs = metaData.getSuperTables("log", "", "dn1"); - ResultSetMetaData meta = rs.getMetaData(); - rs.next(); - { - // TABLE_CAT - Assert.assertEquals("TABLE_CAT", meta.getColumnLabel(1)); - Assert.assertEquals("log", rs.getString(1)); - Assert.assertEquals("log", rs.getString("TABLE_CAT")); - // TABLE_CAT - Assert.assertEquals("TABLE_SCHEM", meta.getColumnLabel(2)); - Assert.assertEquals(null, rs.getString(2)); - Assert.assertEquals(null, rs.getString("TABLE_SCHEM")); - // TABLE_CAT - Assert.assertEquals("TABLE_NAME", meta.getColumnLabel(3)); - Assert.assertEquals("dn1", rs.getString(3)); - Assert.assertEquals("dn1", rs.getString("TABLE_NAME")); - // TABLE_CAT - Assert.assertEquals("SUPERTABLE_NAME", meta.getColumnLabel(4)); - Assert.assertEquals("dn", rs.getString(4)); - Assert.assertEquals("dn", rs.getString("SUPERTABLE_NAME")); - } - } - - @Test - public void getAttributes() throws SQLException { - Assert.assertNotNull(metaData.getAttributes("", "", "", "")); - } - - @Test - public void supportsResultSetHoldability() throws SQLException { - Assert.assertTrue(metaData.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT)); - Assert.assertFalse(metaData.supportsResultSetHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT)); - } - - @Test - public void getResultSetHoldability() throws SQLException { - Assert.assertEquals(1, metaData.getResultSetHoldability()); - } - - @Test - public void getDatabaseMajorVersion() throws SQLException { - Assert.assertEquals(2, metaData.getDatabaseMajorVersion()); - } - - @Test - public void getDatabaseMinorVersion() throws SQLException { - Assert.assertEquals(0, metaData.getDatabaseMinorVersion()); - } - - @Test - public void getJDBCMajorVersion() throws SQLException { - Assert.assertEquals(2, metaData.getJDBCMajorVersion()); - } - - @Test - public void getJDBCMinorVersion() throws SQLException { - Assert.assertEquals(0, metaData.getJDBCMinorVersion()); - } - - @Test - public void getSQLStateType() throws SQLException { - Assert.assertEquals(0, metaData.getSQLStateType()); - } - - @Test - public void locatorsUpdateCopy() throws SQLException { - Assert.assertFalse(metaData.locatorsUpdateCopy()); - } - - @Test - public void supportsStatementPooling() throws SQLException { - Assert.assertFalse(metaData.supportsStatementPooling()); - } - - @Test - public void getRowIdLifetime() throws SQLException { - Assert.assertNull(metaData.getRowIdLifetime()); - } - - @Test - public void supportsStoredFunctionsUsingCallSyntax() throws SQLException { - Assert.assertFalse(metaData.supportsStoredFunctionsUsingCallSyntax()); - } - - @Test - public void autoCommitFailureClosesAllResultSets() throws SQLException { - Assert.assertFalse(metaData.autoCommitFailureClosesAllResultSets()); - } - - @Test - public void getClientInfoProperties() throws SQLException { - Assert.assertNotNull(metaData.getClientInfoProperties()); - } - - @Test - public void getFunctions() throws SQLException { - Assert.assertNotNull(metaData.getFunctions("", "", "")); - } - - @Test - public void getFunctionColumns() throws SQLException { - Assert.assertNotNull(metaData.getFunctionColumns("", "", "", "")); - } - - @Test - public void getPseudoColumns() throws SQLException { - Assert.assertNotNull(metaData.getPseudoColumns("", "", "", "")); - } - - @Test - public void generatedKeyAlwaysReturned() throws SQLException { - Assert.assertFalse(metaData.generatedKeyAlwaysReturned()); - } - - @BeforeClass - public static void beforeClass() { - try { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - connection = DriverManager.getConnection(url, properties); - metaData = connection.getMetaData().unwrap(TSDBDatabaseMetaData.class); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @AfterClass - public static void afterClass() { - try { - if (connection != null) - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBDriverTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBDriverTest.java deleted file mode 100644 index 609523f522..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBDriverTest.java +++ /dev/null @@ -1,160 +0,0 @@ -package com.taosdata.jdbc; - -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; - -import static org.junit.Assert.*; - -public class TSDBDriverTest { - - private static final String[] validURLs = { - "jdbc:TAOS://localhost:0", - "jdbc:TAOS://localhost", - "jdbc:TAOS://localhost:6030/test", - "jdbc:TAOS://localhost:6030", - "jdbc:TAOS://localhost:6030/", - "jdbc:TSDB://localhost:6030", - "jdbc:TSDB://localhost:6030/", - "jdbc:TAOS://127.0.0.1:0/db?user=root&password=taosdata", - "jdbc:TAOS://:", - "jdbc:TAOS://:/", - "jdbc:TAOS://:/test", - "jdbc:TAOS://localhost:0/?user=root&password=taosdata" - }; - private Connection conn; - - @Test - public void connectWithJdbcURL() { - final String url = "jdbc:TAOS://localhost:6030/log?user=root&password=taosdata"; - try { - conn = DriverManager.getConnection(url); - assertNotNull("failure - connection should not be null", conn); - } catch (SQLException e) { - fail("failure - should not throw Exception"); - } - } - - @Test - public void connectWithProperties() { - final String jdbcUrl = "jdbc:TAOS://localhost:6030/log?user=root&password=taosdata"; - Properties connProps = new Properties(); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - try { - conn = DriverManager.getConnection(jdbcUrl, connProps); - assertNotNull("failure - connection should not be null", conn); - } catch (SQLException e) { - fail("failure - should not throw Exception"); - } - } - - @Test - public void connectWithConfigFile() { - String jdbcUrl = "jdbc:TAOS://:/log?user=root&password=taosdata"; - Properties connProps = new Properties(); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - try { - conn = DriverManager.getConnection(jdbcUrl, connProps); - assertNotNull("failure - connection should not be null", conn); - } catch (SQLException e) { - fail("failure - should not throw Exception"); - } - } - - @Test - public void testParseURL() { - TSDBDriver driver = new TSDBDriver(); - - String url = "jdbc:TAOS://127.0.0.1:0/db?user=root&password=taosdata&charset=UTF-8"; - Properties config = new Properties(); - Properties actual = driver.parseURL(url, config); - assertEquals("failure - host should be 127.0.0.1", "127.0.0.1", actual.get("host")); - assertEquals("failure - port should be 0", "0", actual.get("port")); - assertEquals("failure - dbname should be db", "db", actual.get("dbname")); - assertEquals("failure - user should be root", "root", actual.get("user")); - assertEquals("failure - password should be taosdata", "taosdata", actual.get("password")); - assertEquals("failure - charset should be UTF-8", "UTF-8", actual.get("charset")); - - url = "jdbc:TAOS://127.0.0.1:0"; - config = new Properties(); - actual = driver.parseURL(url, config); - assertEquals("failure - host should be 127.0.0.1", "127.0.0.1", actual.getProperty("host")); - assertEquals("failure - port should be 0", "0", actual.get("port")); - assertNull("failure - dbname should be null", actual.get("dbname")); - - url = "jdbc:TAOS://127.0.0.1:0/db"; - config = new Properties(); - actual = driver.parseURL(url, config); - assertEquals("failure - host should be 127.0.0.1", "127.0.0.1", actual.getProperty("host")); - assertEquals("failure - port should be 0", "0", actual.get("port")); - assertEquals("failure - dbname should be db", "db", actual.get("dbname")); - - url = "jdbc:TAOS://:/?"; - config = new Properties(); - config.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root"); - config.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata"); - actual = driver.parseURL(url, config); - assertEquals("failure - user should be root", "root", actual.getProperty("user")); - assertEquals("failure - password should be taosdata", "taosdata", actual.getProperty("password")); - assertNull("failure - host should be null", actual.getProperty("host")); - assertNull("failure - port should be null", actual.getProperty("port")); - assertNull("failure - dbname should be null", actual.getProperty("dbname")); - } - - - @Test(expected = SQLException.class) - public void acceptsURL() throws SQLException { - Driver driver = new TSDBDriver(); - for (String url : validURLs) { - assertTrue("failure - acceptsURL(\" " + url + " \") should be true", driver.acceptsURL(url)); - } - driver.acceptsURL(null); - fail("acceptsURL throws exception when parameter is null"); - } - - @Test - public void getPropertyInfo() throws SQLException { - Driver driver = new TSDBDriver(); - final String url = "jdbc:TAOS://localhost:6030/log?user=root&password=taosdata"; - Properties connProps = new Properties(); - DriverPropertyInfo[] propertyInfo = driver.getPropertyInfo(url, connProps); - for (DriverPropertyInfo info : propertyInfo) { - if (info.name.equals(TSDBDriver.PROPERTY_KEY_HOST)) - assertEquals("failure - host should be localhost", "localhost", info.value); - if (info.name.equals(TSDBDriver.PROPERTY_KEY_PORT)) - assertEquals("failure - port should be 6030", "6030", info.value); - if (info.name.equals(TSDBDriver.PROPERTY_KEY_DBNAME)) - assertEquals("failure - dbname should be test", "log", info.value); - if (info.name.equals(TSDBDriver.PROPERTY_KEY_USER)) - assertEquals("failure - user should be root", "root", info.value); - if (info.name.equals(TSDBDriver.PROPERTY_KEY_PASSWORD)) - assertEquals("failure - password should be root", "taosdata", info.value); - } - } - - @Test - public void getMajorVersion() { - assertEquals(2, new TSDBDriver().getMajorVersion()); - } - - @Test - public void getMinorVersion() { - assertEquals(0, new TSDBDriver().getMinorVersion()); - } - - @Test - public void jdbcCompliant() { - assertFalse(new TSDBDriver().jdbcCompliant()); - } - - @Test - public void getParentLogger() { - assertNull(new TSDBDriver().getParentLogger()); - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBJNIConnectorTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBJNIConnectorTest.java deleted file mode 100644 index 1531966689..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBJNIConnectorTest.java +++ /dev/null @@ -1,255 +0,0 @@ -package com.taosdata.jdbc; - -import com.taosdata.jdbc.enums.SchemalessProtocolType; -import com.taosdata.jdbc.enums.SchemalessTimestampType; -import org.junit.Test; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.Random; -import java.util.stream.IntStream; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class TSDBJNIConnectorTest { - - private static final String host = "127.0.0.1"; - private static TSDBResultSetRowData rowData; - - @Test - public void test() throws SQLException { - // init - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CONFIG_DIR, "/etc/taos"); - TSDBJNIConnector.init(properties); - - // connect - TSDBJNIConnector connector = new TSDBJNIConnector(); - connector.connect(host, 6030, null, "root", "taosdata"); - - // setup - String setupSqlStrs[] = {"create database if not exists d precision \"us\"", - "create table if not exists d.t(ts timestamp, f int)", - "create database if not exists d2", - "create table if not exists d2.t2(ts timestamp, f int)", - "insert into d.t values(now+100s, 100)", - "insert into d2.t2 values(now+200s, 200)" - }; - for (String setupSqlStr : setupSqlStrs) { - long setupSql = connector.executeQuery(setupSqlStr); - - assertEquals(0, connector.getResultTimePrecision(setupSql)); - if (connector.isUpdateQuery(setupSql)) { - connector.freeResultSet(setupSql); - } - } - - { - long sqlObj1 = connector.executeQuery("select * from d2.t2"); - assertEquals(0, connector.getResultTimePrecision(sqlObj1)); - List columnMetaDataList = new ArrayList<>(); - int code = connector.getSchemaMetaData(sqlObj1, columnMetaDataList); - rowData = new TSDBResultSetRowData(columnMetaDataList.size()); - assertTrue(next(connector, sqlObj1)); - assertEquals(0, connector.getResultTimePrecision(sqlObj1)); - connector.freeResultSet(sqlObj1); - } - - // executeQuery - long pSql = connector.executeQuery("select * from d.t"); - - if (connector.isUpdateQuery(pSql)) { - connector.freeResultSet(pSql); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEQUERY); - } - - assertEquals(1, connector.getResultTimePrecision(pSql)); - - // get schema - List columnMetaDataList = new ArrayList<>(); - int code = connector.getSchemaMetaData(pSql, columnMetaDataList); - if (code == TSDBConstants.JNI_CONNECTION_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); - } - if (code == TSDBConstants.JNI_RESULT_SET_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_RESULT_SET_NULL); - } - if (code == TSDBConstants.JNI_NUM_OF_FIELDS_0) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_NUM_OF_FIELDS_0); - } - - assertEquals(1, connector.getResultTimePrecision(pSql)); - int columnSize = columnMetaDataList.size(); - // print metadata - for (int i = 0; i < columnSize; i++) { -// System.out.println(columnMetaDataList.get(i)); - } - rowData = new TSDBResultSetRowData(columnSize); - // iterate resultSet - for (int i = 0; next(connector, pSql); i++) { - assertEquals(1, connector.getResultTimePrecision(pSql)); - } - // close resultSet - code = connector.freeResultSet(pSql); - if (code == TSDBConstants.JNI_CONNECTION_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); - } else if (code == TSDBConstants.JNI_RESULT_SET_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_RESULT_SET_NULL); - } - // close statement - connector.executeQuery("use d"); - String[] lines = new String[]{ - "st,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", - "st,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64 1626006833640000000"}; - connector.insertLines(lines, SchemalessProtocolType.LINE, SchemalessTimestampType.NANO_SECONDS); - - // close connection - connector.executeQuery("drop database if exists d"); - connector.executeQuery("drop database if exists d2"); - connector.closeConnection(); - } - - private static boolean next(TSDBJNIConnector connector, long pSql) throws SQLException { - if (rowData != null) - rowData.clear(); - - int code = connector.fetchRow(pSql, rowData); - if (code == TSDBConstants.JNI_CONNECTION_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); - } else if (code == TSDBConstants.JNI_RESULT_SET_NULL) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_RESULT_SET_NULL); - } else if (code == TSDBConstants.JNI_NUM_OF_FIELDS_0) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_NUM_OF_FIELDS_0); - } else return code != TSDBConstants.JNI_FETCH_END; - } - - @Test - public void param_bind_one_batch_multi_table() throws SQLException { - TSDBJNIConnector connector = new TSDBJNIConnector(); - connector.connect(host, 6030, null, "root", "taosdata"); - connector.executeQuery("drop database if exists test"); - connector.executeQuery("create database if not exists test"); - connector.executeQuery("use test"); - connector.executeQuery("create table weather(ts timestamp, f1 int) tags(t1 int)"); - - // 1. init + prepare - long stmt = connector.prepareStmt("insert into ? using weather tags(?) values(?,?)"); - for (int i = 0; i < 10; i++) { - // 2. set_tbname_tags - stmt_set_table_tags(connector, stmt, "t" + i); - // 3. bind_single_param_batch - // bind timestamp - long ts = System.currentTimeMillis(); - bind_col_timestamp(connector, stmt, ts, 100); - // bind int - bind_col_integer(connector, stmt, 100); - // 4. add_batch - connector.addBatch(stmt); - } - connector.executeBatch(stmt); - connector.closeBatch(stmt); - - connector.executeQuery("drop database if exists test"); - - connector.closeConnection(); - } - - @Test - public void param_bind_multi_batch_multi_table() throws SQLException { - TSDBJNIConnector connector = new TSDBJNIConnector(); - connector.connect(host, 6030, null, "root", "taosdata"); - connector.executeQuery("drop database if exists test"); - connector.executeQuery("create database if not exists test"); - connector.executeQuery("use test"); - connector.executeQuery("create table weather(ts timestamp, f1 int) tags(t1 int)"); - - // 1. init + prepare - long stmt = connector.prepareStmt("insert into ? using weather tags(?) values(?,?)"); - - long ts = System.currentTimeMillis(); - - for (int ind_batch = 0; ind_batch < 10; ind_batch++) { - - ts += ind_batch * 1000 * 1000; - System.out.println("batch: " + ind_batch + ", ts: " + ts); - - for (int i = 0; i < 10; i++) { - // 2. set_tbname_tags - stmt_set_table_tags(connector, stmt, "t" + i); - // 3. bind_single_param_batch - // bind timestamp - - bind_col_timestamp(connector, stmt, ts, 100); - // bind int - bind_col_integer(connector, stmt, 100); - // 4. add_batch - connector.addBatch(stmt); - } - connector.executeBatch(stmt); - } - - connector.closeBatch(stmt); - - connector.executeQuery("drop database if exists test"); - - connector.closeConnection(); - } - - private void bind_col_timestamp(TSDBJNIConnector connector, long stmt, long ts_start, int numOfRows) throws SQLException { - ByteBuffer colDataList = ByteBuffer.allocate(numOfRows * Long.BYTES); - colDataList.order(ByteOrder.LITTLE_ENDIAN); - IntStream.range(0, numOfRows).forEach(ind -> colDataList.putLong(ts_start + ind * 1000L)); - - ByteBuffer lengthList = ByteBuffer.allocate(numOfRows * Long.BYTES); - lengthList.order(ByteOrder.LITTLE_ENDIAN); - IntStream.range(0, numOfRows).forEach(ind -> lengthList.putLong(Integer.BYTES)); - - ByteBuffer isNullList = ByteBuffer.allocate(numOfRows * Integer.BYTES); - isNullList.order(ByteOrder.LITTLE_ENDIAN); - IntStream.range(0, numOfRows).forEach(ind -> isNullList.putInt(0)); - - connector.bindColumnDataArray(stmt, colDataList, lengthList, isNullList, TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP, Long.BYTES, numOfRows, 0); - } - - private void bind_col_integer(TSDBJNIConnector connector, long stmt, int numOfRows) throws SQLException { - ByteBuffer colDataList = ByteBuffer.allocate(numOfRows * Integer.BYTES); - colDataList.order(ByteOrder.LITTLE_ENDIAN); - IntStream.range(0, numOfRows).forEach(ind -> colDataList.putInt(new Random().nextInt(100))); - - ByteBuffer lengthList = ByteBuffer.allocate(numOfRows * Long.BYTES); - lengthList.order(ByteOrder.LITTLE_ENDIAN); - IntStream.range(0, numOfRows).forEach(ind -> lengthList.putLong(Integer.BYTES)); - - ByteBuffer isNullList = ByteBuffer.allocate(numOfRows * Integer.BYTES); - isNullList.order(ByteOrder.LITTLE_ENDIAN); - IntStream.range(0, numOfRows).forEach(ind -> isNullList.putInt(0)); - - connector.bindColumnDataArray(stmt, colDataList, lengthList, isNullList, TSDBConstants.TSDB_DATA_TYPE_INT, Integer.BYTES, numOfRows, 1); - } - - private void stmt_set_table_tags(TSDBJNIConnector connector, long stmt, String tbname) throws SQLException { - ByteBuffer tagDataList = ByteBuffer.allocate(Integer.BYTES); - tagDataList.order(ByteOrder.LITTLE_ENDIAN); - tagDataList.putInt(new Random().nextInt(100)); - - ByteBuffer typeList = ByteBuffer.allocate(1); - typeList.order(ByteOrder.LITTLE_ENDIAN); - typeList.put((byte) TSDBConstants.TSDB_DATA_TYPE_INT); - - ByteBuffer lengthList = ByteBuffer.allocate(1 * Long.BYTES); - lengthList.order(ByteOrder.LITTLE_ENDIAN); - lengthList.putLong(Integer.BYTES); - - ByteBuffer isNullList = ByteBuffer.allocate(1 * Integer.BYTES); - isNullList.order(ByteOrder.LITTLE_ENDIAN); - isNullList.putInt(0); - - connector.setBindTableNameAndTags(stmt, tbname, 1, tagDataList, typeList, lengthList, isNullList); - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBParameterMetaDataTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBParameterMetaDataTest.java deleted file mode 100644 index 56e8b96bbd..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBParameterMetaDataTest.java +++ /dev/null @@ -1,204 +0,0 @@ -package com.taosdata.jdbc; - -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.sql.*; - -public class TSDBParameterMetaDataTest { - - private static final String host = "127.0.0.1"; - private static Connection conn; - private static final String sql_insert = "insert into t1 values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - private static PreparedStatement pstmt_insert; - private static final String sql_select = "select * from t1 where ts > ? and ts <= ? and f1 >= ?"; - private static PreparedStatement pstmt_select; - private static ParameterMetaData parameterMetaData_insert; - private static ParameterMetaData parameterMetaData_select; - private static final String dbname = "test_pstmt"; - - @Test - public void getParameterCount() throws SQLException { - Assert.assertEquals(10, parameterMetaData_insert.getParameterCount()); - } - - @Test - public void isNullable() throws SQLException { - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(1)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(2)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(3)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(4)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(5)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(6)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(7)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(8)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(9)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(10)); - } - - @Test - public void isSigned() throws SQLException { - Assert.assertEquals(false, parameterMetaData_insert.isSigned(1)); - Assert.assertEquals(true, parameterMetaData_insert.isSigned(2)); - Assert.assertEquals(true, parameterMetaData_insert.isSigned(3)); - Assert.assertEquals(true, parameterMetaData_insert.isSigned(4)); - Assert.assertEquals(true, parameterMetaData_insert.isSigned(5)); - Assert.assertEquals(true, parameterMetaData_insert.isSigned(6)); - Assert.assertEquals(true, parameterMetaData_insert.isSigned(7)); - Assert.assertEquals(false, parameterMetaData_insert.isSigned(8)); - Assert.assertEquals(false, parameterMetaData_insert.isSigned(9)); - Assert.assertEquals(false, parameterMetaData_insert.isSigned(10)); - } - - @Test - public void getPrecision() throws SQLException { - //create table weather(ts timestamp, f1 int, f2 bigint, f3 float, f4 double, f5 smallint, f6 tinyint, f7 bool, f8 binary(64), f9 nchar(64)) - Assert.assertEquals(TSDBConstants.TIMESTAMP_MS_PRECISION, parameterMetaData_insert.getPrecision(1)); - Assert.assertEquals(TSDBConstants.INT_PRECISION, parameterMetaData_insert.getPrecision(2)); - Assert.assertEquals(TSDBConstants.BIGINT_PRECISION, parameterMetaData_insert.getPrecision(3)); - Assert.assertEquals(TSDBConstants.FLOAT_PRECISION, parameterMetaData_insert.getPrecision(4)); - Assert.assertEquals(TSDBConstants.DOUBLE_PRECISION, parameterMetaData_insert.getPrecision(5)); - Assert.assertEquals(TSDBConstants.SMALLINT_PRECISION, parameterMetaData_insert.getPrecision(6)); - Assert.assertEquals(TSDBConstants.TINYINT_PRECISION, parameterMetaData_insert.getPrecision(7)); - Assert.assertEquals(TSDBConstants.BOOLEAN_PRECISION, parameterMetaData_insert.getPrecision(8)); - Assert.assertEquals("hello".getBytes().length, parameterMetaData_insert.getPrecision(9)); - Assert.assertEquals("涛思数据".length(), parameterMetaData_insert.getPrecision(10)); - } - - @Test - public void getScale() throws SQLException { - Assert.assertEquals(0, parameterMetaData_insert.getScale(1)); - Assert.assertEquals(0, parameterMetaData_insert.getScale(2)); - Assert.assertEquals(0, parameterMetaData_insert.getScale(3)); - Assert.assertEquals(31, parameterMetaData_insert.getScale(4)); - Assert.assertEquals(31, parameterMetaData_insert.getScale(5)); - Assert.assertEquals(0, parameterMetaData_insert.getScale(6)); - Assert.assertEquals(0, parameterMetaData_insert.getScale(7)); - Assert.assertEquals(0, parameterMetaData_insert.getScale(8)); - Assert.assertEquals(0, parameterMetaData_insert.getScale(9)); - Assert.assertEquals(0, parameterMetaData_insert.getScale(10)); - } - - @Test - public void getParameterType() throws SQLException { - Assert.assertEquals(Types.TIMESTAMP, parameterMetaData_insert.getParameterType(1)); - Assert.assertEquals(Types.INTEGER, parameterMetaData_insert.getParameterType(2)); - Assert.assertEquals(Types.BIGINT, parameterMetaData_insert.getParameterType(3)); - Assert.assertEquals(Types.FLOAT, parameterMetaData_insert.getParameterType(4)); - Assert.assertEquals(Types.DOUBLE, parameterMetaData_insert.getParameterType(5)); - Assert.assertEquals(Types.SMALLINT, parameterMetaData_insert.getParameterType(6)); - Assert.assertEquals(Types.TINYINT, parameterMetaData_insert.getParameterType(7)); - Assert.assertEquals(Types.BOOLEAN, parameterMetaData_insert.getParameterType(8)); - Assert.assertEquals(Types.BINARY, parameterMetaData_insert.getParameterType(9)); - Assert.assertEquals(Types.NCHAR, parameterMetaData_insert.getParameterType(10)); - } - - @Test - public void getParameterTypeName() throws SQLException { - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.TIMESTAMP), parameterMetaData_insert.getParameterTypeName(1)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.INTEGER), parameterMetaData_insert.getParameterTypeName(2)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.BIGINT), parameterMetaData_insert.getParameterTypeName(3)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.FLOAT), parameterMetaData_insert.getParameterTypeName(4)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.DOUBLE), parameterMetaData_insert.getParameterTypeName(5)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.SMALLINT), parameterMetaData_insert.getParameterTypeName(6)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.TINYINT), parameterMetaData_insert.getParameterTypeName(7)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.BOOLEAN), parameterMetaData_insert.getParameterTypeName(8)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.BINARY), parameterMetaData_insert.getParameterTypeName(9)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.NCHAR), parameterMetaData_insert.getParameterTypeName(10)); - } - - @Test - public void getParameterClassName() throws SQLException { - Assert.assertEquals(Timestamp.class.getName(), parameterMetaData_insert.getParameterClassName(1)); - Assert.assertEquals(Integer.class.getName(), parameterMetaData_insert.getParameterClassName(2)); - Assert.assertEquals(Long.class.getName(), parameterMetaData_insert.getParameterClassName(3)); - Assert.assertEquals(Float.class.getName(), parameterMetaData_insert.getParameterClassName(4)); - Assert.assertEquals(Double.class.getName(), parameterMetaData_insert.getParameterClassName(5)); - Assert.assertEquals(Short.class.getName(), parameterMetaData_insert.getParameterClassName(6)); - Assert.assertEquals(Byte.class.getName(), parameterMetaData_insert.getParameterClassName(7)); - Assert.assertEquals(Boolean.class.getName(), parameterMetaData_insert.getParameterClassName(8)); - Assert.assertEquals(byte[].class.getName(), parameterMetaData_insert.getParameterClassName(9)); - Assert.assertEquals(String.class.getName(), parameterMetaData_insert.getParameterClassName(10)); - } - - @Test - public void getParameterMode() throws SQLException { - Assert.assertEquals(ParameterMetaData.parameterModeUnknown, parameterMetaData_insert.getParameterMode(1)); - Assert.assertEquals(ParameterMetaData.parameterModeUnknown, parameterMetaData_insert.getParameterMode(2)); - Assert.assertEquals(ParameterMetaData.parameterModeUnknown, parameterMetaData_insert.getParameterMode(3)); - Assert.assertEquals(ParameterMetaData.parameterModeUnknown, parameterMetaData_insert.getParameterMode(4)); - Assert.assertEquals(ParameterMetaData.parameterModeUnknown, parameterMetaData_insert.getParameterMode(5)); - Assert.assertEquals(ParameterMetaData.parameterModeUnknown, parameterMetaData_insert.getParameterMode(6)); - Assert.assertEquals(ParameterMetaData.parameterModeUnknown, parameterMetaData_insert.getParameterMode(7)); - Assert.assertEquals(ParameterMetaData.parameterModeUnknown, parameterMetaData_insert.getParameterMode(8)); - Assert.assertEquals(ParameterMetaData.parameterModeUnknown, parameterMetaData_insert.getParameterMode(9)); - Assert.assertEquals(ParameterMetaData.parameterModeUnknown, parameterMetaData_insert.getParameterMode(10)); - } - - @Test - public void unwrap() throws SQLException { - TSDBParameterMetaData unwrap = parameterMetaData_insert.unwrap(TSDBParameterMetaData.class); - Assert.assertNotNull(unwrap); - } - - @Test - public void isWrapperFor() throws SQLException { - Assert.assertTrue(parameterMetaData_insert.isWrapperFor(TSDBParameterMetaData.class)); - } - - @BeforeClass - public static void beforeClass() { - try { - conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather(ts timestamp, f1 int, f2 bigint, f3 float, f4 double, f5 smallint, f6 tinyint, f7 bool, f8 binary(64), f9 nchar(64)) tags(loc nchar(64))"); - stmt.execute("create table t1 using weather tags('beijing')"); - } - pstmt_insert = conn.prepareStatement(sql_insert); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setObject(2, 111); - pstmt_insert.setObject(3, Long.MAX_VALUE); - pstmt_insert.setObject(4, 3.14159265354f); - pstmt_insert.setObject(5, Double.MAX_VALUE); - pstmt_insert.setObject(6, Short.MAX_VALUE); - pstmt_insert.setObject(7, Byte.MAX_VALUE); - pstmt_insert.setObject(8, true); - pstmt_insert.setObject(9, "hello".getBytes()); - pstmt_insert.setObject(10, "涛思数据"); - parameterMetaData_insert = pstmt_insert.getParameterMetaData(); - - pstmt_select = conn.prepareStatement(sql_select); - pstmt_select.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_select.setTimestamp(2, new Timestamp(System.currentTimeMillis() + 10000)); - pstmt_select.setInt(3, 0); - parameterMetaData_select = pstmt_select.getParameterMetaData(); - - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @AfterClass - public static void afterClass() { - try { - if (pstmt_insert != null) - pstmt_insert.close(); - if (pstmt_select != null) - pstmt_select.close(); - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists " + dbname); - statement.close(); - conn.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBPreparedStatementTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBPreparedStatementTest.java deleted file mode 100644 index 8cb4628884..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBPreparedStatementTest.java +++ /dev/null @@ -1,1245 +0,0 @@ -package com.taosdata.jdbc; - -import org.junit.*; - -import java.math.BigDecimal; -import java.sql.*; -import java.util.ArrayList; -import java.util.Random; - -public class TSDBPreparedStatementTest { - - private static final String host = "127.0.0.1"; - private static Connection conn; - private static final String sql_insert = "insert into t1 values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - private static final String sql_select = "select * from t1 where ts >= ? and ts < ? and f1 >= ?"; - private static final String dbname = "test_pstmt_jni"; - - private PreparedStatement pstmt_insert; - private PreparedStatement pstmt_select; - //create table weather(ts timestamp, f1 int, f2 bigint, f3 float, f4 double, f5 smallint, f6 tinyint, f7 bool, f8 binary(64), f9 nchar(64)) tags(loc nchar(64)) - - @Test - public void executeQuery() throws SQLException { - // given - long ts = System.currentTimeMillis(); - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setInt(2, 2); - pstmt_insert.setLong(3, 3L); - pstmt_insert.setFloat(4, 3.14f); - pstmt_insert.setDouble(5, 3.1415); - pstmt_insert.setShort(6, (short) 6); - pstmt_insert.setByte(7, (byte) 7); - pstmt_insert.setBoolean(8, true); - pstmt_insert.setBytes(9, "abc".getBytes()); - pstmt_insert.setString(10, "涛思数据"); - pstmt_insert.executeUpdate(); - long start = ts - 1000 * 60 * 60; - long end = ts + 1000 * 60 * 60; - pstmt_select.setTimestamp(1, new Timestamp(start)); - pstmt_select.setTimestamp(2, new Timestamp(end)); - pstmt_select.setInt(3, 0); - - // when - ResultSet rs = pstmt_select.executeQuery(); - ResultSetMetaData meta = rs.getMetaData(); - rs.next(); - - // then - assertMetaData(meta); - { - Assert.assertNotNull(rs); - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(2, rs.getInt(2)); - Assert.assertEquals(2, rs.getInt("f1")); - Assert.assertEquals(3L, rs.getLong(3)); - Assert.assertEquals(3L, rs.getLong("f2")); - Assert.assertEquals(3.14f, rs.getFloat(4), 0.0); - Assert.assertEquals(3.14f, rs.getFloat("f3"), 0.0); - Assert.assertEquals(3.1415, rs.getDouble(5), 0.0); - Assert.assertEquals(3.1415, rs.getDouble("f4"), 0.0); - Assert.assertEquals((short) 6, rs.getShort(6)); - Assert.assertEquals((short) 6, rs.getShort("f5")); - Assert.assertEquals((byte) 7, rs.getByte(7)); - Assert.assertEquals((byte) 7, rs.getByte("f6")); - Assert.assertTrue(rs.getBoolean(8)); - Assert.assertTrue(rs.getBoolean("f7")); - Assert.assertArrayEquals("abc".getBytes(), rs.getBytes(9)); - Assert.assertArrayEquals("abc".getBytes(), rs.getBytes("f8")); - Assert.assertEquals("涛思数据", rs.getString(10)); - Assert.assertEquals("涛思数据", rs.getString("f9")); - } - } - - private void assertMetaData(ResultSetMetaData meta) throws SQLException { - Assert.assertEquals(10, meta.getColumnCount()); - Assert.assertEquals("ts", meta.getColumnLabel(1)); - Assert.assertEquals("f1", meta.getColumnLabel(2)); - Assert.assertEquals("f2", meta.getColumnLabel(3)); - Assert.assertEquals("f3", meta.getColumnLabel(4)); - Assert.assertEquals("f4", meta.getColumnLabel(5)); - Assert.assertEquals("f5", meta.getColumnLabel(6)); - Assert.assertEquals("f6", meta.getColumnLabel(7)); - Assert.assertEquals("f7", meta.getColumnLabel(8)); - Assert.assertEquals("f8", meta.getColumnLabel(9)); - Assert.assertEquals("f9", meta.getColumnLabel(10)); - } - - @Test - public void setNullForTimestamp() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setNull(2, Types.INTEGER); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - assertAllNullExceptTimestamp(rs, ts); - } - } - - private void assertAllNullExceptTimestamp(ResultSet rs, long ts) throws SQLException { - Assert.assertNotNull(rs); - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(0, rs.getInt(2)); - Assert.assertEquals(0, rs.getInt("f1")); - Assert.assertEquals(0, rs.getLong(3)); - Assert.assertEquals(0, rs.getLong("f2")); - Assert.assertEquals(0, rs.getFloat(4), 0.0); - Assert.assertEquals(0, rs.getFloat("f3"), 0.0); - Assert.assertEquals(0, rs.getDouble(5), 0.0); - Assert.assertEquals(0, rs.getDouble("f4"), 0.0); - Assert.assertEquals(0, rs.getShort(6)); - Assert.assertEquals(0, rs.getShort("f5")); - Assert.assertEquals(0, rs.getByte(7)); - Assert.assertEquals(0, rs.getByte("f6")); - Assert.assertFalse(rs.getBoolean(8)); - Assert.assertFalse(rs.getBoolean("f7")); - Assert.assertNull(rs.getBytes(9)); - Assert.assertNull(rs.getBytes("f8")); - Assert.assertNull(rs.getString(10)); - Assert.assertNull(rs.getString("f9")); - } - - @Test - public void setNullForInteger() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setNull(3, Types.BIGINT); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - assertAllNullExceptTimestamp(rs, ts); - } - } - - @Test - public void setNullForFloat() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setNull(4, Types.FLOAT); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - assertAllNullExceptTimestamp(rs, ts); - } - } - - @Test - public void setNullForDouble() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setNull(5, Types.DOUBLE); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - assertAllNullExceptTimestamp(rs, ts); - } - } - - @Test - public void setNullForSmallInt() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setNull(6, Types.SMALLINT); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - assertAllNullExceptTimestamp(rs, ts); - } - } - - @Test - public void setNullForTinyInt() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setNull(7, Types.TINYINT); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - assertAllNullExceptTimestamp(rs, ts); - } - } - - @Test - public void setNullForBoolean() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setNull(8, Types.BOOLEAN); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - assertAllNullExceptTimestamp(rs, ts); - } - } - - @Test - public void setNullForBinary() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setNull(9, Types.BINARY); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - assertAllNullExceptTimestamp(rs, ts); - } - } - - @Test - public void setNullForNchar() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setNull(10, Types.NCHAR); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - assertAllNullExceptTimestamp(rs, ts); - } - } - - @Test - public void executeTest() throws SQLException { - Statement stmt = conn.createStatement(); - - int numOfRows = 1000; - - for (int loop = 0; loop < 10; loop++) { - stmt.execute("drop table if exists weather_test"); - stmt.execute("create table weather_test(ts timestamp, f1 nchar(4), f2 float, f3 double, f4 timestamp, f5 int, f6 bool, f7 binary(10))"); - - TSDBPreparedStatement s = (TSDBPreparedStatement) conn.prepareStatement("insert into ? values(?, ?, ?, ?, ?, ?, ?, ?)"); - Random r = new Random(); - s.setTableName("weather_test"); - - ArrayList ts = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - ts.add(System.currentTimeMillis() + i); - } - s.setTimestamp(0, ts); - - int random = 10 + r.nextInt(5); - ArrayList s2 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - if (i % random == 0) { - s2.add(null); - } else { - s2.add("分支" + i % 4); - } - } - s.setNString(1, s2, 4); - - random = 10 + r.nextInt(5); - ArrayList s3 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - if (i % random == 0) { - s3.add(null); - } else { - s3.add(r.nextFloat()); - } - } - s.setFloat(2, s3); - - random = 10 + r.nextInt(5); - ArrayList s4 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - if (i % random == 0) { - s4.add(null); - } else { - s4.add(r.nextDouble()); - } - } - s.setDouble(3, s4); - - random = 10 + r.nextInt(5); - ArrayList ts2 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - if (i % random == 0) { - ts2.add(null); - } else { - ts2.add(System.currentTimeMillis() + i); - } - } - s.setTimestamp(4, ts2); - - random = 10 + r.nextInt(5); - ArrayList vals = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - if (i % random == 0) { - vals.add(null); - } else { - vals.add(r.nextInt()); - } - } - s.setInt(5, vals); - - random = 10 + r.nextInt(5); - ArrayList sb = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - if (i % random == 0) { - sb.add(null); - } else { - sb.add(i % 2 == 0); - } - } - s.setBoolean(6, sb); - - random = 10 + r.nextInt(5); - ArrayList s5 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - if (i % random == 0) { - s5.add(null); - } else { - s5.add("test" + i % 10); - } - } - s.setString(7, s5, 10); - - s.columnDataAddBatch(); - s.columnDataExecuteBatch(); - s.columnDataCloseBatch(); - - String sql = "select * from weather_test"; - PreparedStatement statement = conn.prepareStatement(sql); - ResultSet rs = statement.executeQuery(); - int rows = 0; - while (rs.next()) { - rows++; - } - Assert.assertEquals(numOfRows, rows); - } - } - - @Test - public void bindDataSelectColumnTest() throws SQLException { - Statement stmt = conn.createStatement(); - - int numOfRows = 1000; - - for (int loop = 0; loop < 10; loop++) { - stmt.execute("drop table if exists weather_test"); - stmt.execute("create table weather_test(ts timestamp, f1 nchar(4), f2 float, f3 double, f4 timestamp, f5 int, f6 bool, f7 binary(10))"); - - TSDBPreparedStatement s = (TSDBPreparedStatement) conn.prepareStatement("insert into ? (ts, f1, f7) values(?, ?, ?)"); - Random r = new Random(); - s.setTableName("weather_test"); - - ArrayList ts = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - ts.add(System.currentTimeMillis() + i); - } - s.setTimestamp(0, ts); - - int random = 10 + r.nextInt(5); - ArrayList s2 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - if (i % random == 0) { - s2.add(null); - } else { - s2.add("分支" + i % 4); - } - } - s.setNString(1, s2, 4); - - random = 10 + r.nextInt(5); - ArrayList s3 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - if (i % random == 0) { - s3.add(null); - } else { - s3.add("test" + i % 10); - } - } - s.setString(2, s3, 10); - - s.columnDataAddBatch(); - s.columnDataExecuteBatch(); - s.columnDataCloseBatch(); - - String sql = "select * from weather_test"; - PreparedStatement statement = conn.prepareStatement(sql); - ResultSet rs = statement.executeQuery(); - int rows = 0; - while (rs.next()) { - rows++; - } - Assert.assertEquals(numOfRows, rows); - } - } - - @Test - public void bindDataWithSingleTagTest() throws SQLException { - Statement stmt = conn.createStatement(); - - String[] types = new String[]{"tinyint", "smallint", "int", "bigint", "bool", "float", "double", "binary(10)", "nchar(10)"}; - - for (String type : types) { - stmt.execute("drop table if exists weather_test"); - stmt.execute("create table weather_test(ts timestamp, f1 nchar(10), f2 binary(10)) tags (t " + type + ")"); - - int numOfRows = 1; - - TSDBPreparedStatement s = (TSDBPreparedStatement) conn.prepareStatement("insert into ? using weather_test tags(?) values(?, ?, ?)"); - Random r = new Random(); - s.setTableName("w1"); - - switch (type) { - case "tinyint": - case "smallint": - case "int": - case "bigint": - s.setTagInt(0, 1); - break; - case "float": - s.setTagFloat(0, 1.23f); - break; - case "double": - s.setTagDouble(0, 3.14159265); - break; - case "bool": - s.setTagBoolean(0, true); - break; - case "binary(10)": - s.setTagString(0, "test"); - break; - case "nchar(10)": - s.setTagNString(0, "test"); - break; - default: - break; - } - - - ArrayList ts = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - ts.add(System.currentTimeMillis() + i); - } - s.setTimestamp(0, ts); - - int random = 10 + r.nextInt(5); - ArrayList s2 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - s2.add("分支" + i % 4); - } - s.setNString(1, s2, 10); - - random = 10 + r.nextInt(5); - ArrayList s3 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - s3.add("test" + i % 4); - } - s.setString(2, s3, 10); - - s.columnDataAddBatch(); - s.columnDataExecuteBatch(); - s.columnDataCloseBatch(); - - String sql = "select * from weather_test"; - PreparedStatement statement = conn.prepareStatement(sql); - ResultSet rs = statement.executeQuery(); - int rows = 0; - while (rs.next()) { - rows++; - } - Assert.assertEquals(numOfRows, rows); - } - } - - - @Test - public void bindDataWithMultipleTagsTest() throws SQLException { - Statement stmt = conn.createStatement(); - - stmt.execute("drop table if exists weather_test"); - stmt.execute("create table weather_test(ts timestamp, f1 nchar(10), f2 binary(10)) tags (t1 int, t2 binary(10))"); - - int numOfRows = 1; - - TSDBPreparedStatement s = (TSDBPreparedStatement) conn.prepareStatement("insert into ? using weather_test tags(?,?) (ts, f2) values(?, ?)"); - s.setTableName("w2"); - s.setTagInt(0, 1); - s.setTagString(1, "test"); - - - ArrayList ts = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - ts.add(System.currentTimeMillis() + i); - } - s.setTimestamp(0, ts); - - ArrayList s2 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - s2.add("test" + i % 4); - } - s.setString(1, s2, 10); - - s.columnDataAddBatch(); - s.columnDataExecuteBatch(); - s.columnDataCloseBatch(); - - String sql = "select * from weather_test"; - PreparedStatement statement = conn.prepareStatement(sql); - ResultSet rs = statement.executeQuery(); - int rows = 0; - while (rs.next()) { - rows++; - } - Assert.assertEquals(numOfRows, rows); - } - - @Test - public void bindDataQueryTest() throws SQLException { - Statement stmt = conn.createStatement(); - - stmt.execute("drop table if exists weather_test"); - stmt.execute("create table weather_test(ts timestamp, f1 nchar(10), f2 binary(10)) tags (t1 int, t2 binary(10))"); - - int numOfRows = 1; - - TSDBPreparedStatement s = (TSDBPreparedStatement) conn.prepareStatement("insert into ? using weather_test tags(?,?) (ts, f2) values(?, ?)"); - s.setTableName("w2"); - s.setTagInt(0, 1); - s.setTagString(1, "test"); - - - ArrayList ts = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - ts.add(System.currentTimeMillis() + i); - } - s.setTimestamp(0, ts); - - ArrayList s2 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - s2.add("test" + i % 4); - } - s.setString(1, s2, 10); - - s.columnDataAddBatch(); - s.columnDataExecuteBatch(); - s.columnDataCloseBatch(); - - String sql = "select * from weather_test where t1 >= ? and t1 <= ?"; - TSDBPreparedStatement s1 = (TSDBPreparedStatement) conn.prepareStatement(sql); - s1.setInt(1, 0); - s1.setInt(2, 10); - - ResultSet rs = s1.executeQuery(); - int rows = 0; - while (rs.next()) { - rows++; - } - Assert.assertEquals(numOfRows, rows); - } - - @Test - public void setTagNullTest()throws SQLException { - Statement stmt = conn.createStatement(); - - stmt.execute("drop table if exists weather_test"); - stmt.execute("create table weather_test(ts timestamp, c1 int) tags (t1 tinyint, t2 smallint, t3 int, t4 bigint, t5 float, t6 double, t7 bool, t8 binary(10), t9 nchar(10))"); - - int numOfRows = 1; - - TSDBPreparedStatement s = (TSDBPreparedStatement) conn.prepareStatement("insert into ? using weather_test tags(?,?,?,?,?,?,?,?,?) values(?, ?)"); - s.setTableName("w3"); - s.setTagNull(0, TSDBConstants.TSDB_DATA_TYPE_TINYINT); - s.setTagNull(1, TSDBConstants.TSDB_DATA_TYPE_SMALLINT); - s.setTagNull(2, TSDBConstants.TSDB_DATA_TYPE_INT); - s.setTagNull(3, TSDBConstants.TSDB_DATA_TYPE_BIGINT); - s.setTagNull(4, TSDBConstants.TSDB_DATA_TYPE_FLOAT); - s.setTagNull(5, TSDBConstants.TSDB_DATA_TYPE_DOUBLE); - s.setTagNull(6, TSDBConstants.TSDB_DATA_TYPE_BOOL); - s.setTagNull(7, TSDBConstants.TSDB_DATA_TYPE_BINARY); - s.setTagNull(8, TSDBConstants.TSDB_DATA_TYPE_NCHAR); - - ArrayList ts = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - ts.add(System.currentTimeMillis() + i); - } - s.setTimestamp(0, ts); - - ArrayList s2 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - s2.add(i); - } - s.setInt(1, s2); - - s.columnDataAddBatch(); - s.columnDataExecuteBatch(); - s.columnDataCloseBatch(); - } - - private String stringGenerator(int length) { - String source = "abcdefghijklmnopqrstuvwxyz"; - StringBuilder sb = new StringBuilder(); - Random rand = new Random(); - for(int i = 0; i < length; i++) { - sb.append(source.charAt(rand.nextInt(26))); - } - return sb.toString(); - } - - @Test(expected = SQLException.class) - public void setMaxTableNameTest()throws SQLException { - Statement stmt = conn.createStatement(); - - stmt.execute("drop table if exists weather_test"); - stmt.execute("create table weather_test(ts timestamp, c1 int) tags (t1 int)"); - - TSDBPreparedStatement s = (TSDBPreparedStatement) conn.prepareStatement("insert into ? using weather_test tags(?) values(?, ?)"); - String tbname = stringGenerator(193); - s.setTableName(tbname); - s.setTagInt(0, 1); - - int numOfRows = 1; - - ArrayList ts = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - ts.add(System.currentTimeMillis() + i); - } - s.setTimestamp(0, ts); - - ArrayList s2 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - s2.add(i); - } - s.setInt(1, s2); - - s.columnDataAddBatch(); - s.columnDataExecuteBatch(); - s.columnDataCloseBatch(); - } - - - @Test(expected = SQLException.class) - public void createTwoSameDbTest() throws SQLException { - // when - Statement stmt = conn.createStatement(); - stmt.execute("create database dbtest"); - stmt.execute("create database dbtest"); - } - - @Test - public void setBoolean() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setBoolean(8, true); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - { - Assert.assertNotNull(rs); - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(ts, rs.getTimestamp("ts").getTime()); - Assert.assertTrue(rs.getBoolean(8)); - Assert.assertTrue(rs.getBoolean("f7")); - } - } - } - - @Test - public void setByte() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setByte(7, (byte) 0x001); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - { - Assert.assertNotNull(rs); - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(ts, rs.getTimestamp("ts").getTime()); - Assert.assertEquals((byte) 0x001, rs.getByte(7)); - Assert.assertEquals((byte) 0x001, rs.getByte("f6")); - } - } - } - - @Test - public void setShort() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setShort(6, (short) 2); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - { - Assert.assertNotNull(rs); - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(ts, rs.getTimestamp("ts").getTime()); - Assert.assertEquals((short) 2, rs.getByte(6)); - Assert.assertEquals((short) 2, rs.getByte("f5")); - } - } - } - - @Test - public void setInt() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setInt(2, 10086); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - { - Assert.assertNotNull(rs); - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(ts, rs.getTimestamp("ts").getTime()); - Assert.assertEquals(10086, rs.getInt(2)); - Assert.assertEquals(10086, rs.getInt("f1")); - } - } - } - - @Test - public void setLong() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setLong(3, Long.MAX_VALUE); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - { - Assert.assertNotNull(rs); - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(ts, rs.getTimestamp("ts").getTime()); - Assert.assertEquals(Long.MAX_VALUE, rs.getLong(3)); - Assert.assertEquals(Long.MAX_VALUE, rs.getLong("f2")); - } - } - } - - @Test - public void setFloat() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setFloat(4, 3.14f); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - { - Assert.assertNotNull(rs); - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(ts, rs.getTimestamp("ts").getTime()); - Assert.assertEquals(3.14f, rs.getFloat(4), 0.0f); - Assert.assertEquals(3.14f, rs.getFloat("f3"), 0.0f); - } - } - } - - @Test - public void setDouble() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setDouble(5, 3.14444); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - { - Assert.assertNotNull(rs); - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(ts, rs.getTimestamp("ts").getTime()); - Assert.assertEquals(3.14444, rs.getDouble(5), 0.0); - Assert.assertEquals(3.14444, rs.getDouble("f4"), 0.0); - } - } - } - - @Test - public void setBigDecimal() throws SQLException { - // given - long ts = System.currentTimeMillis(); - BigDecimal bigDecimal = new BigDecimal("3.14444"); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setBigDecimal(5, bigDecimal); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - { - Assert.assertNotNull(rs); - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(ts, rs.getTimestamp("ts").getTime()); - Assert.assertEquals(3.14444, rs.getDouble(5), 0.0); - Assert.assertEquals(3.14444, rs.getDouble("f4"), 0.0); - } - } - } - - @Test - public void setString() throws SQLException { - // given - long ts = System.currentTimeMillis(); - String f9 = "{\"name\": \"john\", \"age\": 10, \"address\": \"192.168.1.100\"}"; - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setString(10, f9); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - { - Assert.assertNotNull(rs); - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(ts, rs.getTimestamp("ts").getTime()); - Assert.assertEquals(f9, rs.getString(10)); - Assert.assertEquals(f9, rs.getString("f9")); - } - } - } - - @Test - public void setBytes() throws SQLException { - // given - long ts = System.currentTimeMillis(); - byte[] f8 = "{\"name\": \"john\", \"age\": 10, \"address\": \"192.168.1.100\"}".getBytes(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setBytes(9, f8); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - { - Assert.assertNotNull(rs); - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(ts, rs.getTimestamp("ts").getTime()); - Assert.assertArrayEquals(f8, rs.getBytes(9)); - Assert.assertArrayEquals(f8, rs.getBytes("f8")); - } - } - } - - @Test - public void setDate() throws SQLException { - // given - long ts = new java.util.Date().getTime(); - - // when - pstmt_insert.setDate(1, new Date(ts)); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - { - Assert.assertNotNull(rs); - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(ts, rs.getTimestamp("ts").getTime()); - } - } - } - - @Test - public void setTime() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTime(1, new Time(ts)); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - { - Assert.assertNotNull(rs); - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(ts, rs.getTimestamp("ts").getTime()); - } - } - } - - @Test - public void setTimestamp() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - int result = pstmt_insert.executeUpdate(); - - // then - Assert.assertEquals(1, result); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from t1"); - ResultSetMetaData meta = rs.getMetaData(); - assertMetaData(meta); - rs.next(); - { - Assert.assertNotNull(rs); - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(ts, rs.getTimestamp("ts").getTime()); - } - } - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setAsciiStream() throws SQLException { - pstmt_insert.setAsciiStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setBinaryStream() throws SQLException { - pstmt_insert.setBinaryStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setCharacterStream() throws SQLException { - pstmt_insert.setCharacterStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setRef() throws SQLException { - pstmt_insert.setRef(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setBlob() throws SQLException { - pstmt_insert.setBlob(1, (Blob) null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setClob() throws SQLException { - pstmt_insert.setClob(1, (Clob) null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setArray() throws SQLException { - pstmt_insert.setArray(1, null); - } - - @Test - public void getMetaData() throws SQLException { - // given - long ts = System.currentTimeMillis(); - - // when - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - ResultSetMetaData metaData = pstmt_insert.getMetaData(); - - // then - Assert.assertNull(metaData); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setURL() throws SQLException { - pstmt_insert.setURL(1, null); - } - - @Test - public void getParameterMetaData() throws SQLException { - // given - long ts = System.currentTimeMillis(); - pstmt_insert.setTimestamp(1, new Timestamp(ts)); - pstmt_insert.setInt(2, 2); - pstmt_insert.setLong(3, 3L); - pstmt_insert.setFloat(4, 3.14f); - pstmt_insert.setDouble(5, 3.1415); - pstmt_insert.setShort(6, (short) 6); - pstmt_insert.setByte(7, (byte) 7); - pstmt_insert.setBoolean(8, true); - pstmt_insert.setBytes(9, "abc".getBytes()); - pstmt_insert.setString(10, "涛思数据"); - - // when - ParameterMetaData parameterMetaData = pstmt_insert.getParameterMetaData(); - - // then - Assert.assertNotNull(parameterMetaData); - Assert.assertEquals(10, parameterMetaData.getParameterCount()); - Assert.assertEquals(Types.TIMESTAMP, parameterMetaData.getParameterType(1)); - Assert.assertEquals(Types.INTEGER, parameterMetaData.getParameterType(2)); - Assert.assertEquals(Types.BIGINT, parameterMetaData.getParameterType(3)); - Assert.assertEquals(Types.FLOAT, parameterMetaData.getParameterType(4)); - Assert.assertEquals(Types.DOUBLE, parameterMetaData.getParameterType(5)); - Assert.assertEquals(Types.SMALLINT, parameterMetaData.getParameterType(6)); - Assert.assertEquals(Types.TINYINT, parameterMetaData.getParameterType(7)); - Assert.assertEquals(Types.BOOLEAN, parameterMetaData.getParameterType(8)); - Assert.assertEquals(Types.BINARY, parameterMetaData.getParameterType(9)); - Assert.assertEquals(Types.NCHAR, parameterMetaData.getParameterType(10)); - - Assert.assertEquals("TIMESTAMP", parameterMetaData.getParameterTypeName(1)); - Assert.assertEquals("INT", parameterMetaData.getParameterTypeName(2)); - Assert.assertEquals("BIGINT", parameterMetaData.getParameterTypeName(3)); - Assert.assertEquals("FLOAT", parameterMetaData.getParameterTypeName(4)); - Assert.assertEquals("DOUBLE", parameterMetaData.getParameterTypeName(5)); - Assert.assertEquals("SMALLINT", parameterMetaData.getParameterTypeName(6)); - Assert.assertEquals("TINYINT", parameterMetaData.getParameterTypeName(7)); - Assert.assertEquals("BOOL", parameterMetaData.getParameterTypeName(8)); - Assert.assertEquals("BINARY", parameterMetaData.getParameterTypeName(9)); - Assert.assertEquals("NCHAR", parameterMetaData.getParameterTypeName(10)); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setRowId() throws SQLException { - pstmt_insert.setRowId(1, null); - } - - @Test - public void setNString() throws SQLException { - setString(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setNCharacterStream() throws SQLException { - pstmt_insert.setNCharacterStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setNClob() throws SQLException { - pstmt_insert.setNClob(1, (NClob) null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setSQLXML() throws SQLException { - pstmt_insert.setSQLXML(1, null); - } - - @Before - public void before() { - try { - Statement stmt = conn.createStatement(); - stmt.execute("drop table if exists weather"); - stmt.execute("create table if not exists weather(ts timestamp, f1 int, f2 bigint, f3 float, f4 double, f5 smallint, f6 tinyint, f7 bool, f8 binary(64), f9 nchar(64)) tags(loc nchar(64))"); - stmt.execute("create table if not exists t1 using weather tags('beijing')"); - stmt.close(); - - pstmt_insert = conn.prepareStatement(sql_insert); - pstmt_select = conn.prepareStatement(sql_select); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @After - public void after() { - try { - if (pstmt_insert != null) - pstmt_insert.close(); - if (pstmt_select != null) - pstmt_select.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - - } - - @BeforeClass - public static void beforeClass() { - try { - conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @AfterClass - public static void afterClass() { - try { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists " + dbname); - statement.execute("drop database if exists dbtest"); - statement.close(); - if (conn != null) - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBResultSetTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBResultSetTest.java deleted file mode 100644 index 7b9083bf9b..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBResultSetTest.java +++ /dev/null @@ -1,682 +0,0 @@ -package com.taosdata.jdbc; - -import com.google.common.primitives.Ints; -import com.google.common.primitives.Longs; -import com.google.common.primitives.Shorts; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.sql.*; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Arrays; - -public class TSDBResultSetTest { - - private static final String host = "127.0.0.1"; - private static Connection conn; - private static Statement stmt; - private static ResultSet rs; - - @Test - public void wasNull() throws SQLException { - Assert.assertFalse(rs.wasNull()); - } - - @Test - public void getString() throws SQLException { - String f10 = rs.getString("f10"); - Assert.assertEquals("涛思数据", f10); - f10 = rs.getString(10); - Assert.assertEquals("涛思数据", f10); - } - - @Test - public void getBoolean() throws SQLException { - Boolean f9 = rs.getBoolean("f9"); - Assert.assertEquals(true, f9); - f9 = rs.getBoolean(9); - Assert.assertEquals(true, f9); - } - - @Test - public void getByte() throws SQLException { - byte f8 = rs.getByte("f8"); - Assert.assertEquals(10, f8); - f8 = rs.getByte(8); - Assert.assertEquals(10, f8); - } - - @Test - public void getShort() throws SQLException { - short f7 = rs.getShort("f7"); - Assert.assertEquals(10, f7); - f7 = rs.getShort(7); - Assert.assertEquals(10, f7); - } - - @Test - public void getInt() throws SQLException { - int f2 = rs.getInt("f2"); - Assert.assertEquals(1, f2); - f2 = rs.getInt(2); - Assert.assertEquals(1, f2); - } - - @Test - public void getLong() throws SQLException { - long f3 = rs.getLong("f3"); - Assert.assertEquals(100, f3); - f3 = rs.getLong(3); - Assert.assertEquals(100, f3); - } - - @Test - public void getFloat() throws SQLException { - float f4 = rs.getFloat("f4"); - Assert.assertEquals(3.1415f, f4, 0f); - f4 = rs.getFloat(4); - Assert.assertEquals(3.1415f, f4, 0f); - } - - @Test - public void getDouble() throws SQLException { - double f5 = rs.getDouble("f5"); - Assert.assertEquals(3.1415926, f5, 0.0); - f5 = rs.getDouble(5); - Assert.assertEquals(3.1415926, f5, 0.0); - } - - @Test - public void getBigDecimal() throws SQLException { - BigDecimal f1 = rs.getBigDecimal("f1"); - Assert.assertEquals(1609430400000L, f1.longValue()); - - BigDecimal f2 = rs.getBigDecimal("f2"); - Assert.assertEquals(1, f2.intValue()); - - BigDecimal f3 = rs.getBigDecimal("f3"); - Assert.assertEquals(100L, f3.longValue()); - - BigDecimal f4 = rs.getBigDecimal("f4"); - Assert.assertEquals(3.1415f, f4.floatValue(), 0.00000f); - - BigDecimal f5 = rs.getBigDecimal("f5"); - Assert.assertEquals(3.1415926, f5.doubleValue(), 0.0000000); - - BigDecimal f7 = rs.getBigDecimal("f7"); - Assert.assertEquals(10, f7.intValue()); - - BigDecimal f8 = rs.getBigDecimal("f8"); - Assert.assertEquals(10, f8.intValue()); - } - - @Test - public void getBytes() throws SQLException { - byte[] f1 = rs.getBytes("f1"); - Assert.assertEquals("2021-01-01 00:00:00.0", new String(f1)); - - byte[] f2 = rs.getBytes("f2"); - Assert.assertEquals(1, Ints.fromByteArray(f2)); - - byte[] f3 = rs.getBytes("f3"); - Assert.assertEquals(100L, Longs.fromByteArray(f3)); - - byte[] f4 = rs.getBytes("f4"); - Assert.assertEquals(3.1415f, Float.parseFloat(new String(f4)), 0.000000f); - - byte[] f5 = rs.getBytes("f5"); - Assert.assertEquals(3.1415926, Double.parseDouble(new String(f5)), 0.000000f); - - byte[] f6 = rs.getBytes("f6"); - Assert.assertTrue(Arrays.equals("abc".getBytes(), f6)); - - byte[] f7 = rs.getBytes("f7"); - Assert.assertEquals((short) 10, Shorts.fromByteArray(f7)); - - byte[] f8 = rs.getBytes("f8"); - Assert.assertEquals(1, f8.length); - Assert.assertEquals((byte) 10, f8[0]); - - byte[] f9 = rs.getBytes("f9"); - Assert.assertEquals("true", new String(f9)); - - byte[] f10 = rs.getBytes("f10"); - Assert.assertEquals("涛思数据", new String(f10)); - } - - @Test - public void getDate() throws SQLException, ParseException { - Date f1 = rs.getDate("f1"); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - Assert.assertEquals(sdf.parse("2021-01-01"), f1); - } - - @Test - public void getTime() throws SQLException { - Time f1 = rs.getTime("f1"); - Assert.assertNotNull(f1); - Assert.assertEquals("00:00:00", f1.toString()); - } - - @Test - public void getTimestamp() throws SQLException { - Timestamp f1 = rs.getTimestamp("f1"); - Assert.assertEquals("2021-01-01 00:00:00.0", f1.toString()); - f1 = rs.getTimestamp(1); - Assert.assertEquals("2021-01-01 00:00:00.0", f1.toString()); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getAsciiStream() throws SQLException { - rs.getAsciiStream("f1"); - } - - @SuppressWarnings("deprecation") - @Test(expected = SQLFeatureNotSupportedException.class) - public void getUnicodeStream() throws SQLException { - rs.getUnicodeStream("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getBinaryStream() throws SQLException { - rs.getBinaryStream("f1"); - } - - @Test - public void getWarnings() throws SQLException { - Assert.assertNull(rs.getWarnings()); - } - - @Test - public void clearWarnings() throws SQLException { - rs.clearWarnings(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getCursorName() throws SQLException { - rs.getCursorName(); - } - - @Test - public void getMetaData() throws SQLException { - ResultSetMetaData meta = rs.getMetaData(); - Assert.assertNotNull(meta); - } - - @Test - public void getObject() throws SQLException, ParseException { - Object f1 = rs.getObject("f1"); - Assert.assertEquals(Timestamp.class, f1.getClass()); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.sss"); - java.util.Date date = sdf.parse("2021-01-01 00:00:00.000"); - Assert.assertEquals(new Timestamp(date.getTime()), f1); - - Object f2 = rs.getObject("f2"); - Assert.assertEquals(Integer.class, f2.getClass()); - Assert.assertEquals(1, f2); - - Object f3 = rs.getObject("f3"); - Assert.assertEquals(Long.class, f3.getClass()); - Assert.assertEquals(100L, f3); - - Object f4 = rs.getObject("f4"); - Assert.assertEquals(Float.class, f4.getClass()); - Assert.assertEquals(3.1415f, f4); - - Object f5 = rs.getObject("f5"); - Assert.assertEquals(Double.class, f5.getClass()); - Assert.assertEquals(3.1415926, f5); - - Object f6 = rs.getObject("f6"); - Assert.assertEquals(byte[].class, f6.getClass()); - Assert.assertEquals("abc", new String((byte[]) f6)); - - Object f7 = rs.getObject("f7"); - Assert.assertEquals(Short.class, f7.getClass()); - Assert.assertEquals((short) 10, f7); - - Object f8 = rs.getObject("f8"); - Assert.assertEquals(Byte.class, f8.getClass()); - Assert.assertEquals((byte) 10, f8); - - Object f9 = rs.getObject("f9"); - Assert.assertEquals(Boolean.class, f9.getClass()); - Assert.assertEquals(true, f9); - - Object f10 = rs.getObject("f10"); - Assert.assertEquals(String.class, f10.getClass()); - Assert.assertEquals("涛思数据", f10); - } - - @Test(expected = SQLException.class) - public void findColumn() throws SQLException { - int columnIndex = rs.findColumn("f1"); - Assert.assertEquals(1, columnIndex); - columnIndex = rs.findColumn("f2"); - Assert.assertEquals(2, columnIndex); - columnIndex = rs.findColumn("f3"); - Assert.assertEquals(3, columnIndex); - columnIndex = rs.findColumn("f4"); - Assert.assertEquals(4, columnIndex); - columnIndex = rs.findColumn("f5"); - Assert.assertEquals(5, columnIndex); - columnIndex = rs.findColumn("f6"); - Assert.assertEquals(6, columnIndex); - columnIndex = rs.findColumn("f7"); - Assert.assertEquals(7, columnIndex); - columnIndex = rs.findColumn("f8"); - Assert.assertEquals(8, columnIndex); - columnIndex = rs.findColumn("f9"); - Assert.assertEquals(9, columnIndex); - columnIndex = rs.findColumn("f10"); - Assert.assertEquals(10, columnIndex); - - rs.findColumn("f11"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getCharacterStream() throws SQLException { - rs.getCharacterStream(1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void isBeforeFirst() throws SQLException { - rs.isBeforeFirst(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void isAfterLast() throws SQLException { - rs.isAfterLast(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void isFirst() throws SQLException { - rs.isFirst(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void isLast() throws SQLException { - rs.isLast(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void beforeFirst() throws SQLException { - rs.beforeFirst(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void afterLast() throws SQLException { - rs.afterLast(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void first() throws SQLException { - rs.first(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void last() throws SQLException { - rs.last(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getRow() throws SQLException { - rs.getRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void absolute() throws SQLException { - rs.absolute(-1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void relative() throws SQLException { - rs.relative(-1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void previous() throws SQLException { - rs.previous(); - } - - @Test - public void setFetchDirection() throws SQLException { - rs.setFetchDirection(ResultSet.FETCH_FORWARD); - Assert.assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection()); - rs.setFetchDirection(ResultSet.FETCH_UNKNOWN); - Assert.assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection()); - } - - @Test - public void getFetchDirection() throws SQLException { - Assert.assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection()); - } - - @Test - public void setFetchSize() throws SQLException { - rs.setFetchSize(0); - Assert.assertEquals(0, rs.getFetchSize()); - } - - @Test - public void getFetchSize() throws SQLException { - Assert.assertEquals(0, rs.getFetchSize()); - } - - @Test - public void getType() throws SQLException { - Assert.assertEquals(ResultSet.TYPE_FORWARD_ONLY, rs.getType()); - } - - @Test - public void getConcurrency() throws SQLException { - Assert.assertEquals(ResultSet.CONCUR_READ_ONLY, rs.getConcurrency()); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void rowUpdated() throws SQLException { - rs.rowUpdated(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void rowInserted() throws SQLException { - rs.rowInserted(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void rowDeleted() throws SQLException { - rs.rowDeleted(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateNull() throws SQLException { - rs.updateNull("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateBoolean() throws SQLException { - rs.updateBoolean(1, false); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateByte() throws SQLException { - rs.updateByte(1, (byte) 0); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateShort() throws SQLException { - rs.updateShort(1, (short) 0); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateInt() throws SQLException { - rs.updateInt(1, 1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateLong() throws SQLException { - rs.updateLong(1, 1L); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateFloat() throws SQLException { - rs.updateFloat(1, 1f); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateDouble() throws SQLException { - rs.updateDouble(1, 1.0); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateBigDecimal() throws SQLException { - rs.updateBigDecimal(1, new BigDecimal(1)); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateString() throws SQLException { - rs.updateString(1, "abc"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateBytes() throws SQLException { - rs.updateBytes(1, new byte[]{}); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateDate() throws SQLException { - rs.updateDate(1, new Date(System.currentTimeMillis())); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateTime() throws SQLException { - rs.updateTime(1, new Time(System.currentTimeMillis())); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateTimestamp() throws SQLException { - rs.updateTimestamp(1, new Timestamp(System.currentTimeMillis())); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateAsciiStream() throws SQLException { - rs.updateAsciiStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateBinaryStream() throws SQLException { - rs.updateBinaryStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateCharacterStream() throws SQLException { - rs.updateCharacterStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateObject() throws SQLException { - rs.updateObject(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void insertRow() throws SQLException { - rs.insertRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateRow() throws SQLException { - rs.updateRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void deleteRow() throws SQLException { - rs.deleteRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void refreshRow() throws SQLException { - rs.refreshRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void cancelRowUpdates() throws SQLException { - rs.cancelRowUpdates(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void moveToInsertRow() throws SQLException { - rs.moveToInsertRow(); - } - - @Test - public void getStatement() throws SQLException { - Statement stmt = rs.getStatement(); - Assert.assertNotNull(stmt); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void moveToCurrentRow() throws SQLException { - rs.moveToCurrentRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getRef() throws SQLException { - rs.getRef(1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getBlob() throws SQLException { - rs.getBlob("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getClob() throws SQLException { - rs.getClob("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getArray() throws SQLException { - rs.getArray("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getURL() throws SQLException { - rs.getURL("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateRef() throws SQLException { - rs.updateRef("f1", null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateBlob() throws SQLException { - rs.updateBlob(1, (InputStream) null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateClob() throws SQLException { - rs.updateClob(1, (Reader) null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateArray() throws SQLException { - rs.updateArray(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getRowId() throws SQLException { - rs.getRowId("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateRowId() throws SQLException { - rs.updateRowId(1, null); - } - - @Test - public void getHoldability() throws SQLException { - Assert.assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, rs.getHoldability()); - } - - @Test - public void isClosed() throws SQLException { - Assert.assertFalse(rs.isClosed()); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateNString() throws SQLException { - rs.updateNString(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateNClob() throws SQLException { - rs.updateNClob(1, (Reader) null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getNClob() throws SQLException { - rs.getNClob("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getSQLXML() throws SQLException { - rs.getSQLXML("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateSQLXML() throws SQLException { - rs.updateSQLXML(1, null); - } - - @Test - public void getNString() throws SQLException { - String f10 = rs.getNString("f10"); - Assert.assertEquals("涛思数据", f10); - f10 = rs.getNString(10); - Assert.assertEquals("涛思数据", f10); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getNCharacterStream() throws SQLException { - rs.getNCharacterStream("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateNCharacterStream() throws SQLException { - rs.updateNCharacterStream(1, null); - } - - @Test - public void unwrap() throws SQLException { - TSDBResultSet unwrap = rs.unwrap(TSDBResultSet.class); - Assert.assertNotNull(unwrap); - } - - @Test - public void isWrapperFor() throws SQLException { - Assert.assertTrue(rs.isWrapperFor(TSDBResultSet.class)); - } - - @BeforeClass - public static void beforeClass() { - try { - conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); - stmt = conn.createStatement(); - stmt.execute("create database if not exists restful_test"); - stmt.execute("use restful_test"); - stmt.execute("drop table if exists weather"); - stmt.execute("create table if not exists weather(f1 timestamp, f2 int, f3 bigint, f4 float, f5 double, f6 binary(64), f7 smallint, f8 tinyint, f9 bool, f10 nchar(64))"); - stmt.execute("insert into restful_test.weather values('2021-01-01 00:00:00.000', 1, 100, 3.1415, 3.1415926, 'abc', 10, 10, true, '涛思数据')"); - rs = stmt.executeQuery("select * from restful_test.weather"); - rs.next(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @AfterClass - public static void afterClass() { - try { - if (rs != null) - rs.close(); - if (stmt != null) - stmt.close(); - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists restful_test"); - statement.close(); - conn.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBStatementTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBStatementTest.java deleted file mode 100644 index c1dfa42511..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBStatementTest.java +++ /dev/null @@ -1,390 +0,0 @@ -package com.taosdata.jdbc; - -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; -import java.util.UUID; - -public class TSDBStatementTest { - private static final String host = "127.0.0.1"; - private static Connection conn; - private static Statement stmt; - - @Test - public void executeUpdate() { - final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); - try { - int affectRows = stmt.executeUpdate("create database " + dbName); - Assert.assertEquals(0, affectRows); - affectRows = stmt.executeUpdate("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); - Assert.assertEquals(0, affectRows); - affectRows = stmt.executeUpdate("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); - Assert.assertEquals(1, affectRows); - affectRows = stmt.executeUpdate("drop database " + dbName); - Assert.assertEquals(0, affectRows); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void close() { - // test in AfterClass method - } - - - @Test - public void getMaxFieldSize() throws SQLException { - Assert.assertEquals(16 * 1024, stmt.getMaxFieldSize()); - } - - @Test(expected = SQLException.class) - public void setMaxFieldSize() throws SQLException { - - stmt.setMaxFieldSize(0); - stmt.setMaxFieldSize(-1); - } - - @Test - public void getMaxRows() throws SQLException { - Assert.assertEquals(0, stmt.getMaxRows()); - } - - @Test(expected = SQLException.class) - public void setMaxRows() throws SQLException { - stmt.setMaxRows(0); - stmt.setMaxRows(-1); - } - - @Test - public void setEscapeProcessing() throws SQLException { - stmt.setEscapeProcessing(true); - stmt.setEscapeProcessing(false); - } - - @Test - public void getQueryTimeout() throws SQLException { - Assert.assertEquals(0, stmt.getQueryTimeout()); - } - - @Test(expected = SQLException.class) - public void setQueryTimeout() throws SQLException { - stmt.setQueryTimeout(0); - stmt.setQueryTimeout(-1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void cancel() throws SQLException { - stmt.cancel(); - } - - @Test - public void getWarnings() throws SQLException { - Assert.assertNull(stmt.getWarnings()); - } - - @Test - public void clearWarnings() throws SQLException { - stmt.clearWarnings(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setCursorName() throws SQLException { - stmt.setCursorName(""); - } - - @Test - public void execute() { - final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); - try { - boolean isSelect = stmt.execute("create database " + dbName); - Assert.assertEquals(false, isSelect); - int affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(0, affectedRows); - - isSelect = stmt.execute("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); - Assert.assertEquals(false, isSelect); - affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(0, affectedRows); - - isSelect = stmt.execute("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); - Assert.assertEquals(false, isSelect); - affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(1, affectedRows); - - isSelect = stmt.execute("select * from " + dbName + ".weather"); - Assert.assertEquals(true, isSelect); - - isSelect = stmt.execute("drop database " + dbName); - Assert.assertEquals(false, isSelect); - affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(0, affectedRows); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void getResultSet() { - final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); - try { - boolean isSelect = stmt.execute("create database " + dbName); - Assert.assertEquals(false, isSelect); - int affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(0, affectedRows); - - isSelect = stmt.execute("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); - Assert.assertEquals(false, isSelect); - affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(0, affectedRows); - - isSelect = stmt.execute("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); - Assert.assertEquals(false, isSelect); - affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(1, affectedRows); - - isSelect = stmt.execute("select * from " + dbName + ".weather"); - Assert.assertEquals(true, isSelect); - ResultSet rs = stmt.getResultSet(); - Assert.assertNotNull(rs); - ResultSetMetaData meta = rs.getMetaData(); - Assert.assertEquals(3, meta.getColumnCount()); - int count = 0; - while (rs.next()) { - count++; - } - Assert.assertEquals(1, count); - - isSelect = stmt.execute("drop database " + dbName); - Assert.assertEquals(false, isSelect); - affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(0, affectedRows); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void getUpdateCount() { - // already test in execute method - } - - @Test - public void getMoreResults() throws SQLException { - Assert.assertEquals(false, stmt.getMoreResults()); - } - - @Test(expected = SQLException.class) - public void setFetchDirection() throws SQLException { - stmt.setFetchDirection(ResultSet.FETCH_FORWARD); - stmt.setFetchDirection(ResultSet.FETCH_REVERSE); - stmt.setFetchDirection(ResultSet.FETCH_UNKNOWN); - stmt.setFetchDirection(-1); - } - - @Test - public void getFetchDirection() throws SQLException { - Assert.assertEquals(ResultSet.FETCH_FORWARD, stmt.getFetchDirection()); - } - - @Test(expected = SQLException.class) - public void setFetchSize() throws SQLException { - stmt.setFetchSize(0); - stmt.setFetchSize(-1); - } - - @Test - public void getFetchSize() throws SQLException { - stmt.setFetchSize(0); - Assert.assertEquals(0, stmt.getFetchSize()); - stmt.setFetchSize(0); - } - - @Test - public void getResultSetConcurrency() throws SQLException { - Assert.assertEquals(ResultSet.CONCUR_READ_ONLY, stmt.getResultSetConcurrency()); - } - - @Test - public void getResultSetType() throws SQLException { - Assert.assertEquals(ResultSet.TYPE_FORWARD_ONLY, stmt.getResultSetType()); - } - - @Test - public void addBatch() { - final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); - try { - stmt.addBatch("create database " + dbName); - stmt.addBatch("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); - stmt.addBatch("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); - stmt.addBatch("select * from " + dbName + ".weather"); - stmt.addBatch("drop database " + dbName); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void clearBatch() { - final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); - try { - stmt.clearBatch(); - stmt.addBatch("create database " + dbName); - stmt.addBatch("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); - stmt.addBatch("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); - stmt.addBatch("select * from " + dbName + ".weather"); - stmt.addBatch("drop database " + dbName); - stmt.clearBatch(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void executeBatch() { - final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); - try { - stmt.addBatch("create database " + dbName); - stmt.addBatch("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); - stmt.addBatch("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); - stmt.addBatch("select * from " + dbName + ".weather"); - stmt.addBatch("drop database " + dbName); - int[] results = stmt.executeBatch(); - Assert.assertEquals(0, results[0]); - Assert.assertEquals(0, results[1]); - Assert.assertEquals(1, results[2]); - Assert.assertEquals(Statement.SUCCESS_NO_INFO, results[3]); - Assert.assertEquals(0, results[4]); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void getConnection() { - try { - Connection connection = stmt.getConnection(); - Assert.assertNotNull(connection); - Assert.assertTrue(this.conn == connection); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testGetMoreResults() throws SQLException { - Assert.assertEquals(false, stmt.getMoreResults(Statement.CLOSE_CURRENT_RESULT)); - stmt.getMoreResults(Statement.KEEP_CURRENT_RESULT); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getGeneratedKeys() throws SQLException { - stmt.getGeneratedKeys(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testExecuteUpdate() throws SQLException { - stmt.executeUpdate("", 1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testExecuteUpdate1() throws SQLException { - stmt.executeUpdate("", new int[]{}); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testExecuteUpdate2() throws SQLException { - stmt.executeUpdate("", new String[]{}); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testExecute() throws SQLException { - stmt.execute("", 1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testExecute1() throws SQLException { - stmt.execute("", new int[]{}); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testExecute2() throws SQLException { - stmt.execute("", new String[]{}); - } - - @Test - public void getResultSetHoldability() throws SQLException { - Assert.assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, stmt.getResultSetHoldability()); - } - - @Test - public void isClosed() { - try { - Assert.assertEquals(false, stmt.isClosed()); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void setPoolable() throws SQLException { - stmt.setPoolable(true); - stmt.setPoolable(false); - } - - @Test - public void isPoolable() throws SQLException { - Assert.assertEquals(false, stmt.isPoolable()); - } - - @Test - public void closeOnCompletion() throws SQLException { - stmt.closeOnCompletion(); - } - - @Test - public void isCloseOnCompletion() throws SQLException { - Assert.assertFalse(stmt.isCloseOnCompletion()); - } - - @Test - public void unwrap() throws SQLException { - TSDBStatement unwrap = stmt.unwrap(TSDBStatement.class); - Assert.assertNotNull(unwrap); - } - - @Test - public void isWrapperFor() throws SQLException { - Assert.assertTrue(stmt.isWrapperFor(TSDBStatement.class)); - } - - @BeforeClass - public static void beforeClass() { - try { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata", properties); - stmt = conn.createStatement(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @AfterClass - public static void afterClass() { - try { - if (stmt != null) - stmt.close(); - if (conn != null) - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogClass.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogClass.java deleted file mode 100644 index 490346e401..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogClass.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.taosdata.jdbc.annotation; - -import java.util.ArrayList; -import java.util.List; - -/** - * Test class - */ -public class CatalogClass { - - private String name; - private String alias; - private String author; - private String version; - private List methods = new ArrayList<>(); - private int total; - private int failure; - - public void setTotal(int total) { - this.total = total; - } - - public void setFailure(int failure) { - this.failure = failure; - } - - public void setAuthor(String author) { - this.author = author; - } - - public void setVersion(String version) { - this.version = version; - } - - public void setName(String name) { - this.name = name; - } - - public void setAlias(String alias) { - this.alias = alias; - } - - public void setMethods(List methods) { - this.methods = methods; - } - - @Override - public String toString() { - if (methods.size() < 1) - return null; - StringBuilder sb = new StringBuilder(); - sb.append("ClassName: ").append(name); - String msg = trim(alias); - if (null != msg) - sb.append("\tAlias:").append(alias); - sb.append("\tTotal:").append(total) - .append("\tFailure:").append(failure).append("\n"); - for (CatalogMethod method : methods) { - sb.append("\t").append(method.getName()); - sb.append("\t").append(method.isSuccess()); - sb.append("\t").append(method.getMessage()); - String mAuthor = trim(method.getAuthor()); - if (null == mAuthor) { - sb.append("\t").append(author); - } else { - sb.append("\t").append(method.getAuthor()); - } - String mVersion = trim(method.getVersion()); - if (null == mVersion) { - sb.append("\t").append(version); - } else { - sb.append("\t").append(mVersion); - } - sb.append("\n"); - } - return sb.toString(); - } - - private String trim(String s) { - if (null == s || s.trim().equals("")) { - return null; - } else { - return s.trim(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogListener.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogListener.java deleted file mode 100644 index 2d22302d02..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogListener.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.taosdata.jdbc.annotation; - -import org.junit.runner.Description; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; - -import java.io.File; -import java.io.FileWriter; -import java.util.LinkedList; - -public class CatalogListener extends RunListener { - public static final String CATALOG_FILE = "target/TestCaseCatalog.txt"; - CatalogClass catalogClass = null; - private final LinkedList methods = new LinkedList<>(); - - @Override - public void testRunStarted(Description description) throws Exception { - catalogClass = new CatalogClass(); - TestTarget target = description.getAnnotation(TestTarget.class); - if (target != null) { - catalogClass.setAlias(target.alias()); - catalogClass.setAuthor(target.author()); - catalogClass.setVersion(target.version()); - } - catalogClass.setName(getClassName(description.getClassName())); - } - - private String getClassName(String name) { - if (null == name || name.trim().equals("")) { - return null; - } - name = name.trim(); - int pos = name.lastIndexOf("."); - if (-1 == pos) { - return name; - } - return name.substring(pos + 1); - } - - @Override - public void testRunFinished(Result result) throws Exception { - catalogClass.setMethods(methods); - catalogClass.setTotal(result.getRunCount()); - catalogClass.setFailure(result.getFailureCount()); - File file = new File(CATALOG_FILE); - if (!file.exists()) { - synchronized (CatalogListener.class) { - if (!file.exists()) { - file.createNewFile(); - try (FileWriter writer = new FileWriter(file, true)) { - writer.write("\tName\tPass\tMessage\tAuthor\tVersion\n"); - writer.write(catalogClass.toString()); - } - } - } - } else { - try (FileWriter writer = new FileWriter(file, true)) { - writer.write(catalogClass.toString()); - } - } - } - - @Override - public void testStarted(Description description) throws Exception { - } - - @Override - public void testFinished(Description description) throws Exception { - com.taosdata.jdbc.annotation.Description annotation - = description.getAnnotation(com.taosdata.jdbc.annotation.Description.class); - if (annotation != null) { - CatalogMethod method = new CatalogMethod(); - method.setMessage(annotation.value()); - method.setAuthor(annotation.author()); - method.setVersion(annotation.version()); - method.setSuccess(true); - method.setName(description.getMethodName()); - methods.addLast(method); - } - } - - @Override - public void testFailure(Failure failure) throws Exception { - com.taosdata.jdbc.annotation.Description annotation - = failure.getDescription().getAnnotation(com.taosdata.jdbc.annotation.Description.class); - CatalogMethod method = new CatalogMethod(); - method.setMessage(annotation.value()); - method.setAuthor(annotation.author()); - method.setVersion(annotation.version()); - method.setSuccess(false); - method.setName(failure.getDescription().getMethodName()); - methods.addFirst(method); - } - - @Override - public void testAssumptionFailure(Failure failure) { - } - - @Override - public void testIgnored(Description description) throws Exception { - super.testIgnored(description); - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogMethod.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogMethod.java deleted file mode 100644 index 1dd074df2d..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogMethod.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.taosdata.jdbc.annotation; - -/** - * Test method - */ -public class CatalogMethod { - private String name; - private boolean success; - private String message; - private String author; - private String version; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogRunner.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogRunner.java deleted file mode 100644 index 08e5f92122..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogRunner.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.taosdata.jdbc.annotation; - -import org.junit.internal.AssumptionViolatedException; -import org.junit.internal.runners.model.EachTestNotifier; -import org.junit.runner.notification.RunNotifier; -import org.junit.runner.notification.StoppedByUserException; -import org.junit.runners.BlockJUnit4ClassRunner; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.Statement; - -public class CatalogRunner extends BlockJUnit4ClassRunner { - - public CatalogRunner(Class testClass) throws InitializationError { - super(testClass); - } - - @Override - public void run(RunNotifier notifier) { - //add user-defined listener - notifier.addListener(new CatalogListener()); - EachTestNotifier testNotifier = new EachTestNotifier(notifier, getDescription()); - - notifier.fireTestRunStarted(getDescription()); - - try { - Statement statement = classBlock(notifier); - statement.evaluate(); - } catch (AssumptionViolatedException av) { - testNotifier.addFailedAssumption(av); - } catch (StoppedByUserException exception) { - throw exception; - } catch (Throwable e) { - testNotifier.addFailure(e); - } - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/Description.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/Description.java deleted file mode 100644 index 669b0a0886..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/Description.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.taosdata.jdbc.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -public @interface Description { - - String value(); - - // git blame author - String author() default ""; - - // since which version; - String version() default ""; -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/TestTarget.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/TestTarget.java deleted file mode 100644 index 3d1db68164..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/TestTarget.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.taosdata.jdbc.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface TestTarget { - - String alias() default ""; - - String author(); - - String version() default ""; - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/block/TSDBBlockJsonTagTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/block/TSDBBlockJsonTagTest.java deleted file mode 100644 index 4925c14cd8..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/block/TSDBBlockJsonTagTest.java +++ /dev/null @@ -1,1338 +0,0 @@ -package com.taosdata.jdbc.block; - -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.TSDBPreparedStatement; -import com.taosdata.jdbc.annotation.CatalogRunner; -import com.taosdata.jdbc.annotation.Description; -import com.taosdata.jdbc.annotation.TestTarget; -import org.junit.*; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; - -import java.sql.*; -import java.util.*; - -/** - * fetch_block for json tag test - */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(CatalogRunner.class) -@TestTarget(alias = "JsonTag", author = "huolibo", version = "2.0.38") -public class TSDBBlockJsonTagTest { - private static final String dbName = "json_tag_test"; - private static Connection connection; - private static Statement statement; - private static final String superSql = "create table if not exists jsons1(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"; - private static final String[] sql = { - "insert into jsons1_1 using jsons1 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(now, 1, false, 'json1', '你是') (1591060608000, 23, true, '等等', 'json')", - "insert into jsons1_2 using jsons1 tags('{\"tag1\":5,\"tag2\":\"beijing\"}') values (1591060628000, 2, true, 'json2', 'sss')", - "insert into jsons1_3 using jsons1 tags('{\"tag1\":false,\"tag2\":\"beijing\"}') values (1591060668000, 3, false, 'json3', 'efwe')", - "insert into jsons1_4 using jsons1 tags('{\"tag1\":null,\"tag2\":\"shanghai\",\"tag3\":\"hello\"}') values (1591060728000, 4, true, 'json4', '323sd')", - "insert into jsons1_5 using jsons1 tags('{\"tag1\":1.232, \"tag2\":null}') values(1591060928000, 1, false, '你就会', 'ewe')", - "insert into jsons1_6 using jsons1 tags('{\"tag1\":11,\"tag2\":\"\",\"tag2\":null}') values(1591061628000, 11, false, '你就会','')", - "insert into jsons1_7 using jsons1 tags('{\"tag1\":\"收到货\",\"tag2\":\"\",\"tag3\":null}') values(1591062628000, 2, NULL, '你就会', 'dws')", - // test duplicate key using the first one. - "CREATE TABLE if not exists jsons1_8 using jsons1 tags('{\"tag1\":null, \"tag1\":true, \"tag1\":45, \"1tag$\":2, \" \":90}')", - - }; - - private static final String[] invalidJsonInsertSql = { - // test empty json string, save as tag is NULL - "insert into jsons1_9 using jsons1 tags('\t') values (1591062328000, 24, NULL, '你就会', '2sdw')", - }; - - private static final String[] invalidJsonCreateSql = { - "CREATE TABLE if not exists jsons1_10 using jsons1 tags('')", - "CREATE TABLE if not exists jsons1_11 using jsons1 tags(' ')", - "CREATE TABLE if not exists jsons1_12 using jsons1 tags('{}')", - "CREATE TABLE if not exists jsons1_13 using jsons1 tags('null')", - }; - - // test invalidate json - private static final String[] errorJsonInsertSql = { - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('\"efwewf\"')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('3333')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('33.33')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('false')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('[1,true]')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{222}')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"fe\"}')", - }; - - private static final String[] errorSelectSql = { - "select * from jsons1 where jtag->tag1='beijing'", - "select * from jsons1 where jtag->'location'", - "select * from jsons1 where jtag->''", - "select * from jsons1 where jtag->''=9", - "select -> from jsons1", - "select ? from jsons1", - "select * from jsons1 where contains", - "select * from jsons1 where jtag->", - "select jtag->location from jsons1", - "select jtag contains location from jsons1", - "select * from jsons1 where jtag contains location", - "select * from jsons1 where jtag contains ''", - "select * from jsons1 where jtag contains 'location'='beijing'", - // test where with json tag - "select * from jsons1_1 where jtag is not null", - "select * from jsons1 where jtag='{\"tag1\":11,\"tag2\":\"\"}'", - "select * from jsons1 where jtag->'tag1'={}" - }; - - @Test - @Description("insert json tag") - public void case01_InsertTest() throws SQLException { - for (String sql : sql) { - statement.execute(sql); - } - for (String sql : invalidJsonInsertSql) { - statement.execute(sql); - } - for (String sql : invalidJsonCreateSql) { - statement.execute(sql); - } - } - - @Test - @Description("error json tag insert") - public void case02_ErrorJsonInsertTest() { - int count = 0; - for (String sql : errorJsonInsertSql) { - try { - statement.execute(sql); - } catch (SQLException e) { - count++; - } - } - Assert.assertEquals(errorJsonInsertSql.length, count); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json value is array") - public void case02_ArrayErrorTest() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"tag1\":[1,true]}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json value is empty") - public void case02_EmptyValueErrorTest() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"tag1\":{}}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json key is not ASCII") - public void case02_AbnormalKeyErrorTest1() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"。loc\":\"fff\"}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json key is '\\t'") - public void case02_AbnormalKeyErrorTest2() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"\t\":\"fff\"}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json key is chinese") - public void case02_AbnormalKeyErrorTest3() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"试试\":\"fff\"}')"); - } - - @Test - @Description("alter json tag") - public void case03_AlterTag() throws SQLException { - statement.execute("ALTER TABLE jsons1_1 SET TAG jtag='{\"tag1\":\"femail\",\"tag2\":35,\"tag3\":true}'"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when add json tag") - public void case03_AddTagErrorTest() throws SQLException { - statement.execute("ALTER STABLE jsons1 add tag tag2 nchar(20)"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when delete json tag") - public void case03_dropTagErrorTest() throws SQLException { - statement.execute("ALTER STABLE jsons1 drop tag jtag"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when set some json tag value") - public void case03_AlterTagErrorTest() throws SQLException { - statement.execute("ALTER TABLE jsons1_1 SET TAG jtag=4"); - } - - @Test - @Description("exception will throw when select syntax error") - public void case04_SelectErrorTest() { - int count = 0; - for (String sql : errorSelectSql) { - try { - statement.execute(sql); - } catch (SQLException e) { - count++; - } - } - Assert.assertEquals(errorSelectSql.length, count); - } - - @Test - @Description("normal select stable") - public void case04_select01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select dataint from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("select all column from stable") - public void case04_select02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("select json tag from stable") - public void case04_select03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1"); - ResultSetMetaData metaData = resultSet.getMetaData(); - metaData.getColumnTypeName(1); - int count = 0; - Set set = new HashSet<>(); - while (resultSet.next()) { - count++; - set.add(resultSet.getString(1)); - } - Assert.assertTrue(set.contains("{\"tag1\":null,\"1tag$\":2,\" \":90}")); - Assert.assertTrue(set.contains("{\"tag1\":\"收到货\",\"tag2\":\"\",\"tag3\":null}")); - Assert.assertEquals(sql.length + invalidJsonInsertSql.length + invalidJsonCreateSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition tag is null") - public void case04_select04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1 where jtag is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(invalidJsonInsertSql.length + invalidJsonCreateSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition tag is not null") - public void case04_select05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1 where jtag is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length, count); - close(resultSet); - } - - @Test - @Description("select json tag") - public void case04_select06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1_8"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("{\"tag1\":null,\"1tag$\":2,\" \":90}", result); - close(resultSet); - } - - @Test - @Description("select json tag") - public void case04_select07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1_1"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("{\"tag1\":\"femail\",\"tag2\":35,\"tag3\":true}", result); - close(resultSet); - } - - @Test - @Description("select not exist json tag") - public void case04_select08() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1_9"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertNull(result); - close(resultSet); - } - - @Test - @Description("select a json tag") - public void case04_select09() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_1"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("\"femail\"", result); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is empty") - public void case04_select10() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag2' from jsons1_6"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("\"\"", result); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is int") - public void case04_select11() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag2' from jsons1_1"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("35", string); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is boolean") - public void case04_select12() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag3' from jsons1_1"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("true", string); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is null") - public void case04_select13() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_4"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("null", string); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is double") - public void case04_select14() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_5"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("1.232000000", string); - close(resultSet); - } - - @Test - @Description("select a json tag, the key is not exist") - public void case04_select15() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag10' from jsons1_4"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertNull(string); - close(resultSet); - } - - @Test - @Description("select a json tag, the result number equals tables number") - public void case04_select16() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonCreateSql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition '=' for string") - public void case04_select19() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("select and where conditon '=' for string") - public void case04_select20() throws SQLException { - ResultSet resultSet = statement.executeQuery("select dataint,tbname,jtag->'tag1',jtag from jsons1 where jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition result is null") - public void case04_select21() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition equation has chinese") - public void case04_select23() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'='收到货'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '>' for character") - public void case05_symbolOperation01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'>'beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '>=' for character") - public void case05_symbolOperation02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'>='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '<' for character") - public void case05_symbolOperation03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'<'beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition support '<=' in character") - public void case05_symbolOperation04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'<='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' in character") - public void case05_symbolOperation05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'!='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '=' empty") - public void case05_symbolOperation06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'=''"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - // where json value is int - @Test - @Description("where condition support '=' for int") - public void case06_selectValue01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=5"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where conditional support '<' for int") - public void case06_selectValue02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<54"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '<=' for int") - public void case06_selectValue03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<=11"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where conditional support '>' for int") - public void case06_selectValue04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>4"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition support '>=' for int") - public void case06_selectValue05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>=5"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where conditional support '!=' for int") - public void case06_selectValue06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=5"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where conditional support '!=' for int") - public void case06_selectValue07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=55"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where conditional support '!=' for int and result is nothing") - public void case06_selectValue08() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=10"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support '=' for double") - public void case07_selectValue01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '<' for double") - public void case07_doubleOperation01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support '<=' for double") - public void case07_doubleOperation02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '>' for double") - public void case07_doubleOperation03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>1.23"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '>=' for double") - public void case07_doubleOperation04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' for double") - public void case07_doubleOperation05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' for double") - public void case07_doubleOperation06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=3.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when denominator is zero") - public void case07_doubleOperation07() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1'/0=3"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when invalid operation") - public void case07_doubleOperation08() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1'/5=1"); - } - - @Test - @Description("where condition support '=' for boolean") - public void case08_boolOperation01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=true"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support '=' for boolean") - public void case08_boolOperation02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' for boolean") - public void case08_boolOperation03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=false"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when '>' operation for boolean") - public void case08_boolOperation04() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1'>false"); - } - - @Test - @Description("where conditional support '=null'") - public void case09_select01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where conditional support 'is null'") - public void case09_select02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support 'is not null'") - public void case09_select03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag '='") - public void case09_select04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag_no_exist'=3"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag 'is null'") - public void case09_select05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag 'is null'") - public void case09_select06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag4' is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag 'is not null'") - public void case09_select07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag3' is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("contains") - public void case09_select10() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag contains 'tag1'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("contains") - public void case09_select11() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("contains with no exist tag") - public void case09_select12() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag contains 'tag_no_exist'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition with and") - public void case10_selectAndOr01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false and jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition with 'or'") - public void case10_selectAndOr02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false or jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition with 'and'") - public void case10_selectAndOr03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false and jtag->'tag2'='shanghai'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition with 'or'") - public void case10_selectAndOr04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=13 or jtag->'tag2'>35"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition with 'or' and contains") - public void case10_selectAndOr05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' is not null and jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("where condition with 'and' and contains") - public void case10_selectAndOr06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'='femail' and jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3' and dataint=3"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3' and dataint=23"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition like") - public void case12_selectWhere01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,tbname from jsons1 where jtag->'tag2' like 'bei%'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition like") - public void case12_selectWhere02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,tbname from jsons1 where jtag->'tag1' like 'fe%' and jtag->'tag2' is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test(expected = SQLException.class) - @Description("where condition in no support in") - public void case12_selectWhere03() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1' in ('beijing')"); - } - - @Test - @Description("where condition match") - public void case12_selectWhere04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' match 'ma'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition match") - public void case12_selectWhere05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' match 'ma$'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition match") - public void case12_selectWhere06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2' match 'jing$'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition match") - public void case12_selectWhere07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' match '收到'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("insert distinct") - public void case13_selectDistinct01() throws SQLException { - statement.execute("insert into jsons1_14 using jsons1 tags('{\"tag1\":\"收到货\",\"tag2\":\"\",\"tag3\":null}') values(1591062628000, 2, NULL, '你就会', 'dws')"); - } - - @Test - @Description("distinct json tag") - public void case13_selectDistinct02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select distinct jtag->'tag1' from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("distinct json tag") - public void case13_selectDistinct03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select distinct jtag from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(9, count); - close(resultSet); - } - - @Test - @Description("insert json tag") - public void case14_selectDump01() throws SQLException { - statement.execute("INSERT INTO jsons1_15 using jsons1 tags('{\"tbname\":\"tt\",\"databool\":true,\"datastr\":\"是是是\"}') values(1591060828000, 4, false, 'jjsf', \"你就会\")"); - } - - @Test - @Description("test duplicate key with normal column") - public void case14_selectDump02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,tbname,jtag from jsons1 where jtag->'datastr' match '是' and datastr match 'js'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("test duplicate key with normal column") - public void case14_selectDump03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select tbname,jtag->'tbname' from jsons1 where jtag->'tbname'='tt' and tbname='jsons1_14'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("insert json tag for join test") - public void case15_selectJoin01() throws SQLException { - statement.execute("create table if not exists jsons2(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"); - statement.execute("insert into jsons2_1 using jsons2 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(1591060618000, 2, false, 'json2', '你是2')"); - statement.execute("insert into jsons2_2 using jsons2 tags('{\"tag1\":5,\"tag2\":null}') values (1591060628000, 2, true, 'json2', 'sss')"); - - statement.execute("create table if not exists jsons3(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"); - statement.execute("insert into jsons3_1 using jsons3 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(1591060618000, 3, false, 'json3', '你是3')"); - statement.execute("insert into jsons3_2 using jsons3 tags('{\"tag1\":5,\"tag2\":\"beijing\"}') values (1591060638000, 2, true, 'json3', 'sss')"); - } - - @Test - @Description("select json tag from join") - public void case15_selectJoin02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select 'sss',33,a.jtag->'tag3' from jsons2 a,jsons3 b where a.ts=b.ts and a.jtag->'tag1'=b.jtag->'tag1'"); - resultSet.next(); - Assert.assertEquals("sss", resultSet.getString(1)); - close(resultSet); - } - - @Test - @Description("group by and order by json tag desc") - public void case16_selectGroupOrder01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select count(*) from jsons1 group by jtag->'tag1' order by jtag->'tag1' desc"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("group by and order by json tag asc") - public void case16_selectGroupOrder02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select count(*) from jsons1 group by jtag->'tag1' order by jtag->'tag1' asc"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("stddev with group by json tag") - public void case17_selectStddev01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select stddev(dataint) from jsons1 group by jtag->'tag1'"); - String s = ""; - int count = 0; - Set set = new HashSet<>(); - while (resultSet.next()) { - count++; - set.add(resultSet.getString(2)); - } - Assert.assertEquals(8, count); - Assert.assertTrue(set.contains("\"femail\"")); - Assert.assertTrue(set.contains("\"收到货\"")); - } - - @Test - @Description("subquery json tag") - public void case18_selectSubquery01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from (select jtag, dataint from jsons1)"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(11, count); - close(resultSet); - } - - @Test - @Description("subquery some json tags") - public void case18_selectSubquery02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from (select jtag->'tag1', dataint from jsons1)"); - - ResultSetMetaData metaData = resultSet.getMetaData(); - String columnName = metaData.getColumnName(1); - Assert.assertEquals("jtag->'tag1'", columnName); - - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(11, count); - close(resultSet); - } - - @Test - @Description("query some json tags from subquery") - public void case18_selectSubquery04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select ts,tbname,jtag->'tag1' from (select jtag->'tag1',tbname,ts from jsons1 order by ts)"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(11, count); - close(resultSet); - } - - @Test - @Description("query metadata for json") - public void case19_selectMetadata01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1"); - ResultSetMetaData metaData = resultSet.getMetaData(); - int columnType = metaData.getColumnType(1); - String columnTypeName = metaData.getColumnTypeName(1); - Assert.assertEquals(Types.OTHER, columnType); - Assert.assertEquals("JSON", columnTypeName); - close(resultSet); - } - - @Test - @Description("query metadata for json") - public void case19_selectMetadata02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,jtag from jsons1"); - ResultSetMetaData metaData = resultSet.getMetaData(); - int columnType = metaData.getColumnType(6); - String columnTypeName = metaData.getColumnTypeName(6); - Assert.assertEquals(Types.OTHER, columnType); - Assert.assertEquals("JSON", columnTypeName); - close(resultSet); - } - - @Test - @Description("query metadata for one json result") - public void case19_selectMetadata03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_6"); - ResultSetMetaData metaData = resultSet.getMetaData(); - int columnType = metaData.getColumnType(1); - String columnTypeName = metaData.getColumnTypeName(1); - Assert.assertEquals(Types.OTHER, columnType); - Assert.assertEquals("JSON", columnTypeName); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("11", string); - close(resultSet); - } - - @Test - @Description("stmt batch insert with json tag") - public void case20_batchInsert() throws SQLException { - String jsonTag = "{\"tag1\":\"fff\",\"tag2\":5,\"tag3\":true}"; - statement.execute("drop table if exists jsons5"); - statement.execute("CREATE STABLE IF NOT EXISTS jsons5 (ts timestamp, dataInt int, dataStr nchar(20)) TAGS(jtag json)"); - - String sql = "INSERT INTO ? USING jsons5 TAGS (?) VALUES ( ?,?,? )"; - - try (PreparedStatement pst = connection.prepareStatement(sql)) { - TSDBPreparedStatement ps = pst.unwrap(TSDBPreparedStatement.class); - // 设定数据表名: - ps.setTableName("batch_test"); - // 设定 TAGS 取值 setTagNString or setTagJson: -// ps.setTagNString(0, jsonTag); - ps.setTagJson(0, jsonTag); - - // VALUES 部分以逐列的方式进行设置: - int numOfRows = 4; - ArrayList ts = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - ts.add(System.currentTimeMillis() + i); - } - ps.setTimestamp(0, ts); - - Random r = new Random(); - int random = 10 + r.nextInt(5); - ArrayList c1 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - if (i % random == 0) { - c1.add(null); - } else { - c1.add(r.nextInt()); - } - } - ps.setInt(1, c1); - - ArrayList c2 = new ArrayList<>(); - for (int i = 0; i < numOfRows; i++) { - c2.add("分支" + i % 4); - } - ps.setNString(2, c2, 10); - - // AddBatch 之后,缓存并未清空。为避免混乱,并不推荐在 ExecuteBatch 之前再次绑定新一批的数据: - ps.columnDataAddBatch(); - // 执行绑定数据后的语句: - ps.columnDataExecuteBatch(); - } - - ResultSet resultSet = statement.executeQuery("select jtag from batch_test"); - ResultSetMetaData metaData = resultSet.getMetaData(); - String columnName = metaData.getColumnName(1); - Assert.assertEquals("jtag", columnName); - Assert.assertEquals("JSON", metaData.getColumnTypeName(1)); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals(jsonTag, string); - resultSet.close(); - resultSet = statement.executeQuery("select jtag->'tag2' from batch_test"); - resultSet.next(); - long l = resultSet.getLong(1); - Assert.assertEquals(5, l); - resultSet.close(); - } - - private void close(ResultSet resultSet) { - try { - if (null != resultSet) { - resultSet.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @BeforeClass - public static void beforeClass() { - String host = "127.0.0.1"; - final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - try { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true"); - connection = DriverManager.getConnection(url, properties); - statement = connection.createStatement(); - statement.execute("drop database if exists " + dbName); - statement.execute("create database if not exists " + dbName); - statement.execute("use " + dbName); - statement.execute(superSql); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @AfterClass - public static void afterClass() { - try { - if (null != statement) { - statement.execute("drop database " + dbName); - statement.close(); - } - if (null != connection) { - connection.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/block/TSDBBlockResultSetTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/block/TSDBBlockResultSetTest.java deleted file mode 100644 index 205ad2c0dc..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/block/TSDBBlockResultSetTest.java +++ /dev/null @@ -1,687 +0,0 @@ -package com.taosdata.jdbc.block; - -import com.google.common.primitives.Ints; -import com.google.common.primitives.Longs; -import com.google.common.primitives.Shorts; -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.TSDBResultSet; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.sql.*; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Properties; - -public class TSDBBlockResultSetTest { - - private static final String host = "127.0.0.1"; - private static Connection conn; - private static Statement stmt; - private static ResultSet rs; - - @Test - public void wasNull() throws SQLException { - Assert.assertFalse(rs.wasNull()); - } - - @Test - public void getString() throws SQLException { - String f10 = rs.getString("f10"); - Assert.assertEquals("涛思数据", f10); - f10 = rs.getString(10); - Assert.assertEquals("涛思数据", f10); - } - - @Test - public void getBoolean() throws SQLException { - Boolean f9 = rs.getBoolean("f9"); - Assert.assertEquals(true, f9); - f9 = rs.getBoolean(9); - Assert.assertEquals(true, f9); - } - - @Test - public void getByte() throws SQLException { - byte f8 = rs.getByte("f8"); - Assert.assertEquals(10, f8); - f8 = rs.getByte(8); - Assert.assertEquals(10, f8); - } - - @Test - public void getShort() throws SQLException { - short f7 = rs.getShort("f7"); - Assert.assertEquals(10, f7); - f7 = rs.getShort(7); - Assert.assertEquals(10, f7); - } - - @Test - public void getInt() throws SQLException { - int f2 = rs.getInt("f2"); - Assert.assertEquals(1, f2); - f2 = rs.getInt(2); - Assert.assertEquals(1, f2); - } - - @Test - public void getLong() throws SQLException { - long f3 = rs.getLong("f3"); - Assert.assertEquals(100, f3); - f3 = rs.getLong(3); - Assert.assertEquals(100, f3); - } - - @Test - public void getFloat() throws SQLException { - float f4 = rs.getFloat("f4"); - Assert.assertEquals(3.1415f, f4, 0f); - f4 = rs.getFloat(4); - Assert.assertEquals(3.1415f, f4, 0f); - } - - @Test - public void getDouble() throws SQLException { - double f5 = rs.getDouble("f5"); - Assert.assertEquals(3.1415926, f5, 0.0); - f5 = rs.getDouble(5); - Assert.assertEquals(3.1415926, f5, 0.0); - } - - @Test - public void getBigDecimal() throws SQLException { - BigDecimal f1 = rs.getBigDecimal("f1"); - Assert.assertEquals(1609430400000L, f1.longValue()); - - BigDecimal f2 = rs.getBigDecimal("f2"); - Assert.assertEquals(1, f2.intValue()); - - BigDecimal f3 = rs.getBigDecimal("f3"); - Assert.assertEquals(100L, f3.longValue()); - - BigDecimal f4 = rs.getBigDecimal("f4"); - Assert.assertEquals(3.1415f, f4.floatValue(), 0.00000f); - - BigDecimal f5 = rs.getBigDecimal("f5"); - Assert.assertEquals(3.1415926, f5.doubleValue(), 0.0000000); - - BigDecimal f7 = rs.getBigDecimal("f7"); - Assert.assertEquals(10, f7.intValue()); - - BigDecimal f8 = rs.getBigDecimal("f8"); - Assert.assertEquals(10, f8.intValue()); - } - - @Test - public void getBytes() throws SQLException { - byte[] f1 = rs.getBytes("f1"); - Assert.assertEquals("2021-01-01 00:00:00.0", new String(f1)); - - byte[] f2 = rs.getBytes("f2"); - Assert.assertEquals(1, Ints.fromByteArray(f2)); - - byte[] f3 = rs.getBytes("f3"); - Assert.assertEquals(100L, Longs.fromByteArray(f3)); - - byte[] f4 = rs.getBytes("f4"); - Assert.assertEquals(3.1415f, Float.parseFloat(new String(f4)), 0.000000f); - - byte[] f5 = rs.getBytes("f5"); - Assert.assertEquals(3.1415926, Double.parseDouble(new String(f5)), 0.000000f); - - byte[] f6 = rs.getBytes("f6"); - Assert.assertTrue(Arrays.equals("abc".getBytes(), f6)); - - byte[] f7 = rs.getBytes("f7"); - Assert.assertEquals((short) 10, Shorts.fromByteArray(f7)); - - byte[] f8 = rs.getBytes("f8"); - Assert.assertEquals(1, f8.length); - Assert.assertEquals((byte) 10, f8[0]); - - byte[] f9 = rs.getBytes("f9"); - Assert.assertEquals("true", new String(f9)); - - byte[] f10 = rs.getBytes("f10"); - Assert.assertEquals("涛思数据", new String(f10)); - } - - @Test - public void getDate() throws SQLException, ParseException { - Date f1 = rs.getDate("f1"); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - Assert.assertEquals(sdf.parse("2021-01-01"), f1); - } - - @Test - public void getTime() throws SQLException { - Time f1 = rs.getTime("f1"); - Assert.assertNotNull(f1); - Assert.assertEquals("00:00:00", f1.toString()); - } - - @Test - public void getTimestamp() throws SQLException { - Timestamp f1 = rs.getTimestamp("f1"); - Assert.assertEquals("2021-01-01 00:00:00.0", f1.toString()); - f1 = rs.getTimestamp(1); - Assert.assertEquals("2021-01-01 00:00:00.0", f1.toString()); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getAsciiStream() throws SQLException { - rs.getAsciiStream("f1"); - } - - @SuppressWarnings("deprecation") - @Test(expected = SQLFeatureNotSupportedException.class) - public void getUnicodeStream() throws SQLException { - rs.getUnicodeStream("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getBinaryStream() throws SQLException { - rs.getBinaryStream("f1"); - } - - @Test - public void getWarnings() throws SQLException { - Assert.assertNull(rs.getWarnings()); - } - - @Test - public void clearWarnings() throws SQLException { - rs.clearWarnings(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getCursorName() throws SQLException { - rs.getCursorName(); - } - - @Test - public void getMetaData() throws SQLException { - ResultSetMetaData meta = rs.getMetaData(); - Assert.assertNotNull(meta); - } - - @Test - public void getObject() throws SQLException, ParseException { - Object f1 = rs.getObject("f1"); - Assert.assertEquals(Timestamp.class, f1.getClass()); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.sss"); - java.util.Date date = sdf.parse("2021-01-01 00:00:00.000"); - Assert.assertEquals(new Timestamp(date.getTime()), f1); - - Object f2 = rs.getObject("f2"); - Assert.assertEquals(Integer.class, f2.getClass()); - Assert.assertEquals(1, f2); - - Object f3 = rs.getObject("f3"); - Assert.assertEquals(Long.class, f3.getClass()); - Assert.assertEquals(100L, f3); - - Object f4 = rs.getObject("f4"); - Assert.assertEquals(Float.class, f4.getClass()); - Assert.assertEquals(3.1415f, f4); - - Object f5 = rs.getObject("f5"); - Assert.assertEquals(Double.class, f5.getClass()); - Assert.assertEquals(3.1415926, f5); - - Object f6 = rs.getObject("f6"); - Assert.assertEquals(byte[].class, f6.getClass()); - Assert.assertEquals("abc", new String((byte[]) f6)); - - Object f7 = rs.getObject("f7"); - Assert.assertEquals(Short.class, f7.getClass()); - Assert.assertEquals((short) 10, f7); - - Object f8 = rs.getObject("f8"); - Assert.assertEquals(Byte.class, f8.getClass()); - Assert.assertEquals((byte) 10, f8); - - Object f9 = rs.getObject("f9"); - Assert.assertEquals(Boolean.class, f9.getClass()); - Assert.assertEquals(true, f9); - - Object f10 = rs.getObject("f10"); - Assert.assertEquals(String.class, f10.getClass()); - Assert.assertEquals("涛思数据", f10); - } - - @Test(expected = SQLException.class) - public void findColumn() throws SQLException { - int columnIndex = rs.findColumn("f1"); - Assert.assertEquals(1, columnIndex); - columnIndex = rs.findColumn("f2"); - Assert.assertEquals(2, columnIndex); - columnIndex = rs.findColumn("f3"); - Assert.assertEquals(3, columnIndex); - columnIndex = rs.findColumn("f4"); - Assert.assertEquals(4, columnIndex); - columnIndex = rs.findColumn("f5"); - Assert.assertEquals(5, columnIndex); - columnIndex = rs.findColumn("f6"); - Assert.assertEquals(6, columnIndex); - columnIndex = rs.findColumn("f7"); - Assert.assertEquals(7, columnIndex); - columnIndex = rs.findColumn("f8"); - Assert.assertEquals(8, columnIndex); - columnIndex = rs.findColumn("f9"); - Assert.assertEquals(9, columnIndex); - columnIndex = rs.findColumn("f10"); - Assert.assertEquals(10, columnIndex); - - rs.findColumn("f11"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getCharacterStream() throws SQLException { - rs.getCharacterStream(1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void isBeforeFirst() throws SQLException { - rs.isBeforeFirst(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void isAfterLast() throws SQLException { - rs.isAfterLast(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void isFirst() throws SQLException { - rs.isFirst(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void isLast() throws SQLException { - rs.isLast(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void beforeFirst() throws SQLException { - rs.beforeFirst(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void afterLast() throws SQLException { - rs.afterLast(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void first() throws SQLException { - rs.first(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void last() throws SQLException { - rs.last(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getRow() throws SQLException { - rs.getRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void absolute() throws SQLException { - rs.absolute(-1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void relative() throws SQLException { - rs.relative(-1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void previous() throws SQLException { - rs.previous(); - } - - @Test - public void setFetchDirection() throws SQLException { - rs.setFetchDirection(ResultSet.FETCH_FORWARD); - Assert.assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection()); - rs.setFetchDirection(ResultSet.FETCH_UNKNOWN); - Assert.assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection()); - } - - @Test - public void getFetchDirection() throws SQLException { - Assert.assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection()); - } - - @Test - public void setFetchSize() throws SQLException { - rs.setFetchSize(0); - Assert.assertEquals(0, rs.getFetchSize()); - } - - @Test - public void getFetchSize() throws SQLException { - Assert.assertEquals(0, rs.getFetchSize()); - } - - @Test - public void getType() throws SQLException { - Assert.assertEquals(ResultSet.TYPE_FORWARD_ONLY, rs.getType()); - } - - @Test - public void getConcurrency() throws SQLException { - Assert.assertEquals(ResultSet.CONCUR_READ_ONLY, rs.getConcurrency()); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void rowUpdated() throws SQLException { - rs.rowUpdated(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void rowInserted() throws SQLException { - rs.rowInserted(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void rowDeleted() throws SQLException { - rs.rowDeleted(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateNull() throws SQLException { - rs.updateNull("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateBoolean() throws SQLException { - rs.updateBoolean(1, false); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateByte() throws SQLException { - rs.updateByte(1, (byte) 0); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateShort() throws SQLException { - rs.updateShort(1, (short) 0); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateInt() throws SQLException { - rs.updateInt(1, 1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateLong() throws SQLException { - rs.updateLong(1, 1L); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateFloat() throws SQLException { - rs.updateFloat(1, 1f); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateDouble() throws SQLException { - rs.updateDouble(1, 1.0); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateBigDecimal() throws SQLException { - rs.updateBigDecimal(1, new BigDecimal(1)); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateString() throws SQLException { - rs.updateString(1, "abc"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateBytes() throws SQLException { - rs.updateBytes(1, new byte[]{}); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateDate() throws SQLException { - rs.updateDate(1, new Date(System.currentTimeMillis())); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateTime() throws SQLException { - rs.updateTime(1, new Time(System.currentTimeMillis())); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateTimestamp() throws SQLException { - rs.updateTimestamp(1, new Timestamp(System.currentTimeMillis())); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateAsciiStream() throws SQLException { - rs.updateAsciiStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateBinaryStream() throws SQLException { - rs.updateBinaryStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateCharacterStream() throws SQLException { - rs.updateCharacterStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateObject() throws SQLException { - rs.updateObject(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void insertRow() throws SQLException { - rs.insertRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateRow() throws SQLException { - rs.updateRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void deleteRow() throws SQLException { - rs.deleteRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void refreshRow() throws SQLException { - rs.refreshRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void cancelRowUpdates() throws SQLException { - rs.cancelRowUpdates(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void moveToInsertRow() throws SQLException { - rs.moveToInsertRow(); - } - - @Test - public void getStatement() throws SQLException { - Statement stmt = rs.getStatement(); - Assert.assertNotNull(stmt); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void moveToCurrentRow() throws SQLException { - rs.moveToCurrentRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getRef() throws SQLException { - rs.getRef(1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getBlob() throws SQLException { - rs.getBlob("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getClob() throws SQLException { - rs.getClob("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getArray() throws SQLException { - rs.getArray("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getURL() throws SQLException { - rs.getURL("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateRef() throws SQLException { - rs.updateRef("f1", null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateBlob() throws SQLException { - rs.updateBlob(1, (InputStream) null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateClob() throws SQLException { - rs.updateClob(1, (Reader) null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateArray() throws SQLException { - rs.updateArray(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getRowId() throws SQLException { - rs.getRowId("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateRowId() throws SQLException { - rs.updateRowId(1, null); - } - - @Test - public void getHoldability() throws SQLException { - Assert.assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, rs.getHoldability()); - } - - @Test - public void isClosed() throws SQLException { - Assert.assertFalse(rs.isClosed()); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateNString() throws SQLException { - rs.updateNString(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateNClob() throws SQLException { - rs.updateNClob(1, (Reader) null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getNClob() throws SQLException { - rs.getNClob("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getSQLXML() throws SQLException { - rs.getSQLXML("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateSQLXML() throws SQLException { - rs.updateSQLXML(1, null); - } - - @Test - public void getNString() throws SQLException { - String f10 = rs.getNString("f10"); - Assert.assertEquals("涛思数据", f10); - f10 = rs.getNString(10); - Assert.assertEquals("涛思数据", f10); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getNCharacterStream() throws SQLException { - rs.getNCharacterStream("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateNCharacterStream() throws SQLException { - rs.updateNCharacterStream(1, null); - } - - @Test - public void unwrap() throws SQLException { - TSDBResultSet unwrap = rs.unwrap(TSDBResultSet.class); - Assert.assertNotNull(unwrap); - } - - @Test - public void isWrapperFor() throws SQLException { - Assert.assertTrue(rs.isWrapperFor(TSDBResultSet.class)); - } - - @BeforeClass - public static void beforeClass() { - try { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true"); - conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata", properties); - stmt = conn.createStatement(); - stmt.execute("create database if not exists restful_test"); - stmt.execute("use restful_test"); - stmt.execute("drop table if exists weather"); - stmt.execute("create table if not exists weather(f1 timestamp, f2 int, f3 bigint, f4 float, f5 double, f6 binary(64), f7 smallint, f8 tinyint, f9 bool, f10 nchar(64))"); - stmt.execute("insert into restful_test.weather values('2021-01-01 00:00:00.000', 1, 100, 3.1415, 3.1415926, 'abc', 10, 10, true, '涛思数据')"); - rs = stmt.executeQuery("select * from restful_test.weather"); - rs.next(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @AfterClass - public static void afterClass() { - try { - if (rs != null) - rs.close(); - if (stmt != null) - stmt.close(); - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists restful_test"); - statement.close(); - conn.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/AppMemoryLeakTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/AppMemoryLeakTest.java deleted file mode 100644 index 4f37183e71..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/AppMemoryLeakTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.Assert; -import org.junit.Test; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; - -public class AppMemoryLeakTest { - - @Test(expected = SQLException.class) - public void testCreateTooManyConnection() throws ClassNotFoundException, SQLException { - Class.forName("com.taosdata.jdbc.TSDBDriver"); - while (true) { - Connection conn = DriverManager.getConnection("jdbc:TAOS://localhost:6030/?user=root&password=taosdata"); - Assert.assertNotNull(conn); - } - } - - @Test(expected = Exception.class) - public void testCreateTooManyStatement() throws ClassNotFoundException, SQLException { - Class.forName("com.taosdata.jdbc.TSDBDriver"); - Connection conn = DriverManager.getConnection("jdbc:TAOS://localhost:6030/?user=root&password=taosdata"); - while (true) { - Statement stmt = conn.createStatement(); - Assert.assertNotNull(stmt); - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/AuthenticationTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/AuthenticationTest.java deleted file mode 100644 index d2f5b915ee..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/AuthenticationTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.taosdata.jdbc.cases; - -import com.taosdata.jdbc.TSDBErrorNumbers; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - -import java.sql.*; - -public class AuthenticationTest { - - private static final String host = "127.0.0.1"; - private static final String user = "root"; - private static final String password = "taos?data"; - private Connection conn; - - @Test - public void connectWithoutUserByJni() { - try { - DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?"); - } catch (SQLException e) { - Assert.assertEquals(TSDBErrorNumbers.ERROR_USER_IS_REQUIRED, e.getErrorCode()); - Assert.assertEquals("ERROR (2319): user is required", e.getMessage()); - } - } - - @Test - public void connectWithoutUserByRestful() { - try { - DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?"); - } catch (SQLException e) { - Assert.assertEquals(TSDBErrorNumbers.ERROR_USER_IS_REQUIRED, e.getErrorCode()); - Assert.assertEquals("ERROR (2319): user is required", e.getMessage()); - } - } - - @Test - public void connectWithoutPasswordByJni() { - try { - DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?user=root"); - } catch (SQLException e) { - Assert.assertEquals(TSDBErrorNumbers.ERROR_PASSWORD_IS_REQUIRED, e.getErrorCode()); - Assert.assertEquals("ERROR (231a): password is required", e.getMessage()); - } - } - - @Test - public void connectWithoutPasswordByRestful() { - try { - DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root"); - } catch (SQLException e) { - Assert.assertEquals(TSDBErrorNumbers.ERROR_PASSWORD_IS_REQUIRED, e.getErrorCode()); - Assert.assertEquals("ERROR (231a): password is required", e.getMessage()); - } - } - - @Ignore - @Test - public void test() throws SQLException { - // change password - conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=" + user + "&password=taosdata"); - Statement stmt = conn.createStatement(); - stmt.execute("alter user " + user + " pass '" + password + "'"); - stmt.close(); - conn.close(); - - // use new to login and execute query - conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=" + user + "&password=" + password); - stmt = conn.createStatement(); - stmt.execute("show databases"); - ResultSet rs = stmt.getResultSet(); - ResultSetMetaData meta = rs.getMetaData(); - while (rs.next()) { - for (int i = 1; i <= meta.getColumnCount(); i++) { - System.out.print(meta.getColumnLabel(i) + ":" + rs.getString(i) + "\t"); - } - System.out.println(); - } - - // change password back - conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=" + user + "&password=" + password); - stmt = conn.createStatement(); - stmt.execute("alter user " + user + " pass 'taosdata'"); - stmt.close(); - conn.close(); - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/BatchErrorIgnoreTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/BatchErrorIgnoreTest.java deleted file mode 100644 index 548c1cff24..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/BatchErrorIgnoreTest.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.*; - -import java.sql.*; -import java.util.stream.IntStream; - -public class BatchErrorIgnoreTest { - - private static final String host = "127.0.0.1"; - - @Test - public void batchErrorThrowException() throws SQLException { - // given - Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); - - // when - try (Statement stmt = conn.createStatement()) { - IntStream.range(1, 6).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + ")").forEach(sql -> { - try { - stmt.addBatch(sql); - } catch (SQLException ignored) { - } - }); - stmt.addBatch("insert into t11 values(now, 11)"); - IntStream.range(6, 11).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + "),(now + 1s, " + (10 * i) + ")").forEach(sql -> { - try { - stmt.addBatch(sql); - } catch (SQLException ignored) { - } - }); - stmt.addBatch("select count(*) from test.weather"); - - stmt.executeBatch(); - } catch (BatchUpdateException e) { - int[] updateCounts = e.getUpdateCounts(); - Assert.assertEquals(5, updateCounts.length); - Assert.assertEquals(1, updateCounts[0]); - Assert.assertEquals(1, updateCounts[1]); - Assert.assertEquals(1, updateCounts[2]); - Assert.assertEquals(1, updateCounts[3]); - Assert.assertEquals(1, updateCounts[4]); - } - - } - - @Test - public void batchErrorIgnore() throws SQLException { - // given - Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata&batchErrorIgnore=true"); - - // when - int[] results = null; - try (Statement stmt = conn.createStatement()) { - IntStream.range(1, 6).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + ")").forEach(sql -> { - try { - stmt.addBatch(sql); - } catch (SQLException ignored) { - } - }); - stmt.addBatch("insert into t11 values(now, 11)"); - IntStream.range(6, 11).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + "),(now + 1s, " + (10 * i) + ")").forEach(sql -> { - try { - stmt.addBatch(sql); - } catch (SQLException ignored) { - } - }); - stmt.addBatch("select count(*) from test.weather"); - - results = stmt.executeBatch(); - } - - // then - assert results != null; - Assert.assertEquals(12, results.length); - Assert.assertEquals(1, results[0]); - Assert.assertEquals(1, results[1]); - Assert.assertEquals(1, results[2]); - Assert.assertEquals(1, results[3]); - Assert.assertEquals(1, results[4]); - Assert.assertEquals(Statement.EXECUTE_FAILED, results[5]); - Assert.assertEquals(2, results[6]); - Assert.assertEquals(2, results[7]); - Assert.assertEquals(2, results[8]); - Assert.assertEquals(2, results[9]); - Assert.assertEquals(2, results[10]); - Assert.assertEquals(Statement.SUCCESS_NO_INFO, results[11]); - } - - @Before - public void before() throws SQLException { - try (Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); - Statement stmt = conn.createStatement();) { - - stmt.execute("use test"); - stmt.execute("drop table if exists weather"); - stmt.execute("create table weather (ts timestamp, f1 float) tags(t1 int)"); - IntStream.range(1, 11).mapToObj(i -> "create table t" + i + " using weather tags(" + i + ")").forEach(sql -> { - try { - stmt.execute(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - }); - } - } - - @BeforeClass - public static void beforeClass() throws SQLException { - try (Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); - Statement stmt = conn.createStatement()) { - - stmt.execute("drop database if exists test"); - stmt.execute("create database if not exists test"); - } - } - - @AfterClass - public static void afterClass() throws SQLException { - try (Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); - Statement stmt = conn.createStatement()) { - - stmt.execute("drop database if exists test"); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/BatchInsertTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/BatchInsertTest.java deleted file mode 100644 index f2b102cfe7..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/BatchInsertTest.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.taosdata.jdbc.cases; - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; -import java.util.Random; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import static org.junit.Assert.assertEquals; - -public class BatchInsertTest { - - static String host = "127.0.0.1"; - static String dbName = "test"; - static String stbName = "meters"; - static int numOfTables = 30; - final static int numOfRecordsPerTable = 1000; - static long ts = 1496732686000l; - final static String tablePrefix = "t"; - private Connection connection; - - @Before - public void before() { - try { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties); - - Statement statement = connection.createStatement(); - statement.executeUpdate("drop database if exists " + dbName); - statement.executeUpdate("create database if not exists " + dbName); - statement.executeUpdate("use " + dbName); - // create stable - String createTableSql = "create table " + stbName + "(ts timestamp, f1 int, f2 int, f3 int) tags(areaid int, loc binary(20))"; - statement.executeUpdate(createTableSql); - // create tables - for (int i = 0; i < numOfTables; i++) { - String loc = i % 2 == 0 ? "beijing" : "shanghai"; - String createSubTalbesSql = "create table " + tablePrefix + i + " using " + stbName + " tags(" + i + ", '" + loc + "')"; - statement.executeUpdate(createSubTalbesSql); - } - statement.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testBatchInsert() { - ExecutorService executorService = Executors.newFixedThreadPool(numOfTables); - for (int i = 0; i < numOfTables; i++) { - final int index = i; - executorService.execute(() -> { - try { - Statement statement = connection.createStatement(); // get statement - StringBuilder sb = new StringBuilder(); - sb.append("INSERT INTO " + tablePrefix + index + " VALUES"); - Random rand = new Random(); - for (int j = 1; j <= numOfRecordsPerTable; j++) { - sb.append("(" + (ts + j) + ", "); - sb.append(rand.nextInt(100) + ", "); - sb.append(rand.nextInt(100) + ", "); - sb.append(rand.nextInt(100) + ")"); - } - statement.addBatch(sb.toString()); - statement.executeBatch(); - connection.commit(); - statement.close(); - } catch (Exception e) { - e.printStackTrace(); - } - }); - } - - executorService.shutdown(); - try { - executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - try { - Statement statement = connection.createStatement(); - ResultSet rs = statement.executeQuery("select * from meters"); - int num = 0; - while (rs.next()) { - num++; - } - assertEquals(num, numOfTables * numOfRecordsPerTable); - rs.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @After - public void after() { - try { - if (connection != null) - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ConnectMultiTaosdByRestfulWithDifferentTokenTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ConnectMultiTaosdByRestfulWithDifferentTokenTest.java deleted file mode 100644 index 8299cfebec..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ConnectMultiTaosdByRestfulWithDifferentTokenTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.taosdata.jdbc.cases; - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; - -public class ConnectMultiTaosdByRestfulWithDifferentTokenTest { - - private static final String host1 = "192.168.17.156"; - private static final String user1 = "root"; - private static final String password1 = "tqueue"; - private Connection conn1; - private static final String host2 = "192.168.17.82"; - private static final String user2 = "root"; - private static final String password2 = "taosdata"; - private Connection conn2; - - @Test - public void test() throws SQLException { - //when - executeSelectStatus(conn1); - executeSelectStatus(conn2); - executeSelectStatus(conn1); - } - - private void executeSelectStatus(Connection connection) throws SQLException { - try (Statement stmt = connection.createStatement()) { - ResultSet rs = stmt.executeQuery("select server_status()"); - ResultSetMetaData meta = rs.getMetaData(); - Assert.assertNotNull(meta); - while (rs.next()) { - } - } - } - - @Before - public void before() { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - - String url1 = "jdbc:TAOS-RS://" + host1 + ":6041/?user=" + user1 + "&password=" + password1; - String url2 = "jdbc:TAOS-RS://" + host2 + ":6041/?user=" + user2 + "&password=" + password2; - try { - conn1 = DriverManager.getConnection(url1, properties); - conn2 = DriverManager.getConnection(url2, properties); - } catch (SQLException e) { - e.printStackTrace(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ConnectWrongDatabaseTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ConnectWrongDatabaseTest.java deleted file mode 100644 index 5f821c5cc3..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ConnectWrongDatabaseTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.Test; - -import java.sql.DriverManager; -import java.sql.SQLException; - -public class ConnectWrongDatabaseTest { - - @Test(expected = SQLException.class) - public void connectByJni() throws SQLException { - DriverManager.getConnection("jdbc:TAOS://localhost:6030/wrong_db?user=root&password=taosdata"); - } - - @Test(expected = SQLException.class) - public void connectByRestful() throws SQLException { - DriverManager.getConnection("jdbc:TAOS-RS://localhost:6041/wrong_db?user=root&password=taosdata"); - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DatetimeBefore1970Test.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DatetimeBefore1970Test.java deleted file mode 100644 index 4f7f123f5c..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DatetimeBefore1970Test.java +++ /dev/null @@ -1,259 +0,0 @@ -package com.taosdata.jdbc.cases; - -import com.taosdata.jdbc.annotation.CatalogRunner; -import com.taosdata.jdbc.annotation.Description; -import com.taosdata.jdbc.annotation.TestTarget; -import com.taosdata.jdbc.utils.TimestampUtil; -import org.junit.*; -import org.junit.runner.RunWith; - -import java.sql.*; - -@RunWith(CatalogRunner.class) -@TestTarget(alias = "negative value convert to timestamp", author = "huolibo", version = "2.0.37") -public class DatetimeBefore1970Test { - - private static final String host = "127.0.0.1"; - private Connection conn; - - @Test - @Description("millisecond") - public void msTest() throws SQLException { - conn = createEnvironment("ms"); - long now = System.currentTimeMillis(); - try (Statement stmt = conn.createStatement()) { - // given - // before - stmt.executeUpdate("insert into weather(ts) values('1969-12-31 00:00:00.001')"); - stmt.executeUpdate("insert into weather(ts) values('1969-12-31 23:59:59.999')"); - // zero - stmt.executeUpdate("insert into weather(ts) values('1970-01-01 00:00:00.000')"); - //after - stmt.executeUpdate("insert into weather(ts) values('1970-01-01 00:00:00.001')"); - stmt.executeUpdate("insert into weather(ts) values(" + now + ")"); - ResultSet rs = stmt.executeQuery("select * from weather order by ts asc"); - ResultSetMetaData metaData = rs.getMetaData(); - Assert.assertEquals(2, metaData.getColumnCount()); - - // when - rs.next(); - // then - Timestamp ts = rs.getTimestamp("ts"); - Assert.assertEquals(-24 * 60 * 60 * 1000 + 1, ts.getTime()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - Assert.assertEquals(-1, ts.getTime()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - Assert.assertEquals(0, ts.getTime()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - Assert.assertEquals(1, ts.getTime()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - Assert.assertEquals(now, ts.getTime()); - } - } - - @Test - @Description("microsecond") - public void usTest() throws SQLException { - conn = createEnvironment("us"); - long now = System.currentTimeMillis(); - try (Statement stmt = conn.createStatement()) { - // given - stmt.executeUpdate("insert into weather(ts) values('1969-12-31 00:00:00.000001')"); - stmt.executeUpdate("insert into weather(ts) values('1969-12-31 23:59:59.999999')"); - stmt.executeUpdate("insert into weather(ts) values('1970-01-01 00:00:00.000000')"); - stmt.executeUpdate("insert into weather(ts) values('1970-01-01 00:00:00.000001')"); - stmt.executeUpdate("insert into weather(ts) values(" + now + ")"); - ResultSet rs = stmt.executeQuery("select * from weather order by ts asc"); - ResultSetMetaData metaData = rs.getMetaData(); - Assert.assertEquals(2, metaData.getColumnCount()); - - // when - rs.next(); - // then - Timestamp ts = rs.getTimestamp("ts"); - Assert.assertEquals(-24 * 60 * 60 * 1000, ts.getTime()); - Assert.assertEquals(1_000, ts.getNanos()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - Assert.assertEquals(-1, ts.getTime()); - Assert.assertEquals(999_999_000, ts.getNanos()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - Assert.assertEquals(0, ts.getTime()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - Assert.assertEquals(0, ts.getTime()); - Assert.assertEquals(1_000, ts.getNanos()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - String s = String.valueOf(now); - Assert.assertEquals(Long.parseLong(s.substring(0, s.length() - 3)), ts.getTime()); - Assert.assertEquals(Long.parseLong(s.substring(s.length() - 6) + "000"), ts.getNanos()); - } - } - - @Test - @Description("nanosecond") - public void nanoTest() throws SQLException { - conn = createEnvironment("ns"); - long now = System.currentTimeMillis() * 1000_000L + System.nanoTime() % 1000_000L; - try (Statement stmt = conn.createStatement()) { - // given - stmt.executeUpdate("insert into weather(ts) values('1969-12-31 00:00:00.000000123')"); - stmt.executeUpdate("insert into weather(ts) values('1969-12-31 23:59:59.999999999')"); - stmt.executeUpdate("insert into weather(ts) values('1970-01-01 00:00:00.000')"); - stmt.executeUpdate("insert into weather(ts) values('1970-01-01 00:00:00.000000001')"); - stmt.executeUpdate("insert into weather(ts) values(" + now + ")"); - ResultSet rs = stmt.executeQuery("select * from weather order by ts asc"); - ResultSetMetaData metaData = rs.getMetaData(); - Assert.assertEquals(2, metaData.getColumnCount()); - - // when - rs.next(); - // then - Timestamp ts = rs.getTimestamp("ts"); - Assert.assertEquals(-24 * 60 * 60 * 1_000, ts.getTime()); - Assert.assertEquals(123, ts.getNanos()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - Assert.assertEquals(-1, ts.getTime()); - Assert.assertEquals(999999999, ts.getNanos()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - Assert.assertEquals(0, ts.getNanos()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - Assert.assertEquals(1, ts.getNanos()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - String s = String.valueOf(now); - Assert.assertEquals(Long.parseLong(s.substring(0, s.length() - 6)), ts.getTime()); - Assert.assertEquals(Long.parseLong(s.substring(s.length() - 9)), ts.getNanos()); - } - } - - @Test - @Ignore - @Description("nanosecond convert timestamp when timezone is asia shanghai") - public void asiaShanghaiTest() throws SQLException { - conn = createEnvironment("ns"); - long now = System.currentTimeMillis() * 1000_000L + System.nanoTime() % 1000_000L; - try (Statement stmt = conn.createStatement()) { - // given - stmt.executeUpdate("insert into weather(ts) values('1969-12-31 00:00:00.000000123')"); - stmt.executeUpdate("insert into weather(ts) values('1969-12-31 23:59:59.999999999')"); - stmt.executeUpdate("insert into weather(ts) values('1970-01-01 00:00:00.000')"); - stmt.executeUpdate("insert into weather(ts) values('1970-01-01 00:00:00.000000001')"); - stmt.executeUpdate("insert into weather(ts) values(" + now + ")"); - ResultSet rs = stmt.executeQuery("select * from weather order by ts asc"); - ResultSetMetaData metaData = rs.getMetaData(); - Assert.assertEquals(2, metaData.getColumnCount()); - - // when - rs.next(); - // then - Timestamp ts = rs.getTimestamp("ts"); - Assert.assertEquals("1969-12-31 08:00:00.000", TimestampUtil.longToDatetime(ts.getTime())); - Assert.assertEquals(123, ts.getNanos()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - Assert.assertEquals("1970-01-01 07:59:59.999", TimestampUtil.longToDatetime(ts.getTime())); - Assert.assertEquals(999999999, ts.getNanos()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - Assert.assertEquals("1970-01-01 08:00:00.000", TimestampUtil.longToDatetime(ts.getTime())); - Assert.assertEquals(0, ts.getNanos()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - Assert.assertEquals("1970-01-01 08:00:00.000", TimestampUtil.longToDatetime(ts.getTime())); - Assert.assertEquals(1, ts.getNanos()); - - // when - rs.next(); - // then - ts = rs.getTimestamp("ts"); - String s = String.valueOf(now); - Assert.assertEquals(Long.parseLong(s.substring(0, s.length() - 6)), ts.getTime()); - Assert.assertEquals(Long.parseLong(s.substring(s.length() - 9)), ts.getNanos()); - } - } - - private Connection createEnvironment(String precision) throws SQLException { - String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata&timezone=UTC"; - String createSql = "create database if not exists test_timestamp keep 36500"; - if (!isEmpty(precision)) { - createSql += " precision '" + precision + "'"; - } - conn = DriverManager.getConnection(url); - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists test_timestamp"); - stmt.execute(createSql); - stmt.execute("use test_timestamp"); - stmt.execute("create table weather(ts timestamp,f1 float)"); - stmt.close(); - return conn; - } - - private boolean isEmpty(String string) { - return null == string || string.trim().equals(""); - } - - @After - public void after() throws SQLException { - if (conn != null) { - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists test_timestamp"); - stmt.close(); - conn.close(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DoubleQuoteInSqlTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DoubleQuoteInSqlTest.java deleted file mode 100644 index 212a751ec3..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DoubleQuoteInSqlTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.taosdata.jdbc.cases; - -import com.alibaba.fastjson.JSONObject; -import com.taosdata.jdbc.TSDBDriver; -import org.junit.*; - -import java.sql.*; -import java.util.Properties; - -public class DoubleQuoteInSqlTest { - private static final String host = "127.0.0.1"; - private static final String dbname = "td4174"; - - private Connection conn; - - @Test - public void test() { - // given - long ts = System.currentTimeMillis(); - JSONObject value = new JSONObject(); - value.put("name", "John Smith"); - value.put("age", 20); - - // when - int ret = 0; - try (PreparedStatement pstmt = conn.prepareStatement("insert into weather values(" + ts + ", ?)")) { - pstmt.setString(1, value.toJSONString()); - ret = pstmt.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - - // then - Assert.assertEquals("{\"name\":\"John Smith\",\"age\":20}", value.toJSONString()); - Assert.assertEquals(1, ret); - } - - @Before - public void before() { - String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - - try { - conn = DriverManager.getConnection(url, properties); - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather(ts timestamp, text binary(64))"); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @After - public void after() { - try { - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DriverAutoloadTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DriverAutoloadTest.java deleted file mode 100644 index a00c8f4f97..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DriverAutoloadTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.taosdata.jdbc.cases; - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.Properties; - -public class DriverAutoloadTest { - - private Properties properties; - private final String host = "127.0.0.1"; - - @Test - public void testRestful() throws SQLException { - final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - Connection conn = DriverManager.getConnection(url, properties); - Assert.assertNotNull(conn); - conn.close(); - } - - @Test - public void testJni() throws SQLException { - final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - Connection conn = DriverManager.getConnection(url, properties); - Assert.assertNotNull(conn); - conn.close(); - } - - - @Before - public void before() { - properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/FailOverTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/FailOverTest.java deleted file mode 100644 index be2ff94e02..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/FailOverTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.Test; - -import java.sql.*; -import java.text.SimpleDateFormat; -import java.util.concurrent.TimeUnit; - -public class FailOverTest { - - private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); - - @Test - public void testFailOver() throws ClassNotFoundException { - Class.forName("com.taosdata.jdbc.TSDBDriver"); - final String url = "jdbc:TAOS://:/?user=root&password=taosdata"; - - long end = System.currentTimeMillis() + 1000 * 60 * 5; - while (System.currentTimeMillis() < end) { - try (Connection conn = DriverManager.getConnection(url); Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("show dnodes"); - ResultSetMetaData meta = rs.getMetaData(); - while (rs.next()) { - for (int i = 1; i <= meta.getColumnCount(); i++) { - System.out.print(meta.getColumnLabel(i) + ": " + rs.getString(i) + "\t"); - } - System.out.println(); - } - System.out.println("======================="); - rs.close(); - TimeUnit.SECONDS.sleep(5); - } catch (SQLException | InterruptedException e) { - e.printStackTrace(); - } - } - - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/GetLongWithDifferentTimestampPrecision.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/GetLongWithDifferentTimestampPrecision.java deleted file mode 100644 index 1ba7bdc405..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/GetLongWithDifferentTimestampPrecision.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.Assert; -import org.junit.Test; - -import java.sql.*; -import java.text.SimpleDateFormat; - -public class GetLongWithDifferentTimestampPrecision { - - private final String host = "127.0.0.1"; - - @Test - public void testRestful() throws SQLException { - // given - String url = "jdbc:TAOS-RS://" + host + ":6041/"; - Connection conn = DriverManager.getConnection(url, "root", "taosdata"); - long ts = System.currentTimeMillis(); - - // when and then - assertResultSet(conn, "ms", ts, ts); - assertResultSet(conn, "us", ts, ts * 1000); - assertResultSet(conn, "ns", ts, ts * 1000_000); - } - - @Test - public void testJni() throws SQLException { - // given - String url = "jdbc:TAOS://" + host + ":6030/"; - Connection conn = DriverManager.getConnection(url, "root", "taosdata"); - long ts = System.currentTimeMillis(); - - // when and then - assertResultSet(conn, "ms", ts, ts); - assertResultSet(conn, "us", ts, ts * 1000); - assertResultSet(conn, "ns", ts, ts * 1000_000); - } - - private void assertResultSet(Connection conn, String precision, long timestamp, long expect) throws SQLException { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists test"); - stmt.execute("create database if not exists test precision '" + precision + "'"); - stmt.execute("create table test.weather(ts timestamp, f1 int)"); - - String dateTimeStr = sdf.format(new Date(timestamp)); - stmt.execute("insert into test.weather values('" + dateTimeStr + "', 1)"); - - ResultSet rs = stmt.executeQuery("select * from test.weather"); - rs.next(); - long actual = rs.getLong("ts"); - Assert.assertEquals(expect, actual); - stmt.execute("drop database if exists test"); - } - } - - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ImportTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ImportTest.java deleted file mode 100644 index a8fdf4f2ca..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ImportTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.taosdata.jdbc.cases; - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.*; -import org.junit.runners.MethodSorters; - -import java.sql.*; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class ImportTest { - private static Connection connection; - static String dbName = "test_import"; - static String tName = "t0"; - static String host = "127.0.0.1"; - private static long ts; - - @Test - public void case001_insertData() throws Exception { - try (Statement stmt = connection.createStatement()) { - for (int i = 0; i < 50; i++) { - ts++; - int row = stmt.executeUpdate("import into " + dbName + "." + tName + " values (" + ts + ", " + (100 + i) + ", " + i + ")"); - assertEquals(1, row); - } - } - } - - @Test - public void case002_checkSum() throws SQLException { - Assert.assertEquals(50, select()); - } - - private int select() throws SQLException { - int count = 0; - try (Statement stmt = connection.createStatement()) { - String sql = "select * from " + dbName + "." + tName; - ResultSet rs = stmt.executeQuery(sql); - while (rs.next()) { - count++; - } - rs.close(); - } - return count; - } - - @Test - public void case003_importData() throws SQLException { - // 避免时间重复 - try (Statement stmt = connection.createStatement()) { - StringBuilder sqlBuilder = new StringBuilder("import into ").append(dbName).append(".").append(tName).append(" values "); - for (int i = 0; i < 50; i++) { - int a = i / 5; - long t = (++ts) + a; - sqlBuilder.append("(").append(t).append(",").append((100 + i)).append(",").append(i).append(") "); - } - int rows = stmt.executeUpdate(sqlBuilder.toString()); - assertEquals(50, rows); - } - } - - @Test - public void case004_checkSum() throws SQLException { - Assert.assertEquals(100, select()); - } - - - @BeforeClass - public static void before() throws SQLException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties); - - Statement stmt = connection.createStatement(); - stmt.execute("create database if not exists " + dbName); - stmt.execute("create table if not exists " + dbName + "." + tName + " (ts timestamp, k int, v int)"); - stmt.close(); - - ts = System.currentTimeMillis(); - } - - @AfterClass - public static void close() throws SQLException { - if (connection != null) { - Statement statement = connection.createStatement(); - statement.executeUpdate("drop database " + dbName); - statement.close(); - connection.close(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertDbwithoutUseDbTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertDbwithoutUseDbTest.java deleted file mode 100644 index 60edcc506e..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertDbwithoutUseDbTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.*; -import org.junit.runners.MethodSorters; - -import java.sql.*; -import java.util.Properties; -import java.util.Random; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class InsertDbwithoutUseDbTest { - - private static final String host = "127.0.0.1"; - private static Properties properties; - private static final Random random = new Random(System.currentTimeMillis()); - private static final String dbname = "inWithoutDb"; - - @Test - public void case001() throws SQLException { - // prepare schema - String url = "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata"; - Connection conn = DriverManager.getConnection(url, properties); - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("create table " + dbname + ".weather(ts timestamp, f1 int)"); - - conn.close(); - - // execute insert - url = "jdbc:TAOS://127.0.0.1:6030/" + dbname + "?user=root&password=taosdata"; - conn = DriverManager.getConnection(url, properties); - stmt = conn.createStatement(); - int affectedRow = stmt.executeUpdate("insert into weather(ts, f1) values(now," + random.nextInt(100) + ")"); - Assert.assertEquals(1, affectedRow); - boolean flag = stmt.execute("insert into weather(ts, f1) values(now + 10s," + random.nextInt(100) + ")"); - Assert.assertEquals(false, flag); - ResultSet rs = stmt.executeQuery("select count(*) from weather"); - rs.next(); - int count = rs.getInt("count(*)"); - Assert.assertEquals(2, count); - conn.close(); - } - - @Test - public void case002() throws SQLException { - // prepare the schema - final String url = "jdbc:TAOS-RS://" + host + ":6041/inWithoutDb?user=root&password=taosdata"; - Connection conn = DriverManager.getConnection(url, properties); - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("create table " + dbname + ".weather(ts timestamp, f1 int)"); - stmt.close(); - - // execute - stmt = conn.createStatement(); - int affectedRow = stmt.executeUpdate("insert into weather(ts, f1) values(now," + random.nextInt(100) + ")"); - Assert.assertEquals(1, affectedRow); - boolean flag = stmt.execute("insert into weather(ts, f1) values(now + 10s," + random.nextInt(100) + ")"); - Assert.assertEquals(false, flag); - ResultSet rs = stmt.executeQuery("select count(*) from weather"); - rs.next(); - int count = rs.getInt("count(*)"); - Assert.assertEquals(2, count); - stmt.execute("drop database if exists " + dbname); - stmt.close(); - conn.close(); - } - - @BeforeClass - public static void beforeClass() { - properties = new Properties(); - properties.setProperty("charset", "UTF-8"); - properties.setProperty("locale", "en_US.UTF-8"); - properties.setProperty("timezone", "UTC-8"); - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertSpecialCharacterJniTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertSpecialCharacterJniTest.java deleted file mode 100644 index 7cc1c811d1..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertSpecialCharacterJniTest.java +++ /dev/null @@ -1,438 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.*; - -import java.sql.*; - -public class InsertSpecialCharacterJniTest { - - private static final String host = "127.0.0.1"; - private static Connection conn; - private static final String dbName = "spec_char_test"; - private static final String tbname1 = "test"; - private static final String tbname2 = "weather"; - private static final String special_character_str_1 = "$asd$$fsfsf$"; - private static final String special_character_str_2 = "\\\\asdfsfsf\\\\"; - private static final String special_character_str_3 = "\\\\asdfsfsf\\"; - private static final String special_character_str_4 = "?asd??fsf?sf?"; - private static final String special_character_str_5 = "?#sd@$f(('<(s[P)>\"){]}f?s[]{}%vaew|\"fsfs^a&d*jhg)(j))(f@~!?$"; - - @Test - public void testCase01() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, new Timestamp(now)); - pstmt.setBytes(2, special_character_str_1.getBytes()); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query - final String query = "select * from ?"; - try (PreparedStatement pstmt = conn.prepareStatement(query)) { - pstmt.setString(1, tbname1); - - ResultSet rs = pstmt.executeQuery(); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_1, f1); - String f2 = rs.getString(3); - Assert.assertNull(f2); - } - } - - - @Test - public void testCase02() throws SQLException { - //TODO: - // Expected :\asdfsfsf\\ - // Actual :\asdfsfsf\ - - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, new Timestamp(now)); - pstmt.setBytes(2, special_character_str_2.getBytes()); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query - final String query = "select * from " + tbname1; - try (PreparedStatement pstmt = conn.prepareStatement(query)) { - ResultSet rs = pstmt.executeQuery(); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - //TODO: bug to be fixed -// Assert.assertEquals(special_character_str_2, f1); - Assert.assertEquals(special_character_str_2.substring(1, special_character_str_1.length() - 1), f1); - String f2 = rs.getString(3); - Assert.assertNull(f2); - } - } - - @Test(expected = SQLException.class) - public void testCase03() throws SQLException { - //TODO: - // TDengine ERROR (216): Syntax error in SQL - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, new Timestamp(now)); - pstmt.setBytes(2, special_character_str_3.getBytes()); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query - final String query = "select * from " + tbname1; - try (PreparedStatement pstmt = conn.prepareStatement(query)) { - ResultSet rs = pstmt.executeQuery(); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_3, f1); - String f2 = rs.getString(3); - Assert.assertNull(f2); - } - } - - @Test - public void testCase04() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, new Timestamp(now)); - pstmt.setBytes(2, special_character_str_4.getBytes()); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query - final String query = "select * from " + tbname1; - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery(query); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_4, f1); - String f2 = rs.getString(3); - Assert.assertNull(f2); - } - } - - @Test - public void testCase05() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, new Timestamp(now)); - pstmt.setBytes(2, special_character_str_5.getBytes()); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query - final String query = "select * from " + tbname1; - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery(query); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_5, f1); - String f2 = rs.getString(3); - Assert.assertNull(f2); - } - } - - @Test - public void testCase06() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into t? using " + tbname2 + " tags(?) values(?, ?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setInt(1, 1); - pstmt.setString(2, special_character_str_4); - pstmt.setTimestamp(3, new Timestamp(now)); - pstmt.setBytes(4, special_character_str_4.getBytes()); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query t1 - final String query = "select * from t1"; - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery(query); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_4, f1); - String f2 = rs.getString(3); - Assert.assertNull(f2); - } - } - - @Test - public void testCase07() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into " + tbname1 + "(ts, f1, f2) values(?, ?, ?) ; "; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, new Timestamp(now)); - pstmt.setBytes(2, special_character_str_4.getBytes()); - pstmt.setString(3, special_character_str_4); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query - final String query = "select * from " + tbname1; - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery(query); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_4, f1); - String f2 = rs.getString(3); - Assert.assertEquals(special_character_str_4, f2); - } - } - - @Test(expected = SQLException.class) - public void testCase08() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into t? using " + tbname2 + " tags(?) values(?, ?, ?) ? "; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setInt(1, 1); - pstmt.setString(2, special_character_str_5); - pstmt.setTimestamp(3, new Timestamp(now)); - pstmt.setBytes(4, special_character_str_5.getBytes()); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - } - - @Test - public void testCase09() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into ?.t? using " + tbname2 + " tags(?) values(?, ?, ?) t? using weather tags(?) values(?,?,?) "; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - // t1 - pstmt.setString(1, dbName); - pstmt.setInt(2, 1); - pstmt.setString(3, special_character_str_5); - pstmt.setTimestamp(4, new Timestamp(now)); - pstmt.setBytes(5, special_character_str_5.getBytes()); - // t2 - pstmt.setInt(7, 2); - pstmt.setString(8, special_character_str_5); - pstmt.setTimestamp(9, new Timestamp(now)); - pstmt.setString(11, special_character_str_5); - - int ret = pstmt.executeUpdate(); - Assert.assertEquals(2, ret); - } - // query t1 - String query = "select * from t?"; - try (PreparedStatement pstmt = conn.prepareStatement(query)) { - pstmt.setInt(1, 1); - - ResultSet rs = pstmt.executeQuery(); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_5, f1); - String f2 = rs.getString(3); - Assert.assertNull(f2); - } - // query t2 - query = "select * from t2"; - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery(query); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - byte[] f1 = rs.getBytes(2); - Assert.assertNull(f1); - String f2 = new String(rs.getBytes(3)); - Assert.assertEquals(special_character_str_5, f2); - } - } - - @Ignore - @Test - public void testSingleQuotaEscape() throws SQLException { - final long now = System.currentTimeMillis(); - final String sql = "insert into t? using ? tags(?) values(?, ?, ?) t? using " + tbname2 + " tags(?) values(?,?,?) "; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - // t1 - pstmt.setInt(1, 1); - pstmt.setString(2, tbname2); - pstmt.setString(3, special_character_str_5); - pstmt.setTimestamp(4, new Timestamp(now)); - pstmt.setBytes(5, special_character_str_5.getBytes()); - // t2 - pstmt.setInt(7, 2); - pstmt.setString(8, special_character_str_5); - pstmt.setTimestamp(9, new Timestamp(now)); - pstmt.setString(11, special_character_str_5); - - int ret = pstmt.executeUpdate(); - Assert.assertEquals(2, ret); - } - - String query = "select * from ?.t? where ? < ? and ts >= ? and f1 is not null"; - try (PreparedStatement pstmt = conn.prepareStatement(query)) { - pstmt.setString(1, dbName); - pstmt.setInt(2, 1); - pstmt.setString(3, "ts"); - pstmt.setTimestamp(4, new Timestamp(System.currentTimeMillis())); - pstmt.setTimestamp(5, new Timestamp(0)); - - ResultSet rs = pstmt.executeQuery(); - Assert.assertNotNull(rs); - } - } - - @Test - public void testCase10() throws SQLException { - final long now = System.currentTimeMillis(); - - // insert - final String sql = "insert into t? using ? tags(?) values(?, ?, ?) t? using " + tbname2 + " tags(?) values(?,?,?) "; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - // t1 - pstmt.setInt(1, 1); - pstmt.setString(2, tbname2); - pstmt.setString(3, special_character_str_5); - pstmt.setTimestamp(4, new Timestamp(now)); - pstmt.setBytes(5, special_character_str_5.getBytes()); - // t2 - pstmt.setInt(7, 2); - pstmt.setString(8, special_character_str_5); - pstmt.setTimestamp(9, new Timestamp(now)); - pstmt.setString(11, special_character_str_5); - - int ret = pstmt.executeUpdate(); - Assert.assertEquals(2, ret); - } - //query t1 - String query = "select * from ?.t? where ts < ? and ts >= ? and f1 is not null"; - try (PreparedStatement pstmt = conn.prepareStatement(query)) { - pstmt.setString(1, dbName); - pstmt.setInt(2, 1); - pstmt.setTimestamp(3, new Timestamp(System.currentTimeMillis())); - pstmt.setTimestamp(4, new Timestamp(0)); - - ResultSet rs = pstmt.executeQuery(); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_5, f1); - byte[] f2 = rs.getBytes(3); - Assert.assertNull(f2); - } - // query t2 - query = "select * from t? where ts < ? and ts >= ? and f2 is not null"; - try (PreparedStatement pstmt = conn.prepareStatement(query)) { - pstmt.setInt(1, 2); - pstmt.setTimestamp(2, new Timestamp(System.currentTimeMillis())); - pstmt.setTimestamp(3, new Timestamp(0)); - - ResultSet rs = pstmt.executeQuery(); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - byte[] f1 = rs.getBytes(2); - Assert.assertNull(f1); - String f2 = new String(rs.getBytes(3)); - Assert.assertEquals(special_character_str_5, f2); - } - } - - @Test(expected = SQLException.class) - public void testCase11() throws SQLException { - final String speicalCharacterStr = "?#sd@$f(((s[P)){]}f?s[]{}%vs^a&d*jhg)(j))(f@~!?$"; - final long now = System.currentTimeMillis(); - - final String sql = "insert into t? using " + tbname2 + " values(?, ?, 'abc?abc') "; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setInt(1, 1); - pstmt.setTimestamp(2, new Timestamp(now)); - pstmt.setBytes(3, speicalCharacterStr.getBytes()); - - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - } - - - @Test - public void testCase12() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into " + tbname1 + "(ts, f1, f2) values(?, 'HelloTDengine', ?) ; "; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, new Timestamp(now)); - pstmt.setString(2, special_character_str_4); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query - final String query = "select * from " + tbname1; - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery(query); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals("HelloTDengine", f1); - String f2 = rs.getString(3); - Assert.assertEquals(special_character_str_4, f2); - } - } - - @Before - public void before() throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop table if exists " + tbname1 + ""); - stmt.execute("create table " + tbname1 + "(ts timestamp,f1 binary(64),f2 nchar(64))"); - stmt.execute("drop table if exists " + tbname2); - stmt.execute("create table " + tbname2 + "(ts timestamp, f1 binary(64), f2 nchar(64)) tags(loc nchar(64))"); - } - } - - @BeforeClass - public static void beforeClass() throws SQLException { - String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - conn = DriverManager.getConnection(url); - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists " + dbName); - stmt.execute("create database if not exists " + dbName); - stmt.execute("use " + dbName); - } - } - - @AfterClass - public static void afterClass() throws SQLException { - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists " + dbName); - statement.close(); - conn.close(); - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertSpecialCharacterRestfulTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertSpecialCharacterRestfulTest.java deleted file mode 100644 index 81e424971c..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertSpecialCharacterRestfulTest.java +++ /dev/null @@ -1,402 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.*; - -import java.sql.*; - -public class InsertSpecialCharacterRestfulTest { - - private static final String host = "127.0.0.1"; - private static Connection conn; - private static final String dbName = "spec_char_test"; - private static final String tbname1 = "test"; - private static final String tbname2 = "weather"; - private static final String special_character_str_1 = "$asd$$fsfsf$"; - private static final String special_character_str_2 = "\\\\asdfsfsf\\\\"; - private static final String special_character_str_3 = "\\\\asdfsfsf\\"; - private static final String special_character_str_4 = "?asd??fsf?sf?"; - private static final String special_character_str_5 = "?#sd@$f(('<(s[P)>\"){]}f?s[]{}%vaew|\"fsfs^a&d*jhg)(j))(f@~!?$"; - - @Test - public void testCase01() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, new Timestamp(now)); - pstmt.setBytes(2, special_character_str_1.getBytes()); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query - final String query = "select * from ?"; - try (PreparedStatement pstmt = conn.prepareStatement(query)) { - pstmt.setString(1, tbname1); - - ResultSet rs = pstmt.executeQuery(); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_1, f1); - String f2 = rs.getString(3); - Assert.assertNull(f2); - } - } - - - @Test - public void testCase02() throws SQLException { - //TODO: - // Expected :\asdfsfsf\ - // Actual :\asdfsfsf\ - - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, new Timestamp(now)); - pstmt.setBytes(2, special_character_str_2.getBytes()); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query - final String query = "select * from " + tbname1; - try (PreparedStatement pstmt = conn.prepareStatement(query)) { - ResultSet rs = pstmt.executeQuery(); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - //TODO: bug to be fixed -// Assert.assertEquals(special_character_str_2, f1); - Assert.assertEquals(special_character_str_2.substring(1, special_character_str_1.length() - 1), f1); - String f2 = rs.getString(3); - Assert.assertNull(f2); - } - } - - @Test(expected = SQLException.class) - public void testCase03() throws SQLException { - //TODO: - // TDengine ERROR (216): Syntax error in SQL - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, new Timestamp(now)); - pstmt.setBytes(2, special_character_str_3.getBytes()); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query - final String query = "select * from " + tbname1; - try (PreparedStatement pstmt = conn.prepareStatement(query)) { - ResultSet rs = pstmt.executeQuery(); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_3, f1); - String f2 = rs.getString(3); - Assert.assertNull(f2); - } - } - - @Test - public void testCase04() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, new Timestamp(now)); - pstmt.setBytes(2, special_character_str_4.getBytes()); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query - final String query = "select * from " + tbname1; - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery(query); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_4, f1); - String f2 = rs.getString(3); - Assert.assertNull(f2); - } - } - - @Test - public void testCase05() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, new Timestamp(now)); - pstmt.setBytes(2, special_character_str_5.getBytes()); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query - final String query = "select * from " + tbname1; - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery(query); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_5, f1); - String f2 = rs.getString(3); - Assert.assertNull(f2); - } - } - - @Test - public void testCase06() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into t? using " + tbname2 + " tags(?) values(?, ?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setInt(1, 1); - pstmt.setString(2, special_character_str_4); - pstmt.setTimestamp(3, new Timestamp(now)); - pstmt.setBytes(4, special_character_str_4.getBytes()); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query t1 - final String query = "select * from t1"; - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery(query); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_4, f1); - String f2 = rs.getString(3); - Assert.assertNull(f2); - } - } - - @Test - public void testCase07() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into " + tbname1 + "(ts, f1, f2) values(?, ?, ?) ; "; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, new Timestamp(now)); - pstmt.setBytes(2, special_character_str_4.getBytes()); - pstmt.setString(3, special_character_str_4); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query - final String query = "select * from " + tbname1; - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery(query); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_4, f1); - String f2 = rs.getString(3); - Assert.assertEquals(special_character_str_4, f2); - } - } - - @Test(expected = SQLException.class) - public void testCase08() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into t? using " + tbname2 + " tags(?) values(?, ?, ?) ? "; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setInt(1, 1); - pstmt.setString(2, special_character_str_5); - pstmt.setTimestamp(3, new Timestamp(now)); - pstmt.setBytes(4, special_character_str_5.getBytes()); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - } - - @Test - public void testCase09() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into ?.t? using " + tbname2 + " tags(?) values(?, ?, ?) t? using weather tags(?) values(?,?,?) "; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - // t1 - pstmt.setString(1, dbName); - pstmt.setInt(2, 1); - pstmt.setString(3, special_character_str_5); - pstmt.setTimestamp(4, new Timestamp(now)); - pstmt.setBytes(5, special_character_str_5.getBytes()); - // t2 - pstmt.setInt(7, 2); - pstmt.setString(8, special_character_str_5); - pstmt.setTimestamp(9, new Timestamp(now)); - pstmt.setString(11, special_character_str_5); - - int ret = pstmt.executeUpdate(); - Assert.assertEquals(2, ret); - } - // query t1 - String query = "select * from t?"; - try (PreparedStatement pstmt = conn.prepareStatement(query)) { - pstmt.setInt(1, 1); - - ResultSet rs = pstmt.executeQuery(); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_5, f1); - String f2 = rs.getString(3); - Assert.assertNull(f2); - } - // query t2 - query = "select * from t2"; - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery(query); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - byte[] f1 = rs.getBytes(2); - Assert.assertNull(f1); - String f2 = new String(rs.getBytes(3)); - Assert.assertEquals(special_character_str_5, f2); - } - } - - @Test - public void testCase10() throws SQLException { - final long now = System.currentTimeMillis(); - - // insert - final String sql = "insert into t? using ? tags(?) values(?, ?, ?) t? using " + tbname2 + " tags(?) values(?,?,?) "; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - // t1 - pstmt.setInt(1, 1); - pstmt.setString(2, tbname2); - pstmt.setString(3, special_character_str_5); - pstmt.setTimestamp(4, new Timestamp(now)); - pstmt.setBytes(5, special_character_str_5.getBytes()); - // t2 - pstmt.setInt(7, 2); - pstmt.setString(8, special_character_str_5); - pstmt.setTimestamp(9, new Timestamp(now)); - pstmt.setString(11, special_character_str_5); - - int ret = pstmt.executeUpdate(); - Assert.assertEquals(2, ret); - } - //query t1 - String query = "select * from ?.t? where ts < ? and ts >= ? and f1 is not null"; - try (PreparedStatement pstmt = conn.prepareStatement(query)) { - pstmt.setString(1, dbName); - pstmt.setInt(2, 1); - pstmt.setTimestamp(3, new Timestamp(System.currentTimeMillis())); - pstmt.setTimestamp(4, new Timestamp(0)); - - ResultSet rs = pstmt.executeQuery(); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals(special_character_str_5, f1); - byte[] f2 = rs.getBytes(3); - Assert.assertNull(f2); - } - // query t2 - query = "select * from t? where ts < ? and ts >= ? and f2 is not null"; - try (PreparedStatement pstmt = conn.prepareStatement(query)) { - pstmt.setInt(1, 2); - pstmt.setTimestamp(2, new Timestamp(System.currentTimeMillis())); - pstmt.setTimestamp(3, new Timestamp(0)); - - ResultSet rs = pstmt.executeQuery(); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - byte[] f1 = rs.getBytes(2); - Assert.assertNull(f1); - String f2 = new String(rs.getBytes(3)); - Assert.assertEquals(special_character_str_5, f2); - } - } - - @Test(expected = SQLException.class) - public void testCase11() throws SQLException { - final String speicalCharacterStr = "?#sd@$f(((s[P)){]}f?s[]{}%vs^a&d*jhg)(j))(f@~!?$"; - final long now = System.currentTimeMillis(); - - final String sql = "insert into t? using " + tbname2 + " values(?, ?, 'abc?abc') "; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setInt(1, 1); - pstmt.setTimestamp(2, new Timestamp(now)); - pstmt.setBytes(3, speicalCharacterStr.getBytes()); - - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - } - - @Test - public void testCase12() throws SQLException { - final long now = System.currentTimeMillis(); - // insert - final String sql = "insert into " + tbname1 + "(ts, f1, f2) values(?, 'HelloTDengine', ?) ; "; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, new Timestamp(now)); - pstmt.setString(2, special_character_str_4); - int ret = pstmt.executeUpdate(); - Assert.assertEquals(1, ret); - } - // query - final String query = "select * from " + tbname1; - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery(query); - rs.next(); - long timestamp = rs.getTimestamp(1).getTime(); - Assert.assertEquals(now, timestamp); - String f1 = new String(rs.getBytes(2)); - Assert.assertEquals("HelloTDengine", f1); - String f2 = rs.getString(3); - Assert.assertEquals(special_character_str_4, f2); - } - } - - @Before - public void before() throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop table if exists " + tbname1 + ""); - stmt.execute("create table " + tbname1 + "(ts timestamp,f1 binary(64),f2 nchar(64))"); - stmt.execute("drop table if exists " + tbname2); - stmt.execute("create table " + tbname2 + "(ts timestamp, f1 binary(64), f2 nchar(64)) tags(loc nchar(64))"); - } - } - - @BeforeClass - public static void beforeClass() throws SQLException { - String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - conn = DriverManager.getConnection(url); - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists " + dbName); - stmt.execute("create database if not exists " + dbName); - stmt.execute("use " + dbName); - } - } - - @AfterClass - public static void afterClass() throws SQLException { - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists "+ dbName); - statement.close(); - conn.close(); - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InvalidResultSetPointerTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InvalidResultSetPointerTest.java deleted file mode 100644 index 6febdd8497..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InvalidResultSetPointerTest.java +++ /dev/null @@ -1,187 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.BeforeClass; -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; - -public class InvalidResultSetPointerTest { - - private static final String host = "127.0.0.1"; - private static final String dbName = "test"; - private static final String stbName = "stb"; - private static final String tbName = "tb"; - private static Connection connection; - private static final int numOfSTb = 30000; - private static final int numOfTb = 3; - private static int numOfThreads = 100; - - @Test - public void test() throws SQLException { - execute("drop database if exists " + dbName); - execute("create database if not exists " + dbName); - execute("use " + dbName); - createSTable(); - createTable(); - insert(); - selectMultiThreading(); - close(); - } - - private void insert() { - for (int i = 0; i < numOfSTb; i++) { - for (int j = 0; j < numOfTb; j++) { - final String sql = "INSERT INTO " + dbName + "." + tbName + i + "_" + j + " (ts, temperature, humidity, name) values(now, 20.5, 34, \"" + i + "\")"; - System.out.println(sql); - execute(sql); - } - } - } - - private void createSTable() { - for (int i = 0; i < numOfSTb; i++) { - final String sql = "create table if not exists " + dbName + "." + stbName + i + " (ts timestamp, temperature float, humidity int, name BINARY(" + (i % 73 + 10) + ")) TAGS (tag1 INT)"; - execute(sql); - } - } - - private void createTable() { - for (int i = 0; i < numOfSTb; i++) { - for (int j = 0; j < numOfTb; j++) { - final String sql = "create table if not exists " + dbName + "." + tbName + i + "_" + j + " USING " + stbName + i + " TAGS(" + j + ")"; - execute(sql); - } - } - } - - private void close() throws SQLException { - if (connection != null) { - this.connection.close(); - System.out.println("connection closed."); - } - } - - private void selectMultiThreading() { - int a = numOfSTb / numOfThreads; - if (a < 1) { - numOfThreads = numOfSTb; - a = 1; - } - - int b = 0; - if (numOfThreads != 0) { - b = numOfSTb % numOfThreads; - } - - multiThreadingClass[] instance = new multiThreadingClass[numOfThreads]; - - int last = 0; - for (int i = 0; i < numOfThreads; i++) { - instance[i] = new multiThreadingClass(); - instance[i].id = i; - instance[i].from = last; - if (i < b) { - instance[i].to = last + a; - } else { - instance[i].to = last + a - 1; - } - - last = instance[i].to + 1; - instance[i].numOfTb = numOfTb; - instance[i].connection = connection; - instance[i].dbName = dbName; - instance[i].tbName = tbName; - instance[i].start(); - } - - for (int i = 0; i < numOfThreads; i++) { - try { - instance[i].join(); - } catch (InterruptedException ie) { - ie.printStackTrace(); - } - } - } - - @BeforeClass - public static void beforeClass() { - try { - String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - Class.forName("com.taosdata.jdbc.TSDBDriver"); - Properties properties = new Properties(); - properties.setProperty("charset", "UTF-8"); - properties.setProperty("locale", "en_US.UTF-8"); - properties.setProperty("timezone", "UTC-8"); - System.out.println("get connection starting..."); - connection = DriverManager.getConnection(url, properties); - if (connection != null) - System.out.println("[ OK ] Connection established."); - } catch (ClassNotFoundException | SQLException e) { - e.printStackTrace(); - } - } - - private void execute(String sql) { - try (Statement statement = connection.createStatement()) { - long start = System.currentTimeMillis(); - statement.execute(sql); - long end = System.currentTimeMillis(); - printSql(sql, (end - start)); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private void printSql(String sql, long cost) { - System.out.println("time cost: " + cost + " ms, execute statement ====> " + sql); - } - - private void executeQuery(String sql) { - try (Statement statement = connection.createStatement()) { - long start = System.currentTimeMillis(); - ResultSet resultSet = statement.executeQuery(sql); - long end = System.currentTimeMillis(); - printSql(sql, (end - start)); -// printResult(resultSet); - resultSet.close(); - statement.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - class multiThreadingClass extends Thread { - public int id; - public int from, to; - public int numOfTb; - public Connection connection; - public String dbName; - public String tbName; - - public void run() { - System.out.println("ID: " + id + " from: " + from + " to: " + to); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - System.out.println("Thread " + id + " interrupted."); - } - - for (int i = from; i < to; i++) { - for (int j = 0; j < numOfTb; j++) { - if (j % 1000 == 0) { - try { - System.out.print(id + "s."); - Thread.sleep(1); - } catch (InterruptedException e) { - System.out.println("Thread " + id + " interrupted."); - } - } - final String sql = "select last_row(humidity) from " + dbName + "." + tbName + i + "_" + j; - executeQuery(sql); - } - } - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/JDBCTypeAndTypeCompareTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/JDBCTypeAndTypeCompareTest.java deleted file mode 100644 index 38e8d99afe..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/JDBCTypeAndTypeCompareTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.AfterClass; -import org.junit.Test; - -import java.sql.*; - -public class JDBCTypeAndTypeCompareTest { - private static Connection conn; - private static final String dbname = "test"; - - @Test - public void test() throws SQLException { - conn = DriverManager.getConnection("jdbc:TAOS://127.0.0.1:6030/", "root", "taosdata"); - Statement stmt = conn.createStatement(); - - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather(ts timestamp, f1 int, f2 bigint, f3 float, f4 double, f5 smallint, f6 tinyint, f7 bool, f8 binary(10), f9 nchar(10) )"); - stmt.execute("insert into weather values(now, 1, 2, 3.0, 4.0, 5, 6, true, 'test','test')"); - - ResultSet rs = stmt.executeQuery("select * from weather"); - ResultSetMetaData meta = rs.getMetaData(); - while (rs.next()) { - for (int i = 1; i <= meta.getColumnCount(); i++) { - String columnName = meta.getColumnName(i); - String columnTypeName = meta.getColumnTypeName(i); - Object value = rs.getObject(i); - System.out.printf("columnName : %s, columnTypeName: %s, JDBCType: %s\n", columnName, columnTypeName, value.getClass().getName()); - } - } - - stmt.close(); - } - - @AfterClass - public static void afterClass() { - try { - if (null != conn) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists " + dbname); - statement.close(); - conn.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/MicroSecondPrecisionJNITest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/MicroSecondPrecisionJNITest.java deleted file mode 100644 index 0889170e65..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/MicroSecondPrecisionJNITest.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.taosdata.jdbc.cases; - - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; - -public class MicroSecondPrecisionJNITest { - - private static final String host = "127.0.0.1"; - private static final String ms_timestamp_db = "ms_precision_test"; - private static final String us_timestamp_db = "us_precision_test"; - private static final long timestamp1 = System.currentTimeMillis(); - private static final long timestamp2 = timestamp1 * 1000 + 123; - - private static Connection conn; - - @Test - public void testCase1() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather"); - rs.next(); - long ts = rs.getTimestamp(1).getTime(); - Assert.assertEquals(timestamp1, ts); - ts = rs.getLong(1); - Assert.assertEquals(timestamp1, ts); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void testCase2() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather"); - rs.next(); - - Timestamp timestamp = rs.getTimestamp(1); - long ts = timestamp.getTime(); - Assert.assertEquals(timestamp1, ts); - int nanos = timestamp.getNanos(); - Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); - - ts = rs.getLong(1); - Assert.assertEquals(timestamp2, ts); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @BeforeClass - public static void beforeClass() throws SQLException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - - String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - conn = DriverManager.getConnection(url, properties); - - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + ms_timestamp_db); - stmt.execute("create database if not exists " + ms_timestamp_db + " precision 'ms'"); - stmt.execute("create table " + ms_timestamp_db + ".weather(ts timestamp, f1 int)"); - stmt.executeUpdate("insert into " + ms_timestamp_db + ".weather(ts,f1) values(" + timestamp1 + ", 127)"); - - stmt.execute("drop database if exists " + us_timestamp_db); - stmt.execute("create database if not exists " + us_timestamp_db + " precision 'us'"); - stmt.execute("create table " + us_timestamp_db + ".weather(ts timestamp, f1 int)"); - stmt.executeUpdate("insert into " + us_timestamp_db + ".weather(ts,f1) values(" + timestamp2 + ", 127)"); - stmt.close(); - } - - @AfterClass - public static void afterClass() { - try { - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database " + ms_timestamp_db); - statement.execute("drop database " + us_timestamp_db); - statement.close(); - conn.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/MicroSecondPrecisionRestfulTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/MicroSecondPrecisionRestfulTest.java deleted file mode 100644 index 48c5ef8a46..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/MicroSecondPrecisionRestfulTest.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.taosdata.jdbc.cases; - - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; - -public class MicroSecondPrecisionRestfulTest { - - private static final String host = "127.0.0.1"; - private static final String ms_timestamp_db = "ms_precision_test"; - private static final String us_timestamp_db = "us_precision_test"; - private static final long timestamp1 = System.currentTimeMillis(); - private static final long timestamp2 = timestamp1 * 1000 + 123; - - private static Connection conn1; - private static Connection conn2; - private static Connection conn3; - - @Test - public void testCase1() throws SQLException { - try (Statement stmt = conn1.createStatement()) { - ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather"); - rs.next(); - long ts = rs.getTimestamp(1).getTime(); - Assert.assertEquals(timestamp1, ts); - ts = rs.getLong(1); - Assert.assertEquals(timestamp1, ts); - } - } - - @Test - public void testCase2() throws SQLException { - try (Statement stmt = conn1.createStatement()) { - ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather"); - rs.next(); - - Timestamp timestamp = rs.getTimestamp(1); - long ts = timestamp.getTime(); - Assert.assertEquals(timestamp1, ts); - int nanos = timestamp.getNanos(); - Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); - - ts = rs.getLong(1); - Assert.assertEquals(timestamp2, ts); - } - } - - @Test - public void testCase3() throws SQLException { - try (Statement stmt = conn2.createStatement()) { - ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather"); - rs.next(); - Timestamp rsTimestamp = rs.getTimestamp(1); - long ts = rsTimestamp.getTime(); - Assert.assertEquals(timestamp1, ts); - ts = rs.getLong(1); - Assert.assertEquals(timestamp1, ts); - } - } - - @Test - public void testCase4() throws SQLException { - try (Statement stmt = conn2.createStatement()) { - ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather"); - rs.next(); - - Timestamp timestamp = rs.getTimestamp(1); - long ts = timestamp.getTime(); - Assert.assertEquals(timestamp1, ts); - int nanos = timestamp.getNanos(); - Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); - - ts = rs.getLong(1); - Assert.assertEquals(timestamp2, ts); - } - } - - @Test - public void testCase5() throws SQLException { - try (Statement stmt = conn3.createStatement()) { - ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather"); - rs.next(); - Timestamp actual = rs.getTimestamp(1); - long ts = actual == null ? 0 : actual.getTime(); - Assert.assertEquals(timestamp1, ts); - ts = rs.getLong(1); - Assert.assertEquals(timestamp1, ts); - } - } - - @Test - public void testCase6() throws SQLException { - try (Statement stmt = conn3.createStatement()) { - ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather"); - rs.next(); - - Timestamp timestamp = rs.getTimestamp(1); - long ts = timestamp == null ? 0 : timestamp.getTime(); - Assert.assertEquals(timestamp1, ts); - int nanos = timestamp.getNanos(); - Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); - - ts = rs.getLong(1); - Assert.assertEquals(timestamp2, ts); - } - } - - @BeforeClass - public static void beforeClass() throws SQLException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); -// properties.setProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, "TIMESTAMP"); - - String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - conn1 = DriverManager.getConnection(url, properties); - - url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata×tampFormat=timestamp"; - conn2 = DriverManager.getConnection(url, properties); - - url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata×tampFormat=utc"; - conn3 = DriverManager.getConnection(url, properties); - - Statement stmt = conn1.createStatement(); - stmt.execute("drop database if exists " + ms_timestamp_db); - stmt.execute("create database if not exists " + ms_timestamp_db + " precision 'ms'"); - stmt.execute("create table " + ms_timestamp_db + ".weather(ts timestamp, f1 int)"); - stmt.executeUpdate("insert into " + ms_timestamp_db + ".weather(ts,f1) values(" + timestamp1 + ", 127)"); - - stmt.execute("drop database if exists " + us_timestamp_db); - stmt.execute("create database if not exists " + us_timestamp_db + " precision 'us'"); - stmt.execute("create table " + us_timestamp_db + ".weather(ts timestamp, f1 int)"); - stmt.executeUpdate("insert into " + us_timestamp_db + ".weather(ts,f1) values(" + timestamp2 + ", 127)"); - stmt.close(); - } - - @AfterClass - public static void afterClass() { - try { - if (conn1 != null) { - Statement statement = conn1.createStatement(); - statement.execute("drop database if exists " + ms_timestamp_db); - statement.execute("drop database if exists " + us_timestamp_db); - statement.close(); - conn1.close(); - } - if (conn2 != null) - conn2.close(); - if (conn3 != null) - conn3.close(); - }catch (SQLException e){ - e.printStackTrace(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/MultiConnectionWithDifferentDbTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/MultiConnectionWithDifferentDbTest.java deleted file mode 100644 index 220ac0e7ce..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/MultiConnectionWithDifferentDbTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.sql.*; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import static org.junit.Assert.*; - -public class MultiConnectionWithDifferentDbTest { - - private static String host = "127.0.0.1"; - private static String db1 = "db1"; - private static String db2 = "db2"; - - private long ts; - - @Test - public void test() { - List threads = IntStream.range(1, 3).mapToObj(i -> new Thread(new Runnable() { - @Override - public void run() { - for (int j = 0; j < 10; j++) { - try { - queryDb(); - TimeUnit.SECONDS.sleep(1); - } catch (InterruptedException ignored) { - } catch (SQLException throwables) { - fail(); - } - } - } - - private void queryDb() throws SQLException { - String url = "jdbc:TAOS-RS://" + host + ":6041/db" + i + "?user=root&password=taosdata"; - try (Connection connection = DriverManager.getConnection(url)) { - Statement stmt = connection.createStatement(); - - ResultSet rs = stmt.executeQuery("select * from weather"); - assertNotNull(rs); - rs.next(); - long actual = rs.getTimestamp("ts").getTime(); - assertEquals(ts, actual); - - int f1 = rs.getInt("f1"); - assertEquals(i, f1); - - String loc = i == 1 ? "beijing" : "shanghai"; - String loc_actual = rs.getString("loc"); - assertEquals(loc, loc_actual); - - stmt.close(); - } - } - }, "thread-" + i)).collect(Collectors.toList()); - - threads.forEach(Thread::start); - - for (Thread t : threads) { - try { - t.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - } - - @Before - public void before() throws SQLException { - ts = System.currentTimeMillis(); - - try (Connection conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata")) { - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + db1); - stmt.execute("create database if not exists " + db1); - stmt.execute("use " + db1); - stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))"); - stmt.execute("insert into t1 using weather tags('beijing') values(" + ts + ", 1)"); - - stmt.execute("drop database if exists " + db2); - stmt.execute("create database if not exists " + db2); - stmt.execute("use " + db2); - stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))"); - stmt.execute("insert into t1 using weather tags('shanghai') values(" + ts + ", 2)"); - } - } - - @After - public void after() { - String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - try (Connection connection = DriverManager.getConnection(url); - Statement statement = connection.createStatement()) { - statement.execute("drop database if exists " + db1); - statement.execute("drop database if exists " + db2); - } catch (SQLException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NanoSecondTimestampJNITest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NanoSecondTimestampJNITest.java deleted file mode 100644 index f5cc99cde4..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NanoSecondTimestampJNITest.java +++ /dev/null @@ -1,168 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.*; - -import java.sql.*; -import java.time.Instant; -import java.util.Random; - -public class NanoSecondTimestampJNITest { - - private static final String host = "127.0.0.1"; - private static final String dbname = "nano_sec_test"; - private static final Random random = new Random(System.currentTimeMillis()); - private static Connection conn; - - @Test - public void insertUsingLongValue() throws SQLException { - // given - long ms = System.currentTimeMillis(); - long ns = ms * 1000_000 + random.nextInt(1000_000); - - // when - int ret = 0; - try (Statement stmt = conn.createStatement()) { - ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); - } - - // then - Assert.assertEquals(1, ret); - } - - @Test - public void insertUsingStringValue() throws SQLException { - // given - - // when - int ret = 0; - try (Statement stmt = conn.createStatement()) { - ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('2021-01-01 12:00:00.123456789', 12.3, 4)"); - } - - // then - Assert.assertEquals(1, ret); - } - - @Test - public void insertUsingTimestampValue() throws SQLException { - // given - long epochSec = System.currentTimeMillis() / 1000; - long nanoAdjustment = random.nextInt(1000_000_000); - Timestamp ts = Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); - - // when - int ret = 0; - String sql = "insert into weather(ts, temperature, humidity) values( ?, ?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, ts); - pstmt.setFloat(2, 12.34f); - pstmt.setInt(3, 55); - ret = pstmt.executeUpdate(); - } - - // then - Assert.assertEquals(1, ret); - } - - @Test - public void selectUsingLongValue() throws SQLException { - // given - long ms = System.currentTimeMillis(); - long ns = ms * 1000_000L + random.nextInt(1000_000); - - // when - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); - ResultSet rs = stmt.executeQuery("select * from weather"); - rs.next(); - // then - long actual = rs.getLong(1); - Assert.assertEquals(ns, actual); - actual = rs.getLong("ts"); - Assert.assertEquals(ns, actual); - } - } - - @Test - public void selectUsingStringValue() throws SQLException { - // given - String timestampStr = "2021-01-01 12:00:00.123456789"; - - // when - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('" + timestampStr + "', 12.3, 4)"); - ResultSet rs = stmt.executeQuery("select * from weather"); - rs.next(); - // then - String actual = rs.getString(1); - Assert.assertEquals(timestampStr, actual); - actual = rs.getString("ts"); - Assert.assertEquals(timestampStr, actual); - } - } - - @Test - public void selectUsingTimestampValue() throws SQLException { - // given - long timeMillis = System.currentTimeMillis(); - long epochSec = timeMillis / 1000; - long nanoAdjustment = (timeMillis % 1000) * 1000_000L + random.nextInt(1000_000); - Timestamp ts = Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); - - // insert one row - String sql = "insert into weather(ts, temperature, humidity) values( ?, ?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, ts); - pstmt.setFloat(2, 12.34f); - pstmt.setInt(3, 55); - pstmt.executeUpdate(); - } - - // when - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from weather"); - rs.next(); - // then - Timestamp actual = rs.getTimestamp(1); - Assert.assertEquals(ts, actual); - actual = rs.getTimestamp("ts"); - Assert.assertEquals(ts, actual); - Assert.assertEquals(timeMillis, actual.getTime()); - Assert.assertEquals(nanoAdjustment, actual.getNanos()); - } - } - - @Before - public void before() throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop table if exists weather"); - stmt.execute("create table weather(ts timestamp, temperature float, humidity int)"); - } - } - - @BeforeClass - public static void beforeClass() throws SQLException { - final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - conn = DriverManager.getConnection(url); - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname + " precision 'ns'"); - stmt.execute("use " + dbname); - } - } - - @AfterClass - public static void afterClass(){ - try { - if (null != conn){ - Statement statement = conn.createStatement(); - statement.execute("drop database if exists " + dbname); - statement.close(); - conn.close(); - } - }catch (SQLException e){ - e.printStackTrace(); - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NanoSecondTimestampRestfulTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NanoSecondTimestampRestfulTest.java deleted file mode 100644 index 796f21ed21..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NanoSecondTimestampRestfulTest.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.*; - -import java.sql.*; -import java.time.Instant; -import java.util.Random; - -public class NanoSecondTimestampRestfulTest { - - private static final String host = "127.0.0.1"; - private static final String dbname = "nano_sec_test"; - private static final Random random = new Random(System.currentTimeMillis()); - private static Connection conn; - - @Test - public void insertUsingLongValue() throws SQLException { - // given - long ms = System.currentTimeMillis(); - long ns = ms * 1000_000 + random.nextInt(1000_000); - - // when - int ret = 0; - try (Statement stmt = conn.createStatement()) { - ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); - } - - // then - Assert.assertEquals(1, ret); - } - - @Test - public void insertUsingStringValue() throws SQLException { - // given - - // when - int ret = 0; - try (Statement stmt = conn.createStatement()) { - ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('2021-01-01 12:00:00.123456789', 12.3, 4)"); - } - - // then - Assert.assertEquals(1, ret); - } - - @Test - public void insertUsingTimestampValue() throws SQLException { - // given - long epochSec = System.currentTimeMillis() / 1000; - long nanoAdjustment = random.nextInt(1000_000_000); - Timestamp ts = Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); - - // when - int ret = 0; - String sql = "insert into weather(ts, temperature, humidity) values( ?, ?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, ts); - pstmt.setFloat(2, 12.34f); - pstmt.setInt(3, 55); - ret = pstmt.executeUpdate(); - } - - // then - Assert.assertEquals(1, ret); - } - - @Test - public void selectUsingLongValue() throws SQLException { - // given - long ms = System.currentTimeMillis(); - long ns = ms * 1000_000L + random.nextInt(1000_000); - - // when - ResultSet rs; - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); - rs = stmt.executeQuery("select * from weather"); - rs.next(); - } - - // then - long actual = rs.getLong(1); - Assert.assertEquals(ns, actual); - actual = rs.getLong("ts"); - Assert.assertEquals(ns, actual); - } - - @Test - public void selectUsingStringValue() throws SQLException { - // given - String timestampStr = "2021-01-01 12:00:00.123456789"; - - // when - ResultSet rs; - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('" + timestampStr + "', 12.3, 4)"); - rs = stmt.executeQuery("select * from weather"); - rs.next(); - } - - // then - String actual = rs.getString(1); - Assert.assertEquals(timestampStr, actual); - actual = rs.getString("ts"); - Assert.assertEquals(timestampStr, actual); - } - - @Test - public void selectUsingTimestampValue() throws SQLException { - // given - long timeMillis = System.currentTimeMillis(); - long epochSec = timeMillis / 1000; - long nanoAdjustment = (timeMillis % 1000) * 1000_000L + random.nextInt(1000_000); - Timestamp ts = Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); - - // insert one row - String sql = "insert into weather(ts, temperature, humidity) values( ?, ?, ?)"; - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setTimestamp(1, ts); - pstmt.setFloat(2, 12.34f); - pstmt.setInt(3, 55); - pstmt.executeUpdate(); - } - - // when - ResultSet rs = null; - try (Statement stmt = conn.createStatement()) { - rs = stmt.executeQuery("select * from weather"); - rs.next(); - } - - // then - Timestamp actual = rs.getTimestamp(1); - Assert.assertEquals(ts, actual); - actual = rs.getTimestamp("ts"); - Assert.assertEquals(ts, actual); - Assert.assertEquals(timeMillis, actual.getTime()); - Assert.assertEquals(nanoAdjustment, actual.getNanos()); - } - - @Before - public void before() throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop table if exists weather"); - stmt.execute("create table weather(ts timestamp, temperature float, humidity int)"); - } - } - - @BeforeClass - public static void beforeClass() throws SQLException { - final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - conn = DriverManager.getConnection(url); - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname + " precision 'ns'"); - stmt.execute("use " + dbname); - } - } - - @AfterClass - public static void afterClass() throws SQLException { - if (conn != null){ - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists " + dbname); - } - conn.close(); - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NullValueInResultSetJNITest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NullValueInResultSetJNITest.java deleted file mode 100644 index 8bbc2fe077..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NullValueInResultSetJNITest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.sql.*; - -public class NullValueInResultSetJNITest { - - private static final String host = "127.0.0.1"; - Connection conn; - - @Test - public void test() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from weather"); - ResultSetMetaData meta = rs.getMetaData(); - while (rs.next()) { - } - - } - } - - @Before - public void before() throws SQLException { - final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - conn = DriverManager.getConnection(url); - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists test_null"); - stmt.execute("create database if not exists test_null"); - stmt.execute("use test_null"); - stmt.execute("create table weather(ts timestamp, f1 int, f2 bigint, f3 float, f4 double, f5 smallint, f6 tinyint, f7 bool, f8 binary(64), f9 nchar(64))"); - stmt.executeUpdate("insert into weather(ts, f1) values(now+1s, 1)"); - stmt.executeUpdate("insert into weather(ts, f2) values(now+2s, 2)"); - stmt.executeUpdate("insert into weather(ts, f3) values(now+3s, 3.0)"); - stmt.executeUpdate("insert into weather(ts, f4) values(now+4s, 4.0)"); - stmt.executeUpdate("insert into weather(ts, f5) values(now+5s, 5)"); - stmt.executeUpdate("insert into weather(ts, f6) values(now+6s, 6)"); - stmt.executeUpdate("insert into weather(ts, f7) values(now+7s, true)"); - stmt.executeUpdate("insert into weather(ts, f8) values(now+8s, 'hello')"); - stmt.executeUpdate("insert into weather(ts, f9) values(now+9s, '涛思数据')"); - } - } - - @After - public void after() throws SQLException { - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists test_null"); - statement.close(); - conn.close(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NullValueInResultSetRestfulTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NullValueInResultSetRestfulTest.java deleted file mode 100644 index 08f641b96e..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NullValueInResultSetRestfulTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.sql.*; - -public class NullValueInResultSetRestfulTest { - - private static final String host = "127.0.0.1"; - Connection conn; - - @Test - public void test() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from weather"); - ResultSetMetaData meta = rs.getMetaData(); - while (rs.next()) { - for (int i = 1; i <= meta.getColumnCount(); i++) { - Object value = rs.getObject(i); - } - } - } - } - - @Before - public void before() throws SQLException { - final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - conn = DriverManager.getConnection(url); - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists test_null"); - stmt.execute("create database if not exists test_null"); - stmt.execute("use test_null"); - stmt.execute("create table weather(ts timestamp, f1 int, f2 bigint, f3 float, f4 double, f5 smallint, f6 tinyint, f7 bool, f8 binary(64), f9 nchar(64))"); - stmt.executeUpdate("insert into weather(ts, f1) values(now+1s, 1)"); - stmt.executeUpdate("insert into weather(ts, f2) values(now+2s, 2)"); - stmt.executeUpdate("insert into weather(ts, f3) values(now+3s, 3.0)"); - stmt.executeUpdate("insert into weather(ts, f4) values(now+4s, 4.0)"); - stmt.executeUpdate("insert into weather(ts, f5) values(now+5s, 5)"); - stmt.executeUpdate("insert into weather(ts, f6) values(now+6s, 6)"); - stmt.executeUpdate("insert into weather(ts, f7) values(now+7s, true)"); - stmt.executeUpdate("insert into weather(ts, f8) values(now+8s, 'hello')"); - stmt.executeUpdate("insert into weather(ts, f9) values(now+9s, '涛思数据')"); - } - } - - @After - public void after() throws SQLException { - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists test_null"); - statement.close(); - conn.close(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NullValueInResultSetTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NullValueInResultSetTest.java deleted file mode 100644 index 890505ac65..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NullValueInResultSetTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.taosdata.jdbc.cases; - -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.utils.TimestampUtil; -import org.junit.*; - -import java.sql.*; -import java.util.Properties; - -public class NullValueInResultSetTest { - private static final String host = "127.0.0.1"; - private static Properties properties; - private static Connection conn_restful; - private static Connection conn_jni; - - @Test - public void testRestful() throws SQLException { - String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - conn_restful = DriverManager.getConnection(url, properties); - - try (Statement stmt = conn_restful.createStatement()) { - stmt.execute("drop database if exists test_null"); - stmt.execute("create database if not exists test_null"); - stmt.execute("use test_null"); - stmt.execute("create table weather(ts timestamp, f1 timestamp, f2 int, f3 bigint, f4 float, f5 double, f6 smallint, f7 tinyint, f8 bool, f9 binary(64), f10 nchar(64))"); - stmt.executeUpdate("insert into weather(ts, f1) values(now+1s, " + TimestampUtil.datetimeToLong("2021-04-21 12:00:00.000") + ")"); - ResultSet rs = stmt.executeQuery("select * from weather"); - rs.next(); - - Assert.assertEquals("2021-04-21 12:00:00.000", TimestampUtil.longToDatetime(rs.getTimestamp(2).getTime())); - Assert.assertEquals(true, rs.getInt(3) == 0 && rs.wasNull()); - Assert.assertEquals(true, rs.getLong(4) == 0 && rs.wasNull()); - Assert.assertEquals(true, rs.getFloat(5) == 0.0f && rs.wasNull()); - Assert.assertEquals(true, rs.getDouble(6) == 0.0f && rs.wasNull()); - Assert.assertEquals(true, rs.getByte(7) == 0 && rs.wasNull()); - Assert.assertEquals(true, rs.getShort(8) == 0 && rs.wasNull()); - Assert.assertEquals(null, rs.getBytes(9)); - Assert.assertEquals(null, rs.getString(10)); - - rs.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void testJNI() throws SQLException { - final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - conn_jni = DriverManager.getConnection(url, properties); - - try (Statement stmt = conn_jni.createStatement()) { - stmt.execute("drop database if exists test_null"); - stmt.execute("create database if not exists test_null"); - stmt.execute("use test_null"); - stmt.execute("create table weather(ts timestamp, f1 timestamp, f2 int, f3 bigint, f4 float, f5 double, f6 smallint, f7 tinyint, f8 bool, f9 binary(64), f10 nchar(64))"); - stmt.executeUpdate("insert into weather(ts, f1) values(now+1s, " + TimestampUtil.datetimeToLong("2021-04-21 12:00:00.000") + ")"); - ResultSet rs = stmt.executeQuery("select * from weather"); - rs.next(); - - Assert.assertEquals("2021-04-21 12:00:00.000", TimestampUtil.longToDatetime(rs.getTimestamp(2).getTime())); - Assert.assertEquals(true, rs.getInt(3) == 0 && rs.wasNull()); - Assert.assertEquals(true, rs.getLong(4) == 0 && rs.wasNull()); - Assert.assertEquals(true, rs.getFloat(5) == 0.0f && rs.wasNull()); - Assert.assertEquals(true, rs.getDouble(6) == 0.0f && rs.wasNull()); - Assert.assertEquals(true, rs.getByte(7) == 0 && rs.wasNull()); - Assert.assertEquals(true, rs.getShort(8) == 0 && rs.wasNull()); - Assert.assertEquals(null, rs.getBytes(9)); - Assert.assertEquals(null, rs.getString(10)); - - rs.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @BeforeClass - public static void beforeClass() { - properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - } - - @AfterClass - public static void afterClass() throws SQLException { - if (conn_restful != null) - conn_restful.close(); - if (conn_jni != null) { - Statement statement = conn_jni.createStatement(); - statement.execute("drop database if exists test_null"); - statement.close(); - conn_jni.close(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/PreparedStatementBatchInsertJNITest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/PreparedStatementBatchInsertJNITest.java deleted file mode 100644 index ed78c2561e..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/PreparedStatementBatchInsertJNITest.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.sql.*; -import java.util.List; -import java.util.Random; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -public class PreparedStatementBatchInsertJNITest { - - private static final String host = "127.0.0.1"; - private static final String dbname = "td4668"; - - private final Random random = new Random(System.currentTimeMillis()); - private Connection conn; - - @Test - public void test() { - // given - long ts = System.currentTimeMillis(); - List rows = IntStream.range(0, 10).mapToObj(i -> { - Object[] row = new Object[6]; - final String groupId = String.format("%02d", random.nextInt(100)); - // table name (d + groupId)组合 - row[0] = "d" + groupId; - // tag - row[1] = groupId; - // ts - row[2] = ts + i; - // current 电流 - row[3] = random.nextFloat(); - // voltage 电压 - row[4] = Math.random() > 0.5 ? 220 : 380; - // phase 相位 - row[5] = random.nextInt(10); - return row; - }).collect(Collectors.toList()); - final String sql = "INSERT INTO ? (TS,CURRENT,VOLTAGE,PHASE) USING METERS TAGS (?) VALUES (?,?,?,?)"; - - // when - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - for (Object[] row : rows) { - for (int i = 0; i < row.length; i++) { - pstmt.setObject(i + 1, row[i]); - } - pstmt.addBatch(); - } - pstmt.executeBatch(); - } catch (SQLException e) { - e.printStackTrace(); - Assert.fail(); - } - - // then - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from meters"); - int count = 0; - while (rs.next()) { - count++; - } - Assert.assertEquals(10, count); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Before - public void before() { - try { - conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table meters(ts timestamp, current float, voltage int, phase int) tags(groupId int)"); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @After - public void after() { - try { - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/PreparedStatementBatchInsertRestfulTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/PreparedStatementBatchInsertRestfulTest.java deleted file mode 100644 index 85fbeef1b5..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/PreparedStatementBatchInsertRestfulTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.sql.*; -import java.util.List; -import java.util.Random; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -public class PreparedStatementBatchInsertRestfulTest { - - private static final String host = "127.0.0.1"; - private static final String dbname = "td4668"; - - private final Random random = new Random(System.currentTimeMillis()); - private Connection conn; - - @Test - public void test() throws SQLException { - // given - long ts = System.currentTimeMillis(); - List rows = IntStream.range(0, 10).mapToObj(i -> { - Object[] row = new Object[6]; - final String groupId = String.format("%02d", random.nextInt(100)); - // table name (d + groupId)组合 - row[0] = "d" + groupId; - // tag - row[1] = groupId; - // ts - row[2] = ts + i; - // current 电流 - row[3] = random.nextFloat(); - // voltage 电压 - row[4] = Math.random() > 0.5 ? 220 : 380; - // phase 相位 - row[5] = random.nextInt(10); - return row; - }).collect(Collectors.toList()); - final String sql = "INSERT INTO ? (TS,CURRENT,VOLTAGE,PHASE) USING METERS TAGS (?) VALUES (?,?,?,?)"; - - // when - try (PreparedStatement pstmt = conn.prepareStatement(sql)) { - for (Object[] row : rows) { - for (int i = 0; i < row.length; i++) { - pstmt.setObject(i + 1, row[i]); - } - pstmt.addBatch(); - } - pstmt.executeBatch(); - } catch (SQLException e) { - Assert.fail(); - } - - // then - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from meters"); - int count = 0; - while (rs.next()) { - count++; - } - Assert.assertEquals(10, count); - } - } - - @Before - public void before() throws SQLException { - conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table meters(ts timestamp, current float, voltage int, phase int) tags(groupId int)"); - } - - @After - public void after() throws SQLException { - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.close(); - conn.close(); - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/QueryDataTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/QueryDataTest.java deleted file mode 100644 index fd74e9433a..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/QueryDataTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.taosdata.jdbc.cases; - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; - -public class QueryDataTest { - - static Connection connection; - static Statement statement; - static String dbName = "test"; - static String stbName = "meters"; - static String host = "127.0.0.1"; - - @Before - public void createDatabase() throws SQLException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties); - - statement = connection.createStatement(); - statement.executeUpdate("drop database if exists " + dbName); - statement.executeUpdate("create database if not exists " + dbName); - statement.executeUpdate("use " + dbName); - - String createTableSql = "create table " + stbName + "(ts timestamp, name binary(64))"; - statement.executeUpdate(createTableSql); - } - - @Test - public void testQueryBinaryData() throws SQLException { - String insertSql = "insert into " + stbName + " values(now, 'taosdata')"; - statement.executeUpdate(insertSql); - - String querySql = "select * from " + stbName; - ResultSet rs = statement.executeQuery(querySql); - - while (rs.next()) { - String name = rs.getString(2); - assertEquals("taosdata", name); - } - rs.close(); - } - - @After - public void close() throws SQLException { - if (statement != null) - statement.close(); - if (connection != null) - connection.close(); - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ResetQueryCacheTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ResetQueryCacheTest.java deleted file mode 100644 index 48753d62f0..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ResetQueryCacheTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.Test; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -public class ResetQueryCacheTest { - - @Test - public void jni() throws SQLException { - // given - Connection connection = DriverManager.getConnection("jdbc:TAOS://127.0.0.1:0/?user=root&password=taosdata&timezone=UTC-8&charset=UTF-8&locale=en_US.UTF-8"); - Statement statement = connection.createStatement(); - - // when - boolean execute = statement.execute("reset query cache"); - - // then - assertFalse(execute); - assertEquals(0, statement.getUpdateCount()); - - statement.close(); - connection.close(); - } - - @Test - public void restful() throws SQLException { - // given - Connection connection = DriverManager.getConnection("jdbc:TAOS-RS://127.0.0.1:6041/?user=root&password=taosdata&timezone=UTC-8&charset=UTF-8&locale=en_US.UTF-8"); - Statement statement = connection.createStatement(); - - // when - boolean execute = statement.execute("reset query cache"); - - // then - assertFalse(execute); - assertEquals(0, statement.getUpdateCount()); - - statement.close(); - connection.close(); - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ResultSetMetaShouldNotBeNullRestfulTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ResultSetMetaShouldNotBeNullRestfulTest.java deleted file mode 100644 index ff0dad1bda..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ResultSetMetaShouldNotBeNullRestfulTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.sql.*; - -public class ResultSetMetaShouldNotBeNullRestfulTest { - - private static final String host = "127.0.0.1"; - private static final String dbname = "td4745"; - - private Connection connection; - - @Test - public void testExecuteQuery() throws SQLException { - // given - ResultSetMetaData metaData; - int columnCount; - - // when - Statement statement = connection.createStatement(); - metaData = statement.executeQuery("select * from weather").getMetaData(); - columnCount = metaData.getColumnCount(); - - // then - Assert.assertNotNull(metaData); - Assert.assertEquals(2, columnCount); - } - - @Test - public void testExecute() throws SQLException { - // given - ResultSetMetaData metaData; - int columnCount; - boolean execute; - - // when - Statement statement = connection.createStatement(); - execute = statement.execute("select * from weather"); - metaData = statement.getResultSet().getMetaData(); - columnCount = metaData.getColumnCount(); - - // then - Assert.assertEquals(true, execute); - Assert.assertNotNull(metaData); - Assert.assertEquals(2, columnCount); - } - - @Before - public void before() throws SQLException { - connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); - Statement stmt = connection.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather (ts timestamp, temperature float)"); - stmt.close(); - } - - @After - public void after() throws SQLException { - Statement stmt = connection.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.close(); - connection.close(); - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/SelectTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/SelectTest.java deleted file mode 100644 index 79e5602e9e..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/SelectTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.taosdata.jdbc.cases; - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; - -public class SelectTest { - Connection connection; - String dbName = "test"; - String tName = "t0"; - String host = "127.0.0.1"; - - @Before - public void createDatabaseAndTable() throws SQLException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties); - - Statement stmt = connection.createStatement(); - stmt.execute("drop database if exists " + dbName); - stmt.execute("create database if not exists " + dbName); - stmt.execute("create table if not exists " + dbName + "." + tName + " (ts timestamp, k int, v int)"); - stmt.close(); - } - - @Test - public void selectData() { - long ts = 1496732686000l; - - try (Statement stmt = connection.createStatement()) { - for (int i = 0; i < 50; i++) { - ts++; - int row = stmt.executeUpdate("insert into " + dbName + "." + tName + " values (" + ts + ", " + (100 + i) + ", " + i + ")"); - assertEquals(1, row); - } - - String sql = "select * from " + dbName + "." + tName; - ResultSet resSet = stmt.executeQuery(sql); - - int num = 0; - while (resSet.next()) { - num++; - } - resSet.close(); - assertEquals(num, 50); - } catch (SQLException e) { - e.printStackTrace(); - } - - } - - @After - public void close() throws SQLException { - if (connection != null) { - Statement stmt = connection.createStatement(); - stmt.executeUpdate("drop database " + dbName); - stmt.close(); - connection.close(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/StableTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/StableTest.java deleted file mode 100644 index 8e10743e5e..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/StableTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.taosdata.jdbc.cases; - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; - -import java.sql.*; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class StableTest { - - private static Connection connection; - private static final String dbName = "test"; - private static final String stbName = "st"; - private static final String host = "127.0.0.1"; - - @BeforeClass - public static void createDatabase() { - try { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties); - Statement statement = connection.createStatement(); - statement.execute("drop database if exists " + dbName); - statement.execute("create database if not exists " + dbName); - statement.execute("use " + dbName); - statement.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void case001_createSuperTable() { - try (Statement stmt = connection.createStatement()) { - final String sql = "create table " + stbName + " (ts timestamp, v1 int, v2 int) tags (tg nchar(20)) "; - stmt.execute(sql); - } catch (SQLException e) { - assert false : "error create stable" + e.getMessage(); - } - } - - @Test - public void case002_createTable() { - try (Statement stmt = connection.createStatement()) { - final String sql = "create table t1 using " + stbName + " tags (\"beijing\")"; - stmt.execute(sql); - } catch (SQLException e) { - assert false : "error create table" + e.getMessage(); - } - } - - @Test - public void case003_describeSTable() { - int num = 0; - try (Statement stmt = connection.createStatement()) { - String sql = "describe " + stbName; - ResultSet rs = stmt.executeQuery(sql); - while (rs.next()) { - num++; - } - rs.close(); - assertEquals(4, num); - } catch (SQLException e) { - assert false : "error describe stable" + e.getMessage(); - } - } - - @Test - public void case004_describeTable() { - int num = 0; - try (Statement stmt = connection.createStatement()) { - ResultSet rs = stmt.executeQuery("describe t1"); - while (rs.next()) { - num++; - } - rs.close(); - assertEquals(4, num); - } catch (SQLException e) { - assert false : "error describe stable" + e.getMessage(); - } - } - - @AfterClass - public static void close() { - try { - if (connection != null) - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TimestampPrecisionInNanoInJniTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TimestampPrecisionInNanoInJniTest.java deleted file mode 100644 index 76053ccc41..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TimestampPrecisionInNanoInJniTest.java +++ /dev/null @@ -1,510 +0,0 @@ -package com.taosdata.jdbc.cases; - - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.After; -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; -import java.text.Format; -import java.text.SimpleDateFormat; - -public class TimestampPrecisionInNanoInJniTest { - - private static final String host = "127.0.0.1"; - private static final String ns_timestamp_db = "ns_precision_test"; - private static final long timestamp1 = System.currentTimeMillis(); - private static final long timestamp2 = timestamp1 * 1000_000 + 123455; - private static final long timestamp3 = (timestamp1 + 10) * 1000_000 + 123456; - private static final Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - private static final String date1 = format.format(new Date(timestamp1)); - private static final String date4 = format.format(new Date(timestamp1 + 10L)); - private static final String date2 = date1 + "123455"; - private static final String date3 = date4 + "123456"; - - - private static Connection conn; - - @BeforeClass - public static void beforeClass() throws SQLException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - - String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - conn = DriverManager.getConnection(url, properties); - - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + ns_timestamp_db); - stmt.execute("create database if not exists " + ns_timestamp_db + " precision 'ns'"); - stmt.execute("create table " + ns_timestamp_db + ".weather(ts timestamp, ts2 timestamp, f1 int)"); - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(\"" + date3 + "\", \"" + date3 + "\", 128)"); - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp2 + "," + timestamp2 + ", 127)"); - stmt.close(); - } - - @After - public void afterEach() throws SQLException { - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + ns_timestamp_db); - stmt.execute("create database if not exists " + ns_timestamp_db + " precision 'ns'"); - stmt.execute("create table " + ns_timestamp_db + ".weather(ts timestamp, ts2 timestamp, f1 int)"); - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(\"" + date3 + "\", \"" + date3 + "\", 128)"); - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp2 + "," + timestamp2 + ", 127)"); - stmt.close(); - } - - @AfterClass - public static void afterClass() { - try { - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists " + ns_timestamp_db); - statement.close(); - conn.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private void checkCount(long count, ResultSet rs) throws SQLException { - if (count == 0) { - Assert.fail(); - } - rs.next(); - long test_count = rs.getLong(1); - Assert.assertEquals(count, test_count); - } - - private void checkTime(long ts, ResultSet rs) throws SQLException { - rs.next(); - int nanos = rs.getTimestamp(1).getNanos(); - Assert.assertEquals(ts % 1000_000_000l, nanos); - long test_ts = rs.getLong(1); - Assert.assertEquals(ts, test_ts); - } - - @Test - public void canInsertTimestampAndQueryByEqualToInDateTypeInBothFirstAndSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + date3 + "'"); - checkTime(timestamp3, rs); - rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 = '" + date3 + "'"); - checkTime(timestamp3, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canImportTimestampAndQueryByEqualToInDateTypeInBothFirstAndSecondCol() { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("import into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(\"" + date1 + "123123\", \"" + date1 + "123123\", 127)"); - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date1 + "123123'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + date1 + "123123'"); - checkTime(timestamp1 * 1000_000l + 123123l, rs); - rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "123123'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "123123'"); - checkTime(timestamp1 * 1000_000l + 123123l, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canInsertTimestampAndQueryByEqualToInNumberTypeInBothFirstAndSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + timestamp2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + timestamp2 + "'"); - checkTime(timestamp2, rs); - rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + timestamp2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 = '" + timestamp2 + "'"); - checkTime(timestamp2, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canImportTimestampAndQueryByEqualToInNumberTypeInBothFirstAndSecondCol() { - try (Statement stmt = conn.createStatement()) { - long timestamp4 = timestamp1 * 1000_000 + 123123; - stmt.executeUpdate("import into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp4 + ", " + timestamp4 + ", 127)"); - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + timestamp4 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + timestamp4 + "'"); - checkTime(timestamp4, rs); - rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + timestamp4 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 = '" + timestamp4 + "'"); - checkTime(timestamp4, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canSelectLastRowFromWeatherForFirstCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select last(ts) from " + ns_timestamp_db + ".weather"); - checkTime(timestamp3, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canSelectLastRowFromWeatherForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select last(ts2) from " + ns_timestamp_db + ".weather"); - checkTime(timestamp3, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canSelectFirstRowFromWeatherForFirstCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select first(ts) from " + ns_timestamp_db + ".weather"); - checkTime(timestamp2, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canSelectFirstRowFromWeatherForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select first(ts2) from " + ns_timestamp_db + ".weather"); - checkTime(timestamp2, rs); - } - } - - @Test - public void canQueryLargerThanInDateTypeForFirstCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts > '" + date2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts > '" + date2 + "'"); - checkTime(timestamp3, rs); - } - } - - @Test - public void canQueryLargerThanInDateTypeForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 > '" + date2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 > '" + date2 + "'"); - checkTime(timestamp3, rs); - } - } - - @Test - public void canQueryLargerThanInNumberTypeForFirstCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts > '" + timestamp2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts > '" + timestamp2 + "'"); - checkTime(timestamp3, rs); - } - } - - @Test - public void canQueryLargerThanInNumberTypeForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 > '" + timestamp2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 > '" + timestamp2 + "'"); - checkTime(timestamp3, rs); - } - } - - @Test - public void canQueryLargerThanOrEqualToInDateTypeForFirstCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts >= '" + date2 + "'"); - checkCount(2l, rs); - } - } - - @Test - public void canQueryLargerThanOrEqualToInDateTypeForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 >= '" + date2 + "'"); - checkCount(2l, rs); - } - } - - @Test - public void canQueryLargerThanOrEqualToInNumberTypeForFirstCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts >= '" + timestamp2 + "'"); - checkCount(2l, rs); - } - } - - @Test - public void canQueryLargerThanOrEqualToInNumberTypeForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 >= '" + timestamp2 + "'"); - checkCount(2l, rs); - } - } - - @Test - public void canQueryLessThanInDateTypeForFirstCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts < '" + date3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts < '" + date3 + "'"); - checkTime(timestamp2, rs); - } - } - - @Test - public void canQueryLessThanInDateTypeForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 < '" + date3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 < '" + date3 + "'"); - checkTime(timestamp2, rs); - } - } - - @Test - public void canQueryLessThanInNumberTypeForFirstCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts < '" + timestamp3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts < '" + timestamp3 + "'"); - checkTime(timestamp2, rs); - } - } - - @Test - public void canQueryLessThanInNumberTypeForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 < '" + timestamp3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 < '" + timestamp3 + "'"); - checkTime(timestamp2, rs); - } - } - - @Test - public void canQueryLessThanOrEqualToInDateTypeForFirstCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + date3 + "'"); - checkCount(2l, rs); - } - } - - @Test - public void canQueryLessThanOrEqualToInDateTypeForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + date3 + "'"); - checkCount(2l, rs); - } - } - - @Test - public void canQueryLessThanOrEqualToInNumberTypeForFirstCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + timestamp3 + "'"); - checkCount(2l, rs); - } - } - - @Test - public void canQueryLessThanOrEqualToInNumberTypeForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + timestamp3 + "'"); - checkCount(2l, rs); - } - } - - @Test - public void canQueryBetweenAndInDateTypeForFirstCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + date3 + "' AND ts > '" + date2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts <= '" + date3 + "' AND ts > '" + date2 + "'"); - checkTime(timestamp3, rs); - } - } - - @Test - public void canQueryBetweenAndInDateTypeForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + date3 + "' AND ts2 > '" + date2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <= '" + date3 + "' AND ts2 > '" + date2 + "'"); - checkTime(timestamp3, rs); - } - } - - @Test - public void canQueryBetweenAndInNumberTypeForFirstCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + timestamp3 + "' AND ts > '" + timestamp2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts <= '" + timestamp3 + "' AND ts > '" + timestamp2 + "'"); - checkTime(timestamp3, rs); - } - } - - @Test - public void canQueryBetweenAndInNumberTypeForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + timestamp3 + "' AND ts2 > '" + timestamp2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <= '" + timestamp3 + "' AND ts2 > '" + timestamp2 + "'"); - checkTime(timestamp3, rs); - } - } - - @Test - public void canQueryNotEqualToInDateTypeForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <> '" + date3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <> '" + date3 + "'"); - checkTime(timestamp2, rs); - } - } - - @Test - public void canQueryNotEqualToInNumberTypeForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <> '" + timestamp3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <> '" + timestamp3 + "'"); - checkTime(timestamp2, rs); - } - } - - @Test - public void canQueryNotEqualInDateTypeForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 != '" + date3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 != '" + date3 + "'"); - checkTime(timestamp2, rs); - } - } - - @Test - public void canQueryNotEqualInNumberTypeForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 != '" + timestamp3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 != '" + timestamp3 + "'"); - checkTime(timestamp2, rs); - } - } - - @Test - public void canInsertTimestampWithNowAndNsOffsetInBothFirstAndSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(now + 1000b, now - 1000b, 128)"); - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather"); - checkCount(3l, rs); - } - } - - @Test - public void canIntervalAndSlidingAcceptNsUnitForFirstCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select sum(f1) from " + ns_timestamp_db + ".weather where ts >= '" + date2 + "' and ts <= '" + date3 + "' interval(10000000b) sliding(10000000b)"); - rs.next(); - long sum = rs.getLong(2); - Assert.assertEquals(127l, sum); - rs.next(); - sum = rs.getLong(2); - Assert.assertEquals(128l, sum); - } - } - - @Test - public void canIntervalAndSlidingAcceptNsUnitForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select sum(f1) from " + ns_timestamp_db + ".weather where ts2 >= '" + date2 + "' and ts <= '" + date3 + "' interval(10000000b) sliding(10000000b)"); - rs.next(); - long sum = rs.getLong(2); - Assert.assertEquals(127l, sum); - rs.next(); - sum = rs.getLong(2); - Assert.assertEquals(128l, sum); - } - } - - @Test - public void testDataOutOfRangeExceptionForFirstCol() { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(123456789012345678, 1234567890123456789, 127)"); - } catch (SQLException e) { - Assert.assertEquals("TDengine ERROR (8000060b): Timestamp data out of range", e.getMessage()); - } - } - - @Test - public void testDataOutOfRangeExceptionForSecondCol() { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(1234567890123456789, 123456789012345678, 127)"); - } catch (SQLException e) { - Assert.assertEquals("TDengine ERROR (8000060b): Timestamp data out of range", e.getMessage()); - } - } - - @Test - public void willAutomaticallyFillToNsUnitWithZerosForFirstCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "', '" + date1 + "', 127)"); - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date1 + "000000'"); - checkCount(1l, rs); - } - } - - @Test - public void willAutomaticallyFillToNsUnitWithZerosForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "', '" + date1 + "', 127)"); - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "000000'"); - checkCount(1l, rs); - } - } - - @Test - public void willAutomaticallyDropDigitExceedNsDigitNumberForFirstCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "999999999', '" + date1 + "999999999', 127)"); - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date1 + "999999'"); - checkCount(1l, rs); - } - } - - @Test - public void willAutomaticallyDropDigitExceedNsDigitNumberForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "999999999', '" + date1 + "999999999', 127)"); - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "999999'"); - checkCount(1l, rs); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TimestampPrecisonInNanoRestTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TimestampPrecisonInNanoRestTest.java deleted file mode 100644 index 4aedf867d4..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TimestampPrecisonInNanoRestTest.java +++ /dev/null @@ -1,570 +0,0 @@ -package com.taosdata.jdbc.cases; - - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.After; -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; -import java.text.Format; -import java.text.SimpleDateFormat; - -public class TimestampPrecisonInNanoRestTest { - - private static final String host = "127.0.0.1"; - private static final String ns_timestamp_db = "ns_precision_test"; - private static final long timestamp1 = System.currentTimeMillis(); - private static final long timestamp2 = timestamp1 * 1000_000 + 123455; - private static final long timestamp3 = (timestamp1 + 10) * 1000_000 + 123456; - private static final Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - private static final String date1 = format.format(new Date(timestamp1)); - private static final String date4 = format.format(new Date(timestamp1 + 10L)); - private static final String date2 = date1 + "123455"; - private static final String date3 = date4 + "123456"; - - - private static Connection conn; - - @BeforeClass - public static void beforeClass() throws SQLException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - - String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - conn = DriverManager.getConnection(url, properties); - - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + ns_timestamp_db); - stmt.execute("create database if not exists " + ns_timestamp_db + " precision 'ns'"); - stmt.execute("create table " + ns_timestamp_db + ".weather(ts timestamp, ts2 timestamp, f1 int)"); - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(\"" + date3 + "\", \"" + date3 + "\", 128)"); - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp2 + "," + timestamp2 + ", 127)"); - stmt.close(); - } - - @After - public void afterEach() throws SQLException { - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + ns_timestamp_db); - stmt.execute("create database if not exists " + ns_timestamp_db + " precision 'ns'"); - stmt.execute("create table " + ns_timestamp_db + ".weather(ts timestamp, ts2 timestamp, f1 int)"); - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(\"" + date3 + "\", \"" + date3 + "\", 128)"); - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp2 + "," + timestamp2 + ", 127)"); - stmt.close(); - } - - @AfterClass - public static void afterClass() { - try { - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists " + ns_timestamp_db); - statement.close(); - conn.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private void checkCount(long count, ResultSet rs) throws SQLException { - if (count == 0) { - Assert.fail(); - } - rs.next(); - long test_count = rs.getLong(1); - Assert.assertEquals(count, test_count); - } - - private void checkTime(long ts, ResultSet rs) throws SQLException { - rs.next(); - int nanos = rs.getTimestamp(1).getNanos(); - Assert.assertEquals(ts % 1000_000_000l, nanos); - long test_ts = rs.getLong(1); - Assert.assertEquals(ts, test_ts); - } - - @Test - public void canInsertTimestampAndQueryByEqualToInDateTypeInBothFirstAndSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + date3 + "'"); - checkTime(timestamp3, rs); - rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 = '" + date3 + "'"); - checkTime(timestamp3, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canImportTimestampAndQueryByEqualToInDateTypeInBothFirstAndSecondCol() { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("import into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(\"" + date1 + "123123\", \"" + date1 + "123123\", 127)"); - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date1 + "123123'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + date1 + "123123'"); - checkTime(timestamp1 * 1000_000l + 123123l, rs); - rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "123123'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "123123'"); - checkTime(timestamp1 * 1000_000l + 123123l, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canInsertTimestampAndQueryByEqualToInNumberTypeInBothFirstAndSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + timestamp2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + timestamp2 + "'"); - checkTime(timestamp2, rs); - rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + timestamp2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 = '" + timestamp2 + "'"); - checkTime(timestamp2, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canImportTimestampAndQueryByEqualToInNumberTypeInBothFirstAndSecondCol() { - try (Statement stmt = conn.createStatement()) { - long timestamp4 = timestamp1 * 1000_000 + 123123; - stmt.executeUpdate("import into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp4 + ", " + timestamp4 + ", 127)"); - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + timestamp4 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + timestamp4 + "'"); - checkTime(timestamp4, rs); - rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + timestamp4 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 = '" + timestamp4 + "'"); - checkTime(timestamp4, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canSelectLastRowFromWeatherForFirstCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select last(ts) from " + ns_timestamp_db + ".weather"); - checkTime(timestamp3, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canSelectLastRowFromWeatherForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select last(ts2) from " + ns_timestamp_db + ".weather"); - checkTime(timestamp3, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canSelectFirstRowFromWeatherForFirstCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select first(ts) from " + ns_timestamp_db + ".weather"); - checkTime(timestamp2, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canSelectFirstRowFromWeatherForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select first(ts2) from " + ns_timestamp_db + ".weather"); - checkTime(timestamp2, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLargerThanInDateTypeForFirstCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts > '" + date2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts > '" + date2 + "'"); - checkTime(timestamp3, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLargerThanInDateTypeForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 > '" + date2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 > '" + date2 + "'"); - checkTime(timestamp3, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLargerThanInNumberTypeForFirstCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts > '" + timestamp2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts > '" + timestamp2 + "'"); - checkTime(timestamp3, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLargerThanInNumberTypeForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 > '" + timestamp2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 > '" + timestamp2 + "'"); - checkTime(timestamp3, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLargerThanOrEqualToInDateTypeForFirstCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts >= '" + date2 + "'"); - checkCount(2l, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLargerThanOrEqualToInDateTypeForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 >= '" + date2 + "'"); - checkCount(2l, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLargerThanOrEqualToInNumberTypeForFirstCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts >= '" + timestamp2 + "'"); - checkCount(2l, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLargerThanOrEqualToInNumberTypeForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 >= '" + timestamp2 + "'"); - checkCount(2l, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLessThanInDateTypeForFirstCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts < '" + date3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts < '" + date3 + "'"); - checkTime(timestamp2, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLessThanInDateTypeForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 < '" + date3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 < '" + date3 + "'"); - checkTime(timestamp2, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLessThanInNumberTypeForFirstCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts < '" + timestamp3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts < '" + timestamp3 + "'"); - checkTime(timestamp2, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLessThanInNumberTypeForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 < '" + timestamp3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 < '" + timestamp3 + "'"); - checkTime(timestamp2, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLessThanOrEqualToInDateTypeForFirstCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + date3 + "'"); - checkCount(2l, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLessThanOrEqualToInDateTypeForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + date3 + "'"); - checkCount(2l, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLessThanOrEqualToInNumberTypeForFirstCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + timestamp3 + "'"); - checkCount(2l, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryLessThanOrEqualToInNumberTypeForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + timestamp3 + "'"); - checkCount(2l, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryBetweenAndInDateTypeForFirstCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + date3 + "' AND ts > '" + date2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts <= '" + date3 + "' AND ts > '" + date2 + "'"); - checkTime(timestamp3, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryBetweenAndInDateTypeForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + date3 + "' AND ts2 > '" + date2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <= '" + date3 + "' AND ts2 > '" + date2 + "'"); - checkTime(timestamp3, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryBetweenAndInNumberTypeForFirstCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + timestamp3 + "' AND ts > '" + timestamp2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts <= '" + timestamp3 + "' AND ts > '" + timestamp2 + "'"); - checkTime(timestamp3, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryBetweenAndInNumberTypeForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + timestamp3 + "' AND ts2 > '" + timestamp2 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <= '" + timestamp3 + "' AND ts2 > '" + timestamp2 + "'"); - checkTime(timestamp3, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryNotEqualToInDateTypeForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <> '" + date3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <> '" + date3 + "'"); - checkTime(timestamp2, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryNotEqualToInNumberTypeForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <> '" + timestamp3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <> '" + timestamp3 + "'"); - checkTime(timestamp2, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryNotEqualInDateTypeForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 != '" + date3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 != '" + date3 + "'"); - checkTime(timestamp2, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canQueryNotEqualInNumberTypeForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 != '" + timestamp3 + "'"); - checkCount(1l, rs); - rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 != '" + timestamp3 + "'"); - checkTime(timestamp2, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canInsertTimestampWithNowAndNsOffsetInBothFirstAndSecondCol() { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(now + 1000b, now - 1000b, 128)"); - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather"); - checkCount(3l, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canIntervalAndSlidingAcceptNsUnitForFirstCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select sum(f1) from " + ns_timestamp_db + ".weather where ts >= '" + date2 + "' and ts <= '" + date3 + "' interval(10000000b) sliding(10000000b)"); - rs.next(); - long sum = rs.getLong(2); - Assert.assertEquals(127l, sum); - rs.next(); - sum = rs.getLong(2); - Assert.assertEquals(128l, sum); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void canIntervalAndSlidingAcceptNsUnitForSecondCol() { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select sum(f1) from " + ns_timestamp_db + ".weather where ts2 >= '" + date2 + "' and ts <= '" + date3 + "' interval(10000000b) sliding(10000000b)"); - rs.next(); - long sum = rs.getLong(2); - Assert.assertEquals(127l, sum); - rs.next(); - sum = rs.getLong(2); - Assert.assertEquals(128l, sum); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test(expected = SQLException.class) - public void testDataOutOfRangeExceptionForFirstCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(123456789012345678, 1234567890123456789, 127)"); - } - } - - @Test(expected = SQLException.class) - public void testDataOutOfRangeExceptionForSecondCol() throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(1234567890123456789, 123456789012345678, 127)"); - } - } - - @Test - public void willAutomaticallyFillToNsUnitWithZerosForFirstCol() { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "', '" + date1 + "', 127)"); - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date1 + "000000'"); - checkCount(1l, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void willAutomaticallyFillToNsUnitWithZerosForSecondCol() { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "', '" + date1 + "', 127)"); - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "000000'"); - checkCount(1l, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void willAutomaticallyDropDigitExceedNsDigitNumberForFirstCol() { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "999999999', '" + date1 + "999999999', 127)"); - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date1 + "999999'"); - checkCount(1l, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Test - public void willAutomaticallyDropDigitExceedNsDigitNumberForSecondCol() { - try (Statement stmt = conn.createStatement()) { - stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "999999999', '" + date1 + "999999999', 127)"); - ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "999999'"); - checkCount(1l, rs); - } catch (SQLException e) { - e.printStackTrace(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/UnsignedNumberJniTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/UnsignedNumberJniTest.java deleted file mode 100644 index cff353093a..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/UnsignedNumberJniTest.java +++ /dev/null @@ -1,167 +0,0 @@ -package com.taosdata.jdbc.cases; - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.*; -import org.junit.runners.MethodSorters; - -import java.sql.*; -import java.util.Properties; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class UnsignedNumberJniTest { - - private static final String host = "127.0.0.1"; - private static Connection conn; - private static long ts; - - @Test - public void testCase001() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from us_table"); - ResultSetMetaData meta = rs.getMetaData(); - assertResultSetMetaData(meta); - while (rs.next()) { - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals("127", rs.getString(2)); - Assert.assertEquals("32767", rs.getString(3)); - Assert.assertEquals("2147483647", rs.getString(4)); - Assert.assertEquals("9223372036854775807", rs.getString(5)); - } - } - } - - @Test - public void testCase002() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from us_table"); - ResultSetMetaData meta = rs.getMetaData(); - assertResultSetMetaData(meta); - - while (rs.next()) { - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(127, rs.getByte(2)); - Assert.assertEquals(32767, rs.getShort(3)); - Assert.assertEquals(2147483647, rs.getInt(4)); - Assert.assertEquals(9223372036854775807L, rs.getLong(5)); - } - } - } - - @Test(expected = SQLException.class) - public void testCase003() throws SQLException { - try (Statement stmt = conn.createStatement()) { - long now = System.currentTimeMillis(); - stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + now + ", 127, 32767,2147483647, 18446744073709551614)"); - ResultSet rs = stmt.executeQuery("select * from us_table where ts = " + now); - ResultSetMetaData meta = rs.getMetaData(); - assertResultSetMetaData(meta); - while (rs.next()) { - Assert.assertEquals(now, rs.getTimestamp(1).getTime()); - Assert.assertEquals(127, rs.getByte(2)); - Assert.assertEquals(32767, rs.getShort(3)); - Assert.assertEquals(2147483647, rs.getInt(4)); - Assert.assertEquals("18446744073709551614", rs.getString(5)); - rs.getLong(5); - } - } - } - - @Test(expected = SQLException.class) - public void testCase004() throws SQLException { - try (Statement stmt = conn.createStatement()) { - long now = System.currentTimeMillis(); - stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + now + ", 127, 32767,4294967294, 18446744073709551614)"); - ResultSet rs = stmt.executeQuery("select * from us_table where ts = " + now); - ResultSetMetaData meta = rs.getMetaData(); - assertResultSetMetaData(meta); - - while (rs.next()) { - Assert.assertEquals(now, rs.getTimestamp(1).getTime()); - Assert.assertEquals(127, rs.getByte(2)); - Assert.assertEquals(32767, rs.getShort(3)); - Assert.assertEquals("4294967294", rs.getString(4)); - Assert.assertEquals("18446744073709551614", rs.getString(5)); - rs.getInt(4); - } - } - } - - @Test(expected = SQLException.class) - public void testCase005() throws SQLException { - try (Statement stmt = conn.createStatement()) { - long now = System.currentTimeMillis(); - stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + now + ", 127, 65534,4294967294, 18446744073709551614)"); - ResultSet rs = stmt.executeQuery("select * from us_table where ts = " + now); - ResultSetMetaData meta = rs.getMetaData(); - assertResultSetMetaData(meta); - - while (rs.next()) { - Assert.assertEquals(now, rs.getTimestamp(1).getTime()); - Assert.assertEquals(127, rs.getByte(2)); - Assert.assertEquals("65534", rs.getString(3)); - Assert.assertEquals("4294967294", rs.getString(4)); - Assert.assertEquals("18446744073709551614", rs.getString(5)); - rs.getShort(3); - } - } - } - - @Test(expected = SQLException.class) - public void testCase006() throws SQLException { - try (Statement stmt = conn.createStatement()) { - long now = System.currentTimeMillis(); - stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + now + ", 254, 65534,4294967294, 18446744073709551614)"); - ResultSet rs = stmt.executeQuery("select * from us_table where ts = " + now); - ResultSetMetaData meta = rs.getMetaData(); - assertResultSetMetaData(meta); - - while (rs.next()) { - Assert.assertEquals(now, rs.getTimestamp(1).getTime()); - Assert.assertEquals("254", rs.getString(2)); - Assert.assertEquals("65534", rs.getString(3)); - Assert.assertEquals("4294967294", rs.getString(4)); - Assert.assertEquals("18446744073709551614", rs.getString(5)); - rs.getByte(2); - } - } - } - - private void assertResultSetMetaData(ResultSetMetaData meta) throws SQLException { - Assert.assertEquals(5, meta.getColumnCount()); - Assert.assertEquals("ts", meta.getColumnLabel(1)); - Assert.assertEquals("f1", meta.getColumnLabel(2)); - Assert.assertEquals("f2", meta.getColumnLabel(3)); - Assert.assertEquals("f3", meta.getColumnLabel(4)); - Assert.assertEquals("f4", meta.getColumnLabel(5)); - } - - @BeforeClass - public static void beforeClass() throws SQLException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - ts = System.currentTimeMillis(); - - final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - conn = DriverManager.getConnection(url, properties); - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists unsign_jni"); - stmt.execute("create database if not exists unsign_jni"); - stmt.execute("use unsign_jni"); - stmt.execute("create table us_table(ts timestamp, f1 tinyint unsigned, f2 smallint unsigned, f3 int unsigned, f4 bigint unsigned)"); - stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + ts + ", 127, 32767,2147483647, 9223372036854775807)"); - stmt.close(); - } - - @AfterClass - public static void afterClass() throws SQLException { - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists unsign_jni"); - statement.close(); - conn.close(); - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/UnsignedNumberRestfulTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/UnsignedNumberRestfulTest.java deleted file mode 100644 index b3ca6871db..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/UnsignedNumberRestfulTest.java +++ /dev/null @@ -1,177 +0,0 @@ -package com.taosdata.jdbc.cases; - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.*; -import org.junit.runners.MethodSorters; - -import java.sql.*; -import java.util.Properties; - - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class UnsignedNumberRestfulTest { - - private static final String host = "127.0.0.1"; - private static Connection conn; - private static long ts; - private static final String dbname = "unsign_restful"; - - @Test - public void testCase001() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from us_table"); - ResultSetMetaData meta = rs.getMetaData(); - assertResultSetMetaData(meta); - while (rs.next()) { - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals("127", rs.getString(2)); - Assert.assertEquals("32767", rs.getString(3)); - Assert.assertEquals("2147483647", rs.getString(4)); - Assert.assertEquals("9223372036854775807", rs.getString(5)); - } - } - } - - @Test - public void testCase002() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select * from us_table"); - ResultSetMetaData meta = rs.getMetaData(); - assertResultSetMetaData(meta); - - while (rs.next()) { - Assert.assertEquals(ts, rs.getTimestamp(1).getTime()); - Assert.assertEquals(127, rs.getByte(2)); - Assert.assertEquals(32767, rs.getShort(3)); - Assert.assertEquals(2147483647, rs.getInt(4)); - Assert.assertEquals(9223372036854775807L, rs.getLong(5)); - } - } - } - - @Test(expected = SQLException.class) - public void testCase003() throws SQLException { - try (Statement stmt = conn.createStatement()) { - long now = System.currentTimeMillis(); - stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + now + ", 127, 32767,2147483647, 18446744073709551614)"); - ResultSet rs = stmt.executeQuery("select * from us_table where ts = " + now); - ResultSetMetaData meta = rs.getMetaData(); - assertResultSetMetaData(meta); - while (rs.next()) { - Assert.assertEquals(now, rs.getTimestamp(1).getTime()); - Assert.assertEquals(127, rs.getByte(2)); - Assert.assertEquals(32767, rs.getShort(3)); - Assert.assertEquals(2147483647, rs.getInt(4)); - Assert.assertEquals("18446744073709551614", rs.getString(5)); - rs.getLong(5); - } - } - } - - @Test(expected = SQLException.class) - public void testCase004() throws SQLException { - try (Statement stmt = conn.createStatement()) { - long now = System.currentTimeMillis(); - stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + now + ", 127, 32767,4294967294, 18446744073709551614)"); - ResultSet rs = stmt.executeQuery("select * from us_table where ts = " + now); - ResultSetMetaData meta = rs.getMetaData(); - assertResultSetMetaData(meta); - - while (rs.next()) { - Assert.assertEquals(now, rs.getTimestamp(1).getTime()); - Assert.assertEquals(127, rs.getByte(2)); - Assert.assertEquals(32767, rs.getShort(3)); - Assert.assertEquals("4294967294", rs.getString(4)); - Assert.assertEquals("18446744073709551614", rs.getString(5)); - rs.getInt(4); - } - } - } - - @Test(expected = SQLException.class) - public void testCase005() throws SQLException { - try (Statement stmt = conn.createStatement()) { - long now = System.currentTimeMillis(); - stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + now + ", 127, 65534,4294967294, 18446744073709551614)"); - ResultSet rs = stmt.executeQuery("select * from us_table where ts = " + now); - ResultSetMetaData meta = rs.getMetaData(); - assertResultSetMetaData(meta); - - while (rs.next()) { - Assert.assertEquals(now, rs.getTimestamp(1).getTime()); - Assert.assertEquals(127, rs.getByte(2)); - Assert.assertEquals("65534", rs.getString(3)); - Assert.assertEquals("4294967294", rs.getString(4)); - Assert.assertEquals("18446744073709551614", rs.getString(5)); - rs.getShort(3); - } - } - } - - @Test(expected = SQLException.class) - public void testCase006() throws SQLException { - try (Statement stmt = conn.createStatement()) { - long now = System.currentTimeMillis(); - stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + now + ", 254, 65534,4294967294, 18446744073709551614)"); - ResultSet rs = stmt.executeQuery("select * from us_table where ts = " + now); - ResultSetMetaData meta = rs.getMetaData(); - assertResultSetMetaData(meta); - - while (rs.next()) { - Assert.assertEquals(now, rs.getTimestamp(1).getTime()); - Assert.assertEquals("254", rs.getString(2)); - Assert.assertEquals("65534", rs.getString(3)); - Assert.assertEquals("4294967294", rs.getString(4)); - Assert.assertEquals("18446744073709551614", rs.getString(5)); - rs.getByte(2); - } - } - } - - private void assertResultSetMetaData(ResultSetMetaData meta) throws SQLException { - Assert.assertEquals(5, meta.getColumnCount()); - Assert.assertEquals("ts", meta.getColumnLabel(1)); - Assert.assertEquals("f1", meta.getColumnLabel(2)); - Assert.assertEquals("f2", meta.getColumnLabel(3)); - Assert.assertEquals("f3", meta.getColumnLabel(4)); - Assert.assertEquals("f4", meta.getColumnLabel(5)); - } - - @BeforeClass - public static void beforeClass() { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - ts = System.currentTimeMillis(); - - try { - final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - conn = DriverManager.getConnection(url, properties); - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table us_table(ts timestamp, f1 tinyint unsigned, f2 smallint unsigned, f3 int unsigned, f4 bigint unsigned)"); - stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + ts + ", 127, 32767,2147483647, 9223372036854775807)"); - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @AfterClass - public static void afterClass() { - try { - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists " + dbname); - statement.close(); - conn.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/UseNowInsertTimestampTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/UseNowInsertTimestampTest.java deleted file mode 100644 index c4f2cba446..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/UseNowInsertTimestampTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.taosdata.jdbc.cases; - -import org.junit.AfterClass; -import org.junit.Test; - -import java.sql.*; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class UseNowInsertTimestampTest { - private static String url = "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata"; - - @Test - public void millisec() throws SQLException { - try (Connection conn = DriverManager.getConnection(url)) { - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists test"); - stmt.execute("create database if not exists test precision 'ms'"); - stmt.execute("use test"); - stmt.execute("create table weather(ts timestamp, f1 int)"); - stmt.execute("insert into weather values(now, 1)"); - - ResultSet rs = stmt.executeQuery("select * from weather"); - rs.next(); - Timestamp ts = rs.getTimestamp("ts"); - assertEquals(13, Long.toString(ts.getTime()).length()); - - int nanos = ts.getNanos(); - assertEquals(0, nanos % 1000_000); - - stmt.execute("drop database if exists test"); - } - } - - @Test - public void microsec() throws SQLException { - try (Connection conn = DriverManager.getConnection(url)) { - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists test"); - stmt.execute("create database if not exists test precision 'us'"); - stmt.execute("use test"); - stmt.execute("create table weather(ts timestamp, f1 int)"); - stmt.execute("insert into weather values(now, 1)"); - - ResultSet rs = stmt.executeQuery("select * from weather"); - rs.next(); - Timestamp ts = rs.getTimestamp("ts"); - int nanos = ts.getNanos(); - - assertEquals(0, nanos % 1000); - - stmt.execute("drop database if exists test"); - } - } - - @Test - public void nanosec() throws SQLException { - long now_time = System.currentTimeMillis() * 1000_000L + System.nanoTime() % 1000_000L; - try (Connection conn = DriverManager.getConnection(url)) { - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists test"); - stmt.execute("create database if not exists test precision 'ns'"); - stmt.execute("use test"); - stmt.execute("create table weather(ts timestamp, f1 int)"); - stmt.execute("insert into weather values(" + now_time + ", 1)"); - - ResultSet rs = stmt.executeQuery("select * from weather"); - rs.next(); - - Timestamp ts = rs.getTimestamp("ts"); - - int nanos = ts.getNanos(); - assertTrue(nanos % 1000 != 0); - - stmt.execute("drop database if exists test"); - } - } - - @AfterClass - public static void afterClass() { - try (Connection conn = DriverManager.getConnection(url); - Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists test"); - } catch (SQLException e) { - e.printStackTrace(); - } - - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/BadLocaleSettingTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/BadLocaleSettingTest.java deleted file mode 100644 index 7ad7c23136..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/BadLocaleSettingTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.taosdata.jdbc.confprops; - - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Properties; - -public class BadLocaleSettingTest { - - private static final String host = "127.0.0.1"; - private static final String dbName = "bad_locale_test"; - private static Connection conn; - - @Test - public void canSetLocale() throws SQLException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - - String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - conn = DriverManager.getConnection(url, properties); - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbName); - stmt.execute("create database if not exists " + dbName); - stmt.execute("use " + dbName); - stmt.execute("drop table if exists weather"); - stmt.execute("create table weather(ts timestamp, temperature float, humidity int)"); - stmt.executeUpdate("insert into weather values(1624071506435, 12.3, 4)"); - stmt.close(); - } - - @BeforeClass - public static void beforeClass() { - System.setProperty("sun.jnu.encoding", "ANSI_X3.4-1968"); - System.setProperty("file.encoding", "ANSI_X3.4-1968"); - } - - @AfterClass - public static void afterClass() throws SQLException { - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database " + dbName); - statement.close(); - conn.close(); - } - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/BatchFetchTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/BatchFetchTest.java deleted file mode 100644 index 94a5382410..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/BatchFetchTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.taosdata.jdbc.confprops; - -import org.junit.*; -import org.junit.runners.MethodSorters; - -import java.sql.*; -import java.util.Random; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class BatchFetchTest { - - private static String host = "127.0.0.1"; - private long rowFetchCost, batchFetchCost; - - @Test - public void case01_rowFetch() throws SQLException { - String url = "jdbc:TAOS://" + host + ":6030/test?user=root&password=taosdata"; - try (Connection conn = DriverManager.getConnection(url); - Statement stmt = conn.createStatement()) { - - boolean batchfetch = Boolean.parseBoolean(conn.getClientInfo("batchfetch")); - Assert.assertFalse(batchfetch); - - long start = System.currentTimeMillis(); - ResultSet rs = stmt.executeQuery("select * from weather"); - while (rs.next()) { - } - long end = System.currentTimeMillis(); - rowFetchCost = end - start; - } - } - - @Test - public void case02_batchFetch() throws SQLException { - String url = "jdbc:TAOS://" + host + ":6030/test?user=root&password=taosdata&batchfetch=true"; - try (Connection conn = DriverManager.getConnection(url); - Statement stmt = conn.createStatement()) { - - boolean batchfetch = Boolean.parseBoolean(conn.getClientInfo("batchfetch")); - Assert.assertTrue(batchfetch); - - long start = System.currentTimeMillis(); - ResultSet rs = stmt.executeQuery("select * from weather"); - while (rs.next()) { - } - long end = System.currentTimeMillis(); - batchFetchCost = end - start; - } - } - - @Test - public void case03_batchFetchFastThanRowFetch() { - Assert.assertTrue(rowFetchCost - batchFetchCost >= 0); - } - - @BeforeClass - public static void beforeClass() throws SQLException { - String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - try (Connection conn = DriverManager.getConnection(url); - Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists test"); - stmt.execute("create database if not exists test"); - stmt.execute("use test"); - stmt.execute("create table weather(ts timestamp, f int) tags(t int)"); - for (int i = 0; i < 1000; i++) { - stmt.execute(generateSql(100, 100)); - } - } - } - - private static String generateSql(int tableSize, int valueSize) { - Random random = new Random(System.currentTimeMillis()); - StringBuilder builder = new StringBuilder("insert into "); - for (int i = 0; i < tableSize; i++) { - builder.append("t" + i).append(" using weather tags(").append(random.nextInt(100)).append(") values"); - for (int j = 0; j < valueSize; j++) { - builder.append(" (now + ").append(i).append("s, ").append(random.nextInt(100)).append(")"); - } - } - return builder.toString(); - } - - @AfterClass - public static void afterClass(){ - String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - try (Connection conn = DriverManager.getConnection(url); - Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists test"); - } catch (SQLException e) { - e.printStackTrace(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/CharsetTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/CharsetTest.java deleted file mode 100644 index 41629189ae..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/CharsetTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.taosdata.jdbc.confprops; - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; - -public class CharsetTest { - private static final String host = "127.0.0.1"; - - @Test - public void test() throws SQLException { - // given - String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - Properties props = new Properties(); - props.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - - try (Connection conn = DriverManager.getConnection(url, props); - Statement stmt = conn.createStatement()) { - - // when - stmt.execute("drop database if exists test"); - stmt.execute("create database if not exists test"); - stmt.execute("use test"); - stmt.execute("create table weather(ts timestamp, temperature nchar(10))"); - stmt.execute("insert into weather values(now, '北京')"); - - // then - ResultSet rs = stmt.executeQuery("select * from weather"); - while (rs.next()) { - Object value = rs.getObject("temperature"); - Assert.assertTrue(value instanceof String); - Assert.assertEquals("北京", value.toString()); - } - } - } - - @AfterClass - public static void afterClass(){ - String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - Properties props = new Properties(); - props.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - - try (Connection conn = DriverManager.getConnection(url, props); - Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists test"); - } catch (SQLException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/HttpKeepAliveTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/HttpKeepAliveTest.java deleted file mode 100644 index 33c6a60627..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/HttpKeepAliveTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.taosdata.jdbc.confprops; - -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -@Ignore -public class HttpKeepAliveTest { - - private static final String host = "127.0.0.1"; - - @Test - public void test() throws SQLException { - //given - int multi = 4000; - AtomicInteger exceptionCount = new AtomicInteger(); - - //when - Properties props = new Properties(); - props.setProperty("httpKeepAlive", "false"); - props.setProperty("httpPoolSize", "20"); - Connection connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata", props); - - List threads = IntStream.range(0, multi).mapToObj(i -> new Thread( - () -> { - try (Statement stmt = connection.createStatement()) { - stmt.execute("insert into log.tb_not_exists values(now, 1)"); - stmt.execute("select last(*) from log.dn"); - } catch (SQLException throwables) { - exceptionCount.getAndIncrement(); - } - } - )).collect(Collectors.toList()); - - threads.forEach(Thread::start); - - for (Thread thread : threads) { - try { - thread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - //then - Assert.assertEquals(multi, exceptionCount.get()); - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TaosInfoMonitorTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TaosInfoMonitorTest.java deleted file mode 100644 index 4a919db6f4..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TaosInfoMonitorTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.taosdata.jdbc.confprops; - -import org.junit.Assert; -import org.junit.Test; - -import java.sql.*; -import java.util.List; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -public class TaosInfoMonitorTest { - - private static final String host = "127.0.0.1"; - private Random random = new Random(System.currentTimeMillis()); - - @Test - public void testCreateTooManyConnection() throws InterruptedException { - - List threads = IntStream.range(1, 11).mapToObj(i -> new Thread(() -> { - final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - - int connSize = random.nextInt(10); - for (int j = 0; j < connSize; j++) { - - try { - Connection conn = DriverManager.getConnection(url); - TimeUnit.MILLISECONDS.sleep(random.nextInt(3000)); - - int stmtSize = random.nextInt(100); - for (int k = 0; k < stmtSize; k++) { - Statement stmt = conn.createStatement(); - TimeUnit.MILLISECONDS.sleep(random.nextInt(3000)); - - ResultSet rs = stmt.executeQuery("show databases"); - while (rs.next()) { - } - rs.close(); - stmt.close(); - } - } catch (SQLException | InterruptedException throwables) { - Assert.fail(); - } - } - }, "thread-" + i)).collect(Collectors.toList()); - - threads.forEach(Thread::start); - - for (Thread thread : threads) { - thread.join(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TimeZoneTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TimeZoneTest.java deleted file mode 100644 index bc19e63ba6..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TimeZoneTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.taosdata.jdbc.confprops; - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.Test; - -import java.sql.*; -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Properties; - -public class TimeZoneTest { - - private String url = "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata"; - - @Test - public void javaTimeZone() { - LocalDateTime localDateTime = LocalDateTime.of(1970, 1, 1, 0, 0, 0); - - Instant instant = localDateTime.atZone(ZoneId.of("UTC-8")).toInstant(); - System.out.println("UTC-8: " + instant.getEpochSecond() + "," + instant); - - instant = localDateTime.atZone(ZoneId.of("UT")).toInstant(); - System.out.println("UTC: " + instant.getEpochSecond() + "," + instant); - - - instant = localDateTime.atZone(ZoneId.of("UTC+8")).toInstant(); - System.out.println("UTC+8: " + instant.getEpochSecond() + "," + instant); - } - - @Test - public void taosTimeZone() throws SQLException { - // given - Properties props = new Properties(); - props.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - - // when and then - try (Connection connection = DriverManager.getConnection(url, props)) { - Statement stmt = connection.createStatement(); - - stmt.execute("drop database if exists timezone_test"); - stmt.execute("create database if not exists timezone_test keep 36500"); - stmt.execute("use timezone_test"); - stmt.execute("create table weather(ts timestamp, temperature float)"); - - stmt.execute("insert into timezone_test.weather(ts, temperature) values('1970-01-01 00:00:00', 1.0)"); - - ResultSet rs = stmt.executeQuery("select * from timezone_test.weather"); - while (rs.next()) { - Timestamp ts = rs.getTimestamp("ts"); - System.out.println("ts: " + ts.getTime() + "," + ts); - } - - stmt.execute("insert into timezone_test.weather(ts, temperature) values('1970-01-02 00:00:00', 1.0)"); - - rs = stmt.executeQuery("select * from timezone_test.weather"); - while (rs.next()) { - Timestamp ts = rs.getTimestamp("ts"); - System.out.println("ts: " + ts.getTime() + "," + ts); - } - - - stmt.execute("drop database if exists timezone_test"); - - stmt.close(); - } - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TimestampFormatTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TimestampFormatTest.java deleted file mode 100644 index a6f8cf7c0a..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TimestampFormatTest.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.taosdata.jdbc.confprops; - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.*; - -import java.sql.*; -import java.time.Instant; -import java.util.Calendar; -import java.util.Properties; - -public class TimestampFormatTest { - private static final String host = "127.0.0.1"; - private long ts = Instant.now().toEpochMilli(); - private Connection conn; - - @Test - public void string() throws SQLException { - // given - String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - - // when - try (Connection conn = DriverManager.getConnection(url); - Statement stmt = conn.createStatement()) { - // then - String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT); - Assert.assertEquals("STRING", actual); - - ResultSet rs = stmt.executeQuery("select * from test.weather"); - while (rs.next()) { - String value = rs.getString("ts"); - String expect = new Timestamp(ts).toString(); - Assert.assertEquals(expect, value); - } - } - } - - @Test - public void stringInProperties() throws SQLException { - // given - String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - - // when - String timestampFormat = "STRING"; - Properties props = new Properties(); - props.setProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, timestampFormat); - try (Connection conn = DriverManager.getConnection(url, props); - Statement stmt = conn.createStatement()) { - - // then - String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT); - Assert.assertEquals(timestampFormat, actual); - - ResultSet rs = stmt.executeQuery("select * from test.weather"); - while (rs.next()) { - String value = rs.getString("ts"); - String expect = new Timestamp(ts).toString(); - Assert.assertEquals(expect, value); - } - } - } - - @Test - public void timestampInUrl() throws SQLException { - // given - String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata×tampFormat="; - String timestampFormat = "TIMESTAMP"; - - // when - try (Connection conn = DriverManager.getConnection(url + timestampFormat); - Statement stmt = conn.createStatement()) { - // then - String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT); - Assert.assertEquals(timestampFormat, actual); - - ResultSet rs = stmt.executeQuery("select * from test.weather"); - while (rs.next()) { - Object value = rs.getObject("ts"); - String expect = new Timestamp(ts).toString(); - Assert.assertEquals(expect, value.toString()); - } - } - } - - @Test - public void timestampInProperties() throws SQLException { - // given - String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - String timestampFormat = "TIMESTAMP"; - - // when - Properties props = new Properties(); - props.setProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, timestampFormat); - try (Connection conn = DriverManager.getConnection(url, props); - Statement stmt = conn.createStatement()) { - // then - String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT); - Assert.assertEquals(timestampFormat, actual); - - ResultSet rs = stmt.executeQuery("select * from test.weather"); - while (rs.next()) { - Object value = rs.getObject("ts"); - String expect = new Timestamp(ts).toString(); - Assert.assertEquals(expect, value.toString()); - } - } - } - - @Test - public void utcInUrl() throws SQLException { - // given - String timestampFormat = "UTC"; - String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata×tampFormat=" + timestampFormat; - - // when & then - try (Connection conn = DriverManager.getConnection(url); - Statement stmt = conn.createStatement()) { - String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT); - Assert.assertEquals(timestampFormat, actual); - ResultSet rs = stmt.executeQuery("select * from test.weather"); - while (rs.next()) { - Object value = rs.getObject("ts"); - Assert.assertTrue(value instanceof Timestamp); - String expect = new Timestamp(ts).toString(); - Assert.assertEquals(expect, value.toString()); - } - } - } - - @Test - public void utcInProperties() throws SQLException { - // given - String timestampFormat = "UTC"; - String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - - // when - Properties props = new Properties(); - props.setProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, timestampFormat); - try (Connection conn = DriverManager.getConnection(url, props); - Statement stmt = conn.createStatement()) { - - // then - String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT); - Assert.assertEquals(timestampFormat, actual); - ResultSet rs = stmt.executeQuery("select * from test.weather"); - while (rs.next()) { - Object value = rs.getObject("ts"); - Assert.assertTrue(value instanceof Timestamp); - String expect = new Timestamp(ts).toString(); - Assert.assertEquals(expect, value.toString()); - } - } - } - - @Before - public void before() throws SQLException { - String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - conn = DriverManager.getConnection(url); - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists test"); - stmt.execute("create database if not exists test"); - stmt.execute("use test"); - stmt.execute("create table weather(ts timestamp, temperature nchar(10))"); - stmt.execute("insert into weather values(" + ts + ", '北京')"); - stmt.close(); - } - - @After - public void after() { - try { - if (null != conn) { - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists test"); - stmt.close(); - conn.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/DatabaseSpecifiedTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/DatabaseSpecifiedTest.java deleted file mode 100644 index 0a37e255a4..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/DatabaseSpecifiedTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.taosdata.jdbc.rs; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.sql.*; - -import static org.junit.Assert.*; - -public class DatabaseSpecifiedTest { - - private static String host = "127.0.0.1"; - private static String dbname = "test_db_spec"; - - private Connection connection; - private long ts; - - @Test - public void test() throws SQLException { - // when - connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/" + dbname + "?user=root&password=taosdata"); - try (Statement stmt = connection.createStatement();) { - ResultSet rs = stmt.executeQuery("select * from weather"); - - //then - assertNotNull(rs); - rs.next(); - long now = rs.getTimestamp("ts").getTime(); - assertEquals(ts, now); - int f1 = rs.getInt(2); - assertEquals(1, f1); - String loc = rs.getString("loc"); - assertEquals("beijing", loc); - } - } - - @Before - public void before() { - ts = System.currentTimeMillis(); - try { - Connection connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); - Statement stmt = connection.createStatement(); - - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))"); - stmt.execute("insert into t1 using weather tags('beijing') values( " + ts + ", 1)"); - - stmt.close(); - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @After - public void after() { - try { - if (connection != null) { - Statement statement = connection.createStatement(); - statement.execute("drop database if exists " + dbname); - statement.close(); - connection.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulConnectionTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulConnectionTest.java deleted file mode 100644 index e4785a197e..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulConnectionTest.java +++ /dev/null @@ -1,394 +0,0 @@ -package com.taosdata.jdbc.rs; - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; - -public class RestfulConnectionTest { - - private static final String host = "127.0.0.1"; - - private static Connection conn; - - @Test - public void getConnection() { - // already test in beforeClass method - } - - @Test - public void createStatement() throws SQLException { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("select server_status()"); - rs.next(); - int status = rs.getInt("server_status()"); - assertEquals(1, status); - } - } - - @Test - public void prepareStatement() throws SQLException { - PreparedStatement pstmt = conn.prepareStatement("select server_status()"); - ResultSet rs = pstmt.executeQuery(); - rs.next(); - int status = rs.getInt("server_status()"); - assertEquals(1, status); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void prepareCall() throws SQLException { - conn.prepareCall("select server_status()"); - } - - @Test - public void nativeSQL() throws SQLException { - String nativeSQL = conn.nativeSQL("select * from log.log"); - assertEquals("select * from log.log", nativeSQL); - } - - @Test - public void setAutoCommit() throws SQLException { - conn.setAutoCommit(true); - conn.setAutoCommit(false); - } - - @Test - public void getAutoCommit() throws SQLException { - Assert.assertTrue(conn.getAutoCommit()); - } - - @Test - public void commit() throws SQLException { - conn.commit(); - } - - @Test - public void rollback() throws SQLException { - conn.rollback(); - } - - @Test - public void close() { - // connection will close in afterClass method - } - - @Test - public void isClosed() throws SQLException { - Assert.assertFalse(conn.isClosed()); - } - - @Test - public void getMetaData() throws SQLException { - DatabaseMetaData meta = conn.getMetaData(); - Assert.assertNotNull(meta); - assertEquals("com.taosdata.jdbc.rs.RestfulDriver", meta.getDriverName()); - } - - @Test - public void setReadOnly() throws SQLException { - conn.setReadOnly(true); - } - - @Test - public void isReadOnly() throws SQLException { - Assert.assertTrue(conn.isReadOnly()); - } - - @Test - public void setCatalog() throws SQLException { - conn.setCatalog("test"); - assertEquals("test", conn.getCatalog()); - } - - @Test - public void getCatalog() throws SQLException { - conn.setCatalog("log"); - assertEquals("log", conn.getCatalog()); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setTransactionIsolation() throws SQLException { - conn.setTransactionIsolation(Connection.TRANSACTION_NONE); - assertEquals(Connection.TRANSACTION_NONE, conn.getTransactionIsolation()); - conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); - } - - @Test - public void getTransactionIsolation() throws SQLException { - assertEquals(Connection.TRANSACTION_NONE, conn.getTransactionIsolation()); - } - - @Test - public void getWarnings() throws SQLException { - Assert.assertNull(conn.getWarnings()); - } - - @Test - public void clearWarnings() throws SQLException { - conn.clearWarnings(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testCreateStatement() throws SQLException { - Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - ResultSet rs = stmt.executeQuery("select server_status()"); - rs.next(); - int status = rs.getInt("server_status()"); - assertEquals(1, status); - - conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testPrepareStatement() throws SQLException { - PreparedStatement pstmt = conn.prepareStatement("select server_status()", - ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - ResultSet rs = pstmt.executeQuery(); - rs.next(); - int status = rs.getInt("server_status()"); - assertEquals(1, status); - - conn.prepareStatement("select server_status", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testPrepareCall() throws SQLException { - conn.prepareCall("", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getTypeMap() throws SQLException { - conn.getTypeMap(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setTypeMap() throws SQLException { - conn.setTypeMap(null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setHoldability() throws SQLException { - conn.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); - assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, conn.getHoldability()); - conn.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); - } - - @Test - public void getHoldability() throws SQLException { - assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, conn.getHoldability()); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setSavepoint() throws SQLException { - conn.setSavepoint(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testSetSavepoint() throws SQLException { - conn.setSavepoint(null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testRollback() throws SQLException { - conn.rollback(null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void releaseSavepoint() throws SQLException { - conn.releaseSavepoint(null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testCreateStatement1() throws SQLException { - Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); - ResultSet rs = stmt.executeQuery("select server_status()"); - rs.next(); - int status = rs.getInt("server_status()"); - assertEquals(1, status); - - conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testPrepareStatement1() throws SQLException { - PreparedStatement pstmt = conn.prepareStatement("select server_status()", - ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); - ResultSet rs = pstmt.executeQuery(); - rs.next(); - int status = rs.getInt("server_status()"); - assertEquals(1, status); - - conn.prepareStatement("select server_status", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testPrepareCall1() throws SQLException { - conn.prepareCall("", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testPrepareStatement2() throws SQLException { - Assert.assertNotNull("", Statement.NO_GENERATED_KEYS); - conn.prepareStatement("", Statement.RETURN_GENERATED_KEYS); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testPrepareStatement3() throws SQLException { - conn.prepareStatement("", new int[]{}); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testPrepareStatement4() throws SQLException { - conn.prepareStatement("", new String[]{}); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void createClob() throws SQLException { - conn.createClob(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void createBlob() throws SQLException { - conn.createBlob(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void createNClob() throws SQLException { - conn.createNClob(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void createSQLXML() throws SQLException { - conn.createSQLXML(); - } - - @Test(expected = SQLException.class) - public void isValid() throws SQLException { - Assert.assertTrue(conn.isValid(10)); - Assert.assertTrue(conn.isValid(0)); - conn.isValid(-1); - } - - @Test - public void setClientInfo() throws SQLClientInfoException { - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_CHARSET, "en_US.UTF-8"); - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_CHARSET, "UTC-8"); - } - - @Test - public void testSetClientInfo() throws SQLClientInfoException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - conn.setClientInfo(properties); - } - - @Test - public void getClientInfo() throws SQLException { - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - - Properties info = conn.getClientInfo(); - String charset = info.getProperty(TSDBDriver.PROPERTY_KEY_CHARSET); - assertEquals("UTF-8", charset); - String locale = info.getProperty(TSDBDriver.PROPERTY_KEY_LOCALE); - assertEquals("en_US.UTF-8", locale); - String timezone = info.getProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE); - assertEquals("UTC-8", timezone); - } - - @Test - public void testGetClientInfo() throws SQLException { - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - conn.setClientInfo(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - - String charset = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_CHARSET); - assertEquals("UTF-8", charset); - String locale = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_LOCALE); - assertEquals("en_US.UTF-8", locale); - String timezone = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIME_ZONE); - assertEquals("UTC-8", timezone); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void createArrayOf() throws SQLException { - conn.createArrayOf("", null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void createStruct() throws SQLException { - conn.createStruct("", null); - } - - @Test - public void setSchema() throws SQLException { - conn.setSchema("test"); - } - - @Test - public void getSchema() throws SQLException { - Assert.assertNull(conn.getSchema()); - } - - @Test - public void abort() throws SQLException { - conn.abort(null); - } - - @Test - public void setNetworkTimeout() throws SQLException { - conn.setNetworkTimeout(null, 1000); - } - - @Test - public void getNetworkTimeout() throws SQLException { - int timeout = conn.getNetworkTimeout(); - assertEquals(0, timeout); - } - - @Test - public void unwrap() throws SQLException { - RestfulConnection restfulConnection = conn.unwrap(RestfulConnection.class); - Assert.assertNotNull(restfulConnection); - } - - @Test - public void isWrapperFor() throws SQLException { - Assert.assertTrue(conn.isWrapperFor(RestfulConnection.class)); - } - - @BeforeClass - public static void beforeClass() throws SQLException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata", properties); - // create test database for test cases - try (Statement stmt = conn.createStatement()) { - stmt.execute("create database if not exists test"); - } - - } - - @AfterClass - public static void afterClass() throws SQLException { - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists test"); - statement.close(); - conn.close(); - } - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulDatabaseMetaDataTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulDatabaseMetaDataTest.java deleted file mode 100644 index 4ac43033d6..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulDatabaseMetaDataTest.java +++ /dev/null @@ -1,1111 +0,0 @@ -package com.taosdata.jdbc.rs; - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; - -public class RestfulDatabaseMetaDataTest { - - private static final String host = "127.0.0.1"; - private static final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - private static Connection connection; - private static RestfulDatabaseMetaData metaData; - private static final String dbName = "test"; - - @Test - public void unwrap() throws SQLException { - RestfulDatabaseMetaData unwrap = metaData.unwrap(RestfulDatabaseMetaData.class); - Assert.assertNotNull(unwrap); - } - - @Test - public void isWrapperFor() throws SQLException { - Assert.assertTrue(metaData.isWrapperFor(RestfulDatabaseMetaData.class)); - } - - @Test - public void allProceduresAreCallable() throws SQLException { - Assert.assertFalse(metaData.allProceduresAreCallable()); - } - - @Test - public void allTablesAreSelectable() throws SQLException { - Assert.assertFalse(metaData.allTablesAreSelectable()); - } - - @Test - public void getURL() throws SQLException { - Assert.assertEquals(url, metaData.getURL()); - } - - @Test - public void getUserName() throws SQLException { - Assert.assertEquals("root", metaData.getUserName()); - } - - @Test - public void isReadOnly() throws SQLException { - Assert.assertFalse(metaData.isReadOnly()); - } - - @Test - public void nullsAreSortedHigh() throws SQLException { - Assert.assertFalse(metaData.nullsAreSortedHigh()); - } - - @Test - public void nullsAreSortedLow() throws SQLException { - Assert.assertTrue(metaData.nullsAreSortedLow()); - } - - @Test - public void nullsAreSortedAtStart() throws SQLException { - Assert.assertTrue(metaData.nullsAreSortedAtStart()); - } - - @Test - public void nullsAreSortedAtEnd() throws SQLException { - Assert.assertFalse(metaData.nullsAreSortedAtEnd()); - } - - @Test - public void getDatabaseProductName() throws SQLException { - Assert.assertEquals("TDengine", metaData.getDatabaseProductName()); - } - - @Test - public void getDatabaseProductVersion() throws SQLException { - Assert.assertEquals("2.0.x.x", metaData.getDatabaseProductVersion()); - } - - @Test - public void getDriverName() throws SQLException { - Assert.assertEquals("com.taosdata.jdbc.rs.RestfulDriver", metaData.getDriverName()); - } - - @Test - public void getDriverVersion() throws SQLException { - Assert.assertEquals("2.0.x", metaData.getDriverVersion()); - } - - @Test - public void getDriverMajorVersion() { - Assert.assertEquals(2, metaData.getDriverMajorVersion()); - } - - @Test - public void getDriverMinorVersion() { - Assert.assertEquals(0, metaData.getDriverMinorVersion()); - } - - @Test - public void usesLocalFiles() throws SQLException { - Assert.assertFalse(metaData.usesLocalFiles()); - } - - @Test - public void usesLocalFilePerTable() throws SQLException { - Assert.assertFalse(metaData.usesLocalFilePerTable()); - } - - @Test - public void supportsMixedCaseIdentifiers() throws SQLException { - Assert.assertFalse(metaData.supportsMixedCaseIdentifiers()); - } - - @Test - public void storesUpperCaseIdentifiers() throws SQLException { - Assert.assertFalse(metaData.storesUpperCaseIdentifiers()); - } - - @Test - public void storesLowerCaseIdentifiers() throws SQLException { - Assert.assertTrue(metaData.storesLowerCaseIdentifiers()); - } - - @Test - public void storesMixedCaseIdentifiers() throws SQLException { - Assert.assertFalse(metaData.storesMixedCaseIdentifiers()); - } - - @Test - public void supportsMixedCaseQuotedIdentifiers() throws SQLException { - Assert.assertFalse(metaData.supportsMixedCaseQuotedIdentifiers()); - } - - @Test - public void storesUpperCaseQuotedIdentifiers() throws SQLException { - Assert.assertFalse(metaData.storesUpperCaseQuotedIdentifiers()); - } - - @Test - public void storesLowerCaseQuotedIdentifiers() throws SQLException { - Assert.assertFalse(metaData.storesLowerCaseQuotedIdentifiers()); - } - - @Test - public void storesMixedCaseQuotedIdentifiers() throws SQLException { - Assert.assertFalse(metaData.storesMixedCaseQuotedIdentifiers()); - } - - @Test - public void getIdentifierQuoteString() throws SQLException { - Assert.assertEquals(" ", metaData.getIdentifierQuoteString()); - } - - @Test - public void getSQLKeywords() throws SQLException { - Assert.assertEquals(null, metaData.getSQLKeywords()); - } - - @Test - public void getNumericFunctions() throws SQLException { - Assert.assertEquals(null, metaData.getNumericFunctions()); - } - - @Test - public void getStringFunctions() throws SQLException { - Assert.assertEquals(null, metaData.getStringFunctions()); - } - - @Test - public void getSystemFunctions() throws SQLException { - Assert.assertEquals(null, metaData.getSystemFunctions()); - } - - @Test - public void getTimeDateFunctions() throws SQLException { - Assert.assertEquals(null, metaData.getTimeDateFunctions()); - } - - @Test - public void getSearchStringEscape() throws SQLException { - Assert.assertEquals(null, metaData.getSearchStringEscape()); - } - - @Test - public void getExtraNameCharacters() throws SQLException { - Assert.assertEquals(null, metaData.getExtraNameCharacters()); - } - - @Test - public void supportsAlterTableWithAddColumn() throws SQLException { - Assert.assertTrue(metaData.supportsAlterTableWithAddColumn()); - } - - @Test - public void supportsAlterTableWithDropColumn() throws SQLException { - Assert.assertTrue(metaData.supportsAlterTableWithDropColumn()); - } - - @Test - public void supportsColumnAliasing() throws SQLException { - Assert.assertTrue(metaData.supportsColumnAliasing()); - } - - @Test - public void nullPlusNonNullIsNull() throws SQLException { - Assert.assertFalse(metaData.nullPlusNonNullIsNull()); - } - - @Test - public void supportsConvert() throws SQLException { - Assert.assertFalse(metaData.supportsConvert()); - } - - @Test - public void testSupportsConvert() throws SQLException { - Assert.assertFalse(metaData.supportsConvert(1, 1)); - } - - @Test - public void supportsTableCorrelationNames() throws SQLException { - Assert.assertFalse(metaData.supportsTableCorrelationNames()); - } - - @Test - public void supportsDifferentTableCorrelationNames() throws SQLException { - Assert.assertFalse(metaData.supportsDifferentTableCorrelationNames()); - } - - @Test - public void supportsExpressionsInOrderBy() throws SQLException { - Assert.assertFalse(metaData.supportsExpressionsInOrderBy()); - } - - @Test - public void supportsOrderByUnrelated() throws SQLException { - Assert.assertFalse(metaData.supportsOrderByUnrelated()); - } - - @Test - public void supportsGroupBy() throws SQLException { - Assert.assertTrue(metaData.supportsGroupBy()); - } - - @Test - public void supportsGroupByUnrelated() throws SQLException { - Assert.assertFalse(metaData.supportsGroupByUnrelated()); - } - - @Test - public void supportsGroupByBeyondSelect() throws SQLException { - Assert.assertFalse(metaData.supportsGroupByBeyondSelect()); - } - - @Test - public void supportsLikeEscapeClause() throws SQLException { - Assert.assertFalse(metaData.supportsLikeEscapeClause()); - } - - @Test - public void supportsMultipleResultSets() throws SQLException { - Assert.assertFalse(metaData.supportsMultipleResultSets()); - } - - @Test - public void supportsMultipleTransactions() throws SQLException { - Assert.assertFalse(metaData.supportsMultipleTransactions()); - } - - @Test - public void supportsNonNullableColumns() throws SQLException { - Assert.assertFalse(metaData.supportsNonNullableColumns()); - } - - @Test - public void supportsMinimumSQLGrammar() throws SQLException { - Assert.assertFalse(metaData.supportsMinimumSQLGrammar()); - } - - @Test - public void supportsCoreSQLGrammar() throws SQLException { - Assert.assertFalse(metaData.supportsCoreSQLGrammar()); - } - - @Test - public void supportsExtendedSQLGrammar() throws SQLException { - Assert.assertFalse(metaData.supportsExtendedSQLGrammar()); - } - - @Test - public void supportsANSI92EntryLevelSQL() throws SQLException { - Assert.assertFalse(metaData.supportsANSI92EntryLevelSQL()); - } - - @Test - public void supportsANSI92IntermediateSQL() throws SQLException { - Assert.assertFalse(metaData.supportsANSI92IntermediateSQL()); - } - - @Test - public void supportsANSI92FullSQL() throws SQLException { - Assert.assertFalse(metaData.supportsANSI92FullSQL()); - } - - @Test - public void supportsIntegrityEnhancementFacility() throws SQLException { - Assert.assertFalse(metaData.supportsIntegrityEnhancementFacility()); - } - - @Test - public void supportsOuterJoins() throws SQLException { - Assert.assertFalse(metaData.supportsOuterJoins()); - } - - @Test - public void supportsFullOuterJoins() throws SQLException { - Assert.assertFalse(metaData.supportsFullOuterJoins()); - } - - @Test - public void supportsLimitedOuterJoins() throws SQLException { - Assert.assertFalse(metaData.supportsLimitedOuterJoins()); - } - - @Test - public void getSchemaTerm() throws SQLException { - Assert.assertNull(metaData.getSchemaTerm()); - } - - @Test - public void getProcedureTerm() throws SQLException { - Assert.assertNull(metaData.getProcedureTerm()); - } - - @Test - public void getCatalogTerm() throws SQLException { - Assert.assertEquals("database", metaData.getCatalogTerm()); - } - - @Test - public void isCatalogAtStart() throws SQLException { - Assert.assertTrue(metaData.isCatalogAtStart()); - } - - @Test - public void getCatalogSeparator() throws SQLException { - Assert.assertEquals(".", metaData.getCatalogSeparator()); - } - - @Test - public void supportsSchemasInDataManipulation() throws SQLException { - Assert.assertFalse(metaData.supportsSchemasInDataManipulation()); - } - - @Test - public void supportsSchemasInProcedureCalls() throws SQLException { - Assert.assertFalse(metaData.supportsSchemasInProcedureCalls()); - } - - @Test - public void supportsSchemasInTableDefinitions() throws SQLException { - Assert.assertFalse(metaData.supportsSchemasInTableDefinitions()); - } - - @Test - public void supportsSchemasInIndexDefinitions() throws SQLException { - Assert.assertFalse(metaData.supportsSchemasInIndexDefinitions()); - } - - @Test - public void supportsSchemasInPrivilegeDefinitions() throws SQLException { - Assert.assertFalse(metaData.supportsSchemasInPrivilegeDefinitions()); - } - - @Test - public void supportsCatalogsInDataManipulation() throws SQLException { - Assert.assertTrue(metaData.supportsCatalogsInDataManipulation()); - } - - @Test - public void supportsCatalogsInProcedureCalls() throws SQLException { - Assert.assertFalse(metaData.supportsCatalogsInProcedureCalls()); - } - - @Test - public void supportsCatalogsInTableDefinitions() throws SQLException { - Assert.assertFalse(metaData.supportsCatalogsInTableDefinitions()); - } - - @Test - public void supportsCatalogsInIndexDefinitions() throws SQLException { - Assert.assertFalse(metaData.supportsCatalogsInIndexDefinitions()); - } - - @Test - public void supportsCatalogsInPrivilegeDefinitions() throws SQLException { - Assert.assertFalse(metaData.supportsCatalogsInPrivilegeDefinitions()); - } - - @Test - public void supportsPositionedDelete() throws SQLException { - Assert.assertFalse(metaData.supportsPositionedDelete()); - } - - @Test - public void supportsPositionedUpdate() throws SQLException { - Assert.assertFalse(metaData.supportsPositionedUpdate()); - } - - @Test - public void supportsSelectForUpdate() throws SQLException { - Assert.assertFalse(metaData.supportsSelectForUpdate()); - } - - @Test - public void supportsStoredProcedures() throws SQLException { - Assert.assertFalse(metaData.supportsStoredProcedures()); - } - - @Test - public void supportsSubqueriesInComparisons() throws SQLException { - Assert.assertFalse(metaData.supportsSubqueriesInComparisons()); - } - - @Test - public void supportsSubqueriesInExists() throws SQLException { - Assert.assertFalse(metaData.supportsSubqueriesInExists()); - } - - @Test - public void supportsSubqueriesInIns() throws SQLException { - Assert.assertFalse(metaData.supportsSubqueriesInIns()); - } - - @Test - public void supportsSubqueriesInQuantifieds() throws SQLException { - Assert.assertFalse(metaData.supportsSubqueriesInQuantifieds()); - } - - @Test - public void supportsCorrelatedSubqueries() throws SQLException { - Assert.assertFalse(metaData.supportsCorrelatedSubqueries()); - } - - @Test - public void supportsUnion() throws SQLException { - Assert.assertFalse(metaData.supportsUnion()); - } - - @Test - public void supportsUnionAll() throws SQLException { - Assert.assertFalse(metaData.supportsUnionAll()); - } - - @Test - public void supportsOpenCursorsAcrossCommit() throws SQLException { - Assert.assertFalse(metaData.supportsOpenCursorsAcrossCommit()); - } - - @Test - public void supportsOpenCursorsAcrossRollback() throws SQLException { - Assert.assertFalse(metaData.supportsOpenCursorsAcrossRollback()); - } - - @Test - public void supportsOpenStatementsAcrossCommit() throws SQLException { - Assert.assertFalse(metaData.supportsOpenStatementsAcrossCommit()); - } - - @Test - public void supportsOpenStatementsAcrossRollback() throws SQLException { - Assert.assertFalse(metaData.supportsOpenStatementsAcrossRollback()); - } - - @Test - public void getMaxBinaryLiteralLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxBinaryLiteralLength()); - } - - @Test - public void getMaxCharLiteralLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxCharLiteralLength()); - } - - @Test - public void getMaxColumnNameLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxColumnNameLength()); - } - - @Test - public void getMaxColumnsInGroupBy() throws SQLException { - Assert.assertEquals(0, metaData.getMaxColumnsInGroupBy()); - } - - @Test - public void getMaxColumnsInIndex() throws SQLException { - Assert.assertEquals(0, metaData.getMaxColumnsInIndex()); - } - - @Test - public void getMaxColumnsInOrderBy() throws SQLException { - Assert.assertEquals(0, metaData.getMaxColumnsInOrderBy()); - } - - @Test - public void getMaxColumnsInSelect() throws SQLException { - Assert.assertEquals(0, metaData.getMaxColumnsInSelect()); - } - - @Test - public void getMaxColumnsInTable() throws SQLException { - Assert.assertEquals(0, metaData.getMaxColumnsInTable()); - } - - @Test - public void getMaxConnections() throws SQLException { - Assert.assertEquals(0, metaData.getMaxConnections()); - } - - @Test - public void getMaxCursorNameLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxCursorNameLength()); - } - - @Test - public void getMaxIndexLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxIndexLength()); - } - - @Test - public void getMaxSchemaNameLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxSchemaNameLength()); - } - - @Test - public void getMaxProcedureNameLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxProcedureNameLength()); - } - - @Test - public void getMaxCatalogNameLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxCatalogNameLength()); - } - - @Test - public void getMaxRowSize() throws SQLException { - Assert.assertEquals(0, metaData.getMaxRowSize()); - } - - @Test - public void doesMaxRowSizeIncludeBlobs() throws SQLException { - Assert.assertFalse(metaData.doesMaxRowSizeIncludeBlobs()); - } - - @Test - public void getMaxStatementLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxStatementLength()); - } - - @Test - public void getMaxStatements() throws SQLException { - Assert.assertEquals(0, metaData.getMaxStatements()); - } - - @Test - public void getMaxTableNameLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxTableNameLength()); - } - - @Test - public void getMaxTablesInSelect() throws SQLException { - Assert.assertEquals(0, metaData.getMaxTablesInSelect()); - } - - @Test - public void getMaxUserNameLength() throws SQLException { - Assert.assertEquals(0, metaData.getMaxUserNameLength()); - } - - @Test - public void getDefaultTransactionIsolation() throws SQLException { - Assert.assertEquals(Connection.TRANSACTION_NONE, metaData.getDefaultTransactionIsolation()); - } - - @Test - public void supportsTransactions() throws SQLException { - Assert.assertFalse(metaData.supportsTransactions()); - } - - @Test - public void supportsTransactionIsolationLevel() throws SQLException { - Assert.assertTrue(metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_NONE)); - Assert.assertFalse(metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED)); - Assert.assertFalse(metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED)); - Assert.assertFalse(metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ)); - Assert.assertFalse(metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE)); - } - - @Test - public void supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { - Assert.assertFalse(metaData.supportsDataDefinitionAndDataManipulationTransactions()); - } - - @Test - public void supportsDataManipulationTransactionsOnly() throws SQLException { - Assert.assertFalse(metaData.supportsDataManipulationTransactionsOnly()); - } - - @Test - public void dataDefinitionCausesTransactionCommit() throws SQLException { - Assert.assertFalse(metaData.dataDefinitionCausesTransactionCommit()); - } - - @Test - public void dataDefinitionIgnoredInTransactions() throws SQLException { - Assert.assertFalse(metaData.dataDefinitionIgnoredInTransactions()); - } - - @Test - public void getProcedures() throws SQLException { - Assert.assertNull(metaData.getProcedures("*", "*", "*")); - } - - @Test - public void getProcedureColumns() throws SQLException { - Assert.assertNull(metaData.getProcedureColumns("*", "*", "*", "*")); - } - - @Test - public void getTables() throws SQLException { - ResultSet rs = metaData.getTables("log", "", null, null); - ResultSetMetaData meta = rs.getMetaData(); - Assert.assertNotNull(rs); - rs.next(); - { - // TABLE_CAT - Assert.assertEquals("TABLE_CAT", meta.getColumnLabel(1)); - Assert.assertEquals("log", rs.getString(1)); - Assert.assertEquals("log", rs.getString("TABLE_CAT")); - // TABLE_SCHEM - Assert.assertEquals("TABLE_SCHEM", meta.getColumnLabel(2)); - Assert.assertEquals(null, rs.getString(2)); - Assert.assertEquals(null, rs.getString("TABLE_SCHEM")); - // TABLE_NAME - Assert.assertEquals("TABLE_NAME", meta.getColumnLabel(3)); - Assert.assertNotNull(rs.getString(3)); - Assert.assertNotNull(rs.getString("TABLE_NAME")); - // TABLE_TYPE - Assert.assertEquals("TABLE_TYPE", meta.getColumnLabel(4)); - Assert.assertEquals("TABLE", rs.getString(4)); - Assert.assertEquals("TABLE", rs.getString("TABLE_TYPE")); - // REMARKS - Assert.assertEquals("REMARKS", meta.getColumnLabel(5)); - Assert.assertEquals("", rs.getString(5)); - Assert.assertEquals("", rs.getString("REMARKS")); - } - } - - @Test - public void getSchemas() throws SQLException { - Assert.assertNotNull(metaData.getSchemas()); - } - - @Test - public void getCatalogs() throws SQLException { - ResultSet rs = metaData.getCatalogs(); - ResultSetMetaData meta = rs.getMetaData(); - rs.next(); - { - // TABLE_CAT - Assert.assertEquals("TABLE_CAT", meta.getColumnLabel(1)); - Assert.assertNotNull(rs.getString(1)); - Assert.assertNotNull(rs.getString("TABLE_CAT")); - } - } - - @Test - public void getTableTypes() throws SQLException { - ResultSet tableTypes = metaData.getTableTypes(); - tableTypes.next(); - // tableTypes: table - { - Assert.assertEquals("TABLE", tableTypes.getString(1)); - Assert.assertEquals("TABLE", tableTypes.getString("TABLE_TYPE")); - } - tableTypes.next(); - // tableTypes: stable - { - Assert.assertEquals("STABLE", tableTypes.getString(1)); - Assert.assertEquals("STABLE", tableTypes.getString("TABLE_TYPE")); - } - } - - @Test - public void getColumns() throws SQLException { - // when - ResultSet columns = metaData.getColumns("log", "", "dn", ""); - // then - ResultSetMetaData meta = columns.getMetaData(); - columns.next(); - // column: 1 - { - // TABLE_CAT - Assert.assertEquals("TABLE_CAT", meta.getColumnLabel(1)); - Assert.assertEquals("log", columns.getString(1)); - Assert.assertEquals("log", columns.getString("TABLE_CAT")); - // TABLE_NAME - Assert.assertEquals("TABLE_NAME", meta.getColumnLabel(3)); - Assert.assertEquals("dn", columns.getString(3)); - Assert.assertEquals("dn", columns.getString("TABLE_NAME")); - // COLUMN_NAME - Assert.assertEquals("COLUMN_NAME", meta.getColumnLabel(4)); - Assert.assertEquals("ts", columns.getString(4)); - Assert.assertEquals("ts", columns.getString("COLUMN_NAME")); - // DATA_TYPE - Assert.assertEquals("DATA_TYPE", meta.getColumnLabel(5)); - Assert.assertEquals(Types.TIMESTAMP, columns.getInt(5)); - Assert.assertEquals(Types.TIMESTAMP, columns.getInt("DATA_TYPE")); - // TYPE_NAME - Assert.assertEquals("TYPE_NAME", meta.getColumnLabel(6)); - Assert.assertEquals("TIMESTAMP", columns.getString(6)); - Assert.assertEquals("TIMESTAMP", columns.getString("TYPE_NAME")); - // COLUMN_SIZE - Assert.assertEquals("COLUMN_SIZE", meta.getColumnLabel(7)); - Assert.assertEquals(26, columns.getInt(7)); - Assert.assertEquals(26, columns.getInt("COLUMN_SIZE")); - // DECIMAL_DIGITS - Assert.assertEquals("DECIMAL_DIGITS", meta.getColumnLabel(9)); - Assert.assertEquals(0, columns.getInt(9)); - Assert.assertEquals(0, columns.getInt("DECIMAL_DIGITS")); - Assert.assertEquals(null, columns.getString(9)); - Assert.assertEquals(null, columns.getString("DECIMAL_DIGITS")); - // NUM_PREC_RADIX - Assert.assertEquals("NUM_PREC_RADIX", meta.getColumnLabel(10)); - Assert.assertEquals(10, columns.getInt(10)); - Assert.assertEquals(10, columns.getInt("NUM_PREC_RADIX")); - // NULLABLE - Assert.assertEquals("NULLABLE", meta.getColumnLabel(11)); - Assert.assertEquals(DatabaseMetaData.columnNoNulls, columns.getInt(11)); - Assert.assertEquals(DatabaseMetaData.columnNoNulls, columns.getInt("NULLABLE")); - // REMARKS - Assert.assertEquals("REMARKS", meta.getColumnLabel(12)); - Assert.assertEquals(null, columns.getString(12)); - Assert.assertEquals(null, columns.getString("REMARKS")); - } - columns.next(); - // column: 2 - { - // TABLE_CAT - Assert.assertEquals("TABLE_CAT", meta.getColumnLabel(1)); - Assert.assertEquals("log", columns.getString(1)); - Assert.assertEquals("log", columns.getString("TABLE_CAT")); - // TABLE_NAME - Assert.assertEquals("TABLE_NAME", meta.getColumnLabel(3)); - Assert.assertEquals("dn", columns.getString(3)); - Assert.assertEquals("dn", columns.getString("TABLE_NAME")); - // COLUMN_NAME - Assert.assertEquals("COLUMN_NAME", meta.getColumnLabel(4)); - Assert.assertEquals("cpu_taosd", columns.getString(4)); - Assert.assertEquals("cpu_taosd", columns.getString("COLUMN_NAME")); - // DATA_TYPE - Assert.assertEquals("DATA_TYPE", meta.getColumnLabel(5)); - Assert.assertEquals(Types.FLOAT, columns.getInt(5)); - Assert.assertEquals(Types.FLOAT, columns.getInt("DATA_TYPE")); - // TYPE_NAME - Assert.assertEquals("TYPE_NAME", meta.getColumnLabel(6)); - Assert.assertEquals("FLOAT", columns.getString(6)); - Assert.assertEquals("FLOAT", columns.getString("TYPE_NAME")); - // COLUMN_SIZE - Assert.assertEquals("COLUMN_SIZE", meta.getColumnLabel(7)); - Assert.assertEquals(12, columns.getInt(7)); - Assert.assertEquals(12, columns.getInt("COLUMN_SIZE")); - // DECIMAL_DIGITS - Assert.assertEquals("DECIMAL_DIGITS", meta.getColumnLabel(9)); - Assert.assertEquals(0, columns.getInt(9)); - Assert.assertEquals(0, columns.getInt("DECIMAL_DIGITS")); - Assert.assertEquals(null, columns.getString(9)); - Assert.assertEquals(null, columns.getString("DECIMAL_DIGITS")); - // NUM_PREC_RADIX - Assert.assertEquals("NUM_PREC_RADIX", meta.getColumnLabel(10)); - Assert.assertEquals(10, columns.getInt(10)); - Assert.assertEquals(10, columns.getInt("NUM_PREC_RADIX")); - // NULLABLE - Assert.assertEquals("NULLABLE", meta.getColumnLabel(11)); - Assert.assertEquals(DatabaseMetaData.columnNullable, columns.getInt(11)); - Assert.assertEquals(DatabaseMetaData.columnNullable, columns.getInt("NULLABLE")); - // REMARKS - Assert.assertEquals("REMARKS", meta.getColumnLabel(12)); - Assert.assertEquals(null, columns.getString(12)); - } - } - - @Test - public void getColumnPrivileges() throws SQLException { - Assert.assertNotNull(metaData.getColumnPrivileges("", "", "", "")); - } - - @Test - public void getTablePrivileges() throws SQLException { - Assert.assertNotNull(metaData.getTablePrivileges("", "", "")); - } - - @Test - public void getBestRowIdentifier() throws SQLException { - Assert.assertNotNull(metaData.getBestRowIdentifier("", "", "", 0, false)); - } - - @Test - public void getVersionColumns() throws SQLException { - Assert.assertNotNull(metaData.getVersionColumns("", "", "")); - } - - @Test - public void getPrimaryKeys() throws SQLException { - ResultSet rs = metaData.getPrimaryKeys("log", "", "dn1"); - ResultSetMetaData meta = rs.getMetaData(); - rs.next(); - { - // TABLE_CAT - Assert.assertEquals("TABLE_CAT", meta.getColumnLabel(1)); - Assert.assertEquals("log", rs.getString(1)); - Assert.assertEquals("log", rs.getString("TABLE_CAT")); - // TABLE_SCHEM - Assert.assertEquals("TABLE_SCHEM", meta.getColumnLabel(2)); - Assert.assertEquals(null, rs.getString(2)); - Assert.assertEquals(null, rs.getString("TABLE_SCHEM")); - // TABLE_NAME - Assert.assertEquals("TABLE_NAME", meta.getColumnLabel(3)); - Assert.assertEquals("dn1", rs.getString(3)); - Assert.assertEquals("dn1", rs.getString("TABLE_NAME")); - // COLUMN_NAME - Assert.assertEquals("COLUMN_NAME", meta.getColumnLabel(4)); - Assert.assertEquals("ts", rs.getString(4)); - Assert.assertEquals("ts", rs.getString("COLUMN_NAME")); - // KEY_SEQ - Assert.assertEquals("KEY_SEQ", meta.getColumnLabel(5)); - Assert.assertEquals(1, rs.getShort(5)); - Assert.assertEquals(1, rs.getShort("KEY_SEQ")); - // DATA_TYPE - Assert.assertEquals("PK_NAME", meta.getColumnLabel(6)); - Assert.assertEquals("ts", rs.getString(6)); - Assert.assertEquals("ts", rs.getString("PK_NAME")); - } - } - - @Test - public void getImportedKeys() throws SQLException { - Assert.assertNotNull(metaData.getImportedKeys("", "", "")); - } - - @Test - public void getExportedKeys() throws SQLException { - Assert.assertNotNull(metaData.getExportedKeys("", "", "")); - } - - @Test - public void getCrossReference() throws SQLException { - Assert.assertNotNull(metaData.getCrossReference("", "", "", "", "", "")); - } - - @Test - public void getTypeInfo() throws SQLException { - Assert.assertNotNull(metaData.getTypeInfo()); - } - - @Test - public void getIndexInfo() throws SQLException { - Assert.assertNotNull(metaData.getIndexInfo("", "", "", false, false)); - } - - @Test - public void supportsResultSetType() throws SQLException { - Assert.assertFalse(metaData.supportsResultSetType(0)); - } - - @Test - public void supportsResultSetConcurrency() throws SQLException { - Assert.assertFalse(metaData.supportsResultSetConcurrency(0, 0)); - } - - @Test - public void ownUpdatesAreVisible() throws SQLException { - Assert.assertFalse(metaData.ownUpdatesAreVisible(0)); - } - - @Test - public void ownDeletesAreVisible() throws SQLException { - Assert.assertFalse(metaData.ownDeletesAreVisible(0)); - } - - @Test - public void ownInsertsAreVisible() throws SQLException { - Assert.assertFalse(metaData.ownInsertsAreVisible(0)); - } - - @Test - public void othersUpdatesAreVisible() throws SQLException { - Assert.assertFalse(metaData.othersUpdatesAreVisible(0)); - } - - @Test - public void othersDeletesAreVisible() throws SQLException { - Assert.assertFalse(metaData.othersDeletesAreVisible(0)); - } - - @Test - public void othersInsertsAreVisible() throws SQLException { - Assert.assertFalse(metaData.othersInsertsAreVisible(0)); - } - - @Test - public void updatesAreDetected() throws SQLException { - Assert.assertFalse(metaData.updatesAreDetected(0)); - } - - @Test - public void deletesAreDetected() throws SQLException { - Assert.assertFalse(metaData.deletesAreDetected(0)); - } - - @Test - public void insertsAreDetected() throws SQLException { - Assert.assertFalse(metaData.insertsAreDetected(0)); - } - - @Test - public void supportsBatchUpdates() throws SQLException { - Assert.assertFalse(metaData.supportsBatchUpdates()); - } - - @Test - public void getUDTs() throws SQLException { - Assert.assertNotNull(metaData.getUDTs("", "", "", null)); - } - - @Test - public void getConnection() throws SQLException { - Assert.assertNotNull(metaData.getConnection()); - } - - @Test - public void supportsSavepoints() throws SQLException { - Assert.assertFalse(metaData.supportsSavepoints()); - } - - @Test - public void supportsNamedParameters() throws SQLException { - Assert.assertFalse(metaData.supportsNamedParameters()); - } - - @Test - public void supportsMultipleOpenResults() throws SQLException { - Assert.assertFalse(metaData.supportsMultipleOpenResults()); - } - - @Test - public void supportsGetGeneratedKeys() throws SQLException { - Assert.assertFalse(metaData.supportsGetGeneratedKeys()); - } - - @Test - public void getSuperTypes() throws SQLException { - Assert.assertNotNull(metaData.getSuperTypes("", "", "")); - } - - @Test - public void getSuperTables() throws SQLException { - ResultSet rs = metaData.getSuperTables("log", "", "dn1"); - ResultSetMetaData meta = rs.getMetaData(); - rs.next(); - { - // TABLE_CAT - Assert.assertEquals("TABLE_CAT", meta.getColumnLabel(1)); - Assert.assertEquals("log", rs.getString(1)); - Assert.assertEquals("log", rs.getString("TABLE_CAT")); - // TABLE_CAT - Assert.assertEquals("TABLE_SCHEM", meta.getColumnLabel(2)); - Assert.assertEquals(null, rs.getString(2)); - Assert.assertEquals(null, rs.getString("TABLE_SCHEM")); - // TABLE_CAT - Assert.assertEquals("TABLE_NAME", meta.getColumnLabel(3)); - Assert.assertEquals("dn1", rs.getString(3)); - Assert.assertEquals("dn1", rs.getString("TABLE_NAME")); - // TABLE_CAT - Assert.assertEquals("SUPERTABLE_NAME", meta.getColumnLabel(4)); - Assert.assertEquals("dn", rs.getString(4)); - Assert.assertEquals("dn", rs.getString("SUPERTABLE_NAME")); - } - } - - @Test - public void getAttributes() throws SQLException { - Assert.assertNotNull(metaData.getAttributes("", "", "", "")); - } - - @Test - public void supportsResultSetHoldability() throws SQLException { - Assert.assertTrue(metaData.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT)); - Assert.assertFalse(metaData.supportsResultSetHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT)); - } - - @Test - public void getResultSetHoldability() throws SQLException { - Assert.assertEquals(1, metaData.getResultSetHoldability()); - } - - @Test - public void getDatabaseMajorVersion() throws SQLException { - Assert.assertEquals(2, metaData.getDatabaseMajorVersion()); - } - - @Test - public void getDatabaseMinorVersion() throws SQLException { - Assert.assertEquals(0, metaData.getDatabaseMinorVersion()); - } - - @Test - public void getJDBCMajorVersion() throws SQLException { - Assert.assertEquals(2, metaData.getJDBCMajorVersion()); - } - - @Test - public void getJDBCMinorVersion() throws SQLException { - Assert.assertEquals(0, metaData.getJDBCMinorVersion()); - } - - @Test - public void getSQLStateType() throws SQLException { - Assert.assertEquals(0, metaData.getSQLStateType()); - } - - @Test - public void locatorsUpdateCopy() throws SQLException { - Assert.assertFalse(metaData.locatorsUpdateCopy()); - } - - @Test - public void supportsStatementPooling() throws SQLException { - Assert.assertFalse(metaData.supportsStatementPooling()); - } - - @Test - public void getRowIdLifetime() throws SQLException { - Assert.assertNull(metaData.getRowIdLifetime()); - } - - @Test - public void supportsStoredFunctionsUsingCallSyntax() throws SQLException { - Assert.assertFalse(metaData.supportsStoredFunctionsUsingCallSyntax()); - } - - @Test - public void autoCommitFailureClosesAllResultSets() throws SQLException { - Assert.assertFalse(metaData.autoCommitFailureClosesAllResultSets()); - } - - @Test - public void getClientInfoProperties() throws SQLException { - Assert.assertNotNull(metaData.getClientInfoProperties()); - } - - @Test - public void getFunctions() throws SQLException { - Assert.assertNotNull(metaData.getFunctions("", "", "")); - } - - @Test - public void getFunctionColumns() throws SQLException { - Assert.assertNotNull(metaData.getFunctionColumns("", "", "", "")); - } - - @Test - public void getPseudoColumns() throws SQLException { - Assert.assertNotNull(metaData.getPseudoColumns("", "", "", "")); - } - - @Test - public void generatedKeyAlwaysReturned() throws SQLException { - Assert.assertFalse(metaData.generatedKeyAlwaysReturned()); - } - - @BeforeClass - public static void beforeClass() throws SQLException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - connection = DriverManager.getConnection(url, properties); - Statement stmt = connection.createStatement(); - stmt.execute("drop database if exists " + dbName); - stmt.execute("create database if not exists " + dbName + " precision 'us'"); - stmt.execute("use " + dbName); - stmt.execute("create table `dn` (ts TIMESTAMP,cpu_taosd FLOAT,cpu_system FLOAT,cpu_cores INT,mem_taosd FLOAT,mem_system FLOAT,mem_total INT,disk_used FLOAT,disk_total INT,band_speed FLOAT,io_read FLOAT,io_write FLOAT,req_http INT,req_select INT,req_insert INT) TAGS (dnodeid INT,fqdn BINARY(128))"); - stmt.execute("insert into dn1 using dn tags(1,'a') (ts) values(now)"); - - metaData = connection.getMetaData().unwrap(RestfulDatabaseMetaData.class); - } - - @AfterClass - public static void afterClass() throws SQLException { - if (connection != null) - connection.close(); - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulDriverTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulDriverTest.java deleted file mode 100644 index c2f732c869..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulDriverTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.taosdata.jdbc.rs; - -import org.junit.Assert; -import org.junit.Test; - -import java.sql.*; - -public class RestfulDriverTest { - private static final String host = "127.0.0.1"; - - @Test - public void acceptsURL() throws SQLException { - Driver driver = new RestfulDriver(); - boolean isAccept = driver.acceptsURL("jdbc:TAOS-RS://" + host + ":6041"); - Assert.assertTrue(isAccept); - isAccept = driver.acceptsURL("jdbc:TAOS://" + host + ":6041"); - Assert.assertFalse(isAccept); - } - - @Test - public void getPropertyInfo() throws SQLException { - Driver driver = new RestfulDriver(); - final String url = ""; - DriverPropertyInfo[] propertyInfo = driver.getPropertyInfo(url, null); - Assert.assertNotNull(propertyInfo); - } - - @Test - public void getMajorVersion() { - Assert.assertEquals(2, new RestfulDriver().getMajorVersion()); - } - - @Test - public void getMinorVersion() { - Assert.assertEquals(0, new RestfulDriver().getMinorVersion()); - } - - @Test - public void jdbcCompliant() { - Assert.assertFalse(new RestfulDriver().jdbcCompliant()); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getParentLogger() throws SQLFeatureNotSupportedException { - new RestfulDriver().getParentLogger(); - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulJDBCTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulJDBCTest.java deleted file mode 100644 index da30bbd568..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulJDBCTest.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.taosdata.jdbc.rs; - -import org.junit.*; -import org.junit.runners.MethodSorters; - -import java.sql.*; -import java.util.Random; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class RestfulJDBCTest { - - private static final String host = "127.0.0.1"; - private static final Random random = new Random(System.currentTimeMillis()); - private static Connection connection; - private static final String dbname = "restful_test"; - - @Test - public void testCase001() throws SQLException { - // given - String sql = "drop database if exists " + dbname; - // when - boolean execute = execute(connection, sql); - // then - Assert.assertFalse(execute); - - // given - sql = "create database if not exists " + dbname; - // when - execute = execute(connection, sql); - // then - Assert.assertFalse(execute); - - // given - sql = "use " + dbname; - // when - execute = execute(connection, sql); - // then - Assert.assertFalse(execute); - } - - @Test - public void testCase002() throws SQLException { - // given - String sql = "create table " + dbname + ".weather(ts timestamp, temperature float, humidity int) tags(location nchar(64), groupId int)"; - // when - boolean execute = execute(connection, sql); - // then - Assert.assertFalse(execute); - } - - @Test - public void testCase004() throws SQLException { - for (int i = 1; i <= 100; i++) { - // given - String sql = "create table " + dbname + ".t" + i + " using " + dbname + ".weather tags('beijing', '" + i + "')"; - // when - boolean execute = execute(connection, sql); - // then - Assert.assertFalse(execute); - } - } - - @Test - public void testCase005() throws SQLException { - int rows = 0; - for (int i = 0; i < 10; i++) { - for (int j = 1; j <= 100; j++) { - - // given - long currentTimeMillis = System.currentTimeMillis(); - String sql = "insert into " + dbname + ".t" + j + " values(" + currentTimeMillis + "," + (random.nextFloat() * 50) + "," + random.nextInt(100) + ")"; - // when - int affectRows = executeUpdate(connection, sql); - // then - Assert.assertEquals(1, affectRows); - - rows += affectRows; - } - } - Assert.assertEquals(1000, rows); - } - - @Test - public void testCase006() throws SQLException { - // given - String sql = "select * from " + dbname + ".weather"; - // when - ResultSet rs = executeQuery(connection, sql); - ResultSetMetaData meta = rs.getMetaData(); - - // then - Assert.assertEquals(5, meta.getColumnCount()); - - while (rs.next()) { - Assert.assertNotNull(rs.getTimestamp("ts")); - Assert.assertNotNull(rs.getFloat("temperature")); - Assert.assertNotNull(rs.getInt("humidity")); - Assert.assertNotNull(rs.getString("location")); - } - } - - @Test - public void testCase007() throws SQLException { - // given - String sql = "drop database " + dbname; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertFalse(execute); - } - - private int executeUpdate(Connection connection, String sql) throws SQLException { - try (Statement stmt = connection.createStatement()) { - return stmt.executeUpdate(sql); - } - } - - private boolean execute(Connection connection, String sql) throws SQLException { - try (Statement stmt = connection.createStatement()) { - return stmt.execute(sql); - } - } - - - private ResultSet executeQuery(Connection connection, String sql) throws SQLException { - try (Statement statement = connection.createStatement()) { - return statement.executeQuery(sql); - } - } - - @BeforeClass - public static void beforeClass() { - try { - connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @AfterClass - public static void afterClass() throws SQLException { - if (connection != null) { - Statement stmt = connection.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.close(); - connection.close(); - } - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulJsonTagTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulJsonTagTest.java deleted file mode 100644 index df04711eb4..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulJsonTagTest.java +++ /dev/null @@ -1,1280 +0,0 @@ -package com.taosdata.jdbc.rs; - -import com.taosdata.jdbc.annotation.CatalogRunner; -import com.taosdata.jdbc.annotation.Description; -import com.taosdata.jdbc.annotation.TestTarget; -import org.junit.*; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; - -import java.sql.*; -import java.util.HashSet; -import java.util.Set; - -/** - * Most of the functionality is consistent with {@link com.taosdata.jdbc.JsonTagTest}, - * Except for batchInsert, which is not supported by restful API. - * Restful could not distinguish between empty and nonexistent of json value, the result is always null. - * The order of json results may change due to serialization and deserialization - */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(CatalogRunner.class) -@TestTarget(alias = "JsonTag", author = "huolibo", version = "2.0.37") -public class RestfulJsonTagTest { - private static final String dbName = "json_tag_test"; - private static Connection connection; - private static Statement statement; - private static final String superSql = "create table if not exists jsons1(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"; - private static final String[] sql = { - "insert into jsons1_1 using jsons1 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(now, 1, false, 'json1', '你是') (1591060608000, 23, true, '等等', 'json')", - "insert into jsons1_2 using jsons1 tags('{\"tag1\":5,\"tag2\":\"beijing\"}') values (1591060628000, 2, true, 'json2', 'sss')", - "insert into jsons1_3 using jsons1 tags('{\"tag1\":false,\"tag2\":\"beijing\"}') values (1591060668000, 3, false, 'json3', 'efwe')", - "insert into jsons1_4 using jsons1 tags('{\"tag1\":null,\"tag2\":\"shanghai\",\"tag3\":\"hello\"}') values (1591060728000, 4, true, 'json4', '323sd')", - "insert into jsons1_5 using jsons1 tags('{\"tag1\":1.232, \"tag2\":null}') values(1591060928000, 1, false, '你就会', 'ewe')", - "insert into jsons1_6 using jsons1 tags('{\"tag1\":11,\"tag2\":\"\",\"tag2\":null}') values(1591061628000, 11, false, '你就会','')", - "insert into jsons1_7 using jsons1 tags('{\"tag1\":\"收到货\",\"tag2\":\"\",\"tag3\":null}') values(1591062628000, 2, NULL, '你就会', 'dws')", - // test duplicate key using the first one. - "CREATE TABLE if not exists jsons1_8 using jsons1 tags('{\"tag1\":null, \"tag1\":true, \"tag1\":45, \"1tag$\":2, \" \":90}')", - - }; - - private static final String[] invalidJsonInsertSql = { - // test empty json string, save as tag is NULL - "insert into jsons1_9 using jsons1 tags('\t') values (1591062328000, 24, NULL, '你就会', '2sdw')", - }; - - private static final String[] invalidJsonCreateSql = { - "CREATE TABLE if not exists jsons1_10 using jsons1 tags('')", - "CREATE TABLE if not exists jsons1_11 using jsons1 tags(' ')", - "CREATE TABLE if not exists jsons1_12 using jsons1 tags('{}')", - "CREATE TABLE if not exists jsons1_13 using jsons1 tags('null')", - }; - - // test invalidate json - private static final String[] errorJsonInsertSql = { - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('\"efwewf\"')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('3333')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('33.33')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('false')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('[1,true]')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{222}')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"fe\"}')", - }; - - private static final String[] errorSelectSql = { - "select * from jsons1 where jtag->tag1='beijing'", - "select * from jsons1 where jtag->'location'", - "select * from jsons1 where jtag->''", - "select * from jsons1 where jtag->''=9", - "select -> from jsons1", - "select ? from jsons1", - "select * from jsons1 where contains", - "select * from jsons1 where jtag->", - "select jtag->location from jsons1", - "select jtag contains location from jsons1", - "select * from jsons1 where jtag contains location", - "select * from jsons1 where jtag contains ''", - "select * from jsons1 where jtag contains 'location'='beijing'", - // test where with json tag - "select * from jsons1_1 where jtag is not null", - "select * from jsons1 where jtag='{\"tag1\":11,\"tag2\":\"\"}'", - "select * from jsons1 where jtag->'tag1'={}" - }; - - @Test - @Description("insert json tag") - public void case01_InsertTest() throws SQLException { - for (String sql : sql) { - statement.execute(sql); - } - for (String sql : invalidJsonInsertSql) { - statement.execute(sql); - } - for (String sql : invalidJsonCreateSql) { - statement.execute(sql); - } - } - - @Test - @Description("error json tag insert") - public void case02_ErrorJsonInsertTest() { - int count = 0; - for (String sql : errorJsonInsertSql) { - try { - statement.execute(sql); - } catch (SQLException e) { - count++; - } - } - Assert.assertEquals(errorJsonInsertSql.length, count); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json value is array") - public void case02_ArrayErrorTest() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"tag1\":[1,true]}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json value is empty") - public void case02_EmptyValueErrorTest() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"tag1\":{}}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json key is not ASCII") - public void case02_AbnormalKeyErrorTest1() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"。loc\":\"fff\"}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json key is '\\t'") - public void case02_AbnormalKeyErrorTest2() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"\t\":\"fff\"}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json key is chinese") - public void case02_AbnormalKeyErrorTest3() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"试试\":\"fff\"}')"); - } - - @Test - @Description("alter json tag") - public void case03_AlterTag() throws SQLException { - statement.execute("ALTER TABLE jsons1_1 SET TAG jtag='{\"tag1\":\"femail\",\"tag2\":35,\"tag3\":true}'"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when add json tag") - public void case03_AddTagErrorTest() throws SQLException { - statement.execute("ALTER STABLE jsons1 add tag tag2 nchar(20)"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when delete json tag") - public void case03_dropTagErrorTest() throws SQLException { - statement.execute("ALTER STABLE jsons1 drop tag jtag"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when set some json tag value") - public void case03_AlterTagErrorTest() throws SQLException { - statement.execute("ALTER TABLE jsons1_1 SET TAG jtag=4"); - } - - @Test - @Description("exception will throw when select syntax error") - public void case04_SelectErrorTest() { - int count = 0; - for (String sql : errorSelectSql) { - try { - statement.execute(sql); - } catch (SQLException e) { - count++; - } - } - Assert.assertEquals(errorSelectSql.length, count); - } - - @Test - @Description("normal select stable") - public void case04_select01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select dataint from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("select all column from stable") - public void case04_select02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("select json tag from stable") - public void case04_select03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1"); - ResultSetMetaData metaData = resultSet.getMetaData(); - metaData.getColumnTypeName(1); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonInsertSql.length + invalidJsonCreateSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition tag is null") - public void case04_select04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1 where jtag is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(invalidJsonInsertSql.length + invalidJsonCreateSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition tag is not null") - public void case04_select05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1 where jtag is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length, count); - close(resultSet); - } - - @Test - @Description("select json tag") - public void case04_select06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1_8"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("{\" \":90,\"tag1\":null,\"1tag$\":2}", result); - close(resultSet); - } - - @Test - @Description("select json tag") - public void case04_select07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1_1"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("{\"tag1\":\"femail\",\"tag2\":35,\"tag3\":true}", result); - close(resultSet); - } - - @Test - @Description("select not exist json tag") - public void case04_select08() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1_9"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertNull(result); - close(resultSet); - } - - @Test - @Description("select a json tag") - public void case04_select09() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_1"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("\"femail\"", result); - close(resultSet); - } - - @Test - @Description(value = "select a normal value", version = "2.0.37") - public void case04_selectNormal() throws SQLException { - ResultSet resultSet = statement.executeQuery("select datastr from jsons1_1"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("等等", result); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is empty") - public void case04_select10() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag2' from jsons1_6"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("\"\"", result); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is int") - public void case04_select11() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag2' from jsons1_1"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("35", string); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is boolean") - public void case04_select12() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag3' from jsons1_1"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("true", string); - close(resultSet); - } - -// @Test -// @Description("select a json tag, the value is null") -// public void case04_select13() throws SQLException { -// ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_4"); -// resultSet.next(); -// String string = resultSet.getString(1); -// Assert.assertEquals("null", string); -// close(resultSet); -// } - - @Test - @Description("select a json tag, the value is double") - public void case04_select14() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_5"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("1.232000000", string); - close(resultSet); - } - - @Test - @Description("select a json tag, the key is not exist") - public void case04_select15() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag10' from jsons1_4"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertNull(string); - close(resultSet); - } - - @Test - @Description("select a json tag, the result number equals tables number") - public void case04_select16() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonCreateSql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition '=' for string") - public void case04_select19() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("select and where conditon '=' for string") - public void case04_select20() throws SQLException { - ResultSet resultSet = statement.executeQuery("select dataint,tbname,jtag->'tag1',jtag from jsons1 where jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition result is null") - public void case04_select21() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition equation has chinese") - public void case04_select23() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'='收到货'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '>' for character") - public void case05_symbolOperation01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'>'beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '>=' for character") - public void case05_symbolOperation02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'>='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '<' for character") - public void case05_symbolOperation03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'<'beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition support '<=' in character") - public void case05_symbolOperation04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'<='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' in character") - public void case05_symbolOperation05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'!='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '=' empty") - public void case05_symbolOperation06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'=''"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - // where json value is int - @Test - @Description("where condition support '=' for int") - public void case06_selectValue01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=5"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where conditional support '<' for int") - public void case06_selectValue02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<54"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '<=' for int") - public void case06_selectValue03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<=11"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where conditional support '>' for int") - public void case06_selectValue04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>4"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition support '>=' for int") - public void case06_selectValue05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>=5"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where conditional support '!=' for int") - public void case06_selectValue06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=5"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where conditional support '!=' for int") - public void case06_selectValue07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=55"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where conditional support '!=' for int and result is nothing") - public void case06_selectValue08() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=10"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support '=' for double") - public void case07_selectValue01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '<' for double") - public void case07_doubleOperation01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support '<=' for double") - public void case07_doubleOperation02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '>' for double") - public void case07_doubleOperation03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>1.23"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '>=' for double") - public void case07_doubleOperation04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' for double") - public void case07_doubleOperation05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' for double") - public void case07_doubleOperation06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=3.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when denominator is zero") - public void case07_doubleOperation07() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1'/0=3"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when invalid operation") - public void case07_doubleOperation08() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1'/5=1"); - } - - @Test - @Description("where condition support '=' for boolean") - public void case08_boolOperation01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=true"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support '=' for boolean") - public void case08_boolOperation02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' for boolean") - public void case08_boolOperation03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=false"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when '>' operation for boolean") - public void case08_boolOperation04() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1'>false"); - } - - @Test - @Description("where conditional support '=null'") - public void case09_select01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where conditional support 'is null'") - public void case09_select02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support 'is not null'") - public void case09_select03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag '='") - public void case09_select04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag_no_exist'=3"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag 'is null'") - public void case09_select05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag 'is null'") - public void case09_select06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag4' is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag 'is not null'") - public void case09_select07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag3' is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("contains") - public void case09_select10() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag contains 'tag1'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("contains") - public void case09_select11() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("contains with no exist tag") - public void case09_select12() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag contains 'tag_no_exist'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition with and") - public void case10_selectAndOr01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false and jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition with 'or'") - public void case10_selectAndOr02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false or jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition with 'and'") - public void case10_selectAndOr03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false and jtag->'tag2'='shanghai'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition with 'or'") - public void case10_selectAndOr04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=13 or jtag->'tag2'>35"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition with 'or' and contains") - public void case10_selectAndOr05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' is not null and jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("where condition with 'and' and contains") - public void case10_selectAndOr06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'='femail' and jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3' and dataint=3"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3' and dataint=23"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition like") - public void case12_selectWhere01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,tbname from jsons1 where jtag->'tag2' like 'bei%'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition like") - public void case12_selectWhere02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,tbname from jsons1 where jtag->'tag1' like 'fe%' and jtag->'tag2' is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test(expected = SQLException.class) - @Description("where condition in no support in") - public void case12_selectWhere03() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1' in ('beijing')"); - } - - @Test - @Description("where condition match") - public void case12_selectWhere04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' match 'ma'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition match") - public void case12_selectWhere05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' match 'ma$'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition match") - public void case12_selectWhere06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2' match 'jing$'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition match") - public void case12_selectWhere07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' match '收到'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("insert distinct") - public void case13_selectDistinct01() throws SQLException { - statement.execute("insert into jsons1_14 using jsons1 tags('{\"tag1\":\"收到货\",\"tag2\":\"\",\"tag3\":null}') values(1591062628000, 2, NULL, '你就会', 'dws')"); - } - - @Test - @Description("distinct json tag") - public void case13_selectDistinct02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select distinct jtag->'tag1' from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("distinct json tag") - public void case13_selectDistinct03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select distinct jtag from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(9, count); - close(resultSet); - } - - @Test - @Description("insert json tag") - public void case14_selectDump01() throws SQLException { - statement.execute("INSERT INTO jsons1_15 using jsons1 tags('{\"tbname\":\"tt\",\"databool\":true,\"datastr\":\"是是是\"}') values(1591060828000, 4, false, 'jjsf', \"你就会\")"); - } - - @Test - @Description("test duplicate key with normal column") - public void case14_selectDump02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,tbname,jtag from jsons1 where jtag->'datastr' match '是' and datastr match 'js'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("test duplicate key with normal column") - public void case14_selectDump03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select tbname,jtag->'tbname' from jsons1 where jtag->'tbname'='tt' and tbname='jsons1_14'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("insert json tag for join test") - public void case15_selectJoin01() throws SQLException { - statement.execute("create table if not exists jsons2(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"); - statement.execute("insert into jsons2_1 using jsons2 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(1591060618000, 2, false, 'json2', '你是2')"); - statement.execute("insert into jsons2_2 using jsons2 tags('{\"tag1\":5,\"tag2\":null}') values (1591060628000, 2, true, 'json2', 'sss')"); - - statement.execute("create table if not exists jsons3(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"); - statement.execute("insert into jsons3_1 using jsons3 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(1591060618000, 3, false, 'json3', '你是3')"); - statement.execute("insert into jsons3_2 using jsons3 tags('{\"tag1\":5,\"tag2\":\"beijing\"}') values (1591060638000, 2, true, 'json3', 'sss')"); - } - - @Test - @Description("select json tag from join") - public void case15_selectJoin02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select 'sss',33,a.jtag->'tag3' from jsons2 a,jsons3 b where a.ts=b.ts and a.jtag->'tag1'=b.jtag->'tag1'"); - resultSet.next(); - Assert.assertEquals("sss", resultSet.getString(1)); - close(resultSet); - } - - @Test - @Description("group by and order by json tag desc") - public void case16_selectGroupOrder01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select count(*) from jsons1 group by jtag->'tag1' order by jtag->'tag1' desc"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("group by and order by json tag asc") - public void case16_selectGroupOrder02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select count(*) from jsons1 group by jtag->'tag1' order by jtag->'tag1' asc"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("stddev with group by json tag") - public void case17_selectStddev01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select stddev(dataint) from jsons1 group by jtag->'tag1'"); - String s = ""; - int count = 0; - Set set = new HashSet<>(); - while (resultSet.next()) { - count++; - set.add(resultSet.getString(2)); - } - Assert.assertEquals(8, count); - Assert.assertTrue(set.contains("\"femail\"")); - Assert.assertTrue(set.contains("\"收到货\"")); - close(resultSet); - } - - @Test - @Description("subquery json tag") - public void case18_selectSubquery01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from (select jtag, dataint from jsons1)"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(11, count); - close(resultSet); - } - - @Test - @Description("subquery some json tags") - public void case18_selectSubquery02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from (select jtag->'tag1', dataint from jsons1)"); - - ResultSetMetaData metaData = resultSet.getMetaData(); - String columnName = metaData.getColumnName(1); - Assert.assertEquals("jtag->'tag1'", columnName); - - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(11, count); - close(resultSet); - } - - @Test - @Description("query some json tags from subquery") - public void case18_selectSubquery04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select ts,tbname,jtag->'tag1' from (select jtag->'tag1',tbname,ts from jsons1 order by ts)"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(11, count); - close(resultSet); - } - - @Test - @Description(value = "query metadata for json", version = "2.0.37") - public void case19_selectMetadata01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1"); - ResultSetMetaData metaData = resultSet.getMetaData(); - int columnType = metaData.getColumnType(1); - String columnTypeName = metaData.getColumnTypeName(1); - Assert.assertEquals(Types.OTHER, columnType); - Assert.assertEquals("JSON", columnTypeName); - close(resultSet); - } - - @Test - @Description(value = "query metadata for json", version = "2.0.37") - public void case19_selectMetadata02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,jtag from jsons1"); - ResultSetMetaData metaData = resultSet.getMetaData(); - int columnType = metaData.getColumnType(6); - String columnTypeName = metaData.getColumnTypeName(6); - Assert.assertEquals(Types.OTHER, columnType); - Assert.assertEquals("JSON", columnTypeName); - close(resultSet); - } - - @Test - @Description(value = "query metadata for one json result", version = "2.0.37") - public void case19_selectMetadata03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_6"); - ResultSetMetaData metaData = resultSet.getMetaData(); - int columnType = metaData.getColumnType(1); - String columnTypeName = metaData.getColumnTypeName(1); - Assert.assertEquals(Types.OTHER, columnType); - Assert.assertEquals("JSON", columnTypeName); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("11", string); - close(resultSet); - } - - private void close(ResultSet resultSet) { - try { - if (null != resultSet) { - resultSet.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @BeforeClass - public static void beforeClass() { - String host = "127.0.0.1"; - final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - try { - connection = DriverManager.getConnection(url); - statement = connection.createStatement(); - statement.execute("drop database if exists " + dbName); - statement.execute("create database if not exists " + dbName); - statement.execute("use " + dbName); - statement.execute(superSql); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @AfterClass - public static void afterClass() { - try { - if (null != statement) { - statement.execute("drop database " + dbName); - statement.close(); - } - if (null != connection) { - connection.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulParameterMetaDataTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulParameterMetaDataTest.java deleted file mode 100644 index c8ca1a5de7..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulParameterMetaDataTest.java +++ /dev/null @@ -1,200 +0,0 @@ -package com.taosdata.jdbc.rs; - -import com.taosdata.jdbc.TSDBConstants; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.sql.*; - -public class RestfulParameterMetaDataTest { - - private static final String host = "127.0.0.1"; - private static Connection conn; - private static final String sql_insert = "insert into t1 values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - private static PreparedStatement pstmt_insert; - private static final String sql_select = "select * from t1 where ts > ? and ts <= ? and f1 >= ?"; - private static PreparedStatement pstmt_select; - private static ParameterMetaData parameterMetaData_insert; - private static ParameterMetaData parameterMetaData_select; - private static final String dbname = "test_pstmt"; - - @Test - public void getParameterCount() throws SQLException { - Assert.assertEquals(10, parameterMetaData_insert.getParameterCount()); - } - - @Test - public void isNullable() throws SQLException { - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(1)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(2)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(3)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(4)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(5)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(6)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(7)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(8)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(9)); - Assert.assertEquals(ParameterMetaData.parameterNullableUnknown, parameterMetaData_insert.isNullable(10)); - } - - @Test - public void isSigned() throws SQLException { - Assert.assertEquals(false, parameterMetaData_insert.isSigned(1)); - Assert.assertEquals(true, parameterMetaData_insert.isSigned(2)); - Assert.assertEquals(true, parameterMetaData_insert.isSigned(3)); - Assert.assertEquals(true, parameterMetaData_insert.isSigned(4)); - Assert.assertEquals(true, parameterMetaData_insert.isSigned(5)); - Assert.assertEquals(true, parameterMetaData_insert.isSigned(6)); - Assert.assertEquals(true, parameterMetaData_insert.isSigned(7)); - Assert.assertEquals(false, parameterMetaData_insert.isSigned(8)); - Assert.assertEquals(false, parameterMetaData_insert.isSigned(9)); - Assert.assertEquals(false, parameterMetaData_insert.isSigned(10)); - } - - @Test - public void getPrecision() throws SQLException { - //create table weather(ts timestamp, f1 int, f2 bigint, f3 float, f4 double, f5 smallint, f6 tinyint, f7 bool, f8 binary(64), f9 nchar(64)) - Assert.assertEquals(TSDBConstants.TIMESTAMP_MS_PRECISION, parameterMetaData_insert.getPrecision(1)); - Assert.assertEquals(TSDBConstants.INT_PRECISION, parameterMetaData_insert.getPrecision(2)); - Assert.assertEquals(TSDBConstants.BIGINT_PRECISION, parameterMetaData_insert.getPrecision(3)); - Assert.assertEquals(TSDBConstants.FLOAT_PRECISION, parameterMetaData_insert.getPrecision(4)); - Assert.assertEquals(TSDBConstants.DOUBLE_PRECISION, parameterMetaData_insert.getPrecision(5)); - Assert.assertEquals(TSDBConstants.SMALLINT_PRECISION, parameterMetaData_insert.getPrecision(6)); - Assert.assertEquals(TSDBConstants.TINYINT_PRECISION, parameterMetaData_insert.getPrecision(7)); - Assert.assertEquals(TSDBConstants.BOOLEAN_PRECISION, parameterMetaData_insert.getPrecision(8)); - Assert.assertEquals("hello".getBytes().length, parameterMetaData_insert.getPrecision(9)); - Assert.assertEquals("涛思数据".length(), parameterMetaData_insert.getPrecision(10)); - } - - @Test - public void getScale() throws SQLException { - Assert.assertEquals(0, parameterMetaData_insert.getScale(1)); - Assert.assertEquals(0, parameterMetaData_insert.getScale(2)); - Assert.assertEquals(0, parameterMetaData_insert.getScale(3)); - Assert.assertEquals(31, parameterMetaData_insert.getScale(4)); - Assert.assertEquals(31, parameterMetaData_insert.getScale(5)); - Assert.assertEquals(0, parameterMetaData_insert.getScale(6)); - Assert.assertEquals(0, parameterMetaData_insert.getScale(7)); - Assert.assertEquals(0, parameterMetaData_insert.getScale(8)); - Assert.assertEquals(0, parameterMetaData_insert.getScale(9)); - Assert.assertEquals(0, parameterMetaData_insert.getScale(10)); - } - - @Test - public void getParameterType() throws SQLException { - Assert.assertEquals(Types.TIMESTAMP, parameterMetaData_insert.getParameterType(1)); - Assert.assertEquals(Types.INTEGER, parameterMetaData_insert.getParameterType(2)); - Assert.assertEquals(Types.BIGINT, parameterMetaData_insert.getParameterType(3)); - Assert.assertEquals(Types.FLOAT, parameterMetaData_insert.getParameterType(4)); - Assert.assertEquals(Types.DOUBLE, parameterMetaData_insert.getParameterType(5)); - Assert.assertEquals(Types.SMALLINT, parameterMetaData_insert.getParameterType(6)); - Assert.assertEquals(Types.TINYINT, parameterMetaData_insert.getParameterType(7)); - Assert.assertEquals(Types.BOOLEAN, parameterMetaData_insert.getParameterType(8)); - Assert.assertEquals(Types.BINARY, parameterMetaData_insert.getParameterType(9)); - Assert.assertEquals(Types.NCHAR, parameterMetaData_insert.getParameterType(10)); - } - - @Test - public void getParameterTypeName() throws SQLException { - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.TIMESTAMP), parameterMetaData_insert.getParameterTypeName(1)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.INTEGER), parameterMetaData_insert.getParameterTypeName(2)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.BIGINT), parameterMetaData_insert.getParameterTypeName(3)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.FLOAT), parameterMetaData_insert.getParameterTypeName(4)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.DOUBLE), parameterMetaData_insert.getParameterTypeName(5)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.SMALLINT), parameterMetaData_insert.getParameterTypeName(6)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.TINYINT), parameterMetaData_insert.getParameterTypeName(7)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.BOOLEAN), parameterMetaData_insert.getParameterTypeName(8)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.BINARY), parameterMetaData_insert.getParameterTypeName(9)); - Assert.assertEquals(TSDBConstants.jdbcType2TaosTypeName(Types.NCHAR), parameterMetaData_insert.getParameterTypeName(10)); - } - - @Test - public void getParameterClassName() throws SQLException { - Assert.assertEquals(Timestamp.class.getName(), parameterMetaData_insert.getParameterClassName(1)); - Assert.assertEquals(Integer.class.getName(), parameterMetaData_insert.getParameterClassName(2)); - Assert.assertEquals(Long.class.getName(), parameterMetaData_insert.getParameterClassName(3)); - Assert.assertEquals(Float.class.getName(), parameterMetaData_insert.getParameterClassName(4)); - Assert.assertEquals(Double.class.getName(), parameterMetaData_insert.getParameterClassName(5)); - Assert.assertEquals(Short.class.getName(), parameterMetaData_insert.getParameterClassName(6)); - Assert.assertEquals(Byte.class.getName(), parameterMetaData_insert.getParameterClassName(7)); - Assert.assertEquals(Boolean.class.getName(), parameterMetaData_insert.getParameterClassName(8)); - Assert.assertEquals(byte[].class.getName(), parameterMetaData_insert.getParameterClassName(9)); - Assert.assertEquals(String.class.getName(), parameterMetaData_insert.getParameterClassName(10)); - } - - @Test - public void getParameterMode() throws SQLException { - for (int i = 1; i <= parameterMetaData_insert.getParameterCount(); i++) { - int parameterMode = parameterMetaData_insert.getParameterMode(i); - Assert.assertEquals(ParameterMetaData.parameterModeUnknown, parameterMode); - } - } - - @Test - public void unwrap() throws SQLException { - RestfulParameterMetaData unwrap = parameterMetaData_insert.unwrap(RestfulParameterMetaData.class); - Assert.assertNotNull(unwrap); - } - - @Test - public void isWrapperFor() throws SQLException { - Assert.assertTrue(parameterMetaData_insert.isWrapperFor(RestfulParameterMetaData.class)); - } - - @BeforeClass - public static void beforeClass() { - try { - Class.forName("com.taosdata.jdbc.rs.RestfulDriver"); - conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table weather(ts timestamp, f1 int, f2 bigint, f3 float, f4 double, f5 smallint, f6 tinyint, f7 bool, f8 binary(64), f9 nchar(64)) tags(loc nchar(64))"); - stmt.execute("create table t1 using weather tags('beijing')"); - } - pstmt_insert = conn.prepareStatement(sql_insert); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setObject(2, 111); - pstmt_insert.setObject(3, Long.MAX_VALUE); - pstmt_insert.setObject(4, 3.14159265354f); - pstmt_insert.setObject(5, Double.MAX_VALUE); - pstmt_insert.setObject(6, Short.MAX_VALUE); - pstmt_insert.setObject(7, Byte.MAX_VALUE); - pstmt_insert.setObject(8, true); - pstmt_insert.setObject(9, "hello".getBytes()); - pstmt_insert.setObject(10, "涛思数据"); - parameterMetaData_insert = pstmt_insert.getParameterMetaData(); - - pstmt_select = conn.prepareStatement(sql_select); - pstmt_select.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_select.setTimestamp(2, new Timestamp(System.currentTimeMillis() + 10000)); - pstmt_select.setInt(3, 0); - parameterMetaData_select = pstmt_select.getParameterMetaData(); - - } catch (ClassNotFoundException | SQLException e) { - e.printStackTrace(); - } - } - - @AfterClass - public static void afterClass() { - try { - if (pstmt_insert != null) - pstmt_insert.close(); - if (pstmt_select != null) - pstmt_select.close(); - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists " + dbname); - statement.close(); - conn.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulPreparedStatementTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulPreparedStatementTest.java deleted file mode 100644 index 40d0e0214f..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulPreparedStatementTest.java +++ /dev/null @@ -1,414 +0,0 @@ -package com.taosdata.jdbc.rs; - -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.IOException; -import java.sql.*; - -public class RestfulPreparedStatementTest { - private static final String host = "127.0.0.1"; - private static Connection conn; - private static final String sql_insert = "insert into t1 values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - private static PreparedStatement pstmt_insert; - private static final String sql_select = "select * from t1 where ts > ? and ts <= ? and f1 >= ?"; - private static PreparedStatement pstmt_select; - private static final String sql_without_parameters = "select count(*) from t1"; - private static PreparedStatement pstmt_without_parameters; - - @Test - public void executeQuery() throws SQLException { - long end = System.currentTimeMillis(); - long start = end - 1000 * 60 * 60; - pstmt_select.setTimestamp(1, new Timestamp(start)); - pstmt_select.setTimestamp(2, new Timestamp(end)); - pstmt_select.setInt(3, 0); - - ResultSet rs = pstmt_select.executeQuery(); - Assert.assertNotNull(rs); - ResultSetMetaData meta = rs.getMetaData(); - int columnCount = meta.getColumnCount(); - Assert.assertEquals(10, columnCount); - Assert.assertNotNull(rs); - } - - @Test - public void executeUpdate() throws SQLException { - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setFloat(4, 3.14f); - int result = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, result); - } - - @Test - public void setNull() throws SQLException { - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setNull(2, Types.INTEGER); - int result = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, result); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setNull(3, Types.BIGINT); - result = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, result); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setNull(4, Types.FLOAT); - result = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, result); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setNull(5, Types.DOUBLE); - result = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, result); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setNull(6, Types.SMALLINT); - result = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, result); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setNull(7, Types.TINYINT); - result = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, result); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setNull(8, Types.BOOLEAN); - result = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, result); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setNull(9, Types.BINARY); - result = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, result); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setNull(10, Types.NCHAR); - result = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, result); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setNull(10, Types.OTHER); - result = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, result); - } - - @Test - public void setBoolean() throws SQLException { - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setBoolean(8, true); - int ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - } - - @Test - public void setByte() throws SQLException { - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setByte(7, (byte) 0x001); - int ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - } - - @Test - public void setShort() throws SQLException { - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setShort(6, (short) 2); - int ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - } - - @Test - public void setInt() throws SQLException { - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setInt(2, 10086); - int ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - } - - @Test - public void setLong() throws SQLException { - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setLong(3, Long.MAX_VALUE); - int ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - } - - @Test - public void setFloat() throws SQLException { - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setFloat(4, 3.14f); - int ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - } - - @Test - public void setDouble() throws SQLException { - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setDouble(5, 3.14444); - int ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setBigDecimal() throws SQLException { - pstmt_insert.setBigDecimal(1, null); - } - - @Test - public void setString() throws SQLException { - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setString(10, "aaaa"); - boolean execute = pstmt_insert.execute(); - Assert.assertFalse(execute); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setString(10, new Person("john", 33, true).toString()); - Assert.assertFalse(pstmt_insert.execute()); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setString(10, new Person("john", 33, true).toString().replaceAll("'", "\"")); - Assert.assertFalse(pstmt_insert.execute()); - } - - private class Person { - String name; - int age; - boolean sex; - - public Person(String name, int age, boolean sex) { - this.name = name; - this.age = age; - this.sex = sex; - } - - @Override - public String toString() { - return "Person{" + - "name='" + name + '\'' + - ", age=" + age + - ", sex=" + sex + - '}'; - } - } - - @Test - public void setBytes() throws SQLException, IOException { - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - -// ByteArrayOutputStream baos = new ByteArrayOutputStream(); -// ObjectOutputStream oos = new ObjectOutputStream(baos); -// oos.writeObject(new Person("john", 33, true)); -// oos.flush(); -// byte[] bytes = baos.toByteArray(); -// pstmt_insert.setBytes(9, bytes); - - pstmt_insert.setBytes(9, new Person("john", 33, true).toString().getBytes()); - int ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setDate() throws SQLException { - pstmt_insert.setDate(1, new Date(System.currentTimeMillis())); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setTime() throws SQLException { - pstmt_insert.setTime(1, new Time(System.currentTimeMillis())); - } - - @Test - public void setTimestamp() throws SQLException { - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - int ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setAsciiStream() throws SQLException { - pstmt_insert.setAsciiStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setBinaryStream() throws SQLException { - pstmt_insert.setBinaryStream(1, null); - } - - @Test - public void clearParameters() throws SQLException { - pstmt_insert.clearParameters(); - pstmt_without_parameters.clearParameters(); - } - - @Test - public void setObject() throws SQLException { - pstmt_insert.setObject(1, new Timestamp(System.currentTimeMillis())); - int ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setObject(2, 111); - ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setObject(3, Long.MAX_VALUE); - ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setObject(4, 3.14159265354f); - ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setObject(5, Double.MAX_VALUE); - ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setObject(6, Short.MAX_VALUE); - ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setObject(7, Byte.MAX_VALUE); - ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setObject(8, true); - ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setObject(9, "hello".getBytes()); - ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - pstmt_insert.setObject(10, "Hello"); - ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - } - - @Test - public void execute() throws SQLException { - pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - int ret = pstmt_insert.executeUpdate(); - Assert.assertEquals(1, ret); - - executeQuery(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setCharacterStream() throws SQLException { - pstmt_insert.setCharacterStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setRef() throws SQLException { - pstmt_insert.setRef(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setBlob() throws SQLException { - pstmt_insert.setBlob(1, (Blob) null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setClob() throws SQLException { - pstmt_insert.setClob(1, (Clob) null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setArray() throws SQLException { - pstmt_insert.setArray(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getMetaData() throws SQLException { - pstmt_insert.getMetaData(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setURL() throws SQLException { - pstmt_insert.setURL(1, null); - } - - @Test - public void getParameterMetaData() throws SQLException { - ParameterMetaData parameterMetaData = pstmt_insert.getParameterMetaData(); - Assert.assertNotNull(parameterMetaData); - //TODO: modify the test case - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setRowId() throws SQLException { - pstmt_insert.setRowId(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setNString() throws SQLException { - pstmt_insert.setNString(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setNCharacterStream() throws SQLException { - pstmt_insert.setNCharacterStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setNClob() throws SQLException { - pstmt_insert.setNClob(1, (NClob) null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setSQLXML() throws SQLException { - pstmt_insert.setSQLXML(1, null); - } - - @BeforeClass - public static void beforeClass() { - try { - conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); - - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists test_pstmt"); - stmt.execute("create database if not exists test_pstmt"); - stmt.execute("use test_pstmt"); - stmt.execute("create table weather(ts timestamp, f1 int, f2 bigint, f3 float, f4 double, f5 smallint, f6 tinyint, f7 bool, f8 binary(64), f9 nchar(64)) tags(loc nchar(64))"); - stmt.execute("create table t1 using weather tags('beijing')"); - stmt.close(); - - pstmt_insert = conn.prepareStatement(sql_insert); - pstmt_select = conn.prepareStatement(sql_select); - pstmt_without_parameters = conn.prepareStatement(sql_without_parameters); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @AfterClass - public static void afterClass() { - try { - if (pstmt_insert != null) - pstmt_insert.close(); - if (pstmt_select != null) - pstmt_select.close(); - if (pstmt_without_parameters != null) - pstmt_without_parameters.close(); - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists test_pstmt"); - statement.close(); - conn.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetMetaDataTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetMetaDataTest.java deleted file mode 100644 index 6e5851474f..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetMetaDataTest.java +++ /dev/null @@ -1,220 +0,0 @@ -package com.taosdata.jdbc.rs; - -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.sql.*; - -public class RestfulResultSetMetaDataTest { - - private static final String host = "127.0.0.1"; - - private static Connection conn; - private static Statement stmt; - private static ResultSet rs; - private static ResultSetMetaData meta; - private static final String dbname = "restful_test"; - - @Test - public void getColumnCount() throws SQLException { - Assert.assertEquals(10, meta.getColumnCount()); - } - - @Test - public void isAutoIncrement() throws SQLException { - Assert.assertFalse(meta.isAutoIncrement(1)); - Assert.assertFalse(meta.isAutoIncrement(2)); - Assert.assertFalse(meta.isAutoIncrement(3)); - Assert.assertFalse(meta.isAutoIncrement(4)); - Assert.assertFalse(meta.isAutoIncrement(5)); - Assert.assertFalse(meta.isAutoIncrement(6)); - Assert.assertFalse(meta.isAutoIncrement(7)); - Assert.assertFalse(meta.isAutoIncrement(8)); - Assert.assertFalse(meta.isAutoIncrement(9)); - Assert.assertFalse(meta.isAutoIncrement(10)); - } - - @Test - public void isCaseSensitive() throws SQLException { - Assert.assertFalse(meta.isCaseSensitive(1)); - } - - @Test - public void isSearchable() throws SQLException { - Assert.assertTrue(meta.isSearchable(1)); - } - - @Test - public void isCurrency() throws SQLException { - Assert.assertFalse(meta.isCurrency(1)); - } - - @Test - public void isNullable() throws SQLException { - Assert.assertEquals(ResultSetMetaData.columnNoNulls, meta.isNullable(1)); - Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(2)); - Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(3)); - Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(4)); - Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(5)); - Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(6)); - Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(7)); - Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(8)); - Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(9)); - Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(10)); - } - - @Test - public void isSigned() throws SQLException { - Assert.assertFalse(meta.isSigned(1)); - } - - @Test - public void getColumnDisplaySize() throws SQLException { - Assert.assertEquals(64, meta.getColumnDisplaySize(10)); - } - - @Test - public void getColumnLabel() throws SQLException { - Assert.assertEquals("f1", meta.getColumnLabel(1)); - } - - @Test - public void getColumnName() throws SQLException { - Assert.assertEquals("f1", meta.getColumnName(1)); - } - - @Test - public void getSchemaName() throws SQLException { - Assert.assertEquals("", meta.getSchemaName(1)); - } - - @Test - public void getPrecision() throws SQLException { - Assert.assertEquals(0, meta.getPrecision(1)); - } - - @Test - public void getScale() throws SQLException { - Assert.assertEquals(0, meta.getScale(1)); - } - - @Test - public void getTableName() throws SQLException { - Assert.assertEquals("", meta.getTableName(1)); - } - - @Test - public void getCatalogName() throws SQLException { - Assert.assertEquals("restful_test", meta.getCatalogName(1)); - Assert.assertEquals("restful_test", meta.getCatalogName(2)); - Assert.assertEquals("restful_test", meta.getCatalogName(3)); - Assert.assertEquals("restful_test", meta.getCatalogName(4)); - Assert.assertEquals("restful_test", meta.getCatalogName(5)); - Assert.assertEquals("restful_test", meta.getCatalogName(6)); - Assert.assertEquals("restful_test", meta.getCatalogName(7)); - Assert.assertEquals("restful_test", meta.getCatalogName(8)); - Assert.assertEquals("restful_test", meta.getCatalogName(9)); - Assert.assertEquals("restful_test", meta.getCatalogName(10)); - } - - @Test - public void getColumnType() throws SQLException { - Assert.assertEquals(Types.TIMESTAMP, meta.getColumnType(1)); - Assert.assertEquals(Types.INTEGER, meta.getColumnType(2)); - Assert.assertEquals(Types.BIGINT, meta.getColumnType(3)); - Assert.assertEquals(Types.FLOAT, meta.getColumnType(4)); - Assert.assertEquals(Types.DOUBLE, meta.getColumnType(5)); - Assert.assertEquals(Types.BINARY, meta.getColumnType(6)); - Assert.assertEquals(Types.SMALLINT, meta.getColumnType(7)); - Assert.assertEquals(Types.TINYINT, meta.getColumnType(8)); - Assert.assertEquals(Types.BOOLEAN, meta.getColumnType(9)); - Assert.assertEquals(Types.NCHAR, meta.getColumnType(10)); - } - - @Test - public void getColumnTypeName() throws SQLException { - Assert.assertEquals("TIMESTAMP", meta.getColumnTypeName(1)); - Assert.assertEquals("INT", meta.getColumnTypeName(2)); - Assert.assertEquals("BIGINT", meta.getColumnTypeName(3)); - Assert.assertEquals("FLOAT", meta.getColumnTypeName(4)); - Assert.assertEquals("DOUBLE", meta.getColumnTypeName(5)); - Assert.assertEquals("BINARY", meta.getColumnTypeName(6)); - Assert.assertEquals("SMALLINT", meta.getColumnTypeName(7)); - Assert.assertEquals("TINYINT", meta.getColumnTypeName(8)); - Assert.assertEquals("BOOL", meta.getColumnTypeName(9)); - Assert.assertEquals("NCHAR", meta.getColumnTypeName(10)); - } - - @Test - public void isReadOnly() throws SQLException { - Assert.assertTrue(meta.isReadOnly(1)); - } - - @Test - public void isWritable() throws SQLException { - Assert.assertFalse(meta.isWritable(1)); - } - - @Test - public void isDefinitelyWritable() throws SQLException { - Assert.assertFalse(meta.isDefinitelyWritable(1)); - } - - @Test - public void getColumnClassName() throws SQLException { - Assert.assertEquals(Timestamp.class.getName(), meta.getColumnClassName(1)); - Assert.assertEquals(Integer.class.getName(), meta.getColumnClassName(2)); - Assert.assertEquals(Long.class.getName(), meta.getColumnClassName(3)); - Assert.assertEquals(Float.class.getName(), meta.getColumnClassName(4)); - Assert.assertEquals(Double.class.getName(), meta.getColumnClassName(5)); - Assert.assertEquals(String.class.getName(), meta.getColumnClassName(6)); - Assert.assertEquals(Short.class.getName(), meta.getColumnClassName(7)); - Assert.assertEquals(Short.class.getName(), meta.getColumnClassName(8)); - Assert.assertEquals(Boolean.class.getName(), meta.getColumnClassName(9)); - Assert.assertEquals(String.class.getName(), meta.getColumnClassName(10)); - } - - @Test - public void unwrap() throws SQLException { - Assert.assertNotNull(meta.unwrap(RestfulResultSetMetaData.class)); - } - - @Test - public void isWrapperFor() throws SQLException { - Assert.assertTrue(meta.isWrapperFor(RestfulResultSetMetaData.class)); - } - - @BeforeClass - public static void beforeClass() throws SQLException { - conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); - stmt = conn.createStatement(); - stmt.execute("create database if not exists restful_test"); - stmt.execute("use restful_test"); - stmt.execute("drop table if exists weather"); - stmt.execute("create table if not exists weather(f1 timestamp, f2 int, f3 bigint, f4 float, f5 double, f6 binary(64), f7 smallint, f8 tinyint, f9 bool, f10 nchar(64))"); - stmt.execute("insert into restful_test.weather values('2021-01-01 00:00:00.000', 1, 100, 3.1415, 3.1415926, 'abc', 10, 10, true, '涛思数据')"); - rs = stmt.executeQuery("select * from restful_test.weather"); - rs.next(); - meta = rs.getMetaData(); - } - - @AfterClass - public static void afterClass() { - try { - if (rs != null) - rs.close(); - if (stmt != null) - stmt.close(); - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists " + dbname); - statement.close(); - conn.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetTest.java deleted file mode 100644 index b1ca634a21..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetTest.java +++ /dev/null @@ -1,686 +0,0 @@ -package com.taosdata.jdbc.rs; - -import com.google.common.primitives.Ints; -import com.google.common.primitives.Longs; -import com.google.common.primitives.Shorts; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.sql.*; -import java.text.ParseException; -import java.text.SimpleDateFormat; - -public class RestfulResultSetTest { - - private static final String host = "127.0.0.1"; - private static Connection conn; - private static Statement stmt; - private static ResultSet rs; - - @BeforeClass - public static void beforeClass() throws SQLException { - conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); - stmt = conn.createStatement(); - stmt.execute("drop database if exists restful_test"); - stmt.execute("create database if not exists restful_test"); - stmt.execute("use restful_test"); - stmt.execute("drop table if exists weather"); - stmt.execute("create table if not exists weather(f1 timestamp, f2 int, f3 bigint, f4 float, f5 double, f6 binary(64), f7 smallint, f8 tinyint, f9 bool, f10 nchar(64))"); - stmt.execute("insert into restful_test.weather values('2021-01-01 00:00:00.000', 1, 100, 3.1415, 3.1415926, 'abc', 10, 10, true, '涛思数据')"); - rs = stmt.executeQuery("select * from restful_test.weather"); - rs.next(); - } - - @Test - public void wasNull() throws SQLException { - Assert.assertFalse(rs.wasNull()); - } - - @Test - public void getString() throws SQLException { - String f10 = rs.getString("f10"); - Assert.assertEquals("涛思数据", f10); - f10 = rs.getString(10); - Assert.assertEquals("涛思数据", f10); - } - - @Test - public void getBoolean() throws SQLException { - Boolean f9 = rs.getBoolean("f9"); - Assert.assertEquals(true, f9); - f9 = rs.getBoolean(9); - Assert.assertEquals(true, f9); - } - - @Test - public void getByte() throws SQLException { - byte f8 = rs.getByte("f8"); - Assert.assertEquals(10, f8); - f8 = rs.getByte(8); - Assert.assertEquals(10, f8); - } - - @Test - public void getShort() throws SQLException { - short f7 = rs.getShort("f7"); - Assert.assertEquals(10, f7); - f7 = rs.getShort(7); - Assert.assertEquals(10, f7); - } - - @Test - public void getInt() throws SQLException { - int f2 = rs.getInt("f2"); - Assert.assertEquals(1, f2); - f2 = rs.getInt(2); - Assert.assertEquals(1, f2); - } - - @Test - public void getLong() throws SQLException { - long f3 = rs.getLong("f3"); - Assert.assertEquals(100, f3); - f3 = rs.getLong(3); - Assert.assertEquals(100, f3); - } - - @Test - public void getFloat() throws SQLException { - float f4 = rs.getFloat("f4"); - Assert.assertEquals(3.1415f, f4, 0f); - f4 = rs.getFloat(4); - Assert.assertEquals(3.1415f, f4, 0f); - } - - @Test - public void getDouble() throws SQLException { - double f5 = rs.getDouble("f5"); - Assert.assertEquals(3.1415926, f5, 0.0); - f5 = rs.getDouble(5); - Assert.assertEquals(3.1415926, f5, 0.0); - } - - @Test - public void getBigDecimal() throws SQLException { - BigDecimal f1 = rs.getBigDecimal("f1"); - long actual = (f1 == null) ? 0 : f1.longValue(); - Assert.assertEquals(1609430400000L, actual); - - BigDecimal f2 = rs.getBigDecimal("f2"); - Assert.assertEquals(1, f2.intValue()); - - BigDecimal f3 = rs.getBigDecimal("f3"); - Assert.assertEquals(100L, f3.longValue()); - - BigDecimal f4 = rs.getBigDecimal("f4"); - Assert.assertEquals(3.1415f, f4.floatValue(), 0.00000f); - - BigDecimal f5 = rs.getBigDecimal("f5"); - Assert.assertEquals(3.1415926, f5.doubleValue(), 0.0000000); - - BigDecimal f7 = rs.getBigDecimal("f7"); - Assert.assertEquals(10, f7.intValue()); - - BigDecimal f8 = rs.getBigDecimal("f8"); - Assert.assertEquals(10, f8.intValue()); - } - - @Test - public void getBytes() throws SQLException { - byte[] f1 = rs.getBytes("f1"); - Assert.assertEquals("2021-01-01 00:00:00.0", new String(f1)); - - byte[] f2 = rs.getBytes("f2"); - Assert.assertEquals(1, Ints.fromByteArray(f2)); - - byte[] f3 = rs.getBytes("f3"); - Assert.assertEquals(100L, Longs.fromByteArray(f3)); - - byte[] f4 = rs.getBytes("f4"); - Assert.assertEquals(3.1415f, Float.parseFloat(new String(f4)), 0.000000f); - - byte[] f5 = rs.getBytes("f5"); - Assert.assertEquals(3.1415926, Double.parseDouble(new String(f5)), 0.000000f); - - byte[] f6 = rs.getBytes("f6"); - Assert.assertEquals("abc", new String(f6)); - - byte[] f7 = rs.getBytes("f7"); - Assert.assertEquals((short) 10, Shorts.fromByteArray(f7)); - - byte[] f8 = rs.getBytes("f8"); - Assert.assertEquals(1, f8.length); - Assert.assertEquals((byte) 10, f8[0]); - - byte[] f9 = rs.getBytes("f9"); - Assert.assertEquals("true", new String(f9)); - - byte[] f10 = rs.getBytes("f10"); - Assert.assertEquals("涛思数据", new String(f10)); - } - - @Test - public void getDate() throws SQLException, ParseException { - Date f1 = rs.getDate("f1"); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - Assert.assertEquals(sdf.parse("2021-01-01"), f1); - } - - @Test - public void getTime() throws SQLException { - Time f1 = rs.getTime("f1"); - Assert.assertNotNull(f1); - Assert.assertEquals("00:00:00", f1.toString()); - } - - @Test - public void getTimestamp() throws SQLException { - Timestamp f1 = rs.getTimestamp("f1"); - Assert.assertEquals("2021-01-01 00:00:00.0", f1.toString()); - f1 = rs.getTimestamp(1); - Assert.assertEquals("2021-01-01 00:00:00.0", f1.toString()); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getAsciiStream() throws SQLException { - rs.getAsciiStream("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getUnicodeStream() throws SQLException { - rs.getUnicodeStream("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getBinaryStream() throws SQLException { - rs.getBinaryStream("f1"); - } - - @Test - public void getWarnings() throws SQLException { - Assert.assertNull(rs.getWarnings()); - } - - @Test - public void clearWarnings() throws SQLException { - rs.clearWarnings(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getCursorName() throws SQLException { - rs.getCursorName(); - } - - @Test - public void getMetaData() throws SQLException { - ResultSetMetaData meta = rs.getMetaData(); - Assert.assertNotNull(meta); - } - - @Test - public void getObject() throws SQLException, ParseException { - Object f1 = rs.getObject("f1"); - Assert.assertEquals(Timestamp.class, f1.getClass()); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.sss"); - java.util.Date date = sdf.parse("2021-01-01 00:00:00.000"); - Assert.assertEquals(new Timestamp(date.getTime()), f1); - - Object f2 = rs.getObject("f2"); - Assert.assertEquals(Integer.class, f2.getClass()); - Assert.assertEquals(1, f2); - - Object f3 = rs.getObject("f3"); - Assert.assertEquals(Long.class, f3.getClass()); - Assert.assertEquals(100L, f3); - - Object f4 = rs.getObject("f4"); - Assert.assertEquals(Float.class, f4.getClass()); - Assert.assertEquals(3.1415f, f4); - - Object f5 = rs.getObject("f5"); - Assert.assertEquals(Double.class, f5.getClass()); - Assert.assertEquals(3.1415926, f5); - - Object f6 = rs.getObject("f6"); - Assert.assertEquals(byte[].class, f6.getClass()); - Assert.assertEquals("abc", new String((byte[]) f6)); - - Object f7 = rs.getObject("f7"); - Assert.assertEquals(Short.class, f7.getClass()); - Assert.assertEquals((short) 10, f7); - - Object f8 = rs.getObject("f8"); - Assert.assertEquals(Byte.class, f8.getClass()); - Assert.assertEquals((byte) 10, f8); - - Object f9 = rs.getObject("f9"); - Assert.assertEquals(Boolean.class, f9.getClass()); - Assert.assertEquals(true, f9); - - Object f10 = rs.getObject("f10"); - Assert.assertEquals(String.class, f10.getClass()); - Assert.assertEquals("涛思数据", f10); - } - - @Test(expected = SQLException.class) - public void findColumn() throws SQLException { - int columnIndex = rs.findColumn("f1"); - Assert.assertEquals(1, columnIndex); - columnIndex = rs.findColumn("f2"); - Assert.assertEquals(2, columnIndex); - columnIndex = rs.findColumn("f3"); - Assert.assertEquals(3, columnIndex); - columnIndex = rs.findColumn("f4"); - Assert.assertEquals(4, columnIndex); - columnIndex = rs.findColumn("f5"); - Assert.assertEquals(5, columnIndex); - columnIndex = rs.findColumn("f6"); - Assert.assertEquals(6, columnIndex); - columnIndex = rs.findColumn("f7"); - Assert.assertEquals(7, columnIndex); - columnIndex = rs.findColumn("f8"); - Assert.assertEquals(8, columnIndex); - columnIndex = rs.findColumn("f9"); - Assert.assertEquals(9, columnIndex); - columnIndex = rs.findColumn("f10"); - Assert.assertEquals(10, columnIndex); - - rs.findColumn("f11"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getCharacterStream() throws SQLException { - rs.getCharacterStream(1); - } - - @Test - public void isBeforeFirst() throws SQLException { - Assert.assertFalse(rs.isBeforeFirst()); - rs.beforeFirst(); - Assert.assertTrue(rs.isBeforeFirst()); - rs.next(); - } - - @Test - public void isAfterLast() throws SQLException { - Assert.assertFalse(rs.isAfterLast()); - } - - @Test - public void isFirst() throws SQLException { - Assert.assertTrue(rs.isFirst()); - } - - @Test - public void isLast() throws SQLException { - Assert.assertTrue(rs.isLast()); - } - - @Test - public void beforeFirst() throws SQLException { - rs.beforeFirst(); - Assert.assertTrue(rs.isBeforeFirst()); - rs.next(); - } - - @Test - public void afterLast() throws SQLException { - rs.afterLast(); - Assert.assertTrue(rs.isAfterLast()); - rs.first(); - } - - @Test - public void first() throws SQLException { - rs.first(); - Assert.assertEquals("2021-01-01 00:00:00.0", rs.getTimestamp("f1").toString()); - } - - @Test - public void last() throws SQLException { - rs.last(); - Assert.assertEquals("2021-01-01 00:00:00.0", rs.getTimestamp("f1").toString()); - } - - @Test - public void getRow() throws SQLException { - int row = rs.getRow(); - Assert.assertEquals(1, row); - rs.beforeFirst(); - row = rs.getRow(); - Assert.assertEquals(0, row); - rs.first(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void absolute() throws SQLException { - rs.absolute(-1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void relative() throws SQLException { - rs.relative(-1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void previous() throws SQLException { - rs.previous(); - } - - @Test - public void setFetchDirection() throws SQLException { - rs.setFetchDirection(ResultSet.FETCH_FORWARD); - Assert.assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection()); - rs.setFetchDirection(ResultSet.FETCH_UNKNOWN); - Assert.assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection()); - } - - @Test - public void getFetchDirection() throws SQLException { - Assert.assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection()); - } - - @Test - public void setFetchSize() throws SQLException { - rs.setFetchSize(0); - Assert.assertEquals(0, rs.getFetchSize()); - } - - @Test - public void getFetchSize() throws SQLException { - Assert.assertEquals(0, rs.getFetchSize()); - } - - @Test - public void getType() throws SQLException { - Assert.assertEquals(ResultSet.TYPE_FORWARD_ONLY, rs.getType()); - } - - @Test - public void getConcurrency() throws SQLException { - Assert.assertEquals(ResultSet.CONCUR_READ_ONLY, rs.getConcurrency()); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void rowUpdated() throws SQLException { - rs.rowUpdated(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void rowInserted() throws SQLException { - rs.rowInserted(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void rowDeleted() throws SQLException { - rs.rowDeleted(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateNull() throws SQLException { - rs.updateNull("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateBoolean() throws SQLException { - rs.updateBoolean(1, false); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateByte() throws SQLException { - rs.updateByte(1, new Byte("0")); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateShort() throws SQLException { - rs.updateShort(1, new Short("0")); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateInt() throws SQLException { - rs.updateInt(1, 1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateLong() throws SQLException { - rs.updateLong(1, 1L); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateFloat() throws SQLException { - rs.updateFloat(1, 1f); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateDouble() throws SQLException { - rs.updateDouble(1, 1.0); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateBigDecimal() throws SQLException { - rs.updateBigDecimal(1, new BigDecimal(1)); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateString() throws SQLException { - rs.updateString(1, "abc"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateBytes() throws SQLException { - rs.updateBytes(1, new byte[]{}); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateDate() throws SQLException { - rs.updateDate(1, new Date(System.currentTimeMillis())); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateTime() throws SQLException { - rs.updateTime(1, new Time(System.currentTimeMillis())); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateTimestamp() throws SQLException { - rs.updateTimestamp(1, new Timestamp(System.currentTimeMillis())); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateAsciiStream() throws SQLException { - rs.updateAsciiStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateBinaryStream() throws SQLException { - rs.updateBinaryStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateCharacterStream() throws SQLException { - rs.updateCharacterStream(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateObject() throws SQLException { - rs.updateObject(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void insertRow() throws SQLException { - rs.insertRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateRow() throws SQLException { - rs.updateRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void deleteRow() throws SQLException { - rs.deleteRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void refreshRow() throws SQLException { - rs.refreshRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void cancelRowUpdates() throws SQLException { - rs.cancelRowUpdates(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void moveToInsertRow() throws SQLException { - rs.moveToInsertRow(); - } - - @Test - public void getStatement() throws SQLException { - Statement stmt = rs.getStatement(); - Assert.assertNotNull(stmt); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void moveToCurrentRow() throws SQLException { - rs.moveToCurrentRow(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getRef() throws SQLException { - rs.getRef(1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getBlob() throws SQLException { - rs.getBlob("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getClob() throws SQLException { - rs.getClob("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getArray() throws SQLException { - rs.getArray("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getURL() throws SQLException { - rs.getURL("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateRef() throws SQLException { - rs.updateRef("f1", null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateBlob() throws SQLException { - rs.updateBlob(1, (InputStream) null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateClob() throws SQLException { - rs.updateClob(1, (Reader) null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateArray() throws SQLException { - rs.updateArray(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getRowId() throws SQLException { - rs.getRowId("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateRowId() throws SQLException { - rs.updateRowId(1, null); - } - - @Test - public void getHoldability() throws SQLException { - Assert.assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, rs.getHoldability()); - } - - @Test - public void isClosed() throws SQLException { - Assert.assertFalse(rs.isClosed()); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateNString() throws SQLException { - rs.updateNString(1, null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateNClob() throws SQLException { - rs.updateNClob(1, (Reader) null); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getNClob() throws SQLException { - rs.getNClob("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getSQLXML() throws SQLException { - rs.getSQLXML("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateSQLXML() throws SQLException { - rs.updateSQLXML(1, null); - } - - @Test - public void getNString() throws SQLException { - String f10 = rs.getNString("f10"); - Assert.assertEquals("涛思数据", f10); - f10 = rs.getNString(10); - Assert.assertEquals("涛思数据", f10); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getNCharacterStream() throws SQLException { - rs.getNCharacterStream("f1"); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void updateNCharacterStream() throws SQLException { - rs.updateNCharacterStream(1, null); - } - - @Test - public void unwrap() throws SQLException { - RestfulResultSet unwrap = rs.unwrap(RestfulResultSet.class); - Assert.assertNotNull(unwrap); - } - - @Test - public void isWrapperFor() throws SQLException { - Assert.assertTrue(rs.isWrapperFor(RestfulResultSet.class)); - } - - @AfterClass - public static void afterClass() throws SQLException { - if (rs != null) - rs.close(); - if (stmt != null) { - stmt.execute("drop database if exists restful_test"); - stmt.close(); - } - if (conn != null) - conn.close(); - } - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulStatementTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulStatementTest.java deleted file mode 100644 index f6d93217a5..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulStatementTest.java +++ /dev/null @@ -1,365 +0,0 @@ -package com.taosdata.jdbc.rs; - -import com.taosdata.jdbc.TSDBDriver; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.sql.*; -import java.util.Properties; -import java.util.UUID; - -public class RestfulStatementTest { - private static final String host = "127.0.0.1"; - - private static Connection conn; - private static Statement stmt; - - @Test - public void executeQuery() throws SQLException { - ResultSet rs = stmt.executeQuery("show databases"); - Assert.assertNotNull(rs); - ResultSetMetaData meta = rs.getMetaData(); - int columnCount = meta.getColumnCount(); - Assert.assertTrue(columnCount > 1); - while (rs.next()) { - Assert.assertEquals("name", meta.getColumnLabel(1)); - Assert.assertNotNull(rs.getString("name")); - } - rs.close(); - } - - @Test - public void executeUpdate() throws SQLException { - final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); - int affectRows = stmt.executeUpdate("create database " + dbName); - Assert.assertEquals(0, affectRows); - affectRows = stmt.executeUpdate("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); - Assert.assertEquals(0, affectRows); - - try (ResultSet resultSet = stmt.executeQuery("desc " + dbName + ".weather")){ - ResultSetMetaData metaData = resultSet.getMetaData(); - Assert.assertEquals(4, metaData.getColumnCount()); - } - - affectRows = stmt.executeUpdate("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); - Assert.assertEquals(1, affectRows); - affectRows = stmt.executeUpdate("drop database " + dbName); - Assert.assertEquals(0, affectRows); - } - - @Test - public void getMaxFieldSize() throws SQLException { - Assert.assertEquals(16 * 1024, stmt.getMaxFieldSize()); - } - - @Test(expected = SQLException.class) - public void setMaxFieldSize() throws SQLException { - stmt.setMaxFieldSize(0); - stmt.setMaxFieldSize(-1); - } - - @Test - public void getMaxRows() throws SQLException { - Assert.assertEquals(0, stmt.getMaxRows()); - } - - @Test(expected = SQLException.class) - public void setMaxRows() throws SQLException { - stmt.setMaxRows(0); - stmt.setMaxRows(-1); - } - - @Test - public void setEscapeProcessing() throws SQLException { - stmt.setEscapeProcessing(true); - stmt.setEscapeProcessing(false); - } - - @Test - public void getQueryTimeout() throws SQLException { - Assert.assertEquals(0, stmt.getQueryTimeout()); - } - - @Test(expected = SQLException.class) - public void setQueryTimeout() throws SQLException { - stmt.setQueryTimeout(0); - stmt.setQueryTimeout(-1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void cancel() throws SQLException { - stmt.cancel(); - } - - @Test - public void getWarnings() throws SQLException { - Assert.assertNull(stmt.getWarnings()); - } - - @Test - public void clearWarnings() throws SQLException { - stmt.clearWarnings(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void setCursorName() throws SQLException { - stmt.setCursorName(""); - } - - @Test - public void execute() throws SQLException { - final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); - boolean isSelect = stmt.execute("create database if not exists " + dbName); - Assert.assertEquals(false, isSelect); - int affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(0, affectedRows); - - isSelect = stmt.execute("create table if not exists " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); - Assert.assertEquals(false, isSelect); - affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(0, affectedRows); - - isSelect = stmt.execute("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); - Assert.assertEquals(false, isSelect); - affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(1, affectedRows); - - isSelect = stmt.execute("select * from " + dbName + ".weather"); - Assert.assertEquals(true, isSelect); - - isSelect = stmt.execute("drop database " + dbName); - Assert.assertEquals(false, isSelect); - affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(0, affectedRows); - } - - @Test - public void getResultSet() throws SQLException { - final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); - boolean isSelect = stmt.execute("create database if not exists " + dbName); - Assert.assertEquals(false, isSelect); - int affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(0, affectedRows); - - isSelect = stmt.execute("create table if not exists " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); - Assert.assertEquals(false, isSelect); - affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(0, affectedRows); - - isSelect = stmt.execute("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); - Assert.assertEquals(false, isSelect); - affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(1, affectedRows); - - isSelect = stmt.execute("select * from " + dbName + ".weather"); - Assert.assertEquals(true, isSelect); - ResultSet rs = stmt.getResultSet(); - Assert.assertNotNull(rs); - ResultSetMetaData meta = rs.getMetaData(); - Assert.assertEquals(3, meta.getColumnCount()); - int count = 0; - while (rs.next()) { - Assert.assertEquals("ts", meta.getColumnLabel(1)); - Assert.assertNotNull(rs.getTimestamp(1)); - Assert.assertEquals("temperature", meta.getColumnLabel(2)); - Assert.assertEquals(22.33, rs.getFloat(2), 0.001f); - count++; - } - Assert.assertEquals(1, count); - - isSelect = stmt.execute("drop database " + dbName); - Assert.assertEquals(false, isSelect); - affectedRows = stmt.getUpdateCount(); - Assert.assertEquals(0, affectedRows); - } - - @Test - public void getMoreResults() throws SQLException { - Assert.assertEquals(false, stmt.getMoreResults()); - } - - @Test(expected = SQLException.class) - public void setFetchDirection() throws SQLException { - stmt.setFetchDirection(ResultSet.FETCH_FORWARD); - stmt.setFetchDirection(ResultSet.FETCH_REVERSE); - stmt.setFetchDirection(ResultSet.FETCH_UNKNOWN); - stmt.setFetchDirection(-1); - } - - @Test - public void getFetchDirection() throws SQLException { - Assert.assertEquals(ResultSet.FETCH_FORWARD, stmt.getFetchDirection()); - } - - @Test(expected = SQLException.class) - public void setFetchSize() throws SQLException { - stmt.setFetchSize(0); - stmt.setFetchSize(-1); - } - - @Test - public void getFetchSize() throws SQLException { - stmt.setFetchSize(0); - Assert.assertEquals(0, stmt.getFetchSize()); - stmt.setFetchSize(0); - } - - @Test - public void getResultSetConcurrency() throws SQLException { - Assert.assertEquals(ResultSet.CONCUR_READ_ONLY, stmt.getResultSetConcurrency()); - } - - @Test - public void getResultSetType() throws SQLException { - Assert.assertEquals(ResultSet.TYPE_FORWARD_ONLY, stmt.getResultSetType()); - } - - @Test - public void addBatch() throws SQLException { - final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); - stmt.addBatch("create database " + dbName); - stmt.addBatch("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); - stmt.addBatch("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); - stmt.addBatch("select * from " + dbName + ".weather"); - stmt.addBatch("drop database " + dbName); - } - - @Test - public void clearBatch() throws SQLException { - final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); - stmt.clearBatch(); - stmt.addBatch("create database " + dbName); - stmt.addBatch("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); - stmt.addBatch("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); - stmt.addBatch("select * from " + dbName + ".weather"); - stmt.addBatch("drop database " + dbName); - stmt.clearBatch(); - } - - @Test - public void executeBatch() throws SQLException { - final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); - stmt.addBatch("create database " + dbName); - stmt.addBatch("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); - stmt.addBatch("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); - stmt.addBatch("select * from " + dbName + ".weather"); - stmt.addBatch("drop database " + dbName); - int[] results = stmt.executeBatch(); - Assert.assertEquals(0, results[0]); - Assert.assertEquals(0, results[1]); - Assert.assertEquals(1, results[2]); - Assert.assertEquals(Statement.SUCCESS_NO_INFO, results[3]); - Assert.assertEquals(0, results[4]); - } - - @Test - public void getConnection() throws SQLException { - Connection connection = stmt.getConnection(); - Assert.assertNotNull(connection); - Assert.assertTrue(this.conn == connection); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testGetMoreResults() throws SQLException { - Assert.assertEquals(false, stmt.getMoreResults(Statement.CLOSE_CURRENT_RESULT)); - stmt.getMoreResults(Statement.KEEP_CURRENT_RESULT); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void getGeneratedKeys() throws SQLException { - stmt.getGeneratedKeys(); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testExecuteUpdate() throws SQLException { - stmt.executeUpdate("", 1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testExecuteUpdate1() throws SQLException { - stmt.executeUpdate("", new int[]{}); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testExecuteUpdate2() throws SQLException { - stmt.executeUpdate("", new String[]{}); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testExecute() throws SQLException { - stmt.execute("", 1); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testExecute1() throws SQLException { - stmt.execute("", new int[]{}); - } - - @Test(expected = SQLFeatureNotSupportedException.class) - public void testExecute2() throws SQLException { - stmt.execute("", new String[]{}); - } - - @Test - public void getResultSetHoldability() throws SQLException { - Assert.assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, stmt.getResultSetHoldability()); - } - - @Test - public void isClosed() throws SQLException { - Assert.assertEquals(false, stmt.isClosed()); - } - - @Test - public void setPoolable() throws SQLException { - stmt.setPoolable(true); - stmt.setPoolable(false); - } - - @Test - public void isPoolable() throws SQLException { - Assert.assertEquals(false, stmt.isPoolable()); - } - - @Test - public void closeOnCompletion() throws SQLException { - stmt.closeOnCompletion(); - } - - @Test - public void isCloseOnCompletion() throws SQLException { - Assert.assertFalse(stmt.isCloseOnCompletion()); - } - - @Test - public void unwrap() throws SQLException { - RestfulStatement unwrap = stmt.unwrap(RestfulStatement.class); - Assert.assertNotNull(unwrap); - } - - @Test - public void isWrapperFor() throws SQLException { - Assert.assertTrue(stmt.isWrapperFor(RestfulStatement.class)); - } - - @BeforeClass - public static void beforeClass() throws SQLException { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata", properties); - stmt = conn.createStatement(); - } - - @AfterClass - public static void afterClass() throws SQLException { - if (stmt != null) - stmt.close(); - if (conn != null) - conn.close(); - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/SQLTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/SQLTest.java deleted file mode 100644 index 4893e6062f..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/SQLTest.java +++ /dev/null @@ -1,586 +0,0 @@ -package com.taosdata.jdbc.rs; - -import org.junit.*; -import org.junit.runners.MethodSorters; - -import java.sql.*; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class SQLTest { - - private static final String host = "127.0.0.1"; - private static Connection connection; - - @Test - public void testCase001() { - // given - String sql = "create database if not exists restful_test"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertFalse(execute); - } - - @Test - public void testCase002() { - // given - String sql = "use restful_test"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertFalse(execute); - } - - @Test - public void testCase003() { - // given - String sql = "show databases"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertTrue(execute); - } - - @Test - public void testCase004() { - // given - String sql = "show tables"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertTrue(execute); - } - - @Test - public void testCase005() { - // given - String sql = "show stables"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertTrue(execute); - } - - @Test - public void testCase006() { - // given - String sql = "show dnodes"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertTrue(execute); - } - - @Test - public void testCase007() { - // given - String sql = "show vgroups"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertTrue(execute); - } - - @Test - public void testCase008() { - // given - String sql = "drop table if exists restful_test.weather"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertFalse(execute); - } - - @Test - public void testCase009() { - // given - String sql = "create table if not exists restful_test.weather(ts timestamp, temperature float) tags(location nchar(64))"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertFalse(execute); - } - - @Test - public void testCase010() { - // given - String sql = "create table t1 using restful_test.weather tags('北京')"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertFalse(execute); - } - - @Test - public void testCase011() { - // given - String sql = "insert into restful_test.t1 values(now, 22.22)"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertFalse(execute); - } - - @Test - public void testCase012() { - // given - String sql = "insert into restful_test.t1 values('2020-01-01 00:00:00.000', 22.22)"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertFalse(execute); - } - - @Test - public void testCase013() { - // given - String sql = "insert into restful_test.t1 values('2020-01-01 00:01:00.000', 22.22),('2020-01-01 00:02:00.000', 22.22)"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertFalse(execute); - } - - @Test - public void testCase014() { - // given - String sql = "insert into restful_test.t2 using weather tags('上海') values('2020-01-01 00:03:00.000', 22.22)"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertFalse(execute); - } - - @Test - public void testCase015() { - // given - String sql = "insert into restful_test.t2 using weather tags('上海') values('2020-01-01 00:01:00.000', 22.22),('2020-01-01 00:02:00.000', 22.22)"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertFalse(execute); - } - - @Test - public void testCase016() { - // given - String sql = "insert into t1 values('2020-01-01 01:0:00.000', 22.22),('2020-01-01 02:00:00.000', 22.22) t2 values('2020-01-01 01:0:00.000', 33.33),('2020-01-01 02:00:00.000', 33.33)"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertFalse(execute); - } - - @Test - public void testCase017() { - // given - String sql = "Insert into t3 using weather tags('广东') values('2020-01-01 01:0:00.000', 22.22),('2020-01-01 02:00:00.000', 22.22) t4 using weather tags('天津') values('2020-01-01 01:0:00.000', 33.33),('2020-01-01 02:00:00.000', 33.33)"; - - // when - boolean execute = execute(connection, sql); - - // then - Assert.assertFalse(execute); - } - - @Test - public void testCase018() { - // given - String sql = "select * from restful_test.t1"; - // when - boolean execute = execute(connection, sql); - // then - Assert.assertTrue(execute); - } - - @Test - public void testCase019() { - // given - String sql = "select * from restful_test.weather"; - // when - boolean execute = execute(connection, sql); - // then - Assert.assertTrue(execute); - } - - @Test - public void testCase020() { - // given - String sql = "select ts, temperature from restful_test.t1"; - // when - boolean execute = execute(connection, sql); - // then - Assert.assertTrue(execute); - } - - @Test - public void testCase021() { - // given - String sql = "select ts, temperature from restful_test.weather"; - // when - boolean execute = execute(connection, sql); - // then - Assert.assertTrue(execute); - } - - @Test - public void testCase022() { - // given - String sql = "select temperature, ts from restful_test.t1"; - // when - boolean execute = execute(connection, sql); - // then - Assert.assertTrue(execute); - } - - @Test - public void testCase023() { - // given - String sql = "select temperature, ts from restful_test.weather"; - // when - boolean execute = execute(connection, sql); - // then - Assert.assertTrue(execute); - } - - @Test - public void testCase024() { - // given - String sql = "import into restful_test.t5 using weather tags('石家庄') values('2020-01-01 00:01:00.000', 22.22)"; - // when - int affectedRows = executeUpdate(connection, sql); - // then - Assert.assertEquals(1, affectedRows); - } - - @Test - public void testCase025() { - // given - String sql = "import into restful_test.t6 using weather tags('沈阳') values('2020-01-01 00:01:00.000', 22.22),('2020-01-01 00:02:00.000', 22.22)"; - // when - int affectedRows = executeUpdate(connection, sql); - // then - Assert.assertEquals(2, affectedRows); - } - - @Test - public void testCase026() { - // given - String sql = "import into restful_test.t7 using weather tags('长沙') values('2020-01-01 00:01:00.000', 22.22) restful_test.t8 using weather tags('吉林') values('2020-01-01 00:01:00.000', 22.22)"; - - // when - int affectedRows = executeUpdate(connection, sql); - // then - Assert.assertEquals(2, affectedRows); - } - - @Test - public void testCase027() { - // given - String sql = "import into restful_test.t9 using weather tags('武汉') values('2020-01-01 00:01:00.000', 22.22) ,('2020-01-02 00:01:00.000', 22.22) restful_test.t10 using weather tags('哈尔滨') values('2020-01-01 00:01:00.000', 22.22),('2020-01-02 00:01:00.000', 22.22)"; - // when - int affectedRows = executeUpdate(connection, sql); - // then - Assert.assertEquals(4, affectedRows); - } - - @Test - public void testCase028() { - // given - String sql = "select location, temperature, ts from restful_test.weather where temperature > 1"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase029() { - String sql = "select location, temperature, ts from restful_test.weather where temperature < 1"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase030() { - String sql = "select location, temperature, ts from restful_test.weather where ts > now"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase031() { - String sql = "select location, temperature, ts from restful_test.weather where ts < now"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase032() { - String sql = "select count(*) from restful_test.weather"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase033() { - String sql = "select first(*) from restful_test.weather"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase034() { - String sql = "select last(*) from restful_test.weather"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase035() { - String sql = "select last_row(*) from restful_test.weather"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase036() { - String sql = "select ts, ts as primary_key from restful_test.weather"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - - @Test - public void testCase037() { - String sql = "select database()"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase038() { - String sql = "select client_version()"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase039() { - String sql = "select server_status()"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase040() { - String sql = "select server_status() as status"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase041() { - String sql = "select tbname, location from restful_test.weather"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase042() { - String sql = "select count(tbname) from restful_test.weather"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase043() { - String sql = "select * from restful_test.weather where ts < now - 1h"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase044() { - String sql = "select * from restful_test.weather where ts < now - 1h and location like '%'"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase045() { - String sql = "select * from restful_test.weather where ts < now - 1h order by ts"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase046() { - String sql = "select last(*) from restful_test.weather where ts < now - 1h group by tbname order by tbname"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase047() { - String sql = "select * from restful_test.weather limit 2"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase048() { - String sql = "select * from restful_test.weather limit 2 offset 5"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase049() { - String sql = "select * from restful_test.t1, restful_test.t3 where t1.ts = t3.ts "; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase050() { - String sql = "select * from restful_test.t1, restful_test.t3 where t1.ts = t3.ts"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase051() { - String sql = "select * from restful_test.t1 tt, restful_test.t3 yy where tt.ts = yy.ts"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - @Test - public void testCase052() { - String sql = "select server_status()"; - // when - ResultSet rs = executeQuery(connection, sql); - // then - Assert.assertNotNull(rs); - } - - private boolean execute(Connection connection, String sql) { - try (Statement statement = connection.createStatement()) { - return statement.execute(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - return false; - } - - private ResultSet executeQuery(Connection connection, String sql) { - try (Statement statement = connection.createStatement()) { - return statement.executeQuery(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - return null; - } - - private int executeUpdate(Connection connection, String sql) { - try (Statement statement = connection.createStatement()) { - return statement.executeUpdate(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - return 0; - } - - @BeforeClass - public static void before() throws SQLException { - connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); - } - - @AfterClass - public static void after() throws SQLException { - Statement stmt = connection.createStatement(); - stmt.execute("drop database if exists restful_test"); - stmt.close(); - connection.close(); - } - -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/WasNullTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/WasNullTest.java deleted file mode 100644 index f0cd200e04..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/WasNullTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.taosdata.jdbc.rs; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.sql.*; - -public class WasNullTest { - - private static final String host = "127.0.0.1"; - private Connection conn; - - @Test - public void testGetTimestamp() throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop table if exists weather"); - stmt.execute("create table if not exists weather(f1 timestamp, f2 timestamp, f3 int)"); - stmt.execute("insert into restful_test.weather values('2021-01-01 00:00:00.000', NULL, 100)"); - - ResultSet rs = stmt.executeQuery("select * from restful_test.weather"); - ResultSetMetaData meta = rs.getMetaData(); - while (rs.next()) { - for (int i = 1; i <= meta.getColumnCount(); i++) { - if (i == 2) { - Object value = rs.getTimestamp(i); - boolean wasNull = rs.wasNull(); - Assert.assertNull(value); - Assert.assertTrue(wasNull); - } else { - Object value = rs.getObject(i); - boolean wasNull = rs.wasNull(); - Assert.assertNotNull(value); - Assert.assertFalse(wasNull); - } - } - } - } - } - - @Test - public void testGetObject() throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop table if exists weather"); - stmt.execute("create table if not exists weather(f1 timestamp, f2 int, f3 bigint, f4 float, f5 double, f6 binary(64), f7 smallint, f8 tinyint, f9 bool, f10 nchar(64))"); - stmt.execute("insert into restful_test.weather values('2021-01-01 00:00:00.000', 1, 100, 3.1415, 3.1415926, NULL, 10, 10, true, '涛思数据')"); - - ResultSet rs = stmt.executeQuery("select * from restful_test.weather"); - ResultSetMetaData meta = rs.getMetaData(); - while (rs.next()) { - for (int i = 1; i <= meta.getColumnCount(); i++) { - Object value = rs.getObject(i); - boolean wasNull = rs.wasNull(); - if (i == 6) { - Assert.assertNull(value); - Assert.assertTrue(wasNull); - } else { - Assert.assertNotNull(value); - Assert.assertFalse(wasNull); - } - } - } - - } - } - - @Before - public void before() throws SQLException { - conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists restful_test"); - stmt.execute("create database if not exists restful_test"); - stmt.execute("use restful_test"); - } - } - - @After - public void after() throws SQLException { - if (conn != null) { - Statement statement = conn.createStatement(); - statement.execute("drop database if exists restful_test"); - conn.close(); - } - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/HttpClientPoolUtilTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/HttpClientPoolUtilTest.java deleted file mode 100644 index 9c71a8c33b..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/HttpClientPoolUtilTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.taosdata.jdbc.utils; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import org.junit.Test; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.sql.SQLException; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -public class HttpClientPoolUtilTest { - - String user = "root"; - String password = "taosdata"; - String host = "127.0.0.1"; - - @Test - public void useLog() { - // given - int multi = 10; - - // when - List threads = IntStream.range(0, multi).mapToObj(i -> new Thread(() -> { - try { - String token = login(multi); - executeOneSql("use log", token); - } catch (SQLException | UnsupportedEncodingException e) { - e.printStackTrace(); - } - })).collect(Collectors.toList()); - - threads.forEach(Thread::start); - - for (Thread thread : threads) { - try { - thread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - @Test - public void tableNotExist() { - // given - int multi = 20; - - // when - List threads = IntStream.range(0, multi * 25).mapToObj(i -> new Thread(() -> { - try { -// String token = "/KfeAzX/f9na8qdtNZmtONryp201ma04bEl8LcvLUd7a8qdtNZmtONryp201ma04"; - String token = login(multi); - executeOneSql("insert into log.tb_not_exist values(now, 1)", token); - executeOneSql("select last(*) from log.dn", token); - } catch (SQLException | UnsupportedEncodingException e) { - e.printStackTrace(); - } - })).collect(Collectors.toList()); - - threads.forEach(Thread::start); - - for (Thread thread : threads) { - try { - thread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - private String login(int connPoolSize) throws SQLException, UnsupportedEncodingException { - user = URLEncoder.encode(user, StandardCharsets.UTF_8.displayName()); - password = URLEncoder.encode(password, StandardCharsets.UTF_8.displayName()); - String loginUrl = "http://" + host + ":" + 6041 + "/rest/login/" + user + "/" + password + ""; - HttpClientPoolUtil.init(connPoolSize, false); - String result = HttpClientPoolUtil.execute(loginUrl); - JSONObject jsonResult = JSON.parseObject(result); - String status = jsonResult.getString("status"); - String token = jsonResult.getString("desc"); - if (!status.equals("succ")) { - throw new SQLException(jsonResult.getString("desc")); - } - return "Basic " + token; - } - - private boolean executeOneSql(String sql, String token) throws SQLException { - String url = "http://" + host + ":6041/rest/sql"; - String result = HttpClientPoolUtil.execute(url, sql, token); - JSONObject resultJson = JSON.parseObject(result); - if (resultJson.getString("status").equals("error")) { -// HttpClientPoolUtil.reset(); -// throw TSDBError.createSQLException(resultJson.getInteger("code"), resultJson.getString("desc")); - return false; - } - return true; - } - - -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/OSUtilsTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/OSUtilsTest.java deleted file mode 100644 index 269a19e7a0..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/OSUtilsTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.taosdata.jdbc.utils; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class OSUtilsTest { - - private String OS; - - @Test - public void inWindows() { - Assert.assertEquals(OS.contains("win"), OSUtils.isWindows()); - } - - @Test - public void isMac() { - Assert.assertEquals(OS.contains("mac"), OSUtils.isMac()); - } - - @Test - public void isLinux() { - Assert.assertEquals(OS.contains("nux"), OSUtils.isLinux()); - } - - @Before - public void before() { - OS = System.getProperty("os.name").toLowerCase(); - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/TimestampUtil.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/TimestampUtil.java deleted file mode 100644 index eaebd92d8e..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/TimestampUtil.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.taosdata.jdbc.utils; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -public class TimestampUtil { - - private static final String datetimeFormat = "yyyy-MM-dd HH:mm:ss.SSS"; - - public static long datetimeToLong(String dateTime) { - SimpleDateFormat sdf = new SimpleDateFormat(datetimeFormat); - try { - return sdf.parse(dateTime).getTime(); - } catch (ParseException e) { - throw new IllegalArgumentException("invalid datetime string >>> " + dateTime); - } - } - - public static String longToDatetime(long time) { - SimpleDateFormat sdf = new SimpleDateFormat(datetimeFormat); - return sdf.format(new Date(time)); - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/UtilsTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/UtilsTest.java deleted file mode 100644 index 66ecb9d63b..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/UtilsTest.java +++ /dev/null @@ -1,208 +0,0 @@ -package com.taosdata.jdbc.utils; - -import org.junit.Assert; -import org.junit.Test; - -import java.util.stream.Stream; - -public class UtilsTest { - - @Test - public void escapeSingleQuota() { - // given - String s = "'''''a\\'"; - // when - String news = Utils.escapeSingleQuota(s); - // then - Assert.assertEquals("\\'\\'\\'\\'\\'a\\'", news); - - // given - s = "'''''a\\'"; - // when - news = Utils.escapeSingleQuota(s); - // then - Assert.assertEquals("\\'\\'\\'\\'\\'a\\'", news); - - // given - s = "'''''a\\'"; - // when - news = Utils.escapeSingleQuota(s); - // then - Assert.assertEquals("\\'\\'\\'\\'\\'a\\'", news); - } - - @Test - public void lowerCase() { - // given - String nativeSql = "insert into ?.? (ts, temperature, humidity) using ?.? tags(?,?) values(now, ?, ?)"; - Object[] parameters = Stream.of("test", "t1", "test", "weather", "beijing", 1, 12.2, 4).toArray(); - - // when - String actual = Utils.getNativeSql(nativeSql, parameters); - - // then - String expected = "insert into test.t1 (ts, temperature, humidity) using test.weather tags('beijing',1) values(now, 12.2, 4)"; - Assert.assertEquals(expected, actual); - } - - @Test - public void upperCase() { - // given - String nativeSql = "INSERT INTO ? (TS,CURRENT,VOLTAGE,PHASE) USING METERS TAGS (?) VALUES (?,?,?,?)"; - Object[] parameters = Stream.of("d1", 1, 123, 3.14, 220, 4).toArray(); - - // when - String actual = Utils.getNativeSql(nativeSql, parameters); - - // then - String expected = "INSERT INTO d1 (TS,CURRENT,VOLTAGE,PHASE) USING METERS TAGS (1) VALUES (123,3.14,220,4)"; - Assert.assertEquals(expected, actual); - } - - @Test - public void multiValues() { - // given - String nativeSql = "INSERT INTO ? (TS,CURRENT,VOLTAGE,PHASE) USING METERS TAGS (?) VALUES (?,?,?,?),(?,?,?,?)"; - Object[] parameters = Stream.of("d1", 1, 100, 3.14, "abc", 4, 200, 3.1415, "xyz", 5).toArray(); - - // when - String actual = Utils.getNativeSql(nativeSql, parameters); - - // then - String expected = "INSERT INTO d1 (TS,CURRENT,VOLTAGE,PHASE) USING METERS TAGS (1) VALUES (100,3.14,'abc',4),(200,3.1415,'xyz',5)"; - Assert.assertEquals(expected, actual); - } - - @Test - public void multiValuesAndWhitespace() { - // given - String nativeSql = "INSERT INTO ? (TS,CURRENT,VOLTAGE,PHASE) USING METERS TAGS (?) VALUES (?,?,?,?) (?,?,?,?) (?,?,?,?)"; - Object[] parameters = Stream.of("d1", 1, 100, 3.14, "abc", 4, 200, 3.1415, "xyz", 5, 300, 3.141592, "uvw", 6).toArray(); - - // when - String actual = Utils.getNativeSql(nativeSql, parameters); - - // then - String expected = "INSERT INTO d1 (TS,CURRENT,VOLTAGE,PHASE) USING METERS TAGS (1) VALUES (100,3.14,'abc',4) (200,3.1415,'xyz',5) (300,3.141592,'uvw',6)"; - Assert.assertEquals(expected, actual); - } - - @Test - public void multiValuesNoSeparator() { - // given - String nativeSql = "INSERT INTO ? (TS,CURRENT,VOLTAGE,PHASE) USING METERS TAGS (?) VALUES (?,?,?,?)(?,?,?,?)(?,?,?,?)"; - Object[] parameters = Stream.of("d1", 1, 100, 3.14, "abc", 4, 200, 3.1415, "xyz", 5, 300, 3.141592, "uvw", 6).toArray(); - - // when - String actual = Utils.getNativeSql(nativeSql, parameters); - - // then - String expected = "INSERT INTO d1 (TS,CURRENT,VOLTAGE,PHASE) USING METERS TAGS (1) VALUES (100,3.14,'abc',4)(200,3.1415,'xyz',5)(300,3.141592,'uvw',6)"; - Assert.assertEquals(expected, actual); - } - - @Test - public void multiValuesMultiSeparator() { - // given - String nativeSql = "INSERT INTO ? (TS,CURRENT,VOLTAGE,PHASE) USING METERS TAGS (?) VALUES (?,?,?,?) (?,?,?,?), (?,?,?,?)"; - Object[] parameters = Stream.of("d1", 1, 100, 3.14, "abc", 4, 200, 3.1415, "xyz", 5, 300, 3.141592, "uvw", 6).toArray(); - - // when - String actual = Utils.getNativeSql(nativeSql, parameters); - - // then - String expected = "INSERT INTO d1 (TS,CURRENT,VOLTAGE,PHASE) USING METERS TAGS (1) VALUES (100,3.14,'abc',4) (200,3.1415,'xyz',5), (300,3.141592,'uvw',6)"; - Assert.assertEquals(expected, actual); - } - - @Test - public void lineTerminator() { - // given - String nativeSql = "INSERT INTO ? (TS,CURRENT,VOLTAGE,PHASE) USING METERS TAGS (?) VALUES (?,?,\r\n?,?),(?,?,?,?)"; - Object[] parameters = Stream.of("d1", 1, 100, 3.14, "abc", 4, 200, 3.1415, "xyz", 5).toArray(); - - // when - String actual = Utils.getNativeSql(nativeSql, parameters); - - // then - String expected = "INSERT INTO d1 (TS,CURRENT,VOLTAGE,PHASE) USING METERS TAGS (1) VALUES (100,3.14,\r\n'abc',4),(200,3.1415,'xyz',5)"; - Assert.assertEquals(expected, actual); - } - - @Test - public void lineTerminatorAndMultiValues() { - String nativeSql = "INSERT Into ? TAGS(?) VALUES(?,?,\r\n?,?),(?,? ,\r\n?,?) t? tags (?) Values (?,?,?\r\n,?),(?,?,?,?) t? Tags(?) values (?,?,?,?) , (?,?,?,?)"; - Object[] parameters = Stream.of("t1", "abc", 100, 1.1, "xxx", "xxx", 200, 2.2, "xxx", "xxx", 2, "bcd", 300, 3.3, "xxx", "xxx", 400, 4.4, "xxx", "xxx", 3, "cde", 500, 5.5, "xxx", "xxx", 600, 6.6, "xxx", "xxx").toArray(); - - // when - String actual = Utils.getNativeSql(nativeSql, parameters); - - // then - String expected = "INSERT Into t1 TAGS('abc') VALUES(100,1.1,\r\n'xxx','xxx'),(200,2.2 ,\r\n'xxx','xxx') t2 tags ('bcd') Values (300,3.3,'xxx'\r\n,'xxx'),(400,4.4,'xxx','xxx') t3 Tags('cde') values (500,5.5,'xxx','xxx') , (600,6.6,'xxx','xxx')"; - Assert.assertEquals(expected, actual); - } - - @Test - public void lineTerminatorAndMultiValuesAndNoneOrMoreWhitespace() { - String nativeSql = "INSERT Into ? TAGS(?) VALUES(?,?,\r\n?,?),(?,? ,\r\n?,?) t? tags (?) Values (?,?,?\r\n,?) (?,?,?,?) t? Tags(?) values (?,?,?,?) , (?,?,?,?)"; - Object[] parameters = Stream.of("t1", "abc", 100, 1.1, "xxx", "xxx", 200, 2.2, "xxx", "xxx", 2, "bcd", 300, 3.3, "xxx", "xxx", 400, 4.4, "xxx", "xxx", 3, "cde", 500, 5.5, "xxx", "xxx", 600, 6.6, "xxx", "xxx").toArray(); - - // when - String actual = Utils.getNativeSql(nativeSql, parameters); - - // then - String expected = "INSERT Into t1 TAGS('abc') VALUES(100,1.1,\r\n'xxx','xxx'),(200,2.2 ,\r\n'xxx','xxx') t2 tags ('bcd') Values (300,3.3,'xxx'\r\n,'xxx') (400,4.4,'xxx','xxx') t3 Tags('cde') values (500,5.5,'xxx','xxx') , (600,6.6,'xxx','xxx')"; - Assert.assertEquals(expected, actual); - } - - @Test - public void multiValuesAndNoneOrMoreWhitespace() { - String nativeSql = "INSERT INTO ? USING traces TAGS (?, ?) VALUES (?, ?, ?, ?, ?, ?, ?) (?, ?, ?, ?, ?, ?, ?)"; - Object[] parameters = Stream.of("t1", "t1", "t2", 1632968284000L, 111.111, 119.001, 0.4, 90, 99.1, "WGS84", 1632968285000L, 111.21109999999999, 120.001, 0.5, 91, 99.19999999999999, "WGS84").toArray(); - - // when - String actual = Utils.getNativeSql(nativeSql, parameters); - - // then - String expected = "INSERT INTO t1 USING traces TAGS ('t1', 't2') VALUES (1632968284000, 111.111, 119.001, 0.4, 90, 99.1, 'WGS84') (1632968285000, 111.21109999999999, 120.001, 0.5, 91, 99.19999999999999, 'WGS84')"; - Assert.assertEquals(expected, actual); - } - - @Test - public void replaceNothing() { - // given - String nativeSql = "insert into test.t1 (ts, temperature, humidity) using test.weather tags('beijing',1) values(now, 12.2, 4)"; - - // when - String actual = Utils.getNativeSql(nativeSql, null); - - // then - Assert.assertEquals(nativeSql, actual); - } - - @Test - public void replaceNothing2() { - // given - String nativeSql = "insert into test.t1 (ts, temperature, humidity) using test.weather tags('beijing',1) values(now, 12.2, 4)"; - Object[] parameters = Stream.of("test", "t1", "test", "weather", "beijing", 1, 12.2, 4).toArray(); - - // when - String actual = Utils.getNativeSql(nativeSql, parameters); - - // then - Assert.assertEquals(nativeSql, actual); - } - - @Test - public void replaceNothing3() { - // given - String nativeSql = "insert into ?.? (ts, temperature, humidity) using ?.? tags(?,?) values(now, ?, ?)"; - - // when - String actual = Utils.getNativeSql(nativeSql, null); - - // then - Assert.assertEquals(nativeSql, actual); - - } -} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSConnectionTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSConnectionTest.java deleted file mode 100644 index 1e531e65c1..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSConnectionTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.taosdata.jdbc.ws; - -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.annotation.CatalogRunner; -import com.taosdata.jdbc.annotation.Description; -import com.taosdata.jdbc.annotation.TestTarget; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.sql.*; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -/** - * You need to start taosadapter before testing this method - */ -@Ignore -@RunWith(CatalogRunner.class) -@TestTarget(alias = "test connection with server", author = "huolibo", version = "2.0.37") -public class WSConnectionTest { - // private static final String host = "192.168.1.98"; - private static final String host = "127.0.0.1"; - private static final int port = 6041; - private Connection connection; - - @Test - @Description("normal test with websocket server") - public void normalConection() throws SQLException { - String url = "jdbc:TAOS-RS://" + host + ":" + port + "/log?user=root&password=taosdata"; - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true"); - connection = DriverManager.getConnection(url, properties); - } - - @Test - @Description("url has no db") - public void withoutDBConection() throws SQLException { - String url = "jdbc:TAOS-RS://" + host + ":" + port + "/?user=root&password=taosdata"; - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true"); - connection = DriverManager.getConnection(url, properties); - } - - @Test - @Description("user and password in property") - public void propertyUserPassConection() throws SQLException { - String url = "jdbc:TAOS-RS://" + host + ":" + port + "/"; - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true"); - connection = DriverManager.getConnection(url, properties); - } - - @Test(expected = SQLException.class) - @Description("wrong password or user") - public void wrongUserOrPasswordConection() throws SQLException { - String url = "jdbc:TAOS-RS://" + host + ":" + port + "/log?user=abc&password=taosdata"; - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true"); - connection = DriverManager.getConnection(url, properties); - } - - @Test - @Description("sleep keep connection") - public void keepConnection() throws SQLException, InterruptedException { - String url = "jdbc:TAOS-RS://" + host + ":" + port + "/?user=root&password=taosdata"; - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true"); - connection = DriverManager.getConnection(url, properties); - TimeUnit.SECONDS.sleep(20); - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery("show databases"); - TimeUnit.SECONDS.sleep(20); - resultSet.next(); - resultSet.close(); - statement.close(); - connection.close(); - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSJsonTagTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSJsonTagTest.java deleted file mode 100644 index 4709c85868..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSJsonTagTest.java +++ /dev/null @@ -1,1277 +0,0 @@ -package com.taosdata.jdbc.ws; - -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.annotation.CatalogRunner; -import com.taosdata.jdbc.annotation.Description; -import com.taosdata.jdbc.annotation.TestTarget; -import org.junit.*; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; - -import java.sql.*; -import java.util.Properties; - -@Ignore -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(CatalogRunner.class) -@TestTarget(alias = "JsonTag", author = "huolibo", version = "2.0.38") -public class WSJsonTagTest { - private static final String dbName = "json_tag_test"; - private static Connection connection; - private static Statement statement; - private static final String superSql = "create table if not exists jsons1(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"; - private static final String[] sql = { - "insert into jsons1_1 using jsons1 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(now, 1, false, 'json1', '你是') (1591060608000, 23, true, '等等', 'json')", - "insert into jsons1_2 using jsons1 tags('{\"tag1\":5,\"tag2\":\"beijing\"}') values (1591060628000, 2, true, 'json2', 'sss')", - "insert into jsons1_3 using jsons1 tags('{\"tag1\":false,\"tag2\":\"beijing\"}') values (1591060668000, 3, false, 'json3', 'efwe')", - "insert into jsons1_4 using jsons1 tags('{\"tag1\":null,\"tag2\":\"shanghai\",\"tag3\":\"hello\"}') values (1591060728000, 4, true, 'json4', '323sd')", - "insert into jsons1_5 using jsons1 tags('{\"tag1\":1.232, \"tag2\":null}') values(1591060928000, 1, false, '你就会', 'ewe')", - "insert into jsons1_6 using jsons1 tags('{\"tag1\":11,\"tag2\":\"\",\"tag2\":null}') values(1591061628000, 11, false, '你就会','')", - "insert into jsons1_7 using jsons1 tags('{\"tag1\":\"收到货\",\"tag2\":\"\",\"tag3\":null}') values(1591062628000, 2, NULL, '你就会', 'dws')", - // test duplicate key using the first one. - "CREATE TABLE if not exists jsons1_8 using jsons1 tags('{\"tag1\":null, \"tag1\":true, \"tag1\":45, \"1tag$\":2, \" \":90}')", - - }; - - private static final String[] invalidJsonInsertSql = { - // test empty json string, save as tag is NULL - "insert into jsons1_9 using jsons1 tags('\t') values (1591062328000, 24, NULL, '你就会', '2sdw')", - }; - - private static final String[] invalidJsonCreateSql = { - "CREATE TABLE if not exists jsons1_10 using jsons1 tags('')", - "CREATE TABLE if not exists jsons1_11 using jsons1 tags(' ')", - "CREATE TABLE if not exists jsons1_12 using jsons1 tags('{}')", - "CREATE TABLE if not exists jsons1_13 using jsons1 tags('null')", - }; - - // test invalidate json - private static final String[] errorJsonInsertSql = { - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('\"efwewf\"')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('3333')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('33.33')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('false')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('[1,true]')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{222}')", - "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"fe\"}')", - }; - - private static final String[] errorSelectSql = { - "select * from jsons1 where jtag->tag1='beijing'", - "select * from jsons1 where jtag->'location'", - "select * from jsons1 where jtag->''", - "select * from jsons1 where jtag->''=9", - "select -> from jsons1", - "select ? from jsons1", - "select * from jsons1 where contains", - "select * from jsons1 where jtag->", - "select jtag->location from jsons1", - "select jtag contains location from jsons1", - "select * from jsons1 where jtag contains location", - "select * from jsons1 where jtag contains ''", - "select * from jsons1 where jtag contains 'location'='beijing'", - // test where with json tag - "select * from jsons1_1 where jtag is not null", - "select * from jsons1 where jtag='{\"tag1\":11,\"tag2\":\"\"}'", - "select * from jsons1 where jtag->'tag1'={}" - }; - - @Test - @Description("insert json tag") - public void case01_InsertTest() throws SQLException { - for (String sql : sql) { - statement.execute(sql); - } - for (String sql : invalidJsonInsertSql) { - statement.execute(sql); - } - for (String sql : invalidJsonCreateSql) { - statement.execute(sql); - } - } - - @Test - @Description("error json tag insert") - public void case02_ErrorJsonInsertTest() { - int count = 0; - for (String sql : errorJsonInsertSql) { - try { - statement.execute(sql); - } catch (SQLException e) { - count++; - } - } - Assert.assertEquals(errorJsonInsertSql.length, count); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json value is array") - public void case02_ArrayErrorTest() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"tag1\":[1,true]}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json value is empty") - public void case02_EmptyValueErrorTest() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"tag1\":{}}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json key is not ASCII") - public void case02_AbnormalKeyErrorTest1() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"。loc\":\"fff\"}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json key is '\\t'") - public void case02_AbnormalKeyErrorTest2() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"\t\":\"fff\"}')"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when json key is chinese") - public void case02_AbnormalKeyErrorTest3() throws SQLException { - statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"试试\":\"fff\"}')"); - } - - @Test - @Description("alter json tag") - public void case03_AlterTag() throws SQLException { - statement.execute("ALTER TABLE jsons1_1 SET TAG jtag='{\"tag1\":\"femail\",\"tag2\":35,\"tag3\":true}'"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when add json tag") - public void case03_AddTagErrorTest() throws SQLException { - statement.execute("ALTER STABLE jsons1 add tag tag2 nchar(20)"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when delete json tag") - public void case03_dropTagErrorTest() throws SQLException { - statement.execute("ALTER STABLE jsons1 drop tag jtag"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when set some json tag value") - public void case03_AlterTagErrorTest() throws SQLException { - statement.execute("ALTER TABLE jsons1_1 SET TAG jtag=4"); - } - - @Test - @Description("exception will throw when select syntax error") - public void case04_SelectErrorTest() { - int count = 0; - for (String sql : errorSelectSql) { - try { - statement.execute(sql); - } catch (SQLException e) { - count++; - } - } - Assert.assertEquals(errorSelectSql.length, count); - } - - @Test - @Description("normal select stable") - public void case04_select01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select dataint from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("select all column from stable") - public void case04_select02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("select json tag from stable") - public void case04_select03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1"); - ResultSetMetaData metaData = resultSet.getMetaData(); - metaData.getColumnTypeName(1); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonInsertSql.length + invalidJsonCreateSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition tag is null") - public void case04_select04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1 where jtag is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(invalidJsonInsertSql.length + invalidJsonCreateSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition tag is not null") - public void case04_select05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1 where jtag is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length, count); - close(resultSet); - } - - @Test - @Description("select json tag") - public void case04_select06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1_8"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("{\" \":90,\"tag1\":null,\"1tag$\":2}", result); - close(resultSet); - } - - @Test - @Description("select json tag") - public void case04_select07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1_1"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("{\"tag1\":\"femail\",\"tag2\":35,\"tag3\":true}", result); - close(resultSet); - } - - @Test - @Description("select not exist json tag") - public void case04_select08() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1_9"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertNull(result); - close(resultSet); - } - - @Test - @Description("select a json tag") - public void case04_select09() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_1"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("\"femail\"", result); - close(resultSet); - } - - @Test - @Description(value = "select a normal value", version = "2.0.37") - public void case04_selectNormal() throws SQLException { - ResultSet resultSet = statement.executeQuery("select datastr from jsons1_1"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("等等", result); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is empty") - public void case04_select10() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag2' from jsons1_6"); - resultSet.next(); - String result = resultSet.getString(1); - Assert.assertEquals("\"\"", result); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is int") - public void case04_select11() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag2' from jsons1_1"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("35", string); - close(resultSet); - } - - @Test - @Description("select a json tag, the value is boolean") - public void case04_select12() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag3' from jsons1_1"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("true", string); - close(resultSet); - } - -// @Test -// @Description("select a json tag, the value is null") -// public void case04_select13() throws SQLException { -// ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_4"); -// resultSet.next(); -// String string = resultSet.getString(1); -// Assert.assertEquals("null", string); -// close(resultSet); -// } - - @Test - @Description("select a json tag, the value is double") - public void case04_select14() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_5"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("1.232000000", string); - close(resultSet); - } - - @Test - @Description("select a json tag, the key is not exist") - public void case04_select15() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag10' from jsons1_4"); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertNull(string); - close(resultSet); - } - - @Test - @Description("select a json tag, the result number equals tables number") - public void case04_select16() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonCreateSql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition '=' for string") - public void case04_select19() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("select and where conditon '=' for string") - public void case04_select20() throws SQLException { - ResultSet resultSet = statement.executeQuery("select dataint,tbname,jtag->'tag1',jtag from jsons1 where jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition result is null") - public void case04_select21() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition equation has chinese") - public void case04_select23() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'='收到货'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '>' for character") - public void case05_symbolOperation01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'>'beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '>=' for character") - public void case05_symbolOperation02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'>='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '<' for character") - public void case05_symbolOperation03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'<'beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition support '<=' in character") - public void case05_symbolOperation04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'<='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' in character") - public void case05_symbolOperation05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'!='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '=' empty") - public void case05_symbolOperation06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'=''"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - // where json value is int - @Test - @Description("where condition support '=' for int") - public void case06_selectValue01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=5"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where conditional support '<' for int") - public void case06_selectValue02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<54"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '<=' for int") - public void case06_selectValue03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<=11"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where conditional support '>' for int") - public void case06_selectValue04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>4"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition support '>=' for int") - public void case06_selectValue05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>=5"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where conditional support '!=' for int") - public void case06_selectValue06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=5"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where conditional support '!=' for int") - public void case06_selectValue07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=55"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where conditional support '!=' for int and result is nothing") - public void case06_selectValue08() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=10"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support '=' for double") - public void case07_selectValue01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '<' for double") - public void case07_doubleOperation01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support '<=' for double") - public void case07_doubleOperation02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '>' for double") - public void case07_doubleOperation03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>1.23"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '>=' for double") - public void case07_doubleOperation04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' for double") - public void case07_doubleOperation05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=1.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' for double") - public void case07_doubleOperation06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=3.232"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(3, count); - close(resultSet); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when denominator is zero") - public void case07_doubleOperation07() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1'/0=3"); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when invalid operation") - public void case07_doubleOperation08() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1'/5=1"); - } - - @Test - @Description("where condition support '=' for boolean") - public void case08_boolOperation01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=true"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support '=' for boolean") - public void case08_boolOperation02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support '!=' for boolean") - public void case08_boolOperation03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=false"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test(expected = SQLException.class) - @Description("exception will throw when '>' operation for boolean") - public void case08_boolOperation04() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1'>false"); - } - - @Test - @Description("where conditional support '=null'") - public void case09_select01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where conditional support 'is null'") - public void case09_select02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition support 'is not null'") - public void case09_select03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag '='") - public void case09_select04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag_no_exist'=3"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag 'is null'") - public void case09_select05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag 'is null'") - public void case09_select06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag4' is null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(sql.length + invalidJsonInsertSql.length, count); - close(resultSet); - } - - @Test - @Description("where condition support one tag 'is not null'") - public void case09_select07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag3' is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("contains") - public void case09_select10() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag contains 'tag1'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("contains") - public void case09_select11() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("contains with no exist tag") - public void case09_select12() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag contains 'tag_no_exist'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition with and") - public void case10_selectAndOr01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false and jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition with 'or'") - public void case10_selectAndOr02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false or jtag->'tag2'='beijing'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition with 'and'") - public void case10_selectAndOr03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false and jtag->'tag2'='shanghai'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition with 'or'") - public void case10_selectAndOr04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=13 or jtag->'tag2'>35"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition with 'or' and contains") - public void case10_selectAndOr05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' is not null and jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(4, count); - close(resultSet); - } - - @Test - @Description("where condition with 'and' and contains") - public void case10_selectAndOr06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'='femail' and jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3' and dataint=3"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("test with tbname/normal column") - public void case11_selectTbName04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3' and dataint=23"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("where condition like") - public void case12_selectWhere01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,tbname from jsons1 where jtag->'tag2' like 'bei%'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition like") - public void case12_selectWhere02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,tbname from jsons1 where jtag->'tag1' like 'fe%' and jtag->'tag2' is not null"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test(expected = SQLException.class) - @Description("where condition in no support in") - public void case12_selectWhere03() throws SQLException { - statement.executeQuery("select * from jsons1 where jtag->'tag1' in ('beijing')"); - } - - @Test - @Description("where condition match") - public void case12_selectWhere04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' match 'ma'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition match") - public void case12_selectWhere05() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' match 'ma$'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("where condition match") - public void case12_selectWhere06() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2' match 'jing$'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(2, count); - close(resultSet); - } - - @Test - @Description("where condition match") - public void case12_selectWhere07() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' match '收到'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("insert distinct") - public void case13_selectDistinct01() throws SQLException { - statement.execute("insert into jsons1_14 using jsons1 tags('{\"tag1\":\"收到货\",\"tag2\":\"\",\"tag3\":null}') values(1591062628000, 2, NULL, '你就会', 'dws')"); - } - - @Test - @Description("distinct json tag") - public void case13_selectDistinct02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select distinct jtag->'tag1' from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("distinct json tag") - public void case13_selectDistinct03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select distinct jtag from jsons1"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(9, count); - close(resultSet); - } - - @Test - @Description("insert json tag") - public void case14_selectDump01() throws SQLException { - statement.execute("INSERT INTO jsons1_15 using jsons1 tags('{\"tbname\":\"tt\",\"databool\":true,\"datastr\":\"是是是\"}') values(1591060828000, 4, false, 'jjsf', \"你就会\")"); - } - - @Test - @Description("test duplicate key with normal column") - public void case14_selectDump02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,tbname,jtag from jsons1 where jtag->'datastr' match '是' and datastr match 'js'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(1, count); - close(resultSet); - } - - @Test - @Description("test duplicate key with normal column") - public void case14_selectDump03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select tbname,jtag->'tbname' from jsons1 where jtag->'tbname'='tt' and tbname='jsons1_14'"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(0, count); - close(resultSet); - } - - @Test - @Description("insert json tag for join test") - public void case15_selectJoin01() throws SQLException { - statement.execute("create table if not exists jsons2(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"); - statement.execute("insert into jsons2_1 using jsons2 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(1591060618000, 2, false, 'json2', '你是2')"); - statement.execute("insert into jsons2_2 using jsons2 tags('{\"tag1\":5,\"tag2\":null}') values (1591060628000, 2, true, 'json2', 'sss')"); - - statement.execute("create table if not exists jsons3(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"); - statement.execute("insert into jsons3_1 using jsons3 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(1591060618000, 3, false, 'json3', '你是3')"); - statement.execute("insert into jsons3_2 using jsons3 tags('{\"tag1\":5,\"tag2\":\"beijing\"}') values (1591060638000, 2, true, 'json3', 'sss')"); - } - - @Test - @Description("select json tag from join") - public void case15_selectJoin02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select 'sss',33,a.jtag->'tag3' from jsons2 a,jsons3 b where a.ts=b.ts and a.jtag->'tag1'=b.jtag->'tag1'"); - resultSet.next(); - Assert.assertEquals("sss", resultSet.getString(1)); - close(resultSet); - } - - @Test - @Description("group by and order by json tag desc") - public void case16_selectGroupOrder01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select count(*) from jsons1 group by jtag->'tag1' order by jtag->'tag1' desc"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("group by and order by json tag asc") - public void case16_selectGroupOrder02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select count(*) from jsons1 group by jtag->'tag1' order by jtag->'tag1' asc"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(8, count); - close(resultSet); - } - - @Test - @Description("stddev with group by json tag") - public void case17_selectStddev01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select stddev(dataint) from jsons1 group by jtag->'tag1'"); - String s = ""; - int count = 0; - while (resultSet.next()) { - count++; - s = resultSet.getString(2); - - } - Assert.assertEquals(8, count); - Assert.assertEquals("\"收到货\"", s); - close(resultSet); - } - - @Test - @Description("subquery json tag") - public void case18_selectSubquery01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select * from (select jtag, dataint from jsons1)"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(11, count); - close(resultSet); - } - - @Test - @Description("subquery some json tags") - public void case18_selectSubquery02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from (select jtag->'tag1', dataint from jsons1)"); - - ResultSetMetaData metaData = resultSet.getMetaData(); - String columnName = metaData.getColumnName(1); - Assert.assertEquals("jtag->'tag1'", columnName); - - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(11, count); - close(resultSet); - } - - @Test - @Description("query some json tags from subquery") - public void case18_selectSubquery04() throws SQLException { - ResultSet resultSet = statement.executeQuery("select ts,tbname,jtag->'tag1' from (select jtag->'tag1',tbname,ts from jsons1 order by ts)"); - int count = 0; - while (resultSet.next()) { - count++; - } - Assert.assertEquals(11, count); - close(resultSet); - } - - @Test - @Description(value = "query metadata for json", version = "2.0.37") - public void case19_selectMetadata01() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag from jsons1"); - ResultSetMetaData metaData = resultSet.getMetaData(); - int columnType = metaData.getColumnType(1); - String columnTypeName = metaData.getColumnTypeName(1); - Assert.assertEquals(Types.OTHER, columnType); - Assert.assertEquals("JSON", columnTypeName); - close(resultSet); - } - - @Test - @Description(value = "query metadata for json", version = "2.0.37") - public void case19_selectMetadata02() throws SQLException { - ResultSet resultSet = statement.executeQuery("select *,jtag from jsons1"); - ResultSetMetaData metaData = resultSet.getMetaData(); - int columnType = metaData.getColumnType(6); - String columnTypeName = metaData.getColumnTypeName(6); - Assert.assertEquals(Types.OTHER, columnType); - Assert.assertEquals("JSON", columnTypeName); - close(resultSet); - } - - @Test - @Description(value = "query metadata for one json result", version = "2.0.37") - public void case19_selectMetadata03() throws SQLException { - ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_6"); - ResultSetMetaData metaData = resultSet.getMetaData(); - int columnType = metaData.getColumnType(1); - String columnTypeName = metaData.getColumnTypeName(1); - Assert.assertEquals(Types.OTHER, columnType); - Assert.assertEquals("JSON", columnTypeName); - resultSet.next(); - String string = resultSet.getString(1); - Assert.assertEquals("11", string); - close(resultSet); - } - - private void close(ResultSet resultSet) { - try { - if (null != resultSet) { - resultSet.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @BeforeClass - public static void beforeClass() { -// String host = "192.168.1.98"; - String host = "127.0.0.1"; - final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - try { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true"); - connection = DriverManager.getConnection(url, properties); - statement = connection.createStatement(); - statement.execute("drop database if exists " + dbName); - statement.execute("create database if not exists " + dbName); - statement.execute("use " + dbName); - statement.execute(superSql); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @AfterClass - public static void afterClass() { - try { - if (null != statement) { -// statement.execute("drop database " + dbName); - statement.close(); - } - if (null != connection) { - connection.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSQueryTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSQueryTest.java deleted file mode 100644 index f00f850dd4..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSQueryTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.taosdata.jdbc.ws; - -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.annotation.CatalogRunner; -import com.taosdata.jdbc.annotation.Description; -import com.taosdata.jdbc.annotation.TestTarget; -import org.junit.*; -import org.junit.runner.RunWith; - -import java.sql.*; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.IntStream; - -@Ignore -@RunWith(CatalogRunner.class) -@TestTarget(alias = "query test", author = "huolibo", version = "2.0.38") -@FixMethodOrder -public class WSQueryTest { - // private static final String host = "192.168.1.98"; - private static final String host = "127.0.0.1"; - private static final int port = 6041; - private static final String databaseName = "ws_query"; - private static final String tableName = "wq"; - private Connection connection; - private long now; - - @Description("query") - @Test - public void queryBlock() throws InterruptedException { - CountDownLatch latch = new CountDownLatch(1000); - IntStream.range(1, 10000).limit(1000).parallel().forEach(x -> { - try (Statement statement = connection.createStatement()) { - statement.execute("insert into " + databaseName + "." + tableName + " values(now+100s, 100)"); - - ResultSet resultSet = statement.executeQuery("select * from " + databaseName + "." + tableName); - resultSet.next(); - Assert.assertEquals(100, resultSet.getInt(2)); - statement.close(); - latch.countDown(); - } catch (SQLException e) { - e.printStackTrace(); - } - }); - latch.await(); - } - - @Before - public void before() throws SQLException { - String url = "jdbc:TAOS-RS://" + host + ":" + port + "/log?user=root&password=taosdata"; - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true"); - connection = DriverManager.getConnection(url, properties); - Statement statement = connection.createStatement(); - statement.execute("drop database if exists " + databaseName); - statement.execute("create database " + databaseName); - statement.execute("use " + databaseName); - statement.execute("create table if not exists " + databaseName + "." + tableName + "(ts timestamp, f int)"); - statement.close(); - } -} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSSelectTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSSelectTest.java deleted file mode 100644 index fa48480592..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSSelectTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.taosdata.jdbc.ws; - -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.enums.TimestampFormat; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import java.sql.*; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -@Ignore -public class WSSelectTest { - // private static final String host = "192.168.1.98"; - private static final String host = "127.0.0.1"; - private static final int port = 6041; - private static Connection connection; - private static final String databaseName = "driver"; - - private static void testInsert() throws SQLException { - Statement statement = connection.createStatement(); - long cur = System.currentTimeMillis(); - List timeList = new ArrayList<>(); - for (long i = 0L; i < 3000; i++) { - long t = cur + i; - timeList.add("insert into " + databaseName + ".alltype_query values(" + t + ",1,1,1,1,1,1,1,1,1,1,1,'test_binary','test_nchar')"); - } - for (int i = 0; i < 3000; i++) { - statement.execute(timeList.get(i)); - } - statement.close(); - } - - @Test - public void testWSSelect() throws SQLException { - Statement statement = connection.createStatement(); - int count = 0; - long start = System.nanoTime(); - for (int i = 0; i < 1000; i++) { - ResultSet resultSet = statement.executeQuery("select ts,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13 from " + databaseName + ".alltype_query limit 3000"); - while (resultSet.next()) { - count++; - resultSet.getTimestamp(1); - resultSet.getBoolean(2); - resultSet.getInt(3); - resultSet.getInt(4); - resultSet.getInt(5); - resultSet.getLong(6); - resultSet.getInt(7); - resultSet.getInt(8); - resultSet.getLong(9); - resultSet.getLong(10); - resultSet.getFloat(11); - resultSet.getDouble(12); - resultSet.getString(13); - resultSet.getString(14); - } - } - long d = System.nanoTime() - start; - System.out.println(d / 1000); - System.out.println(count); - statement.close(); - } - - @BeforeClass - public static void beforeClass() throws SQLException { - String url = "jdbc:TAOS-RS://" + host + ":" + port + "/?user=root&password=taosdata"; - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, String.valueOf(TimestampFormat.UTC)); - properties.setProperty(TSDBDriver.PROPERTY_KEY_MESSAGE_WAIT_TIMEOUT, "100000"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true"); - connection = DriverManager.getConnection(url, properties); - Statement statement = connection.createStatement(); - statement.execute("drop database if exists " + databaseName); - statement.execute("create database " + databaseName); - statement.execute("create table " + databaseName + ".alltype_query(ts timestamp, c1 bool,c2 tinyint, c3 smallint, c4 int, c5 bigint, c6 tinyint unsigned, c7 smallint unsigned, c8 int unsigned, c9 bigint unsigned, c10 float, c11 double, c12 binary(20), c13 nchar(30) )"); - statement.close(); - testInsert(); - } -} diff --git a/src/connector/jdbc/src/test/resources/commons-logging.properties b/src/connector/jdbc/src/test/resources/commons-logging.properties deleted file mode 100644 index ac435a2a1b..0000000000 --- a/src/connector/jdbc/src/test/resources/commons-logging.properties +++ /dev/null @@ -1,2 +0,0 @@ -#org.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog - diff --git a/src/connector/jdbc/src/test/resources/simplelog.properties b/src/connector/jdbc/src/test/resources/simplelog.properties deleted file mode 100644 index abcc1ef6d5..0000000000 --- a/src/connector/jdbc/src/test/resources/simplelog.properties +++ /dev/null @@ -1,5 +0,0 @@ -org.apache.commons.logging.simplelog.defaultlog=TRACE -org.apache.commons.logging.simplelog.showlogname=true -org.apache.commons.logging.simplelog.showShortLogname=restful -org.apache.commons.logging.simplelog.showdatetime=true -org.apache.commons.logging.simplelog.dateTimeFormat=yyyy-mm-dd hh:MM:ss.SSS \ No newline at end of file diff --git a/tests/develop-test/3-connectors/R/test.sh b/tests/develop-test/3-connectors/R/test.sh index 90b9489365..1d90dd44b6 100644 --- a/tests/develop-test/3-connectors/R/test.sh +++ b/tests/develop-test/3-connectors/R/test.sh @@ -22,7 +22,9 @@ cd ../../ WKC=`pwd` #echo "WKC:${WKC}" -JDBC_PATH=${WKC}'/src/connector/jdbc/' +git clone git@github.com:taosdata/taos-connector-jdbc.git --branch main --single-branch --depth 1 + +JDBC_PATH=${WKC}'/taos-connector-jdbc/' CASE_PATH=${WKC}'/tests/examples/R/' cd ${JDBC_PATH} #echo "JDBC_PATH:${JDBC_PATH}" diff --git a/tests/parallel_test/cases.task b/tests/parallel_test/cases.task index fda76ba216..e8e7b28668 100644 --- a/tests/parallel_test/cases.task +++ b/tests/parallel_test/cases.task @@ -816,7 +816,7 @@ 3,,develop-test,python3 ./test.py -f 2-query/function_tail.py 2,,develop-test,python3 ./test.py -f 2-query/function_unique.py 2,,develop-test,python3 ./test.py -f 2-query/function_hll.py -1,,docs-examples-test, ./test_R.sh +#1,,docs-examples-test, ./test_R.sh 1,,develop-test,python3 ./test.py -f 2-query/function_state.py 1,,develop-test,python3 ./test.py -f 5-taos-tools/taosbenchmark/demo.py 3,,develop-test,python3 ./test.py -f 5-taos-tools/taosdump/taosdumpTestInspect.py diff --git a/tests/perftest-scripts/coverage_test.sh b/tests/perftest-scripts/coverage_test.sh index 1be2053f24..44f9466ef6 100755 --- a/tests/perftest-scripts/coverage_test.sh +++ b/tests/perftest-scripts/coverage_test.sh @@ -110,7 +110,9 @@ function runTest { $TDENGINE_DIR/debug/build/bin/taosd -c $TDENGINE_DIR/debug/test/cfg > /dev/null & sleep 10 - cd $TDENGINE_DIR/src/connector/jdbc + # cd $TDENGINE_DIR/src/connector/jdbc + git clone git@github.com:taosdata/taos-connector-jdbc.git --branch main --single-branch --depth 1 + cd taos-connector-jdbc mvn clean package > /dev/null 2>&1 mvn test > /dev/null 2>&1 | tee -a $TDENGINE_COVERAGE_REPORT diff --git a/tests/test-all.sh b/tests/test-all.sh index 3c6bb67f26..bccb565d2e 100755 --- a/tests/test-all.sh +++ b/tests/test-all.sh @@ -422,7 +422,9 @@ if [ "$2" != "sim" ] && [ "$2" != "python" ] && [ "$2" != "unit" ] && [ "$2" != nohup build/bin/taosd -c /etc/taos/ > /dev/null 2>&1 & sleep 30 - cd $tests_dir/../src/connector/jdbc + # cd $tests_dir/../src/connector/jdbc + git clone git@github.com:taosdata/taos-connector-jdbc.git --branch main --single-branch --depth 1 + cd taos-connector-jdbc mvn test > jdbc-out.log 2>&1 tail -n 20 jdbc-out.log -- GitLab