From 90f532a0ea0184630248fa832ddaebcd53b9cd1f Mon Sep 17 00:00:00 2001 From: zyyang Date: Mon, 20 Dec 2021 15:56:01 +0800 Subject: [PATCH] copy jdbc from develop to master --- src/connector/jdbc/CMakeLists.txt | 2 +- src/connector/jdbc/deploy-pom.xml | 2 +- src/connector/jdbc/pom.xml | 22 +- .../com/taosdata/jdbc/AbstractConnection.java | 16 +- .../jdbc/AbstractDatabaseMetaData.java | 88 +- .../com/taosdata/jdbc/AbstractResultSet.java | 5 + .../com/taosdata/jdbc/AbstractStatement.java | 2 + .../jdbc/DatabaseMetaDataResultSet.java | 2 +- .../com/taosdata/jdbc/SchemalessWriter.java | 67 + .../com/taosdata/jdbc/TSDBConnection.java | 16 +- .../java/com/taosdata/jdbc/TSDBDriver.java | 31 +- .../java/com/taosdata/jdbc/TSDBError.java | 1 + .../java/com/taosdata/jdbc/TSDBException.java | 22 + .../com/taosdata/jdbc/TSDBJNIConnector.java | 88 +- .../taosdata/jdbc/TSDBPreparedStatement.java | 56 +- .../java/com/taosdata/jdbc/TSDBResultSet.java | 66 +- .../taosdata/jdbc/TSDBResultSetBlockData.java | 144 +- .../taosdata/jdbc/TSDBResultSetRowData.java | 27 +- .../taosdata/jdbc/TSDBResultSetWrapper.java | 2 +- .../java/com/taosdata/jdbc/TSDBStatement.java | 13 +- .../jdbc/enums/SchemalessProtocolType.java | 18 + .../jdbc/enums/SchemalessTimestampType.java | 13 + .../jdbc/enums/TimestampPrecision.java | 9 +- .../com/taosdata/jdbc/rs/RestfulDriver.java | 16 +- .../taosdata/jdbc/rs/RestfulResultSet.java | 165 ++- .../taosdata/jdbc/rs/RestfulStatement.java | 7 +- .../jdbc/utils/HttpClientPoolUtil.java | 77 +- .../com/taosdata/jdbc/utils/TaosInfo.java | 5 +- .../java/com/taosdata/jdbc/utils/Utils.java | 11 +- .../java/com/taosdata/jdbc/JsonTagTest.java | 1220 +++++++++++++++++ .../com/taosdata/jdbc/ParameterBindTest.java | 139 ++ .../taosdata/jdbc/SchemalessInsertTest.java | 195 +++ .../jdbc/SetConfigurationInJNITest.java | 249 ++++ .../com/taosdata/jdbc/TSDBConnectionTest.java | 82 +- .../com/taosdata/jdbc/TSDBDriverTest.java | 14 +- .../taosdata/jdbc/TSDBJNIConnectorTest.java | 200 ++- .../jdbc/TSDBParameterMetaDataTest.java | 13 +- .../jdbc/TSDBPreparedStatementTest.java | 1 + .../com/taosdata/jdbc/TSDBResultSetTest.java | 6 +- .../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/cases/AuthenticationTest.java | 1 - .../jdbc/cases/BadLocaleSettingTest.java | 59 - .../jdbc/cases/BatchErrorIgnoreTest.java | 50 +- ...iTaosdByRestfulWithDifferentTokenTest.java | 6 +- .../jdbc/cases/DatetimeBefore1970Test.java | 39 +- ...etLongWithDifferentTimestampPrecision.java | 59 + .../com/taosdata/jdbc/cases/ImportTest.java | 71 +- .../jdbc/cases/InsertDbwithoutUseDbTest.java | 78 +- .../cases/InsertSpecialCharacterJniTest.java | 6 +- .../InsertSpecialCharacterRestfulTest.java | 6 +- .../cases/JDBCTypeAndTypeCompareTest.java | 50 + .../cases/MicroSecondPrecisionJNITest.java | 9 +- .../MicroSecondPrecisionRestfulTest.java | 39 +- .../MultiConnectionWithDifferentDbTest.java | 31 +- .../MultiThreadsWithSameStatementTest.java | 85 -- .../cases/NanoSecondTimestampJNITest.java | 56 +- .../cases/NanoSecondTimestampRestfulTest.java | 56 +- .../cases/NullValueInResultSetJNITest.java | 18 +- .../NullValueInResultSetRestfulTest.java | 19 +- .../jdbc/cases/NullValueInResultSetTest.java | 6 +- ...eparedStatementBatchInsertRestfulTest.java | 37 +- .../taosdata/jdbc/cases/QueryDataTest.java | 50 +- ...sultSetMetaShouldNotBeNullRestfulTest.java | 71 +- .../com/taosdata/jdbc/cases/SelectTest.java | 47 +- .../jdbc/cases/TaosInfoMonitorTest.java | 49 - .../TimestampPrecisionInNanoInJniTest.java | 152 +- .../TimestampPrecisonInNanoRestTest.java | 570 ++++++++ .../jdbc/cases/UnsignedNumberJniTest.java | 44 +- .../jdbc/cases/UnsignedNumberRestfulTest.java | 21 +- .../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 | 57 + .../jdbc/confprops/TaosInfoMonitorTest.java | 54 + .../{cases => confprops}/TimeZoneTest.java | 10 +- .../jdbc/confprops/TimestampFormatTest.java | 181 +++ .../jdbc/rs/DatabaseSpecifiedTest.java | 7 +- .../jdbc/rs/RestfulConnectionTest.java | 26 +- .../jdbc/rs/RestfulDatabaseMetaDataTest.java | 38 +- .../com/taosdata/jdbc/rs/RestfulJDBCTest.java | 19 +- .../jdbc/rs/RestfulParameterMetaDataTest.java | 13 +- .../jdbc/rs/RestfulPreparedStatementTest.java | 6 +- .../jdbc/rs/RestfulResultSetMetaDataTest.java | 7 +- .../jdbc/rs/RestfulResultSetTest.java | 28 +- .../jdbc/rs/RestfulStatementTest.java | 296 ++-- .../java/com/taosdata/jdbc/rs/SQLTest.java | 9 - .../com/taosdata/jdbc/rs/WasNullTest.java | 86 ++ .../jdbc/utils/HttpClientPoolUtilTest.java | 91 +- .../test/resources/commons-logging.properties | 2 + .../src/test/resources/simplelog.properties | 5 + 96 files changed, 4817 insertions(+), 1623 deletions(-) create mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/SchemalessWriter.java create mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBException.java create mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/SchemalessProtocolType.java create mode 100644 src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/SchemalessTimestampType.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/JsonTagTest.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/ParameterBindTest.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/SchemalessInsertTest.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/SetConfigurationInJNITest.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogClass.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogListener.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogMethod.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogRunner.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/Description.java create 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/cases/BadLocaleSettingTest.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/GetLongWithDifferentTimestampPrecision.java create 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/MultiThreadsWithSameStatementTest.java delete mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TaosInfoMonitorTest.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TimestampPrecisonInNanoRestTest.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/UseNowInsertTimestampTest.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/BadLocaleSettingTest.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/BatchFetchTest.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/CharsetTest.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/HttpKeepAliveTest.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TaosInfoMonitorTest.java rename src/connector/jdbc/src/test/java/com/taosdata/jdbc/{cases => confprops}/TimeZoneTest.java (91%) create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TimestampFormatTest.java create mode 100644 src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/WasNullTest.java create mode 100644 src/connector/jdbc/src/test/resources/commons-logging.properties create mode 100644 src/connector/jdbc/src/test/resources/simplelog.properties diff --git a/src/connector/jdbc/CMakeLists.txt b/src/connector/jdbc/CMakeLists.txt index e432dac1ce..1cde4683f0 100644 --- a/src/connector/jdbc/CMakeLists.txt +++ b/src/connector/jdbc/CMakeLists.txt @@ -8,7 +8,7 @@ IF (TD_MVN_INSTALLED) ADD_CUSTOM_COMMAND(OUTPUT ${JDBC_CMD_NAME} POST_BUILD 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.34-dist.jar ${LIBRARY_OUTPUT_PATH} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/target/taos-jdbcdriver-2.0.36-dist.jar ${LIBRARY_OUTPUT_PATH} COMMAND mvn -Dmaven.test.skip=true clean -f ${CMAKE_CURRENT_SOURCE_DIR}/pom.xml COMMENT "build jdbc driver") ADD_CUSTOM_TARGET(${JDBC_TARGET_NAME} ALL WORKING_DIRECTORY ${EXECUTABLE_OUTPUT_PATH} DEPENDS ${JDBC_CMD_NAME}) diff --git a/src/connector/jdbc/deploy-pom.xml b/src/connector/jdbc/deploy-pom.xml index ef57198e78..926a5ef483 100755 --- a/src/connector/jdbc/deploy-pom.xml +++ b/src/connector/jdbc/deploy-pom.xml @@ -5,7 +5,7 @@ com.taosdata.jdbc taos-jdbcdriver - 2.0.34 + 2.0.36 jar JDBCDriver diff --git a/src/connector/jdbc/pom.xml b/src/connector/jdbc/pom.xml index 13b59928df..04115e2a0e 100644 --- a/src/connector/jdbc/pom.xml +++ b/src/connector/jdbc/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.taosdata.jdbc taos-jdbcdriver - 2.0.34 + 2.0.36 jar JDBCDriver https://github.com/taosdata/TDengine/tree/master/src/connector/jdbc @@ -58,6 +58,13 @@ 4.13.1 test + + + commons-logging + commons-logging + 1.2 + test + @@ -70,6 +77,18 @@ + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + org.apache.maven.plugins maven-assembly-plugin @@ -114,6 +133,7 @@ **/HttpClientPoolUtilTest.java **/AppMemoryLeakTest.java + **/JDBCTypeAndTypeCompareTest.java **/ConnectMultiTaosdByRestfulWithDifferentTokenTest.java **/DatetimeBefore1970Test.java **/FailOverTest.java 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 index 9950dbeb64..15695ae920 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractConnection.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractConnection.java @@ -107,16 +107,6 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti public void setCatalog(String catalog) throws SQLException { if (isClosed()) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); - /* - try (Statement stmt = createStatement()) { - boolean execute = stmt.execute("use " + catalog); - if (execute) - this.catalog = catalog; - } catch (SQLException e) { - // do nothing - } - */ - this.catalog = catalog; } @@ -392,7 +382,7 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti //true if the connection is valid, false otherwise if (isClosed()) return false; - if (timeout < 0) //SQLException - if the value supplied for timeout is less then 0 + 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(); @@ -413,11 +403,9 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti status = future.get(); else status = future.get(timeout, TimeUnit.SECONDS); - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); + } catch (InterruptedException | ExecutionException ignored) { } catch (TimeoutException e) { future.cancel(true); - status = false; } finally { executor.shutdownNow(); } 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 index 7dbb62d849..6343a802af 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDatabaseMetaData.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDatabaseMetaData.java @@ -562,25 +562,27 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da List rowDataList = new ArrayList<>(); try (Statement stmt = connection.createStatement()) { stmt.execute("use " + catalog); - ResultSet tables = stmt.executeQuery("show tables"); - 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); + try (ResultSet tables = stmt.executeQuery("show tables")) { + 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("show stables"); - 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); + try (ResultSet stables = stmt.executeQuery("show stables")) { + 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); } @@ -595,7 +597,7 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da return col4; } - public ResultSet getSchemas() throws SQLException { + public ResultSet getSchemas() { return getEmptyResultSet(); } @@ -627,7 +629,7 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da 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) { + 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)) @@ -638,8 +640,9 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da resultSet.setColumnMetaDataList(buildGetColumnsColumnMetaDataList()); // set up rowDataList List rowDataList = new ArrayList<>(); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("describe " + catalog + "." + tableNamePattern); + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("describe " + catalog + "." + tableNamePattern)) { + int rowIndex = 0; while (rs.next()) { TSDBResultSetRowData rowData = new TSDBResultSetRowData(24); @@ -679,8 +682,6 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da rowIndex++; } resultSet.setRowDataList(rowDataList); - } catch (SQLException e) { - e.printStackTrace(); } return resultSet; } @@ -1147,9 +1148,9 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da columnMetaDataList.add(buildTableCatalogMeta(1)); // 1. TABLE_CAT resultSet.setColumnMetaDataList(columnMetaDataList); - try (Statement stmt = conn.createStatement()) { + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("show databases")) { List rowDataList = new ArrayList<>(); - ResultSet rs = stmt.executeQuery("show databases"); while (rs.next()) { TSDBResultSetRowData rowData = new TSDBResultSetRowData(1); rowData.setStringValue(1, rs.getString("name")); @@ -1168,12 +1169,13 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da return new EmptyResultSet(); DatabaseMetaDataResultSet resultSet = new DatabaseMetaDataResultSet(); - try (Statement stmt = conn.createStatement()) { + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("describe " + catalog + "." + table)) { // set up ColumnMetaDataList resultSet.setColumnMetaDataList(buildGetPrimaryKeysMetadataList()); // set rowData List rowDataList = new ArrayList<>(); - ResultSet rs = stmt.executeQuery("describe " + catalog + "." + table); + rs.next(); TSDBResultSetRowData rowData = new TSDBResultSetRowData(6); rowData.setStringValue(1, catalog); @@ -1216,18 +1218,15 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da return col6; } - private boolean isAvailableCatalog(Connection connection, String catalog) { - try (Statement stmt = connection.createStatement()) { - ResultSet databases = stmt.executeQuery("show databases"); + 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; } - databases.close(); - } catch (SQLException e) { - e.printStackTrace(); } return false; } @@ -1246,17 +1245,18 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da resultSet.setColumnMetaDataList(buildGetSuperTablesColumnMetaDataList()); // set result set row data stmt.execute("use " + catalog); - 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); + 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); } - resultSet.setRowDataList(rowDataList); } return resultSet; } 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 index e17548055c..07553d7ef4 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractResultSet.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractResultSet.java @@ -11,6 +11,11 @@ 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()) 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 index a801f5a674..12641087fb 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractStatement.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractStatement.java @@ -9,6 +9,7 @@ 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; @@ -247,6 +248,7 @@ public abstract class AbstractStatement extends WrapperImpl implements Statement 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; 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 index db4a5ccaa8..8a494f3a50 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/DatabaseMetaDataResultSet.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/DatabaseMetaDataResultSet.java @@ -149,7 +149,7 @@ public class DatabaseMetaDataResultSet extends AbstractResultSet { public BigDecimal getBigDecimal(int columnIndex) throws SQLException { int colType = columnMetaDataList.get(columnIndex - 1).getColType(); double value = rowCursor.getDouble(columnIndex, colType); - return new BigDecimal(value); + return BigDecimal.valueOf(value); } @Override 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 new file mode 100644 index 0000000000..d8cb5795f0 --- /dev/null +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/SchemalessWriter.java @@ -0,0 +1,67 @@ +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 index 8cd8da6de4..77a97d644c 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConnection.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConnection.java @@ -1,17 +1,3 @@ -/*************************************************************************** - * 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.*; @@ -66,7 +52,7 @@ public class TSDBConnection extends AbstractConnection { throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); } - long id = this.connector.subscribe(topic, sql, restart, 0); + long id = this.connector.subscribe(topic, sql, restart); if (id == 0) { throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_SUBSCRIBE_FAILED); } 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 index 521a88b128..00eff99f45 100755 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBDriver.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBDriver.java @@ -1,23 +1,8 @@ -/*************************************************************************** - * 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.net.URLEncoder; -import java.nio.charset.StandardCharsets; import java.sql.*; -import java.util.*; +import java.util.Properties; +import java.util.StringTokenizer; import java.util.logging.Logger; /** @@ -118,9 +103,6 @@ public class TSDBDriver extends AbstractDriver { } public Connection connect(String url, Properties info) throws SQLException { - if (url == null) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_URL_NOT_SET); - if (!acceptsURL(url)) return null; @@ -135,16 +117,14 @@ public class TSDBDriver extends AbstractDriver { throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PASSWORD_IS_REQUIRED); try { - TSDBJNIConnector.init((String) props.get(PROPERTY_KEY_CONFIG_DIR), (String) props.get(PROPERTY_KEY_LOCALE), - (String) props.get(PROPERTY_KEY_CHARSET), (String) props.get(PROPERTY_KEY_TIME_ZONE)); + TSDBJNIConnector.init(props); return new TSDBConnection(props, this.dbMetaData); } catch (SQLWarning sqlWarning) { - sqlWarning.printStackTrace(); return new TSDBConnection(props, this.dbMetaData); } catch (SQLException sqlEx) { throw sqlEx; } catch (Exception ex) { - throw new SQLException("SQLException:" + ex.toString(), ex); + throw new SQLException("SQLException:" + ex, ex); } } @@ -157,7 +137,7 @@ public class TSDBDriver extends AbstractDriver { public boolean acceptsURL(String url) throws SQLException { if (url == null) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_URL_NOT_SET); - return url.length() > 0 && url.trim().length() > 0 && (url.startsWith(URL_PREFIX) || url.startsWith(URL_PREFIX1)); + return url.trim().length() > 0 && (url.startsWith(URL_PREFIX) || url.startsWith(URL_PREFIX1)); } public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { @@ -205,6 +185,7 @@ public class TSDBDriver extends AbstractDriver { 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); 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 index bdb3ea4100..0970148b1d 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBError.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBError.java @@ -35,6 +35,7 @@ public class TSDBError { 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"); 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 new file mode 100644 index 0000000000..31299a1c6f --- /dev/null +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBException.java @@ -0,0 +1,22 @@ +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 index 4a9e80ba53..247ae929da 100755 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBJNIConnector.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBJNIConnector.java @@ -1,33 +1,23 @@ -/** - * ************************************************************************* - * 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.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 volatile Boolean isInitialized = false; + 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 @@ -38,24 +28,27 @@ public class TSDBJNIConnector { System.loadLibrary("taos"); } - public boolean isClosed() { - return this.taos == TSDBConstants.JNI_NULL_POINTER; - } + public static void init(Properties props) throws SQLWarning { + synchronized (LOCK) { + if (!isInitialized) { - public boolean isResultsetClosed() { - return this.isResultsetClosed; - } + JSONObject configJSON = new JSONObject(); + for (String key : props.stringPropertyNames()) { + configJSON.put(key, props.getProperty(key)); + } + setConfigImp(configJSON.toJSONString()); - public static void init(String configDir, String locale, String charset, String timezone) throws SQLWarning { - synchronized (isInitialized) { - if (!isInitialized) { - initImp(configDir); + 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."); } @@ -65,11 +58,13 @@ public class TSDBJNIConnector { } } - public static native void initImp(String configDir); + private static native void initImp(String configDir); + + private static native int setOptions(int optionIndex, String optionValue); - public static native int setOptions(int optionIndex, String optionValue); + private static native String getTsCharset(); - public 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) { @@ -97,8 +92,7 @@ public class TSDBJNIConnector { try { pSql = this.executeQueryImp(sql.getBytes(TaosGlobalConfig.getCharset()), this.taos); taosInfo.stmt_count_increment(); - } catch (Exception e) { - e.printStackTrace(); + } catch (UnsupportedEncodingException e) { this.freeResultSetImp(this.taos, pSql); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_ENCODING); } @@ -159,6 +153,14 @@ public class TSDBJNIConnector { 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 */ @@ -243,8 +245,8 @@ public class TSDBJNIConnector { /** * Create a subscription */ - long subscribe(String topic, String sql, boolean restart, int period) { - return subscribeImp(this.taos, restart, topic, sql, period); + 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); @@ -267,16 +269,6 @@ public class TSDBJNIConnector { private native void unsubscribeImp(long subscription, boolean isKeep); - /** - * Validate if a create table SQL statement is correct without actually creating that table - */ - public boolean validateCreateTableSql(String sql) { - int res = validateCreateTableSqlImp(taos, sql.getBytes()); - return res == 0; - } - - private native int validateCreateTableSqlImp(long connection, byte[] sqlBytes); - public long prepareStmt(String sql) throws SQLException { long stmt = prepareStmtImp(sql.getBytes(), this.taos); @@ -343,12 +335,14 @@ public class TSDBJNIConnector { private native int closeStmt(long stmt, long con); - public void insertLines(String[] lines) throws SQLException { - int code = insertLinesImp(lines, this.taos); + public void insertLines(String[] lines, SchemalessProtocolType protocolType, SchemalessTimestampType timestampType) throws SQLException { + int code = insertLinesImp(lines, this.taos, protocolType.ordinal(), timestampType.ordinal()); if (code != TSDBConstants.JNI_SUCCESS) { throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "failed to insertLines"); } } - private native int insertLinesImp(String[] lines, long conn); + private native int insertLinesImp(String[] lines, long conn, int type, int precision); + + } 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 index 22fb0c4ae4..5fd8f18138 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBPreparedStatement.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBPreparedStatement.java @@ -36,15 +36,15 @@ import java.util.regex.Pattern; * compatibility needs. */ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStatement { + // for jdbc preparedStatement interface private String rawSql; private Object[] parameters; - - private ArrayList colData; + // for parameter binding + private long nativeStmtHandle = 0; + private String tableName; private ArrayList tableTags; private int tagValueLength; - - private String tableName; - private long nativeStmtHandle = 0; + private ArrayList colData; TSDBPreparedStatement(TSDBConnection connection, String sql) { super(connection); @@ -72,10 +72,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat 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 @@ -250,13 +246,10 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat @Override public void setObject(int parameterIndex, Object x) throws SQLException { - if (isClosed()) { + if (isClosed()) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - } - - if (parameterIndex < 1 && parameterIndex >= parameters.length) { + if (parameterIndex < 1 && parameterIndex >= parameters.length) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - } parameters[parameterIndex - 1] = x; } @@ -335,7 +328,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { if (isClosed()) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - // TODO: throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); } @@ -419,7 +411,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { if (isClosed()) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - //TODO: throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); } @@ -477,7 +468,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat if (isClosed()) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); - } @Override @@ -496,7 +486,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat /////////////////////////////////////////////////////////////////////// // NOTE: the following APIs are not JDBC compatible - // set the bind table name + // parameter binding private static class ColumnInfo { @SuppressWarnings("rawtypes") private ArrayList data; @@ -539,7 +529,11 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat } } - public void setTableName(String name) { + public void setTableName(String name) throws SQLException { + if (this.tableName != null) { + this.columnDataExecuteBatch(); + this.columnDataClearBatchInternal(); + } this.tableName = name; } @@ -617,7 +611,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat try { this.tagValueLength += value.getBytes(charset).length; } catch (UnsupportedEncodingException e) { - e.printStackTrace(); + throw new RuntimeException(e.getMessage()); } } @@ -792,7 +786,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat b = val.getBytes(charset); } } catch (UnsupportedEncodingException e) { - e.printStackTrace(); + throw new RuntimeException(e.getMessage()); } tagDataList.put(b); @@ -927,7 +921,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat b = val.getBytes(charset); } } catch (UnsupportedEncodingException e) { - e.printStackTrace(); + throw new RuntimeException(e.getMessage()); } if (val.length() > col1.bytes) { @@ -960,17 +954,22 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat public void columnDataExecuteBatch() throws SQLException { TSDBJNIConnector connector = ((TSDBConnection) this.getConnection()).getConnector(); connector.executeBatch(this.nativeStmtHandle); - this.columnDataClearBatch(); + this.columnDataClearBatchInternal(); } + @Deprecated public void columnDataClearBatch() { + columnDataClearBatchInternal(); + } + + private void columnDataClearBatchInternal() { int size = this.colData.size(); this.colData.clear(); - this.colData.addAll(Collections.nCopies(size, null)); this.tableName = null; // clear the table name } + public void columnDataCloseBatch() throws SQLException { TSDBJNIConnector connector = ((TSDBConnection) this.getConnection()).getConnector(); connector.closeBatch(this.nativeStmtHandle); @@ -978,4 +977,13 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat 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 index 00a62206fc..003324d27a 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSet.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSet.java @@ -19,6 +19,7 @@ import com.google.common.primitives.Longs; import com.google.common.primitives.Shorts; import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; import java.sql.*; import java.util.ArrayList; import java.util.Calendar; @@ -73,9 +74,8 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { public boolean next() throws SQLException { if (this.getBatchFetch()) { - if (this.blockData.forward()) { + if (this.blockData.forward()) return true; - } int code = this.jniConnector.fetchBlock(this.resultSetPointer, this.blockData); this.blockData.reset(); @@ -213,7 +213,18 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { if (!lastWasNull) { Object value = this.rowData.getObject(columnIndex); if (value instanceof Timestamp) { - res = ((Timestamp) value).getTime(); + 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); @@ -256,7 +267,11 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { public byte[] getBytes(int columnIndex) throws SQLException { checkAvailability(columnIndex, this.columnMetaDataList.size()); + if (this.getBatchFetch()) + return this.blockData.getString(columnIndex).getBytes(); + Object value = this.rowData.getObject(columnIndex); + this.lastWasNull = value == null; if (value == null) return null; @@ -331,25 +346,26 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { return new BigDecimal(this.blockData.getLong(columnIndex - 1)); this.lastWasNull = this.rowData.wasNull(columnIndex); - BigDecimal res = null; - if (!lastWasNull) { - 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()); - } + 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; } @@ -465,12 +481,6 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { public boolean isClosed() throws SQLException { return isClosed; -// if (isClosed) -// return true; -// if (jniConnector != null) { -// isClosed = jniConnector.isResultsetClosed(); -// } -// return isClosed; } public String getNString(int columnIndex) throws SQLException { 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 index ff49677b01..e404db64e3 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetBlockData.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetBlockData.java @@ -92,75 +92,71 @@ public class TSDBResultSetBlockData { } public void setByteArray(int col, int length, byte[] value) { - try { - 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_NCHAR: { - ByteBuffer buf = ByteBuffer.wrap(value, 0, length); - buf.order(ByteOrder.LITTLE_ENDIAN); - this.colData.set(col, buf); - break; - } + 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_NCHAR: { + ByteBuffer buf = ByteBuffer.wrap(value, 0, length); + buf.order(ByteOrder.LITTLE_ENDIAN); + this.colData.set(col, buf); + break; } - } catch (Exception e) { - e.printStackTrace(); } } @@ -283,14 +279,8 @@ public class TSDBResultSetBlockData { return 0; } - public Timestamp getTimestamp(int col) { - try { - return new Timestamp(getLong(col)); - } catch (SQLException e) { - e.printStackTrace(); - } - - return null; + public Timestamp getTimestamp(int col) throws SQLException { + return new Timestamp(getLong(col)); } public double getDouble(int col) { @@ -429,7 +419,7 @@ public class TSDBResultSetBlockData { String charset = TaosGlobalConfig.getCharset(); return new String(dest, charset); } catch (UnsupportedEncodingException e) { - e.printStackTrace(); + throw new RuntimeException(e.getMessage()); } } } 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 index 2ff0d86c92..d8ac10d839 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java @@ -16,6 +16,7 @@ package com.taosdata.jdbc; import com.taosdata.jdbc.utils.NullType; +import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.sql.SQLException; import java.sql.Timestamp; @@ -49,7 +50,7 @@ public class TSDBResultSetRowData { } /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use a index start from 1 in JDBC api + * $$$ 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); @@ -86,7 +87,7 @@ public class TSDBResultSetRowData { } /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use a index start from 1 in JDBC api + * $$$ 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); @@ -100,7 +101,7 @@ public class TSDBResultSetRowData { } /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use a index start from 1 in JDBC api + * $$$ 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); @@ -114,7 +115,7 @@ public class TSDBResultSetRowData { } /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use a index start from 1 in JDBC api + * $$$ 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); @@ -189,12 +190,12 @@ public class TSDBResultSetRowData { long value = (long) obj; if (value < 0) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_NUMERIC_VALUE_OUT_OF_RANGE); - return Long.valueOf(value).intValue(); + return (int) value; } /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use a index start from 1 in JDBC api + * $$$ 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); @@ -262,7 +263,7 @@ public class TSDBResultSetRowData { } /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use a index start from 1 in JDBC api + * $$$ 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); @@ -302,7 +303,7 @@ public class TSDBResultSetRowData { } /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use a index start from 1 in JDBC api + * $$$ 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); @@ -342,7 +343,7 @@ public class TSDBResultSetRowData { } /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use a index start from 1 in JDBC api + * $$$ 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); @@ -361,7 +362,7 @@ public class TSDBResultSetRowData { } /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use a index start from 1 in JDBC api + * $$$ 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); @@ -378,8 +379,8 @@ public class TSDBResultSetRowData { // 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 (Exception e) { - e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e.getMessage()); } } @@ -424,7 +425,7 @@ public class TSDBResultSetRowData { } /** - * $$$ this method is invoked by databaseMetaDataResultSet and so on which use a index start from 1 in JDBC api + * $$$ 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); 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 index 48854e773f..0a9f017cbb 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetWrapper.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetWrapper.java @@ -23,7 +23,7 @@ import java.util.Calendar; import java.util.Map; /* - * TDengine only supports a subset of the standard SQL, thus this implemetation of the + * 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. */ 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 index e1ebc4ab3c..ce877987e6 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBStatement.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBStatement.java @@ -23,7 +23,6 @@ public class TSDBStatement extends AbstractStatement { * Status of current statement */ private boolean isClosed; - private int affectedRows = -1; private TSDBConnection connection; private TSDBResultSet resultSet; @@ -48,6 +47,8 @@ public class TSDBStatement extends AbstractStatement { throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEQUERY); } TSDBResultSet res = new TSDBResultSet(this, this.connection.getConnector(), pSql); + int timestampPrecision = this.connection.getConnector().getResultTimePrecision(pSql); + res.setTimestampPrecision(timestampPrecision); res.setBatchFetch(this.connection.getBatchFetch()); return res; } @@ -80,7 +81,7 @@ public class TSDBStatement extends AbstractStatement { if (isClosed()) { throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); } - + // execute query long pSql = this.connection.getConnector().executeQuery(sql); // if pSql is create/insert/update/delete/alter SQL @@ -99,7 +100,7 @@ public class TSDBStatement extends AbstractStatement { if (isClosed()) { throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); } - + return this.resultSet; } @@ -113,14 +114,14 @@ public class TSDBStatement extends AbstractStatement { 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; } 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 new file mode 100644 index 0000000000..2a0bea1570 --- /dev/null +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/SchemalessProtocolType.java @@ -0,0 +1,18 @@ +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 new file mode 100644 index 0000000000..fa10a23634 --- /dev/null +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/SchemalessTimestampType.java @@ -0,0 +1,13 @@ +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/TimestampPrecision.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/TimestampPrecision.java index 79350076c7..4558dfa84b 100644 --- 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 @@ -1,8 +1,7 @@ package com.taosdata.jdbc.enums; -public enum TimestampPrecision { - MS, - US, - NS, - UNKNOWN +public class TimestampPrecision { + public static final int MS = 0; + public static final int US = 1; + public static final int NS = 2; } 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 index 0a8809e84f..fdd034a641 100644 --- 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 @@ -39,7 +39,7 @@ public class RestfulDriver extends AbstractDriver { 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 loginUrl = "http://" + host + ":" + port + "/rest/login/" + props.getProperty(TSDBDriver.PROPERTY_KEY_USER) + "/" + props.getProperty(TSDBDriver.PROPERTY_KEY_PASSWORD) + ""; + String loginUrl; try { if (!props.containsKey(TSDBDriver.PROPERTY_KEY_USER)) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_USER_IS_REQUIRED); @@ -50,9 +50,13 @@ public class RestfulDriver extends AbstractDriver { String password = URLEncoder.encode(props.getProperty(TSDBDriver.PROPERTY_KEY_PASSWORD), StandardCharsets.UTF_8.displayName()); loginUrl = "http://" + props.getProperty(TSDBDriver.PROPERTY_KEY_HOST) + ":" + props.getProperty(TSDBDriver.PROPERTY_KEY_PORT) + "/rest/login/" + user + "/" + password + ""; } catch (UnsupportedEncodingException e) { - e.printStackTrace(); + 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)); } + 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 result = HttpClientPoolUtil.execute(loginUrl); JSONObject jsonResult = JSON.parseObject(result); String status = jsonResult.getString("status"); @@ -64,9 +68,9 @@ public class RestfulDriver extends AbstractDriver { RestfulConnection conn = new RestfulConnection(host, port, props, database, url, token); if (database != null && !database.trim().replaceAll("\\s", "").isEmpty()) { - Statement stmt = conn.createStatement(); - stmt.execute("use " + database); - stmt.close(); + try (Statement stmt = conn.createStatement()) { + stmt.execute("use " + database); + } } return conn; } @@ -75,7 +79,7 @@ public class RestfulDriver extends AbstractDriver { public boolean acceptsURL(String url) throws SQLException { if (url == null) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_URL_NOT_SET); - return url.length() > 0 && url.trim().length() > 0 && url.startsWith(URL_PREFIX); + return url.trim().length() > 0 && url.startsWith(URL_PREFIX); } @Override 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 index 1ea39236b6..78420083a1 100644 --- 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 @@ -14,13 +14,43 @@ 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<>(); @@ -168,35 +198,67 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { 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) + if (value < 1_0000_0000_0000_0L) { + this.timestampPrecision = TimestampPrecision.MS; return new Timestamp(value); - long epochSec = value / 1000_000L; - long nanoAdjustment = value % 1000_000L * 1000L; - return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); + } + 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); - 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() > 31) { - // ns timestamp: yyyy-MM-ddTHH:mm:ss.SSSSSSSSS+0x00 - nanoAdjustment = fractionalSec; - } else if (value.length() > 28) { - // ms timestamp: yyyy-MM-ddTHH:mm:ss.SSSSSS+0x00 - nanoAdjustment = fractionalSec * 1000L; + 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 { - // ms timestamp: yyyy-MM-ddTHH:mm:ss.SSS+0x00 - nanoAdjustment = fractionalSec * 1000_000L; + 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); } - 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); - TimestampPrecision precision = Utils.guessTimestampPrecision(value); + int precision = Utils.guessTimestampPrecision(value); + this.timestampPrecision = precision; + if (precision == TimestampPrecision.MS) { // ms timestamp: yyyy-MM-dd HH:mm:ss.SSS return row.getTimestamp(colIndex); @@ -255,6 +317,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { 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[]) @@ -267,11 +330,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, resultSet.get(pos).size()); Object value = resultSet.get(pos).get(columnIndex - 1); - if (value == null) { - wasNull = true; + wasNull = value == null; + if (value == null) return false; - } - wasNull = false; if (value instanceof Boolean) return (boolean) value; return Boolean.parseBoolean(value.toString()); @@ -282,11 +343,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, resultSet.get(pos).size()); Object value = resultSet.get(pos).get(columnIndex - 1); - if (value == null) { - wasNull = true; + wasNull = value == null; + if (value == null) return 0; - } - wasNull = false; long valueAsLong = Long.parseLong(value.toString()); if (valueAsLong == Byte.MIN_VALUE) return 0; @@ -306,11 +365,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, resultSet.get(pos).size()); Object value = resultSet.get(pos).get(columnIndex - 1); - if (value == null) { - wasNull = true; + wasNull = value == null; + if (value == null) return 0; - } - wasNull = false; long valueAsLong = Long.parseLong(value.toString()); if (valueAsLong == Short.MIN_VALUE) return 0; @@ -324,11 +381,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, resultSet.get(pos).size()); Object value = resultSet.get(pos).get(columnIndex - 1); - if (value == null) { - wasNull = true; + wasNull = value == null; + if (value == null) return 0; - } - wasNull = false; long valueAsLong = Long.parseLong(value.toString()); if (valueAsLong == Integer.MIN_VALUE) return 0; @@ -342,14 +397,20 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, resultSet.get(pos).size()); Object value = resultSet.get(pos).get(columnIndex - 1); - if (value == null) { - wasNull = true; + wasNull = value == null; + if (value == null) return 0; - } - - wasNull = false; if (value instanceof Timestamp) { - return ((Timestamp) value).getTime(); + 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 { @@ -367,11 +428,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, resultSet.get(pos).size()); Object value = resultSet.get(pos).get(columnIndex - 1); - if (value == null) { - wasNull = true; + wasNull = value == null; + if (value == null) return 0; - } - wasNull = false; if (value instanceof Float) return (float) value; if (value instanceof Double) @@ -384,11 +443,10 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, resultSet.get(pos).size()); Object value = resultSet.get(pos).get(columnIndex - 1); + wasNull = value == null; if (value == null) { - wasNull = true; return 0; } - wasNull = false; if (value instanceof Double || value instanceof Float) return (double) value; return Double.parseDouble(value.toString()); @@ -399,6 +457,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { 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[]) @@ -425,6 +484,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { 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) @@ -437,6 +497,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { 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) @@ -454,6 +515,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { 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) @@ -470,6 +532,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ret = Utils.parseTimestamp(value.toString()); } catch (Exception e) { ret = null; + wasNull = true; } return ret; } @@ -485,7 +548,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { public Object getObject(int columnIndex) throws SQLException { checkAvailability(columnIndex, resultSet.get(pos).size()); - return resultSet.get(pos).get(columnIndex - 1); + Object value = resultSet.get(pos).get(columnIndex - 1); + wasNull = value == null; + return value; } @Override @@ -504,9 +569,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { 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) @@ -663,4 +728,4 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { return isClosed; } -} \ No newline at end of file +} 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 index eba92741dd..dada75e4a0 100644 --- 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 @@ -22,7 +22,6 @@ public class RestfulStatement extends AbstractStatement { private final RestfulConnection conn; private volatile RestfulResultSet resultSet; - private volatile int affectedRows; public RestfulStatement(RestfulConnection conn, String database) { this.conn = conn; @@ -73,6 +72,7 @@ public class RestfulStatement extends AbstractStatement { } this.database = sql.trim().replace("use", "").trim(); this.conn.setCatalog(this.database); + this.conn.setClientInfo(TSDBDriver.PROPERTY_KEY_DBNAME, this.database); result = false; } else if (SqlSyntaxValidator.isDatabaseUnspecifiedQuery(sql)) { executeOneQuery(sql); @@ -122,7 +122,7 @@ public class RestfulStatement extends AbstractStatement { throw TSDBError.createSQLException(resultJson.getInteger("code"), "sql: " + sql + ", desc: " + resultJson.getString("desc")); } this.resultSet = new RestfulResultSet(database, this, resultJson); - this.affectedRows = 0; + this.affectedRows = -1; return resultSet; } @@ -142,8 +142,9 @@ public class RestfulStatement extends AbstractStatement { 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) + if (data != null) { return data.getJSONArray(0).getInteger(0); + } throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE, "invalid variable: [" + jsonObject.toJSONString() + "]"); } 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 index 99e46bc64f..cdadcd2d28 100644 --- 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 @@ -7,10 +7,10 @@ import org.apache.http.HeaderElementIterator; import org.apache.http.HttpEntity; import org.apache.http.NoHttpResponseException; import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.HttpRequestRetryHandler; 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; @@ -21,21 +21,20 @@ import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; -import javax.net.ssl.SSLException; import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.UnknownHostException; 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; - private static final int DEFAULT_MAX_TOTAL = 50; - private static final int DEFAULT_MAX_PER_ROUTE = 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)); @@ -55,36 +54,39 @@ public class HttpClientPoolUtil { private static CloseableHttpClient httpClient; - static { - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); - connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL); - connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE); - - httpClient = HttpClients.custom() - .setKeepAliveStrategy(DEFAULT_KEEP_ALIVE_STRATEGY) - .setConnectionManager(connectionManager) - .setRetryHandler((exception, executionCount, httpContext) -> executionCount < DEFAULT_MAX_RETRY_COUNT) - .build(); + 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 = ""; - try { - HttpRequestBase method = getRequest(uri, HttpGet.METHOD_NAME); - HttpContext context = HttpClientContext.create(); - CloseableHttpResponse httpResponse = httpClient.execute(method, context); + 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) { - e.printStackTrace(); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_Protocol_Exception, e.getMessage()); } catch (IOException exception) { - exception.printStackTrace(); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_IOException, exception.getMessage()); } finally { if (httpEntity != null) { @@ -94,30 +96,27 @@ public class HttpClientPoolUtil { return responseBody; } - /*** execute POST request ***/ public static String execute(String uri, String data, String token) 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", "Taosd " + token); + method.setEntity(new StringEntity(data, StandardCharsets.UTF_8)); + HttpContext context = HttpClientContext.create(); + HttpEntity httpEntity = null; String responseBody = ""; - try { - HttpEntityEnclosingRequestBase method = (HttpEntityEnclosingRequestBase) getRequest(uri, HttpPost.METHOD_NAME); - method.setHeader(HTTP.CONTENT_TYPE, "text/plain"); - method.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); - method.setHeader("Authorization", "Taosd " + token); - - method.setEntity(new StringEntity(data, StandardCharsets.UTF_8)); - HttpContext context = HttpClientContext.create(); - CloseableHttpResponse httpResponse = httpClient.execute(method, context); + 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) { - e.printStackTrace(); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_Protocol_Exception, e.getMessage()); } catch (IOException exception) { - exception.printStackTrace(); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_IOException, exception.getMessage()); } finally { if (httpEntity != null) { @@ -148,4 +147,12 @@ public class HttpClientPoolUtil { 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/TaosInfo.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/TaosInfo.java index a427103770..583c2c3236 100644 --- 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 @@ -16,9 +16,8 @@ public class TaosInfo implements TaosInfoMBean { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName("TaosInfoMBean:name=TaosInfo"); server.registerMBean(TaosInfo.getInstance(), name); - - } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { - e.printStackTrace(); + } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException ignored) { + throw new RuntimeException("registerMBean failed"); } } 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 index e1c4bddb28..6ec76fffd9 100644 --- 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 @@ -49,14 +49,9 @@ public class Utils { try { return parseMicroSecTimestamp(timeStampStr); } catch (DateTimeParseException ee) { - try { - return parseNanoSecTimestamp(timeStampStr); - } catch (DateTimeParseException eee) { - eee.printStackTrace(); - } + return parseNanoSecTimestamp(timeStampStr); } } - return null; } private static LocalDateTime parseMilliSecTimestamp(String timeStampStr) throws DateTimeParseException { @@ -199,14 +194,14 @@ public class Utils { return timestamp.toLocalDateTime().format(milliSecFormatter); } - public static TimestampPrecision guessTimestampPrecision(String value) { + 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.UNKNOWN; + return TimestampPrecision.MS; } private static boolean isMilliSecFormat(String timestampStr) { 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 new file mode 100644 index 0000000000..501c7e17c8 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/JsonTagTest.java @@ -0,0 +1,1220 @@ +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.*; + +@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"); + 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; + while (resultSet.next()) { + count++; + s = resultSet.getString(2); + + } + Assert.assertEquals(8, count); + Assert.assertEquals("\"femail\"", 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); + } + + 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 new file mode 100644 index 0000000000..63c3a6318a --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ParameterBindTest.java @@ -0,0 +1,139 @@ +package com.taosdata.jdbc; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.sql.*; +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 test() { + // given + String[] tbnames = {"t1", "t2", "t3"}; + int rows = 10; + + // when + insertIntoTables(tbnames, 10); + + // then + assertRows(stable, tbnames.length * rows); + for (String t : tbnames) { + assertRows(t, rows); + } + } + + @Test + public void testMultiThreads() { + // 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(() -> insertIntoTables(tbnames, rows))).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); + } + } + + } + + 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(String[] tbnames, int rowsEachTable) { + long current = System.currentTimeMillis(); + String sql = "insert into ? using " + stable + " tags(?, ?) values(?, ?, ?)"; + try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { + for (int i = 0; i < tbnames.length; i++) { + pstmt.setTableName(tbnames[i]); + pstmt.setTagInt(0, random.nextInt(100)); + pstmt.setTagInt(1, random.nextInt(100)); + + ArrayList timestampList = new ArrayList<>(); + for (int j = 0; j < rowsEachTable; j++) { + timestampList.add(current + i * 1000 + j); + } + pstmt.setTimestamp(0, timestampList); + + ArrayList f1List = new ArrayList<>(); + for (int j = 0; j < rowsEachTable; j++) { + f1List.add(random.nextInt(100)); + } + pstmt.setInt(1, f1List); + + ArrayList f2List = new ArrayList<>(); + for (int j = 0; j < rowsEachTable; j++) { + f2List.add(random.nextInt(100)); + } + pstmt.setInt(2, f2List); + + pstmt.columnDataAddBatch(); + } + + pstmt.columnDataExecuteBatch(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @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 new file mode 100644 index 0000000000..cc47a47f1c --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SchemalessInsertTest.java @@ -0,0 +1,195 @@ +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 new file mode 100644 index 0000000000..6a983cd5bd --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SetConfigurationInJNITest.java @@ -0,0 +1,249 @@ +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/TSDBConnectionTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBConnectionTest.java index 7cdda572a7..c69a556ae4 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBConnectionTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBConnectionTest.java @@ -30,42 +30,6 @@ public class TSDBConnectionTest { } } - @Test - public void runSubscribe() { - try { - // given - TSDBConnection unwrap = conn.unwrap(TSDBConnection.class); - TSDBSubscribe subscribe = unwrap.subscribe("topic1", "select * from log.log", false); - // when - TSDBResultSet rs = subscribe.consume(); - ResultSetMetaData metaData = rs.getMetaData(); - - // then - Assert.assertNotNull(rs); - Assert.assertEquals(4, metaData.getColumnCount()); - Assert.assertEquals("ts", metaData.getColumnLabel(1)); - Assert.assertEquals("level", metaData.getColumnLabel(2)); - Assert.assertEquals("content", metaData.getColumnLabel(3)); - Assert.assertEquals("ipaddr", metaData.getColumnLabel(4)); - rs.next(); - // row 1 - { - Assert.assertNotNull(rs.getTimestamp(1)); - Assert.assertNotNull(rs.getTimestamp("ts")); - Assert.assertNotNull(rs.getByte(2)); - Assert.assertNotNull(rs.getByte("level")); - Assert.assertNotNull(rs.getString(3)); - Assert.assertNotNull(rs.getString("content")); - Assert.assertNotNull(rs.getString(4)); - Assert.assertNotNull(rs.getString("ipaddr")); - } - subscribe.close(false); - } catch (SQLException e) { - e.printStackTrace(); - } - - } - @Test public void prepareStatement() throws SQLException { PreparedStatement pstmt = conn.prepareStatement("select server_status()"); @@ -391,13 +355,9 @@ public class TSDBConnectionTest { } @Test - public void unwrap() { - try { - TSDBConnection tsdbConnection = conn.unwrap(TSDBConnection.class); - Assert.assertNotNull(tsdbConnection); - } catch (SQLException e) { - e.printStackTrace(); - } + public void unwrap() throws SQLException { + TSDBConnection tsdbConnection = conn.unwrap(TSDBConnection.class); + Assert.assertNotNull(tsdbConnection); } @Test @@ -406,31 +366,25 @@ public class TSDBConnectionTest { } @BeforeClass - public static void beforeClass() { - try { - Class.forName("com.taosdata.jdbc.TSDBDriver"); - 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"); - } - - } catch (ClassNotFoundException | SQLException e) { - e.printStackTrace(); + 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() { - try { - if (conn != null) - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); + public static void afterClass() throws SQLException { + if (conn != null) { + Statement statement = conn.createStatement(); + statement.execute("drop database if exists test"); + statement.close(); + conn.close(); } } 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 index 671ecd723d..609523f522 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBDriverTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBDriverTest.java @@ -1,6 +1,5 @@ package com.taosdata.jdbc; -import org.junit.BeforeClass; import org.junit.Test; import java.sql.*; @@ -33,7 +32,6 @@ public class TSDBDriverTest { conn = DriverManager.getConnection(url); assertNotNull("failure - connection should not be null", conn); } catch (SQLException e) { - e.printStackTrace(); fail("failure - should not throw Exception"); } } @@ -49,7 +47,6 @@ public class TSDBDriverTest { conn = DriverManager.getConnection(jdbcUrl, connProps); assertNotNull("failure - connection should not be null", conn); } catch (SQLException e) { - e.printStackTrace(); fail("failure - should not throw Exception"); } } @@ -65,7 +62,6 @@ public class TSDBDriverTest { conn = DriverManager.getConnection(jdbcUrl, connProps); assertNotNull("failure - connection should not be null", conn); } catch (SQLException e) { - e.printStackTrace(); fail("failure - should not throw Exception"); } } @@ -157,16 +153,8 @@ public class TSDBDriverTest { } @Test - public void getParentLogger() throws SQLFeatureNotSupportedException { + public void getParentLogger() { assertNull(new TSDBDriver().getParentLogger()); } - @BeforeClass - public static void before() { - try { - Class.forName("com.taosdata.jdbc.TSDBDriver"); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - } } \ 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 index 88ff5d3a81..f508fbdeed 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBJNIConnectorTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBJNIConnectorTest.java @@ -1,5 +1,7 @@ package com.taosdata.jdbc; +import com.taosdata.jdbc.enums.SchemalessProtocolType; +import com.taosdata.jdbc.enums.SchemalessTimestampType; import org.junit.Test; import java.lang.management.ManagementFactory; @@ -8,6 +10,7 @@ import java.sql.SQLException; import java.sql.SQLWarning; import java.util.ArrayList; import java.util.List; +import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -17,116 +20,111 @@ public class TSDBJNIConnectorTest { private static TSDBResultSetRowData rowData; @Test - public void test() { + public void test() throws SQLException { try { - - try { - //change sleepSeconds when debugging with attach to process to find PID - int sleepSeconds = -1; - if (sleepSeconds>0) { - RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); - String jvmName = runtimeBean.getName(); - long pid = Long.valueOf(jvmName.split("@")[0]); - System.out.println("JVM PID = " + pid); - - Thread.sleep(sleepSeconds*1000); - } - } - catch (Exception e) { - e.printStackTrace(); + //change sleepSeconds when debugging with attach to process to find PID + int sleepSeconds = -1; + if (sleepSeconds > 0) { + RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); + String jvmName = runtimeBean.getName(); + long pid = Long.valueOf(jvmName.split("@")[0]); + System.out.println("JVM PID = " + pid); + + Thread.sleep(sleepSeconds * 1000); } + } catch (Exception e) { + e.printStackTrace(); + } - // init - TSDBJNIConnector.init("/etc/taos", null, null, null); - - // connect - TSDBJNIConnector connector = new TSDBJNIConnector(); - connector.connect("127.0.0.1", 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); - } + // init + Properties properties = new Properties(); + properties.setProperty(TSDBDriver.PROPERTY_KEY_CONFIG_DIR, "/etc/taos"); + TSDBJNIConnector.init(properties); + + // connect + TSDBJNIConnector connector = new TSDBJNIConnector(); + connector.connect("127.0.0.1", 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); - } + { + 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"); + // executeQuery + long pSql = connector.executeQuery("select * from d.t"); - if (connector.isUpdateQuery(pSql)) { - connector.freeResultSet(pSql); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEQUERY); - } + if (connector.isUpdateQuery(pSql)) { + connector.freeResultSet(pSql); + throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEQUERY); + } - assertEquals(1, connector.getResultTimePrecision(pSql)); + 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); - } + // 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)); - 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)); - System.out.println(); - } - // 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 1626006833639000000ns", - "st,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64 1626006833640000000ns"}; - connector.insertLines(lines); - - // close connection - connector.closeConnection(); - - } catch (SQLWarning throwables) { - throwables.printStackTrace(); - } catch (SQLException e) { - e.printStackTrace(); } + // 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 { @@ -140,11 +138,7 @@ public class TSDBJNIConnectorTest { 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; - } + } else return code != TSDBConstants.JNI_FETCH_END; } } 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 index dc41d85cf3..56e8b96bbd 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBParameterMetaDataTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBParameterMetaDataTest.java @@ -17,6 +17,7 @@ public class TSDBParameterMetaDataTest { 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 { @@ -152,9 +153,9 @@ public class TSDBParameterMetaDataTest { try { conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); try (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("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')"); } @@ -190,8 +191,12 @@ public class TSDBParameterMetaDataTest { pstmt_insert.close(); if (pstmt_select != null) pstmt_select.close(); - if (conn != null) + 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/TSDBPreparedStatementTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBPreparedStatementTest.java index 3d76e1f98d..8cb4628884 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBPreparedStatementTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBPreparedStatementTest.java @@ -1233,6 +1233,7 @@ public class TSDBPreparedStatementTest { 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(); 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 index f72cbbec8c..7b9083bf9b 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBResultSetTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBResultSetTest.java @@ -668,8 +668,12 @@ public class TSDBResultSetTest { rs.close(); if (stmt != null) stmt.close(); - if (conn != null) + if (conn != null) { + Statement statement = conn.createStatement(); + statement.execute("drop database if exists restful_test"); + statement.close(); 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 new file mode 100644 index 0000000000..490346e401 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogClass.java @@ -0,0 +1,86 @@ +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 new file mode 100644 index 0000000000..2d22302d02 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogListener.java @@ -0,0 +1,104 @@ +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 new file mode 100644 index 0000000000..1dd074df2d --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogMethod.java @@ -0,0 +1,52 @@ +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 new file mode 100644 index 0000000000..08e5f92122 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/CatalogRunner.java @@ -0,0 +1,36 @@ +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 new file mode 100644 index 0000000000..669b0a0886 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/Description.java @@ -0,0 +1,19 @@ +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 new file mode 100644 index 0000000000..3d1db68164 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/annotation/TestTarget.java @@ -0,0 +1,18 @@ +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/cases/AuthenticationTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/AuthenticationTest.java index 5ff4b1a412..d2f5b915ee 100644 --- 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 @@ -2,7 +2,6 @@ package com.taosdata.jdbc.cases; import com.taosdata.jdbc.TSDBErrorNumbers; import org.junit.Assert; -import org.junit.Before; import org.junit.Ignore; import org.junit.Test; diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/BadLocaleSettingTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/BadLocaleSettingTest.java deleted file mode 100644 index 2211e0fa17..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/BadLocaleSettingTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.taosdata.jdbc.cases; - - -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() { - 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"); - - 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(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @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() { - try { - 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/cases/BatchErrorIgnoreTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/BatchErrorIgnoreTest.java index 2934b54b5b..548c1cff24 100644 --- 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 @@ -19,16 +19,14 @@ public class BatchErrorIgnoreTest { IntStream.range(1, 6).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + ")").forEach(sql -> { try { stmt.addBatch(sql); - } catch (SQLException e) { - e.printStackTrace(); + } 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 e) { - e.printStackTrace(); + } catch (SQLException ignored) { } }); stmt.addBatch("select count(*) from test.weather"); @@ -57,23 +55,19 @@ public class BatchErrorIgnoreTest { IntStream.range(1, 6).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + ")").forEach(sql -> { try { stmt.addBatch(sql); - } catch (SQLException e) { - e.printStackTrace(); + } 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 e) { - e.printStackTrace(); + } catch (SQLException ignored) { } }); stmt.addBatch("select count(*) from test.weather"); results = stmt.executeBatch(); - } catch (SQLException e) { - e.printStackTrace(); } // then @@ -94,10 +88,10 @@ public class BatchErrorIgnoreTest { } @Before - public void before() { - try { - Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); - Statement stmt = conn.createStatement(); + 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)"); @@ -108,37 +102,25 @@ public class BatchErrorIgnoreTest { e.printStackTrace(); } }); - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); } } @BeforeClass - public static void beforeClass() { - try { - Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); - Statement stmt = conn.createStatement(); + 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"); - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); } } @AfterClass - public static void afterClass() { - try { - Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); - Statement stmt = conn.createStatement(); + 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"); - stmt.close(); - conn.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 index fcb6ab7aaf..8299cfebec 100644 --- 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 @@ -20,22 +20,20 @@ public class ConnectMultiTaosdByRestfulWithDifferentTokenTest { private Connection conn2; @Test - public void test() { + public void test() throws SQLException { //when executeSelectStatus(conn1); executeSelectStatus(conn2); executeSelectStatus(conn1); } - private void executeSelectStatus(Connection connection) { + 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()) { } - } catch (SQLException e) { - e.printStackTrace(); } } 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 index 14c7698548..bfffaa4a12 100644 --- 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 @@ -11,7 +11,7 @@ public class DatetimeBefore1970Test { private Connection conn; @Test - public void test() { + public void test() throws SQLException { try (Statement stmt = conn.createStatement()) { // given stmt.executeUpdate("insert into weather(ts) values('1969-12-31 23:59:59.999')"); @@ -45,36 +45,25 @@ public class DatetimeBefore1970Test { // then ts = rs.getTimestamp("ts"); Assert.assertEquals("1970-01-01 07:59:59.999", TimestampUtil.longToDatetime(ts.getTime())); - - } 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 test_timestamp"); - stmt.execute("create database if not exists test_timestamp keep 36500"); - stmt.execute("use test_timestamp"); - stmt.execute("create table weather(ts timestamp,f1 float)"); - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } + public void before() throws SQLException { + conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); + Statement stmt = conn.createStatement(); + stmt.execute("drop database if exists test_timestamp"); + stmt.execute("create database if not exists test_timestamp keep 36500"); + stmt.execute("use test_timestamp"); + stmt.execute("create table weather(ts timestamp,f1 float)"); + stmt.close(); } @After - public void after() { - try { - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists test_timestamp"); - if (conn != null) - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } + public void after() throws SQLException { + Statement stmt = conn.createStatement(); + stmt.execute("drop database if exists test_timestamp"); + if (conn != null) + conn.close(); } } 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 new file mode 100644 index 0000000000..1ba7bdc405 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/GetLongWithDifferentTimestampPrecision.java @@ -0,0 +1,59 @@ +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 index 1297a6b4c4..a8fdf4f2ca 100644 --- 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 @@ -17,29 +17,6 @@ public class ImportTest { static String host = "127.0.0.1"; private static long ts; - @BeforeClass - public static 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 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(); - } catch (SQLException e) { - e.printStackTrace(); - } - - } - @Test public void case001_insertData() throws Exception { try (Statement stmt = connection.createStatement()) { @@ -52,28 +29,25 @@ public class ImportTest { } @Test - public void case002_checkSum() { + public void case002_checkSum() throws SQLException { Assert.assertEquals(50, select()); } - private int 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(); - } catch (SQLException e) { - e.printStackTrace(); } return count; } @Test - public void case003_importData() { + public void case003_importData() throws SQLException { // 避免时间重复 try (Statement stmt = connection.createStatement()) { StringBuilder sqlBuilder = new StringBuilder("import into ").append(dbName).append(".").append(tName).append(" values "); @@ -84,27 +58,40 @@ public class ImportTest { } int rows = stmt.executeUpdate(sqlBuilder.toString()); assertEquals(50, rows); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void case004_checkSum() { + 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() { - try { - if (connection != null) { - Statement statement = connection.createStatement(); - statement.executeUpdate("drop database " + dbName); - statement.close(); - connection.close(); - } - } catch (SQLException e) { - e.printStackTrace(); + 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 index 05c7b0feca..60edcc506e 100644 --- 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 @@ -1,9 +1,6 @@ package com.taosdata.jdbc.cases; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; +import org.junit.*; import org.junit.runners.MethodSorters; import java.sql.*; @@ -16,36 +13,32 @@ 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); - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists inWithoutDb"); - stmt.execute("create database if not exists inWithoutDb"); - stmt.execute("create table inWithoutDb.weather(ts timestamp, f1 int)"); - } + 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/inWithoutDb?user=root&password=taosdata"; + url = "jdbc:TAOS://127.0.0.1:6030/" + dbname + "?user=root&password=taosdata"; conn = DriverManager.getConnection(url, properties); - try (Statement 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); - - } catch (SQLException e) { - e.printStackTrace(); - } - + 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(); } @@ -54,28 +47,25 @@ public class InsertDbwithoutUseDbTest { // prepare the schema final String url = "jdbc:TAOS-RS://" + host + ":6041/inWithoutDb?user=root&password=taosdata"; Connection conn = DriverManager.getConnection(url, properties); - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists inWithoutDb"); - stmt.execute("create database if not exists inWithoutDb"); - stmt.execute("create table inWithoutDb.weather(ts timestamp, f1 int)"); - } - conn.close(); + 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 - conn = DriverManager.getConnection(url, properties); - try (Statement 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); - - } catch (SQLException e) { - e.printStackTrace(); - } + 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 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 index ac254bebf3..7cc1c811d1 100644 --- 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 @@ -427,8 +427,12 @@ public class InsertSpecialCharacterJniTest { @AfterClass public static void afterClass() throws SQLException { - if (conn != null) + 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 index eedccec6f1..81e424971c 100644 --- 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 @@ -391,8 +391,12 @@ public class InsertSpecialCharacterRestfulTest { @AfterClass public static void afterClass() throws SQLException { - if (conn != null) + 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/JDBCTypeAndTypeCompareTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/JDBCTypeAndTypeCompareTest.java new file mode 100644 index 0000000000..38e8d99afe --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/JDBCTypeAndTypeCompareTest.java @@ -0,0 +1,50 @@ +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 index eb8f134227..0889170e65 100644 --- 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 @@ -47,7 +47,7 @@ public class MicroSecondPrecisionJNITest { Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); ts = rs.getLong(1); - Assert.assertEquals(timestamp1, ts); + Assert.assertEquals(timestamp2, ts); } catch (SQLException e) { e.printStackTrace(); } @@ -79,8 +79,13 @@ public class MicroSecondPrecisionJNITest { @AfterClass public static void afterClass() { try { - if (conn != null) + 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 index 7e9f04cd63..48c5ef8a46 100644 --- 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 @@ -23,7 +23,7 @@ public class MicroSecondPrecisionRestfulTest { private static Connection conn3; @Test - public void testCase1() { + 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(); @@ -31,13 +31,11 @@ public class MicroSecondPrecisionRestfulTest { Assert.assertEquals(timestamp1, ts); ts = rs.getLong(1); Assert.assertEquals(timestamp1, ts); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void testCase2() { + 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(); @@ -49,14 +47,12 @@ public class MicroSecondPrecisionRestfulTest { Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); ts = rs.getLong(1); - Assert.assertEquals(timestamp1, ts); - } catch (SQLException e) { - e.printStackTrace(); + Assert.assertEquals(timestamp2, ts); } } @Test - public void testCase3() { + 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(); @@ -65,13 +61,11 @@ public class MicroSecondPrecisionRestfulTest { Assert.assertEquals(timestamp1, ts); ts = rs.getLong(1); Assert.assertEquals(timestamp1, ts); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void testCase4() { + 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(); @@ -83,14 +77,12 @@ public class MicroSecondPrecisionRestfulTest { Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); ts = rs.getLong(1); - Assert.assertEquals(timestamp1, ts); - } catch (SQLException e) { - e.printStackTrace(); + Assert.assertEquals(timestamp2, ts); } } @Test - public void testCase5() { + 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(); @@ -99,13 +91,11 @@ public class MicroSecondPrecisionRestfulTest { Assert.assertEquals(timestamp1, ts); ts = rs.getLong(1); Assert.assertEquals(timestamp1, ts); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void testCase6() { + 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(); @@ -117,9 +107,7 @@ public class MicroSecondPrecisionRestfulTest { Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); ts = rs.getLong(1); - Assert.assertEquals(timestamp1, ts); - } catch (SQLException e) { - e.printStackTrace(); + Assert.assertEquals(timestamp2, ts); } } @@ -156,13 +144,18 @@ public class MicroSecondPrecisionRestfulTest { @AfterClass public static void afterClass() { try { - if (conn1 != null) + 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) { + }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 index 18a2c32aca..220ac0e7ce 100644 --- 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 @@ -1,5 +1,6 @@ package com.taosdata.jdbc.cases; +import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -9,8 +10,7 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.IntStream; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; public class MultiConnectionWithDifferentDbTest { @@ -26,16 +26,17 @@ public class MultiConnectionWithDifferentDbTest { @Override public void run() { for (int j = 0; j < 10; j++) { - queryDb(); try { + queryDb(); TimeUnit.SECONDS.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); + } catch (InterruptedException ignored) { + } catch (SQLException throwables) { + fail(); } } } - private void queryDb() { + 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(); @@ -54,8 +55,6 @@ public class MultiConnectionWithDifferentDbTest { assertEquals(loc, loc_actual); stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); } } }, "thread-" + i)).collect(Collectors.toList()); @@ -73,12 +72,10 @@ public class MultiConnectionWithDifferentDbTest { } @Before - public void before() { + public void before() throws SQLException { ts = System.currentTimeMillis(); - try { - Connection conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); - + 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); @@ -91,8 +88,16 @@ public class MultiConnectionWithDifferentDbTest { 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)"); + } + } - conn.close(); + @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/MultiThreadsWithSameStatementTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/MultiThreadsWithSameStatementTest.java deleted file mode 100644 index 73da79f357..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/MultiThreadsWithSameStatementTest.java +++ /dev/null @@ -1,85 +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.concurrent.TimeUnit; - -public class MultiThreadsWithSameStatementTest { - - private static class Service { - public Connection conn; - public Statement stmt; - - public Service() { - try { - conn = DriverManager.getConnection("jdbc:TAOS://localhost:6030/?user=root&password=taosdata"); - stmt = conn.createStatement(); - stmt.execute("create database if not exists jdbctest"); - stmt.executeUpdate("create table if not exists jdbctest.weather (ts timestamp, f1 int)"); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public void release() { - try { - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - } - - @Before - public void before() { - } - - @Test - public void test() { - Thread t1 = new Thread(() -> { - try { - Service service = new Service(); - ResultSet resultSet = service.stmt.executeQuery("select * from jdbctest.weather"); - while (resultSet.next()) { - ResultSetMetaData metaData = resultSet.getMetaData(); - } - resultSet.close(); - service.release(); - } catch (SQLException e) { - e.printStackTrace(); - } - }); - - Thread t2 = new Thread(() -> { - while (true) { - try { - Service service = new Service(); - service.stmt.executeUpdate("insert into jdbctest.weather values(now,1)"); - service.release(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - }); - t1.start(); - sleep(1000); - t2.start(); - } - - private void sleep(long mills) { - try { - TimeUnit.MILLISECONDS.sleep(mills); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - @After - public void after() { - } -} 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 index 4f2c87966a..c85c6f95a9 100644 --- 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 @@ -1,9 +1,6 @@ package com.taosdata.jdbc.cases; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; import java.sql.*; import java.time.Instant; @@ -17,7 +14,7 @@ public class NanoSecondTimestampJNITest { private static Connection conn; @Test - public void insertUsingLongValue() { + public void insertUsingLongValue() throws SQLException { // given long ms = System.currentTimeMillis(); long ns = ms * 1000_000 + random.nextInt(1000_000); @@ -26,8 +23,6 @@ public class NanoSecondTimestampJNITest { int ret = 0; try (Statement stmt = conn.createStatement()) { ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); - } catch (SQLException e) { - e.printStackTrace(); } // then @@ -35,15 +30,13 @@ public class NanoSecondTimestampJNITest { } @Test - public void insertUsingStringValue() { + 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)"); - } catch (SQLException e) { - e.printStackTrace(); } // then @@ -51,7 +44,7 @@ public class NanoSecondTimestampJNITest { } @Test - public void insertUsingTimestampValue() { + public void insertUsingTimestampValue() throws SQLException { // given long epochSec = System.currentTimeMillis() / 1000; long nanoAdjustment = random.nextInt(1000_000_000); @@ -65,8 +58,6 @@ public class NanoSecondTimestampJNITest { pstmt.setFloat(2, 12.34f); pstmt.setInt(3, 55); ret = pstmt.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); } // then @@ -85,15 +76,13 @@ public class NanoSecondTimestampJNITest { stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); rs = stmt.executeQuery("select * from weather"); rs.next(); - } catch (SQLException e) { - e.printStackTrace(); } // then long actual = rs.getLong(1); - Assert.assertEquals(ms, actual); + Assert.assertEquals(ns, actual); actual = rs.getLong("ts"); - Assert.assertEquals(ms, actual); + Assert.assertEquals(ns, actual); } @Test @@ -102,13 +91,11 @@ public class NanoSecondTimestampJNITest { String timestampStr = "2021-01-01 12:00:00.123456789"; // when - ResultSet rs = null; + 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(); - } catch (SQLException e) { - e.printStackTrace(); } // then @@ -133,8 +120,6 @@ public class NanoSecondTimestampJNITest { pstmt.setFloat(2, 12.34f); pstmt.setInt(3, 55); pstmt.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); } // when @@ -142,8 +127,6 @@ public class NanoSecondTimestampJNITest { try (Statement stmt = conn.createStatement()) { rs = stmt.executeQuery("select * from weather"); rs.next(); - } catch (SQLException e) { - e.printStackTrace(); } // then @@ -156,25 +139,34 @@ public class NanoSecondTimestampJNITest { } @Before - public void 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)"); - } catch (SQLException e) { - e.printStackTrace(); } } @BeforeClass - public static void beforeClass() { + public static void beforeClass() throws SQLException { final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - try { - conn = DriverManager.getConnection(url); - Statement stmt = conn.createStatement(); + 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); - } catch (SQLException e) { + } + } + + @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 index 4271f918b9..796f21ed21 100644 --- 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 @@ -1,9 +1,6 @@ package com.taosdata.jdbc.cases; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; import java.sql.*; import java.time.Instant; @@ -17,7 +14,7 @@ public class NanoSecondTimestampRestfulTest { private static Connection conn; @Test - public void insertUsingLongValue() { + public void insertUsingLongValue() throws SQLException { // given long ms = System.currentTimeMillis(); long ns = ms * 1000_000 + random.nextInt(1000_000); @@ -26,8 +23,6 @@ public class NanoSecondTimestampRestfulTest { int ret = 0; try (Statement stmt = conn.createStatement()) { ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); - } catch (SQLException e) { - e.printStackTrace(); } // then @@ -35,15 +30,13 @@ public class NanoSecondTimestampRestfulTest { } @Test - public void insertUsingStringValue() { + 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)"); - } catch (SQLException e) { - e.printStackTrace(); } // then @@ -51,7 +44,7 @@ public class NanoSecondTimestampRestfulTest { } @Test - public void insertUsingTimestampValue() { + public void insertUsingTimestampValue() throws SQLException { // given long epochSec = System.currentTimeMillis() / 1000; long nanoAdjustment = random.nextInt(1000_000_000); @@ -65,8 +58,6 @@ public class NanoSecondTimestampRestfulTest { pstmt.setFloat(2, 12.34f); pstmt.setInt(3, 55); ret = pstmt.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); } // then @@ -80,20 +71,18 @@ public class NanoSecondTimestampRestfulTest { long ns = ms * 1000_000L + random.nextInt(1000_000); // when - ResultSet rs = null; + 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(); - } catch (SQLException e) { - e.printStackTrace(); } // then long actual = rs.getLong(1); - Assert.assertEquals(ms, actual); + Assert.assertEquals(ns, actual); actual = rs.getLong("ts"); - Assert.assertEquals(ms, actual); + Assert.assertEquals(ns, actual); } @Test @@ -102,13 +91,11 @@ public class NanoSecondTimestampRestfulTest { String timestampStr = "2021-01-01 12:00:00.123456789"; // when - ResultSet rs = null; + 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(); - } catch (SQLException e) { - e.printStackTrace(); } // then @@ -133,8 +120,6 @@ public class NanoSecondTimestampRestfulTest { pstmt.setFloat(2, 12.34f); pstmt.setInt(3, 55); pstmt.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); } // when @@ -142,8 +127,6 @@ public class NanoSecondTimestampRestfulTest { try (Statement stmt = conn.createStatement()) { rs = stmt.executeQuery("select * from weather"); rs.next(); - } catch (SQLException e) { - e.printStackTrace(); } // then @@ -156,26 +139,31 @@ public class NanoSecondTimestampRestfulTest { } @Before - public void 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)"); - } catch (SQLException e) { - e.printStackTrace(); } } @BeforeClass - public static void beforeClass() { + public static void beforeClass() throws SQLException { final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; - try { - conn = DriverManager.getConnection(url); - Statement stmt = conn.createStatement(); + 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); - } catch (SQLException e) { - e.printStackTrace(); + } + } + + @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 index ae0241bf31..8bbc2fe077 100644 --- 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 @@ -12,15 +12,13 @@ public class NullValueInResultSetJNITest { Connection conn; @Test - public void 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()) { } - } catch (SQLException e) { - e.printStackTrace(); } } @@ -42,18 +40,16 @@ public class NullValueInResultSetJNITest { 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, '涛思数据')"); - } catch (SQLException e) { - e.printStackTrace(); } } @After - public void after() { - try { - if (conn != null) - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); + 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 index 7fbb30a524..08f641b96e 100644 --- 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 @@ -12,7 +12,7 @@ public class NullValueInResultSetRestfulTest { Connection conn; @Test - public void test() { + public void test() throws SQLException { try (Statement stmt = conn.createStatement()) { ResultSet rs = stmt.executeQuery("select * from weather"); ResultSetMetaData meta = rs.getMetaData(); @@ -21,9 +21,6 @@ public class NullValueInResultSetRestfulTest { Object value = rs.getObject(i); } } - - } catch (SQLException e) { - e.printStackTrace(); } } @@ -45,18 +42,16 @@ public class NullValueInResultSetRestfulTest { 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, '涛思数据')"); - } catch (SQLException e) { - e.printStackTrace(); } } @After - public void after() { - try { - if (conn != null) - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); + 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 index 61d767b5cf..890505ac65 100644 --- 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 @@ -85,7 +85,11 @@ public class NullValueInResultSetTest { public static void afterClass() throws SQLException { if (conn_restful != null) conn_restful.close(); - if (conn_jni != null) + 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/PreparedStatementBatchInsertRestfulTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/PreparedStatementBatchInsertRestfulTest.java index 90b285381a..85fbeef1b5 100644 --- 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 @@ -20,7 +20,7 @@ public class PreparedStatementBatchInsertRestfulTest { private Connection conn; @Test - public void test() { + public void test() throws SQLException { // given long ts = System.currentTimeMillis(); List rows = IntStream.range(0, 10).mapToObj(i -> { @@ -52,7 +52,6 @@ public class PreparedStatementBatchInsertRestfulTest { } pstmt.executeBatch(); } catch (SQLException e) { - e.printStackTrace(); Assert.fail(); } @@ -64,35 +63,25 @@ public class PreparedStatementBatchInsertRestfulTest { count++; } Assert.assertEquals(10, count); - } catch (SQLException e) { - e.printStackTrace(); } } @Before - public void before() { - try { - 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)"); - } catch (SQLException e) { - e.printStackTrace(); - } + 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() { - try { - Statement stmt = conn.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } + 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 index b4449491a9..fd74e9433a 100644 --- 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 @@ -19,26 +19,22 @@ public class QueryDataTest { static String host = "127.0.0.1"; @Before - public 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 = 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); - } catch (SQLException e) { - e.printStackTrace(); - } + 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 @@ -57,15 +53,11 @@ public class QueryDataTest { } @After - public void close() { - try { - if (statement != null) - statement.close(); - if (connection != null) - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } + 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/ResultSetMetaShouldNotBeNullRestfulTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/ResultSetMetaShouldNotBeNullRestfulTest.java index be27b13507..ff0dad1bda 100644 --- 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 @@ -15,19 +15,15 @@ public class ResultSetMetaShouldNotBeNullRestfulTest { private Connection connection; @Test - public void testExecuteQuery() { + public void testExecuteQuery() throws SQLException { // given - ResultSetMetaData metaData = null; - int columnCount = -1; + ResultSetMetaData metaData; + int columnCount; // when - try { - Statement statement = connection.createStatement(); - metaData = statement.executeQuery("select * from weather").getMetaData(); - columnCount = metaData.getColumnCount(); - } catch (SQLException e) { - e.printStackTrace(); - } + Statement statement = connection.createStatement(); + metaData = statement.executeQuery("select * from weather").getMetaData(); + columnCount = metaData.getColumnCount(); // then Assert.assertNotNull(metaData); @@ -35,20 +31,17 @@ public class ResultSetMetaShouldNotBeNullRestfulTest { } @Test - public void testExecute() { + public void testExecute() throws SQLException { // given - ResultSetMetaData metaData = null; - int columnCount = -1; - boolean execute = false; + ResultSetMetaData metaData; + int columnCount; + boolean execute; + // when - try { - Statement statement = connection.createStatement(); - execute = statement.execute("select * from weather"); - metaData = statement.getResultSet().getMetaData(); - columnCount = metaData.getColumnCount(); - } catch (SQLException e) { - e.printStackTrace(); - } + Statement statement = connection.createStatement(); + execute = statement.execute("select * from weather"); + metaData = statement.getResultSet().getMetaData(); + columnCount = metaData.getColumnCount(); // then Assert.assertEquals(true, execute); @@ -57,30 +50,22 @@ public class ResultSetMetaShouldNotBeNullRestfulTest { } @Before - public void before() { - try { - 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(); - } catch (SQLException e) { - e.printStackTrace(); - } + 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() { - try { - Statement stmt = connection.createStatement(); - stmt.execute("drop database if exists " + dbname); - stmt.close(); - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } + 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 index b51c0309be..79e5602e9e 100644 --- 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 @@ -17,25 +17,20 @@ public class SelectTest { String host = "127.0.0.1"; @Before - public void createDatabaseAndTable() { - 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 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(); - } catch (SQLException e) { - e.printStackTrace(); - } + 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 @@ -65,16 +60,12 @@ public class SelectTest { } @After - public void close() { - try { - if (connection != null) { - Statement stmt = connection.createStatement(); - stmt.executeUpdate("drop database " + dbName); - stmt.close(); - connection.close(); - } - } catch (SQLException e) { - e.printStackTrace(); + 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/TaosInfoMonitorTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TaosInfoMonitorTest.java deleted file mode 100644 index 7df9f73807..0000000000 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TaosInfoMonitorTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.taosdata.jdbc.cases; - -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; - -public class TaosInfoMonitorTest { - - @Test - public void testCreateTooManyConnection() throws ClassNotFoundException { - Class.forName("com.taosdata.jdbc.TSDBDriver"); - final String url = "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata"; - - List connectionList = IntStream.range(0, 100).mapToObj(i -> { - try { - TimeUnit.MILLISECONDS.sleep(100); - return DriverManager.getConnection(url); - } catch (SQLException | InterruptedException e) { - e.printStackTrace(); - } - return null; - }).collect(Collectors.toList()); - - connectionList.forEach(conn -> { - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("show databases"); - while (rs.next()) { - - } - TimeUnit.MILLISECONDS.sleep(100); - } catch (SQLException | InterruptedException e) { - e.printStackTrace(); - } - }); - - connectionList.forEach(conn -> { - try { - conn.close(); - TimeUnit.MILLISECONDS.sleep(100); - } catch (SQLException | InterruptedException 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 index 72734cb0ec..76053ccc41 100644 --- 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 @@ -25,7 +25,7 @@ public class TimestampPrecisionInNanoInJniTest { 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; @@ -43,7 +43,7 @@ public class TimestampPrecisionInNanoInJniTest { 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(\"" + date3 + "\", \"" + date3 + "\", 128)"); stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp2 + "," + timestamp2 + ", 127)"); stmt.close(); } @@ -54,7 +54,7 @@ public class TimestampPrecisionInNanoInJniTest { 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(\"" + date3 + "\", \"" + date3 + "\", 128)"); stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp2 + "," + timestamp2 + ", 127)"); stmt.close(); } @@ -62,8 +62,12 @@ public class TimestampPrecisionInNanoInJniTest { @AfterClass public static void afterClass() { try { - if (conn != null) + 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(); } @@ -83,7 +87,7 @@ public class TimestampPrecisionInNanoInJniTest { int nanos = rs.getTimestamp(1).getNanos(); Assert.assertEquals(ts % 1000_000_000l, nanos); long test_ts = rs.getLong(1); - Assert.assertEquals(ts / 1000_000l, test_ts); + Assert.assertEquals(ts, test_ts); } @Test @@ -105,7 +109,7 @@ public class TimestampPrecisionInNanoInJniTest { @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)"); + 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'"); @@ -139,7 +143,7 @@ public class TimestampPrecisionInNanoInJniTest { 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)"); + 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 + "'"); @@ -184,300 +188,248 @@ public class TimestampPrecisionInNanoInJniTest { } @Test - public void canSelectFirstRowFromWeatherForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryLargerThanInDateTypeForFirstCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryLargerThanInDateTypeForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } - } + } @Test - public void canQueryLargerThanInNumberTypeForFirstCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryLargerThanInNumberTypeForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryLargerThanOrEqualToInDateTypeForFirstCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryLargerThanOrEqualToInDateTypeForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryLargerThanOrEqualToInNumberTypeForFirstCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryLargerThanOrEqualToInNumberTypeForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } - } + } @Test - public void canQueryLessThanInDateTypeForFirstCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryLessThanInDateTypeForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryLessThanInNumberTypeForFirstCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryLessThanInNumberTypeForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryLessThanOrEqualToInDateTypeForFirstCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryLessThanOrEqualToInDateTypeForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } - } + } @Test - public void canQueryLessThanOrEqualToInNumberTypeForFirstCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryLessThanOrEqualToInNumberTypeForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryBetweenAndInDateTypeForFirstCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryBetweenAndInDateTypeForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryBetweenAndInNumberTypeForFirstCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryBetweenAndInNumberTypeForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryNotEqualToInDateTypeForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryNotEqualToInNumberTypeForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryNotEqualInDateTypeForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canQueryNotEqualInNumberTypeForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canInsertTimestampWithNowAndNsOffsetInBothFirstAndSecondCol(){ + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canIntervalAndSlidingAcceptNsUnitForFirstCol(){ + 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(); @@ -486,13 +438,11 @@ public class TimestampPrecisionInNanoInJniTest { rs.next(); sum = rs.getLong(2); Assert.assertEquals(128l, sum); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void canIntervalAndSlidingAcceptNsUnitForSecondCol(){ + 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(); @@ -501,8 +451,6 @@ public class TimestampPrecisionInNanoInJniTest { rs.next(); sum = rs.getLong(2); Assert.assertEquals(128l, sum); - } catch (SQLException e) { - e.printStackTrace(); } } @@ -525,46 +473,38 @@ public class TimestampPrecisionInNanoInJniTest { } @Test - public void willAutomaticallyFillToNsUnitWithZerosForFirstCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void willAutomaticallyFillToNsUnitWithZerosForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void willAutomaticallyDropDigitExceedNsDigitNumberForFirstCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void willAutomaticallyDropDigitExceedNsDigitNumberForSecondCol() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } } 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 new file mode 100644 index 0000000000..4aedf867d4 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TimestampPrecisonInNanoRestTest.java @@ -0,0 +1,570 @@ +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 index e4149793ac..cff353093a 100644 --- 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 @@ -15,7 +15,7 @@ public class UnsignedNumberJniTest { private static long ts; @Test - public void testCase001() { + public void testCase001() throws SQLException { try (Statement stmt = conn.createStatement()) { ResultSet rs = stmt.executeQuery("select * from us_table"); ResultSetMetaData meta = rs.getMetaData(); @@ -27,13 +27,11 @@ public class UnsignedNumberJniTest { Assert.assertEquals("2147483647", rs.getString(4)); Assert.assertEquals("9223372036854775807", rs.getString(5)); } - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void testCase002() { + public void testCase002() throws SQLException { try (Statement stmt = conn.createStatement()) { ResultSet rs = stmt.executeQuery("select * from us_table"); ResultSetMetaData meta = rs.getMetaData(); @@ -46,8 +44,6 @@ public class UnsignedNumberJniTest { Assert.assertEquals(2147483647, rs.getInt(4)); Assert.assertEquals(9223372036854775807L, rs.getLong(5)); } - } catch (SQLException e) { - e.printStackTrace(); } } @@ -140,35 +136,31 @@ public class UnsignedNumberJniTest { } @BeforeClass - public static void 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(); - try { - 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(); - } catch (SQLException e) { - e.printStackTrace(); - } + 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() { - try { - if (conn != null) - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); + 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 index 3bdf5ae4f2..b3ca6871db 100644 --- 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 @@ -14,9 +14,10 @@ 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() { + public void testCase001() throws SQLException { try (Statement stmt = conn.createStatement()) { ResultSet rs = stmt.executeQuery("select * from us_table"); ResultSetMetaData meta = rs.getMetaData(); @@ -28,13 +29,11 @@ public class UnsignedNumberRestfulTest { Assert.assertEquals("2147483647", rs.getString(4)); Assert.assertEquals("9223372036854775807", rs.getString(5)); } - } catch (SQLException e) { - e.printStackTrace(); } } @Test - public void testCase002() { + public void testCase002() throws SQLException { try (Statement stmt = conn.createStatement()) { ResultSet rs = stmt.executeQuery("select * from us_table"); ResultSetMetaData meta = rs.getMetaData(); @@ -47,8 +46,6 @@ public class UnsignedNumberRestfulTest { Assert.assertEquals(2147483647, rs.getInt(4)); Assert.assertEquals(9223372036854775807L, rs.getLong(5)); } - } catch (SQLException e) { - e.printStackTrace(); } } @@ -152,9 +149,9 @@ public class UnsignedNumberRestfulTest { 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 unsign_restful"); - stmt.execute("create database if not exists unsign_restful"); - stmt.execute("use unsign_restful"); + 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(); @@ -166,8 +163,12 @@ public class UnsignedNumberRestfulTest { @AfterClass public static void afterClass() { try { - if (conn != null) + 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 new file mode 100644 index 0000000000..c4f2cba446 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/UseNowInsertTimestampTest.java @@ -0,0 +1,90 @@ +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 new file mode 100644 index 0000000000..7ad7c23136 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/BadLocaleSettingTest.java @@ -0,0 +1,55 @@ +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 new file mode 100644 index 0000000000..94a5382410 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/BatchFetchTest.java @@ -0,0 +1,93 @@ +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 new file mode 100644 index 0000000000..41629189ae --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/CharsetTest.java @@ -0,0 +1,55 @@ +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 new file mode 100644 index 0000000000..7f7979eb01 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/HttpKeepAliveTest.java @@ -0,0 +1,57 @@ +package com.taosdata.jdbc.confprops; + +import org.junit.Assert; +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; + +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 new file mode 100644 index 0000000000..4a919db6f4 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TaosInfoMonitorTest.java @@ -0,0 +1,54 @@ +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/cases/TimeZoneTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TimeZoneTest.java similarity index 91% rename from src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TimeZoneTest.java rename to src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TimeZoneTest.java index 94a175ad5c..bc19e63ba6 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TimeZoneTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TimeZoneTest.java @@ -1,4 +1,4 @@ -package com.taosdata.jdbc.cases; +package com.taosdata.jdbc.confprops; import com.taosdata.jdbc.TSDBDriver; import org.junit.Test; @@ -29,7 +29,7 @@ public class TimeZoneTest { } @Test - public void taosTimeZone() { + public void taosTimeZone() throws SQLException { // given Properties props = new Properties(); props.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); @@ -39,7 +39,7 @@ public class TimeZoneTest { Statement stmt = connection.createStatement(); stmt.execute("drop database if exists timezone_test"); - stmt.execute("create database if not exists timezone_test keep 365000"); + 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)"); @@ -51,7 +51,7 @@ public class TimeZoneTest { System.out.println("ts: " + ts.getTime() + "," + ts); } - stmt.execute("insert into timezone_test.weather(ts, temperature, humidity) values('1970-01-02 00:00:00', 1.0, 2.0)"); + 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()) { @@ -63,8 +63,6 @@ public class TimeZoneTest { stmt.execute("drop database if exists timezone_test"); stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); } } 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 new file mode 100644 index 0000000000..a6f8cf7c0a --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/confprops/TimestampFormatTest.java @@ -0,0 +1,181 @@ +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 index 9fe51e7203..0a37e255a4 100644 --- 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 @@ -33,7 +33,6 @@ public class DatabaseSpecifiedTest { String loc = rs.getString("loc"); assertEquals("beijing", loc); } - connection.close(); } @Before @@ -59,8 +58,12 @@ public class DatabaseSpecifiedTest { @After public void after() { try { - if (connection != null) + 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 index d50b56b434..e4785a197e 100644 --- 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 @@ -23,14 +23,12 @@ public class RestfulConnectionTest { } @Test - public void createStatement() { + 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); - } catch (SQLException e) { - e.printStackTrace(); } } @@ -359,13 +357,9 @@ public class RestfulConnectionTest { } @Test - public void unwrap() { - try { - RestfulConnection restfulConnection = conn.unwrap(RestfulConnection.class); - Assert.assertNotNull(restfulConnection); - } catch (SQLException e) { - e.printStackTrace(); - } + public void unwrap() throws SQLException { + RestfulConnection restfulConnection = conn.unwrap(RestfulConnection.class); + Assert.assertNotNull(restfulConnection); } @Test @@ -388,12 +382,12 @@ public class RestfulConnectionTest { } @AfterClass - public static void afterClass() { - try { - if (conn != null) - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); + public static void afterClass() throws SQLException { + if (conn != null) { + Statement statement = conn.createStatement(); + statement.execute("drop database if exists test"); + statement.close(); + conn.close(); } } 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 index 85007db0e5..50b0b97d90 100644 --- 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 @@ -1085,30 +1085,26 @@ public class RestfulDatabaseMetaDataTest { } @BeforeClass - public static void beforeClass() { - try { - Class.forName("com.taosdata.jdbc.rs.RestfulDriver"); - 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(RestfulDatabaseMetaData.class); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (SQLException e) { - e.printStackTrace(); - } + 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 log"); + stmt.execute("create database if not exists log precision 'us'"); + stmt.execute("use log"); + 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() { - try { - if (connection != null) - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } + 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/RestfulJDBCTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulJDBCTest.java index 4f727d43a0..da30bbd568 100644 --- 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 @@ -12,25 +12,26 @@ 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 restful_test"; + String sql = "drop database if exists " + dbname; // when boolean execute = execute(connection, sql); // then Assert.assertFalse(execute); // given - sql = "create database if not exists restful_test"; + sql = "create database if not exists " + dbname; // when execute = execute(connection, sql); // then Assert.assertFalse(execute); // given - sql = "use restful_test"; + sql = "use " + dbname; // when execute = execute(connection, sql); // then @@ -40,7 +41,7 @@ public class RestfulJDBCTest { @Test public void testCase002() throws SQLException { // given - String sql = "create table weather(ts timestamp, temperature float, humidity int) tags(location nchar(64), groupId int)"; + 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 @@ -51,7 +52,7 @@ public class RestfulJDBCTest { public void testCase004() throws SQLException { for (int i = 1; i <= 100; i++) { // given - String sql = "create table t" + i + " using weather tags('beijing', '" + i + "')"; + String sql = "create table " + dbname + ".t" + i + " using " + dbname + ".weather tags('beijing', '" + i + "')"; // when boolean execute = execute(connection, sql); // then @@ -67,7 +68,7 @@ public class RestfulJDBCTest { // given long currentTimeMillis = System.currentTimeMillis(); - String sql = "insert into t" + j + " values(" + currentTimeMillis + "," + (random.nextFloat() * 50) + "," + random.nextInt(100) + ")"; + String sql = "insert into " + dbname + ".t" + j + " values(" + currentTimeMillis + "," + (random.nextFloat() * 50) + "," + random.nextInt(100) + ")"; // when int affectRows = executeUpdate(connection, sql); // then @@ -82,7 +83,7 @@ public class RestfulJDBCTest { @Test public void testCase006() throws SQLException { // given - String sql = "select * from weather"; + String sql = "select * from " + dbname + ".weather"; // when ResultSet rs = executeQuery(connection, sql); ResultSetMetaData meta = rs.getMetaData(); @@ -101,7 +102,7 @@ public class RestfulJDBCTest { @Test public void testCase007() throws SQLException { // given - String sql = "drop database restful_test"; + String sql = "drop database " + dbname; // when boolean execute = execute(connection, sql); @@ -142,7 +143,7 @@ public class RestfulJDBCTest { public static void afterClass() throws SQLException { if (connection != null) { Statement stmt = connection.createStatement(); - stmt.execute("drop database if exists restful_test"); + stmt.execute("drop database if exists " + dbname); stmt.close(); connection.close(); } 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 index 81d7f5b56c..c8ca1a5de7 100644 --- 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 @@ -18,6 +18,7 @@ public class RestfulParameterMetaDataTest { 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 { @@ -148,9 +149,9 @@ public class RestfulParameterMetaDataTest { 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 test_pstmt"); - stmt.execute("create database if not exists test_pstmt"); - stmt.execute("use test_pstmt"); + 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')"); } @@ -186,8 +187,12 @@ public class RestfulParameterMetaDataTest { pstmt_insert.close(); if (pstmt_select != null) pstmt_select.close(); - if (conn != null) + 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/rs/RestfulPreparedStatementTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulPreparedStatementTest.java index 4760a723e4..40d0e0214f 100644 --- 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 @@ -400,8 +400,12 @@ public class RestfulPreparedStatementTest { pstmt_select.close(); if (pstmt_without_parameters != null) pstmt_without_parameters.close(); - if (conn != null) + if (conn != null) { + Statement statement = conn.createStatement(); + statement.execute("drop database if exists test_pstmt"); + statement.close(); conn.close(); + } } catch (SQLException e) { e.printStackTrace(); } 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 index f3011af799..6e5851474f 100644 --- 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 @@ -15,6 +15,7 @@ public class RestfulResultSetMetaDataTest { 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 { @@ -206,8 +207,12 @@ public class RestfulResultSetMetaDataTest { rs.close(); if (stmt != null) stmt.close(); - if (conn != null) + 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/rs/RestfulResultSetTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetTest.java index 8ffa1de21c..c1ca31ae38 100644 --- 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 @@ -22,6 +22,20 @@ public class RestfulResultSetTest { 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()); @@ -657,20 +671,6 @@ public class RestfulResultSetTest { Assert.assertTrue(rs.isWrapperFor(RestfulResultSet.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("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(); - } - @AfterClass public static void afterClass() throws SQLException { if (rs != null) 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 index a7b3ceb9d3..83ab2c7263 100644 --- 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 @@ -17,46 +17,32 @@ public class RestfulStatementTest { private static Statement stmt; @Test - public void executeQuery() { - try { - 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(); - } catch (SQLException e) { - e.printStackTrace(); + 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() { + public void executeUpdate() throws SQLException { 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(); - } + 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); } - @Test - public void close() { - // test in AfterClass method - } - - @Test public void getMaxFieldSize() throws SQLException { Assert.assertEquals(16 * 1024, stmt.getMaxFieldSize()); @@ -64,7 +50,6 @@ public class RestfulStatementTest { @Test(expected = SQLException.class) public void setMaxFieldSize() throws SQLException { - stmt.setMaxFieldSize(0); stmt.setMaxFieldSize(-1); } @@ -118,83 +103,70 @@ public class RestfulStatementTest { } @Test - public void execute() { + public void execute() throws SQLException { final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); - try { - 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); - } catch (SQLException e) { - e.printStackTrace(); - } + 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() { + public void getResultSet() throws SQLException { final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); - try { - 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); - } catch (SQLException e) { - e.printStackTrace(); + 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); - @Test - public void getUpdateCount() { - // already test in execute method + isSelect = stmt.execute("drop database " + dbName); + Assert.assertEquals(false, isSelect); + affectedRows = stmt.getUpdateCount(); + Assert.assertEquals(0, affectedRows); } @Test @@ -239,64 +211,48 @@ public class RestfulStatementTest { } @Test - public void addBatch() { + public void addBatch() throws SQLException { 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(); - } + 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() { + public void clearBatch() throws SQLException { 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(); - } + 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() { + public void executeBatch() throws SQLException { 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(); - } + 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() { - try { - Connection connection = stmt.getConnection(); - Assert.assertNotNull(connection); - Assert.assertTrue(this.conn == connection); - } catch (SQLException e) { - e.printStackTrace(); - } + public void getConnection() throws SQLException { + Connection connection = stmt.getConnection(); + Assert.assertNotNull(connection); + Assert.assertTrue(this.conn == connection); } @Test(expected = SQLFeatureNotSupportedException.class) @@ -346,12 +302,8 @@ public class RestfulStatementTest { } @Test - public void isClosed() { - try { - Assert.assertEquals(false, stmt.isClosed()); - } catch (SQLException e) { - e.printStackTrace(); - } + public void isClosed() throws SQLException { + Assert.assertEquals(false, stmt.isClosed()); } @Test @@ -387,29 +339,21 @@ public class RestfulStatementTest { } @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-RS://" + host + ":6041/?user=root&password=taosdata", properties); - stmt = conn.createStatement(); - } catch (SQLException e) { - e.printStackTrace(); - } + 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() { - try { - if (stmt != null) - stmt.close(); - if (conn != null) - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } + 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 index 7dff90a775..4893e6062f 100644 --- 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 @@ -543,15 +543,6 @@ public class SQLTest { Assert.assertNotNull(rs); } - @Test - public void testCase053() { - String sql = "select avg(cpu_taosd), avg(cpu_system), max(cpu_cores), avg(mem_taosd), avg(mem_system), max(mem_total), avg(disk_used), max(disk_total), avg(band_speed), avg(io_read), avg(io_write), sum(req_http), sum(req_select), sum(req_insert) from log.dn1 where ts> now - 60m and ts<= now interval(1m) fill(value, 0)"; - // 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); 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 new file mode 100644 index 0000000000..f0cd200e04 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/WasNullTest.java @@ -0,0 +1,86 @@ +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 index cae33f18e7..128a62e5d9 100644 --- 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 @@ -2,8 +2,6 @@ package com.taosdata.jdbc.utils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.TSDBError; import org.junit.Test; import java.io.UnsupportedEncodingException; @@ -11,7 +9,6 @@ import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.sql.SQLException; import java.util.List; -import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -20,18 +17,20 @@ public class HttpClientPoolUtilTest { String user = "root"; String password = "taosdata"; String host = "127.0.0.1"; - String dbname = "log"; @Test - public void test() { + public void useLog() { // given - List threads = IntStream.range(0, 4000).mapToObj(i -> new Thread(() -> { - useDB(); -// try { -// TimeUnit.SECONDS.sleep(10); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } + 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); @@ -43,34 +42,62 @@ public class HttpClientPoolUtilTest { e.printStackTrace(); } } - } - private void useDB() { - try { - 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 + ""; - 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")); + @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()); - String url = "http://" + host + ":6041/rest/sql"; - String sql = "use " + dbname; - result = HttpClientPoolUtil.execute(url, sql, token); + threads.forEach(Thread::start); - JSONObject resultJson = JSON.parseObject(result); - if (resultJson.getString("status").equals("error")) { - throw TSDBError.createSQLException(resultJson.getInteger("code"), resultJson.getString("desc")); + for (Thread thread : threads) { + try { + thread.join(); + } catch (InterruptedException e) { + e.printStackTrace(); } - } catch (UnsupportedEncodingException | SQLException 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 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/resources/commons-logging.properties b/src/connector/jdbc/src/test/resources/commons-logging.properties new file mode 100644 index 0000000000..ac435a2a1b --- /dev/null +++ b/src/connector/jdbc/src/test/resources/commons-logging.properties @@ -0,0 +1,2 @@ +#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 new file mode 100644 index 0000000000..abcc1ef6d5 --- /dev/null +++ b/src/connector/jdbc/src/test/resources/simplelog.properties @@ -0,0 +1,5 @@ +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 -- GitLab