diff --git a/cmake/install.inc b/cmake/install.inc index 48d594e8898b5a278dc46fbec1e61ebe90ead905..3844198047d2a1d5b5e2fd75b0f5bc887c9e50ec 100755 --- a/cmake/install.inc +++ b/cmake/install.inc @@ -53,7 +53,7 @@ ELSEIF (TD_WINDOWS) #INSTALL(TARGETS taos RUNTIME DESTINATION driver) #INSTALL(TARGETS shell RUNTIME DESTINATION .) IF (TD_MVN_INSTALLED) - INSTALL(FILES ${LIBRARY_OUTPUT_PATH}/taos-jdbcdriver-2.0.34-dist.jar DESTINATION connector/jdbc) + INSTALL(FILES ${LIBRARY_OUTPUT_PATH}/taos-jdbcdriver-2.0.36-dist.jar DESTINATION connector/jdbc) ENDIF () ELSEIF (TD_DARWIN) SET(TD_MAKE_INSTALL_SH "${TD_COMMUNITY_DIR}/packaging/tools/make_install.sh") diff --git a/src/client/jni/com_taosdata_jdbc_TSDBJNIConnector.h b/src/client/jni/com_taosdata_jdbc_TSDBJNIConnector.h index 7181c658ddcdfde3efe7df3c0784c20f18bd4c03..79d481498e218d5c0be157ff9d145fb37655349e 100644 --- a/src/client/jni/com_taosdata_jdbc_TSDBJNIConnector.h +++ b/src/client/jni/com_taosdata_jdbc_TSDBJNIConnector.h @@ -41,6 +41,14 @@ JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_initImp JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setOptions (JNIEnv *, jclass, jint, jstring); +/* + * Class: com_taosdata_jdbc_TSDBJNIConnector + * Method: setConfigImp + * Signature: (Ljava/lang/String;)Lcom/taosdata/jdbc/TSDBException; + */ +JNIEXPORT jobject JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setConfigImp + (JNIEnv *, jclass, jstring); + /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: getTsCharset @@ -231,6 +239,14 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_closeStmt(JNIEnv JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setTableNameTagsImp (JNIEnv *, jobject, jlong, jstring, jint, jbyteArray, jbyteArray, jbyteArray, jbyteArray, jlong); +/* + * Class: com_taosdata_jdbc_TSDBJNIConnector + * Method: insertLinesImp + * Signature: ([Ljava/lang/String;JII)I + */ +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_insertLinesImp + (JNIEnv *, jobject, jobjectArray, jlong, jint, jint); + #ifdef __cplusplus } #endif diff --git a/src/client/src/TSDBJNIConnector.c b/src/client/src/TSDBJNIConnector.c index 506c8d64b9f4213713656ecd08612a103e0b1b2d..5fd5371fb3cc7ab61c83201dcc1b1c2daff1d228 100644 --- a/src/client/src/TSDBJNIConnector.c +++ b/src/client/src/TSDBJNIConnector.c @@ -200,6 +200,11 @@ JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_initImp(JNIEnv *e jniDebug("jni initialized successfully, config directory: %s", configDir); } +JNIEXPORT jobject JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setConfigImp(JNIEnv *env, jclass jobj, + jstring config) { + return NULL;// nothing to do +} + JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setOptions(JNIEnv *env, jobject jobj, jint optionIndex, jstring optionValue) { if (optionValue == NULL) { @@ -993,8 +998,8 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setTableNameTagsI return JNI_SUCCESS; } -JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_insertLinesImp(JNIEnv *env, jobject jobj, - jobjectArray lines, jlong conn) { +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_insertLinesImp + (JNIEnv *env, jobject jobj, jobjectArray lines, jlong conn, jint protocol, jint precision){ TAOS *taos = (TAOS *)conn; if (taos == NULL) { jniError("jobj:%p, connection already closed", jobj); diff --git a/src/client/src/tscPrepare.c b/src/client/src/tscPrepare.c index 4bb61d2ed8fc7c3091d67b14fa10ffd881822009..4c49840d8b43d2d6f3d4253c9138026c4bd6e3e1 100644 --- a/src/client/src/tscPrepare.c +++ b/src/client/src/tscPrepare.c @@ -1717,19 +1717,29 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags pStmt->last = STMT_SETTBNAME; - uint64_t* uid = (uint64_t*)taosHashGet(pStmt->mtb.pTableHash, name, strlen(name)); + char* tbname = strdup(name); + if (!tbname) { + tscError("0x%" PRIx64 " out of memory", pSql->self); + STMT_RET(TSDB_CODE_TSC_OUT_OF_MEMORY); + } + strntolower(tbname, tbname, (int32_t)strlen(tbname)); // N.B. use lowercase in following codes + uint32_t nameLen = (uint32_t)strlen(tbname); + + uint64_t* uid = (uint64_t*)taosHashGet(pStmt->mtb.pTableHash, tbname, nameLen); if (uid != NULL) { pStmt->mtb.currentUid = *uid; STableDataBlocks** t1 = (STableDataBlocks**)taosHashGet(pStmt->mtb.pTableBlockHashList, (const char*)&pStmt->mtb.currentUid, sizeof(pStmt->mtb.currentUid)); if (t1 == NULL) { tscError("0x%"PRIx64" no table data block in hash list, uid:%" PRId64 , pSql->self, pStmt->mtb.currentUid); + tfree(tbname); STMT_RET(TSDB_CODE_TSC_APP_ERROR); } if ((*t1)->pData == NULL) { code = tscCreateDataBlockData(*t1, TSDB_PAYLOAD_SIZE, (*t1)->pTableMeta->tableInfo.rowSize, sizeof(SSubmitBlk)); if (code != TSDB_CODE_SUCCESS) { + tfree(tbname); STMT_RET(code); } } @@ -1744,7 +1754,8 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags taosHashPut(pCmd->insertParam.pTableBlockHashList, (void *)&pStmt->mtb.currentUid, sizeof(pStmt->mtb.currentUid), (void*)t1, POINTER_BYTES); - tscDebug("0x%"PRIx64" table:%s is already prepared, uid:%" PRIu64, pSql->self, name, pStmt->mtb.currentUid); + tscDebug("0x%" PRIx64 " table:%s is already prepared, uid:%" PRIu64, pSql->self, tbname, pStmt->mtb.currentUid); + tfree(tbname); STMT_RET(TSDB_CODE_SUCCESS); } @@ -1756,8 +1767,8 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags SStrToken tname = {0}; tname.type = TK_STRING; - tname.z = (char *)name; - tname.n = (uint32_t)strlen(name); + tname.z = tbname; + tname.n = nameLen; SName fullname = {0}; tscSetTableFullName(&fullname, &tname, pSql); @@ -1765,6 +1776,7 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags code = tscGetTableMetaEx(pSql, pTableMetaInfo, false, true); if (code != TSDB_CODE_SUCCESS) { + tfree(tbname); STMT_RET(code); } @@ -1772,6 +1784,7 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags if (strcmp(sTableName, pTableMeta->sTableName)) { tscError("0x%"PRIx64" only tables belongs to one stable is allowed", pSql->self); + tfree(tbname); STMT_RET(TSDB_CODE_TSC_APP_ERROR); } @@ -1786,22 +1799,24 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags taosHashPut(pCmd->insertParam.pTableBlockHashList, (void *)&pStmt->mtb.currentUid, sizeof(pStmt->mtb.currentUid), (void*)&pBlock, POINTER_BYTES); taosHashPut(pStmt->mtb.pTableBlockHashList, (void *)&pStmt->mtb.currentUid, sizeof(pStmt->mtb.currentUid), (void*)&pBlock, POINTER_BYTES); - taosHashPut(pStmt->mtb.pTableHash, name, strlen(name), (char*) &pTableMeta->id.uid, sizeof(pTableMeta->id.uid)); + taosHashPut(pStmt->mtb.pTableHash, tbname, nameLen, (char*)&pTableMeta->id.uid, sizeof(pTableMeta->id.uid)); - tscDebug("0x%"PRIx64" table:%s is prepared, uid:%" PRIx64, pSql->self, name, pStmt->mtb.currentUid); - + tscDebug("0x%" PRIx64 " table:%s is prepared, uid:%" PRIx64, pSql->self, tbname, pStmt->mtb.currentUid); + tfree(tbname); STMT_RET(TSDB_CODE_SUCCESS); } if (pStmt->mtb.tagSet) { - pStmt->mtb.tbname = tscReplaceStrToken(&pSql->sqlstr, &pStmt->mtb.tbname, name); + pStmt->mtb.tbname = tscReplaceStrToken(&pSql->sqlstr, &pStmt->mtb.tbname, tbname); } else { if (tags == NULL) { tscError("No tags set"); + tfree(tbname); STMT_RET(invalidOperationMsg(tscGetErrorMsgPayload(&pStmt->pSql->cmd), "no tags set")); } - int32_t ret = stmtGenInsertStatement(pSql, pStmt, name, tags); + int32_t ret = stmtGenInsertStatement(pSql, pStmt, tbname, tags); if (ret != TSDB_CODE_SUCCESS) { + tfree(tbname); STMT_RET(ret); } } @@ -1846,15 +1861,16 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags pStmt->mtb.tbNum++; taosHashPut(pStmt->mtb.pTableBlockHashList, (void *)&pStmt->mtb.currentUid, sizeof(pStmt->mtb.currentUid), (void*)&pBlock, POINTER_BYTES); - taosHashPut(pStmt->mtb.pTableHash, name, strlen(name), (char*) &pTableMeta->id.uid, sizeof(pTableMeta->id.uid)); + taosHashPut(pStmt->mtb.pTableHash, tbname, nameLen, (char*)&pTableMeta->id.uid, sizeof(pTableMeta->id.uid)); if (pStmt->mtb.lastBlock == NULL) { insertStmtGenLastBlock(&pStmt->mtb.lastBlock, pBlock); } - tscDebug("0x%"PRIx64" table:%s is prepared, uid:%" PRIx64, pSql->self, name, pStmt->mtb.currentUid); + tscDebug("0x%" PRIx64 " table:%s is prepared, uid:%" PRIx64, pSql->self, tbname, pStmt->mtb.currentUid); } + tfree(tbname); STMT_RET(code); } diff --git a/src/connector/jdbc/CMakeLists.txt b/src/connector/jdbc/CMakeLists.txt index e432dac1cea593b371a173f334e5313236091ab3..1cde4683f0b0f402c592da0177d94175a0f77692 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 ef57198e78d2268faba526d5506b0dc384f5766f..926a5ef483d9f1da07dbfdeb796567d3ea077c87 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 13b59928dfa9c769bac5b7a26b4bb8e8aa904d48..cdfeed557ccd6930391bf8f827f672526a3db695 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,7 @@ 4.13.1 test + @@ -70,6 +71,18 @@ + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + org.apache.maven.plugins maven-assembly-plugin @@ -114,6 +127,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 9950dbeb64c8cf4457b692a834d587ff8fd2e808..15695ae9204c40db16c9f4d367c80a285335cbef 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 7dbb62d8496e9ae9b758c1a6440531e15e352dc9..6343a802af280415b4d21f56476eb4403b4608ac 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 e17548055c792e900a1e2fb5b510de8bf65de7a7..07553d7ef4e1ea0745d25523d0fd1612086c3826 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 a801f5a674acdd23f1ca7f949cbb7092f4633bda..12641087fb774a82e80c8339f752ff5f514524a0 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 db4a5ccaa8fc15aa637363bc3f5e1b34c71dc5be..8a494f3a5066368ceb55533eb38b0e03c3bf35c7 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 0000000000000000000000000000000000000000..d8cb5795f05e0fad785fc0c4ffcdaea7be411be6 --- /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 8cd8da6de4f7d5324afbc6d5a5d54d6b8dcc7a8d..77a97d644ca3da3a51bce021ab7904883ed885f4 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 521a88b128ff930510bf00cdcb6a12cbc3211742..00eff99f45cb6aa8cc0fbc7bce40e0d82f401e05 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 bdb3ea410005cadd865de1d9e080dd5b9f20834f..0970148b1dfb6c6c1fb85330e312bf2c8168b3c7 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 0000000000000000000000000000000000000000..31299a1c6f37a8b75521a65e7de09f5162558dd6 --- /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 4a9e80ba53b096f057840eab67e61418332dbf81..b1e0d5e062f0ed1e75f9dfc85abfddd2f2c91c77 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,24 @@ -/** - * ************************************************************************* - * 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.Arrays; 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 +29,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 +59,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 +93,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 +154,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 +246,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 +270,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); @@ -301,7 +294,7 @@ public class TSDBJNIConnector { public void setBindTableName(long stmt, String tableName) throws SQLException { int code = setBindTableNameImp(stmt, tableName, this.taos); if (code != TSDBConstants.JNI_SUCCESS) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "failed to set table name"); + throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "table name: " + tableName + ", failed to set table name"); } } @@ -343,12 +336,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"); + throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "schemaless line: " + Arrays.toString(lines) + ", 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 22fb0c4ae4987ade0a406fe5628bf80d975f3ae5..5fd8f181388824bccd4a2ab2b488667af117b172 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 00a62206fc7861a87177d14cc4b274c464dc4184..003324d27a57c3557f0bb3205fcee208aa776ed5 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 ff49677b01fa1c3a4d482cebd51269d5f1589e43..e404db64e3dffbdcc0d2c2845279723874f6b5d8 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 2ff0d86c920aa0aae67f71448bf9112564293350..d8ac10d839651bb476a8688f28917aa356b5b1fe 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 48854e773f89a45784de3cd709ec5bbe6185e09b..0a9f017cbbd775cf710f3bac4440ee8a43403870 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 e1ebc4ab3cf498168181dbea08a3ac28194a5c7d..ce877987e6e9073defbff62e283910ee34366c4d 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 0000000000000000000000000000000000000000..2a0bea15702a79b3440f95771cf56b879a814626 --- /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 0000000000000000000000000000000000000000..fa10a23634ec75182365d42ebfb79aff7b14b08f --- /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 79350076c7f4b31743ab9fb61226e506186f0f17..4558dfa84bfccacf9f0d4fa2d7991c8bd0546b30 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 0a8809e84f92f1e948ea5306648610dfeca57c8f..fdd034a641d7fd829059c73061305bdf38eae1bf 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 1ea39236b666fda106c3ee3534560b6380d7bec9..78420083a1d235036203bb3d57b2617663032d8d 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 eba92741dd8bb3c20f114e35c9a8190193139988..dada75e4a04b035cbe20da72075215c77f1c5883 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 99e46bc64f44f6326aec12734849cc5ef518c903..cdadcd2d28a03d3db4b490049a4e84f2fc38ea02 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 a427103770cff7f51355024688454824d7263c77..583c2c3236574b8474b834513b28160c37d5b250 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 e1c4bddb2812f658336c895249886f603681e632..6ec76fffd93751b0cb57e116085de9da550f214e 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 0000000000000000000000000000000000000000..2618226ebddf646bdf2270144cd86562d17cfcd4 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/JsonTagTest.java @@ -0,0 +1,1221 @@ +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.*; + +@Ignore +@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 0000000000000000000000000000000000000000..63c3a6318a611f7159c0ac16dc85cd5e05de47c0 --- /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 0000000000000000000000000000000000000000..129948c38432c8a329b9bf6d4cb4e8b5d849d056 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SchemalessInsertTest.java @@ -0,0 +1,193 @@ +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.*; +import org.junit.runner.RunWith; + +import java.sql.*; +import java.util.ArrayList; +import java.util.List; + +@Ignore +@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 0000000000000000000000000000000000000000..6a983cd5bdd6d886dcac01f6085c70eade4f7cf5 --- /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 7cdda572a7e6950005d47798bece6cc5c6fef7d1..c69a556ae4e6c6b31dbb106c7ff4a3e2352296ee 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 671ecd723d6fea8d6b9b8ccf94cba06689ce26b8..609523f522724a9bf49e7ded76d2855cbdda6ac1 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 88ff5d3a811e17aaabbeb0a451fbff010307ab6d..f508fbdeed5bf617cf81330985981b5715678472 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 dc41d85cf38c5fbedb6e5f5c26d593c8c9d5c4d7..56e8b96bbd9dee496969a010b0385c4ecd7f1145 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 3d76e1f98d4f8aa1d0ba3d68395e4036c5b069e6..8cb4628884fdd85c1bfd6f24ac311d82687da5ab 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 f72cbbec8c1b4c0acad1c83ffcbcb35c1fb8ea7b..7b9083bf9be242f8bcb21565a47d6092675e2d6e 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 0000000000000000000000000000000000000000..490346e401dba956c8743abb452bcc943df67904 --- /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 0000000000000000000000000000000000000000..2d22302d02f531eca055fa76dea18d8de9f7371f --- /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 0000000000000000000000000000000000000000..1dd074df2d1298781bbbfa7e7709113db2c6ca01 --- /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 0000000000000000000000000000000000000000..08e5f9212287d517838448d0122ab0876812cc1d --- /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 0000000000000000000000000000000000000000..669b0a088656c030281e82620117469b3a375c75 --- /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 0000000000000000000000000000000000000000..3d1db681647d3b23818143156ffd513c46a6e495 --- /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 5ff4b1a41232f57eb21d8394d62cc2dcd27c9cf3..d2f5b915ee1b39146ccc91131fae801c291d08cc 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 2211e0fa176c67329ac13ee4374daf4667da933b..0000000000000000000000000000000000000000 --- 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 2934b54b5bd2e7f5450a9a1a00cb5bddca37e945..548c1cff240a811ba998373167588185305a0d59 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 fcb6ab7aaff2406acf59262a9cdef90b628b8934..8299cfebec6ba54be42dc1fbe8dcff1b14034860 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 14c76985484857a92e174955c943caa21bdd2e72..bfffaa4a129dc7fe19a92c34abbcc886d5e4e22f 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 0000000000000000000000000000000000000000..1ba7bdc4057e5c9e2977d3723fe329e761e7258c --- /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 1297a6b4c4eb0eca208950363c13e9bb4d1cd3a9..a8fdf4f2caa88d2651bebf2a1c46b95644b488d2 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 05c7b0feca21f3f5b9062f9cbc26921aa607732a..60edcc506e9fea7bc055322b7b00d0f9e9d75591 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 ac254bebf39f55b358883716e23ba72b695703f7..7cc1c811d136a974a8cd9b8d4b990fe206c9e98d 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 eedccec6f1ad3aecbaebbd525788a68e7c236511..81e424971c90e75a0ca3e8d14b82eefc45e417c8 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 0000000000000000000000000000000000000000..38e8d99afe4a9fbca8d7167df482b6c2ac6976d8 --- /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 eb8f134227713e4c41224dc6a561916427290864..0889170e656910181fe39f844e585c11f0d78d5e 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 7e9f04cd6360431a3fe6c29a2f0eb61fbdc9e7c4..48c5ef8a463452dc205c43247678bfd0f3e761a2 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 18a2c32aca0535567dd42e886bc87ae618596a40..220ac0e7ce023229c1e897b9125a4ebb2cae3687 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 73da79f357b1c066943e2f39bf9f8bdc86382d7e..0000000000000000000000000000000000000000 --- 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 4f2c87966ad6bb8390bab47b795e7d952725baf5..c85c6f95a93df565cd5ff8eca91c0beeac3b3c02 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 4271f918b9b096000cc59b730d7b70f032a0ab29..796f21ed21bb69e952042e89f61e0eb98fcf4273 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 ae0241bf31eea85083bf102c4123f7e30c2bd693..8bbc2fe077a1292b24ee7cb67158620c96f9a605 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 7fbb30a5244a53129807cd76472674ff1cfd6ae4..08f641b96e86398d72d9ab42ccaed57e2227ecdc 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 61d767b5cf2bcd2e478de74e5f4bb8d66ad21678..890505ac65cf02deb85dd362ebd700291317e849 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 90b285381a2ab57b170da327a95dde4c8991ce21..85fbeef1b589434dc17267af20510bc2a8ebd554 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 b4449491a93c2ffc857448b8697e771eabd0f97a..fd74e9433a786f407f75e2a28a9b5672f7373b8b 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 be27b1350781245e3056185db4bbaa8b5105d2f0..ff0dad1bda4b8defa8c515011604deeddf13f95b 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 b51c0309be809250839a5241d12296182067dfd3..79e5602e9e6c436d5671cc1c92847e54949d9025 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 7df9f7380704eefb51b26214295624995811c84f..0000000000000000000000000000000000000000 --- 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 72734cb0ecdfe67cbd02306acef3ae8625f942b0..76053ccc41895fcdc00ffe9da2252bf63313894e 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 0000000000000000000000000000000000000000..4aedf867d408536fde6896e01f61ef13873d1624 --- /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 e4149793aca46ebe5df47aec002828441fef481d..cff353093aca6772e96a88f1083bc428a49ab9b2 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 3bdf5ae4f2404db5f56e27b740d4e4951e10818d..b3ca6871db7cbf0888737856e66d236c4cc80d49 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 0000000000000000000000000000000000000000..c4f2cba446e6138679ae9f8b8efff3666c056deb --- /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 0000000000000000000000000000000000000000..7ad7c23136f8e24b0c7139e97fb4b46c04a98abb --- /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 0000000000000000000000000000000000000000..94a5382410ba05c1fbf3afb4f8bb73d6c5271c3a --- /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 0000000000000000000000000000000000000000..41629189aea4658514bd317c90bc055340397a23 --- /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 0000000000000000000000000000000000000000..7f7979eb01154a85b25bbea7b9d3f042b4f1c104 --- /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 0000000000000000000000000000000000000000..4a919db6f403a9f6ad54e261fdb28f93dddf4958 --- /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 94a175ad5c7fd50fa35d6b45ea59ab26ffc02ce1..bc19e63ba6e05c8170366de4375148ebde0138d0 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 0000000000000000000000000000000000000000..a6f8cf7c0ad79d1a046a5075f05f6930ea1d19ce --- /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 9fe51e7203fac7133783e47fd5b0cc07f33b2494..0a37e255a4ac8e8db2b07fc915ab7ba6dd54397c 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 d50b56b434fba5795750ec2d92af9f73ae0a02d3..e4785a197e659977ae22745e14e664fd803464f7 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 85007db0e555634b25dee4f10446b1041bf19b21..de1305b284dde54fec885bee52387f0aa6a2284c 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 4f727d43a01ce3c4c459fcd2d7328e1c4b132976..da30bbd568c7043af493baeecc118f256ad73b10 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 81d7f5b56c4b4e67b9573522ee031006a7e11a2b..c8ca1a5de7ac870c01d248a8b042cffefa4857b7 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 4760a723e4b4e662326987290c2c630803f8f470..40d0e0214fe1016df8d42e9dfd8d31472165c798 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 f3011af799c987ed399920875ae512fd8533ec77..6e5851474f2697022eef5dc62be3f69ca5878df9 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 8ffa1de21c604c2235c23e63e93b008f5a1d146c..c1ca31ae388f577a33cc6f3a6bc943ce52112507 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 a7b3ceb9d3bb243a2a053d5289afe39d3c870d79..83ab2c7263cb61388d6cbdfd31b241d547520f53 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 7dff90a77556f029049a4216e789dc64e42a2e96..4893e6062f8719152539d80a6da21730d47dfa92 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 0000000000000000000000000000000000000000..f0cd200e04bc66bb0571534c99a348c3a823fcb3 --- /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 cae33f18e7a04e443092d8e696bb32be9600a435..128a62e5d964bc2276328312eb9998895923547f 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 0000000000000000000000000000000000000000..ac435a2a1bd64ca9925948d486b453638cb8caac --- /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 0000000000000000000000000000000000000000..abcc1ef6d56112c892377ca47453b65ed924a9a9 --- /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 diff --git a/src/plugins/http/inc/httpInt.h b/src/plugins/http/inc/httpInt.h index af0f4c579557d1bd919847ef858af8dc1616bb6f..a2117132d83163e366edc64bbedf2a6a5d94b5c9 100644 --- a/src/plugins/http/inc/httpInt.h +++ b/src/plugins/http/inc/httpInt.h @@ -37,7 +37,7 @@ #define HTTP_BUFFER_SIZE 8388608 #define HTTP_STEP_SIZE 4096 //http message get process step by step #define HTTP_METHOD_SCANNER_SIZE 7 //http method fp size -#define HTTP_GC_TARGET_SIZE 512 +#define HTTP_GC_TARGET_SIZE 16384 #define HTTP_WRITE_RETRY_TIMES 500 #define HTTP_WRITE_WAIT_TIME_MS 5 #define HTTP_PASSWORD_LEN TSDB_UNI_LEN diff --git a/src/plugins/http/src/httpGcJson.c b/src/plugins/http/src/httpGcJson.c index 2d361d37940a93c3627ef53883a342d12183e6a1..7e4658b36465e88e30ceb4315730d784becb99d4 100644 --- a/src/plugins/http/src/httpGcJson.c +++ b/src/plugins/http/src/httpGcJson.c @@ -130,14 +130,34 @@ bool gcBuildQueryJson(HttpContext *pContext, HttpSqlCmd *cmd, TAOS_RES *result, // for group by if (groupFields != -1) { char target[HTTP_GC_TARGET_SIZE] = {0}; - int32_t len; - len = snprintf(target, HTTP_GC_TARGET_SIZE, "%s{", aliasBuffer); + int32_t len = 0, cur = 0; + cur = snprintf(target, HTTP_GC_TARGET_SIZE, "%s{", aliasBuffer); + if (cur < 0 || cur >= HTTP_GC_TARGET_SIZE) { + httpError("context:%p, fd:%d, too long alias: %s", pContext, pContext->fd, aliasBuffer); + return false; + } + + len += cur; for (int32_t i = dataFields + 1; i < num_fields; i++) { + // -2 means the last '}' and '\0' +#define HTTP_GC_CHECK_SIZE(name) if (cur < 0 || cur >= HTTP_GC_TARGET_SIZE - len - 2) { \ + if (cur < 0) { \ + httpError("context:%p, fd:%d, failed to snprintf for: %s", pContext, pContext->fd, name); \ + } else { \ + httpError("context:%p, fd:%d, snprintf overflow for: %s", pContext, pContext->fd, name); \ + target[len] = '\0'; \ + } \ + break; \ + } else { \ + len += cur; \ + } if (row[i] == NULL) { - len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:nil", fields[i].name); + cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:nil", fields[i].name); + HTTP_GC_CHECK_SIZE(fields[i].name) if (i < num_fields - 1) { - len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, ", "); + cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, ", "); + HTTP_GC_CHECK_SIZE(fields[i].name) } continue; @@ -146,40 +166,49 @@ bool gcBuildQueryJson(HttpContext *pContext, HttpSqlCmd *cmd, TAOS_RES *result, switch (fields[i].type) { case TSDB_DATA_TYPE_BOOL: case TSDB_DATA_TYPE_TINYINT: - len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:%d", fields[i].name, *((int8_t *)row[i])); + cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:%d", fields[i].name, *((int8_t *)row[i])); + HTTP_GC_CHECK_SIZE(fields[i].name) break; case TSDB_DATA_TYPE_SMALLINT: - len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:%d", fields[i].name, *((int16_t *)row[i])); + cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:%d", fields[i].name, *((int16_t *)row[i])); + HTTP_GC_CHECK_SIZE(fields[i].name) break; case TSDB_DATA_TYPE_INT: - len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:%d,", fields[i].name, *((int32_t *)row[i])); + cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:%d,", fields[i].name, *((int32_t *)row[i])); + HTTP_GC_CHECK_SIZE(fields[i].name) break; case TSDB_DATA_TYPE_BIGINT: - len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:%" PRId64, fields[i].name, *((int64_t *)row[i])); + cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:%" PRId64, fields[i].name, *((int64_t *)row[i])); + HTTP_GC_CHECK_SIZE(fields[i].name) break; case TSDB_DATA_TYPE_FLOAT: - len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:%.5f", fields[i].name, GET_FLOAT_VAL(row[i])); + cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:%.5f", fields[i].name, GET_FLOAT_VAL(row[i])); + HTTP_GC_CHECK_SIZE(fields[i].name) break; case TSDB_DATA_TYPE_DOUBLE: - len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:%.9f", fields[i].name, GET_DOUBLE_VAL(row[i])); + cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:%.9f", fields[i].name, GET_DOUBLE_VAL(row[i])); + HTTP_GC_CHECK_SIZE(fields[i].name) break; case TSDB_DATA_TYPE_BINARY: case TSDB_DATA_TYPE_NCHAR: if (row[i] != NULL) { - len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:", fields[i].name); - memcpy(target + len, (char *)row[i], length[i]); + cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:", fields[i].name); + HTTP_GC_CHECK_SIZE(fields[i].name) + memcpy(target + len, (char *)row[i], MIN(length[i], HTTP_GC_TARGET_SIZE - len - 3)); len = (int32_t)strlen(target); } break; default: - len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:%s", fields[i].name, "-"); + cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:%s", fields[i].name, "-"); + HTTP_GC_CHECK_SIZE(fields[i].name) break; } if (i < num_fields - 1) { - len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, ", "); + cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, ", "); + HTTP_GC_CHECK_SIZE(fields[i].name) } } - len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "}"); + cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 1, "}"); if (strcmp(target, targetBuffer) != 0) { // first target not write this section diff --git a/src/query/src/qFilterfunc.c b/src/query/src/qFilterfunc.c index 1c1ec21d653b5b96fe792aa05641191a441b8e8d..3c03b4c29196bf97fc12f859859eff4665a1a9a0 100644 --- a/src/query/src/qFilterfunc.c +++ b/src/query/src/qFilterfunc.c @@ -183,7 +183,7 @@ bool likeOperator(SColumnFilterElem *pFilter, const char *minval, const char *ma return patternMatch((char *)pFilter->filterInfo.pz, varDataVal(minval), varDataLen(minval), &info) == TSDB_PATTERN_MATCH; } else if (type == TSDB_DATA_TYPE_NCHAR) { SPatternCompareInfo info = PATTERN_COMPARE_INFO_INITIALIZER; - return WCSPatternMatch((wchar_t*)pFilter->filterInfo.pz, varDataVal(minval), varDataLen(minval)/TSDB_NCHAR_SIZE, &info) == TSDB_PATTERN_MATCH; + return WCSPatternMatch((uint32_t *) pFilter->filterInfo.pz, (uint32_t *) varDataVal(minval), varDataLen(minval)/TSDB_NCHAR_SIZE, &info) == TSDB_PATTERN_MATCH; } else { return false; } diff --git a/src/util/inc/tcompare.h b/src/util/inc/tcompare.h index 84346cc79cc08aca123f61adfa0f21b4ad41798b..d019d5390345c26aa3738c9748874ac60c9139b1 100644 --- a/src/util/inc/tcompare.h +++ b/src/util/inc/tcompare.h @@ -43,7 +43,7 @@ typedef struct SPatternCompareInfo { int patternMatch(const char *pattern, const char *str, size_t size, const SPatternCompareInfo *pInfo); -int WCSPatternMatch(const wchar_t *pattern, const wchar_t *str, size_t size, const SPatternCompareInfo *pInfo); +int WCSPatternMatch(const uint32_t *pattern, const uint32_t *str, size_t size, const SPatternCompareInfo *pInfo); int32_t doCompare(const char* a, const char* b, int32_t type, size_t size); diff --git a/src/util/src/tcompare.c b/src/util/src/tcompare.c index 3a5f3e368b7fec8a67a1fa0363c59ba820d86248..f2f0f1de4c90ffa113b1331600b8937353f83b62 100644 --- a/src/util/src/tcompare.c +++ b/src/util/src/tcompare.c @@ -275,29 +275,94 @@ int patternMatch(const char *patterStr, const char *str, size_t size, const SPat return (str[j] == 0 || j >= size) ? TSDB_PATTERN_MATCH : TSDB_PATTERN_NOMATCH; } -int WCSPatternMatch(const wchar_t *patterStr, const wchar_t *str, size_t size, const SPatternCompareInfo *pInfo) { - wchar_t c, c1; - wchar_t matchOne = L'_'; // "_" - wchar_t matchAll = L'%'; // "%" +static uint32_t * +taosWcschr (const uint32_t *wcs, const uint32_t wc) +{ + const uint32_t *wcs2 = wcs + 1; + if (*wcs == wc) + return (uint32_t *) wcs; + if (*wcs == L'\0') + return NULL; + do + { + wcs += 2; + if (*wcs2 == wc) + return (uint32_t *) wcs2; + if (*wcs2 == L'\0') + return NULL; + wcs2 += 2; + if (*wcs == wc) + return (uint32_t *) wcs; + if (*wcs == L'\0') + return NULL; + wcs += 2; + if (*wcs2 == wc) + return (uint32_t *) wcs2; + if (*wcs2 == L'\0') + return NULL; + wcs2 += 2; + if (*wcs == wc) + return (uint32_t *) wcs; + if (*wcs == L'\0') + return NULL; + wcs += 2; + if (*wcs2 == wc) + return (uint32_t *) wcs2; + if (*wcs2 == L'\0') + return NULL; + wcs2 += 2; + if (*wcs == wc) + return (uint32_t *) wcs; + if (*wcs == L'\0') + return NULL; + wcs += 2; + if (*wcs2 == wc) + return (uint32_t *) wcs2; + if (*wcs2 == L'\0') + return NULL; + wcs2 += 2; + if (*wcs == wc) + return (uint32_t *) wcs; + } + while (*wcs != L'\0'); + return NULL; +} + +static size_t +taosWcscspn (const uint32_t *wcs, const uint32_t *reject) +{ + size_t count = 0; + while (*wcs != L'\0') + if (taosWcschr (reject, *wcs++) == NULL) + ++count; + else + return count; + return count; +} + +int WCSPatternMatch(const uint32_t *patterStr, const uint32_t *str, size_t size, const SPatternCompareInfo *pInfo) { + uint32_t c, c1; + uint32_t matchOne = (uint32_t) L'_'; // "_" + uint32_t matchAll = (uint32_t) L'%'; // "%" int32_t i = 0; int32_t j = 0; while ((c = patterStr[i++]) != 0) { if (c == matchAll) { /* Match "%" */ - while ((c = patterStr[i++]) == matchAll || c == matchOne) { if (c == matchOne && (j > size || str[j++] == 0)) { return TSDB_PATTERN_NOWILDCARDMATCH; } } + if (c == 0) { return TSDB_PATTERN_MATCH; } - wchar_t utl_accept[3] = {towupper(c), towlower(c), 0}; + uint32_t utl_accept[3] = {towupper(c), towlower(c), 0}; while (1) { - size_t n = wcscspn(str, utl_accept); + size_t n = taosWcscspn((uint32_t *)str, utl_accept); str += n; if (str[0] == 0 || (n >= size)) { @@ -368,7 +433,7 @@ int32_t compareWStrPatternComp(const void* pLeft, const void* pRight) { memcpy(pattern, varDataVal(pRight), varDataLen(pRight)); memcpy(str, varDataVal(pLeft), size * sizeof(wchar_t)); - int32_t ret = WCSPatternMatch(pattern, str, size, &pInfo); + int32_t ret = WCSPatternMatch((uint32_t *)pattern, (uint32_t *)str, size, &pInfo); free(pattern); free(str); diff --git a/tests/examples/JDBC/JDBCDemo/pom.xml b/tests/examples/JDBC/JDBCDemo/pom.xml index 8cf0356721f8ffd568e87fa4a77c86eb0f90a62b..b0b07d58f4e59645e5ebe78a938d0043558a9c80 100644 --- a/tests/examples/JDBC/JDBCDemo/pom.xml +++ b/tests/examples/JDBC/JDBCDemo/pom.xml @@ -17,7 +17,7 @@ com.taosdata.jdbc taos-jdbcdriver - 2.0.34 + 2.0.36 diff --git a/tests/examples/c/prepare.c b/tests/examples/c/prepare.c index de92032c18cc8acc9cbb4e06b7abfee8673b8203..14573c0daa396383190bbecd92c5aba54452037d 100644 --- a/tests/examples/c/prepare.c +++ b/tests/examples/c/prepare.c @@ -841,6 +841,543 @@ void verify_prepare3(TAOS* taos) { free(blob_len); } +/** + * @brief Verify the upper/lower case of tableName for create(by setTableName)/query/show/describe/drop. + * https://jira.taosdata.com:18080/browse/TS-904 + * https://jira.taosdata.com:18090/pages/viewpage.action?pageId=129140555 + * @param taos + */ +void verify_prepare4(TAOS* taos) { + printf("Verify the upper/lower case of tableName for create(by setTableName)/query/show/describe/drop etc.\n"); + + TAOS_RES* result = taos_query(taos, "drop database if exists test;"); + taos_free_result(result); + usleep(100000); + result = taos_query(taos, "create database test;"); + + int code = taos_errno(result); + if (code != 0) { + printf("\033[31mfailed to create database, reason:%s\033[0m\n", taos_errstr(result)); + taos_free_result(result); + exit(EXIT_FAILURE); + } + taos_free_result(result); + + usleep(100000); + taos_select_db(taos, "test"); + + // create table + const char* sql = + "create stable st1 (ts timestamp, b bool, v1 tinyint, v2 smallint, v4 int, v8 bigint, f4 float, f8 double, bin " + "binary(40), blob nchar(10), u1 tinyint unsigned, u2 smallint unsigned, u4 int unsigned, u8 bigint unsigned) " + "tags " + "(b_tag bool, v1_tag tinyint, v2_tag smallint, v4_tag int, v8_tag bigint, f4_tag float, f8_tag double, bin_tag " + "binary(40), blob_tag nchar(10), u1_tag tinyint unsigned, u2_tag smallint unsigned, u4_tag int unsigned, u8_tag " + "bigint " + "unsigned)"; + result = taos_query(taos, sql); + code = taos_errno(result); + if (code != 0) { + printf("\033[31mfailed to create table, reason:%s\033[0m\n", taos_errstr(result)); + taos_free_result(result); + exit(EXIT_FAILURE); + } + taos_free_result(result); + + TAOS_BIND tags[13]; + + struct { + int8_t b; + int8_t v1; + int16_t v2; + int32_t v4; + int64_t v8; + float f4; + double f8; + char bin[40]; + char blob[80]; + uint8_t u1; + uint16_t u2; + uint32_t u4; + uint64_t u8; + } id = {0}; + + id.b = (int8_t)1; + id.v1 = (int8_t)1; + id.v2 = (int16_t)2; + id.v4 = (int32_t)4; + id.v8 = (int64_t)8; + id.f4 = (float)40; + id.f8 = (double)80; + for (int j = 0; j < sizeof(id.bin); ++j) { + id.bin[j] = (char)('1' + '0'); + } + strcpy(id.blob, "一二三四五六七八九十"); + id.u1 = (uint8_t)1; + id.u2 = (uint16_t)2; + id.u4 = (uint32_t)4; + id.u8 = (uint64_t)8; + + tags[0].buffer_type = TSDB_DATA_TYPE_BOOL; + tags[0].buffer_length = sizeof(id.b); + tags[0].buffer = &id.b; + tags[0].length = &tags[0].buffer_length; + tags[0].is_null = NULL; + + tags[1].buffer_type = TSDB_DATA_TYPE_TINYINT; + tags[1].buffer_length = sizeof(id.v1); + tags[1].buffer = &id.v1; + tags[1].length = &tags[1].buffer_length; + tags[1].is_null = NULL; + + tags[2].buffer_type = TSDB_DATA_TYPE_SMALLINT; + tags[2].buffer_length = sizeof(id.v2); + tags[2].buffer = &id.v2; + tags[2].length = &tags[2].buffer_length; + tags[2].is_null = NULL; + + tags[3].buffer_type = TSDB_DATA_TYPE_INT; + tags[3].buffer_length = sizeof(id.v4); + tags[3].buffer = &id.v4; + tags[3].length = &tags[3].buffer_length; + tags[3].is_null = NULL; + + tags[4].buffer_type = TSDB_DATA_TYPE_BIGINT; + tags[4].buffer_length = sizeof(id.v8); + tags[4].buffer = &id.v8; + tags[4].length = &tags[4].buffer_length; + tags[4].is_null = NULL; + + tags[5].buffer_type = TSDB_DATA_TYPE_FLOAT; + tags[5].buffer_length = sizeof(id.f4); + tags[5].buffer = &id.f4; + tags[5].length = &tags[5].buffer_length; + tags[5].is_null = NULL; + + tags[6].buffer_type = TSDB_DATA_TYPE_DOUBLE; + tags[6].buffer_length = sizeof(id.f8); + tags[6].buffer = &id.f8; + tags[6].length = &tags[6].buffer_length; + tags[6].is_null = NULL; + + tags[7].buffer_type = TSDB_DATA_TYPE_BINARY; + tags[7].buffer_length = sizeof(id.bin); + tags[7].buffer = &id.bin; + tags[7].length = &tags[7].buffer_length; + tags[7].is_null = NULL; + + tags[8].buffer_type = TSDB_DATA_TYPE_NCHAR; + tags[8].buffer_length = strlen(id.blob); + tags[8].buffer = &id.blob; + tags[8].length = &tags[8].buffer_length; + tags[8].is_null = NULL; + + tags[9].buffer_type = TSDB_DATA_TYPE_UTINYINT; + tags[9].buffer_length = sizeof(id.u1); + tags[9].buffer = &id.u1; + tags[9].length = &tags[9].buffer_length; + tags[9].is_null = NULL; + + tags[10].buffer_type = TSDB_DATA_TYPE_USMALLINT; + tags[10].buffer_length = sizeof(id.u2); + tags[10].buffer = &id.u2; + tags[10].length = &tags[10].buffer_length; + tags[10].is_null = NULL; + + tags[11].buffer_type = TSDB_DATA_TYPE_UINT; + tags[11].buffer_length = sizeof(id.u4); + tags[11].buffer = &id.u4; + tags[11].length = &tags[11].buffer_length; + tags[11].is_null = NULL; + + tags[12].buffer_type = TSDB_DATA_TYPE_UBIGINT; + tags[12].buffer_length = sizeof(id.u8); + tags[12].buffer = &id.u8; + tags[12].length = &tags[12].buffer_length; + tags[12].is_null = NULL; + // insert 10 records + struct { + int64_t ts[10]; + int8_t b[10]; + int8_t v1[10]; + int16_t v2[10]; + int32_t v4[10]; + int64_t v8[10]; + float f4[10]; + double f8[10]; + char bin[10][40]; + char blob[10][80]; + uint8_t u1[10]; + uint16_t u2[10]; + uint32_t u4[10]; + uint64_t u8[10]; + } v; + + int32_t* t8_len = malloc(sizeof(int32_t) * 10); + int32_t* t16_len = malloc(sizeof(int32_t) * 10); + int32_t* t32_len = malloc(sizeof(int32_t) * 10); + int32_t* t64_len = malloc(sizeof(int32_t) * 10); + int32_t* float_len = malloc(sizeof(int32_t) * 10); + int32_t* double_len = malloc(sizeof(int32_t) * 10); + int32_t* bin_len = malloc(sizeof(int32_t) * 10); + int32_t* blob_len = malloc(sizeof(int32_t) * 10); + int32_t* u8_len = malloc(sizeof(int32_t) * 10); + int32_t* u16_len = malloc(sizeof(int32_t) * 10); + int32_t* u32_len = malloc(sizeof(int32_t) * 10); + int32_t* u64_len = malloc(sizeof(int32_t) * 10); + + TAOS_MULTI_BIND params[14]; + char is_null[10] = {0}; + params[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP; + params[0].buffer_length = sizeof(v.ts[0]); + params[0].buffer = v.ts; + params[0].length = t64_len; + params[0].is_null = is_null; + params[0].num = 10; + + params[1].buffer_type = TSDB_DATA_TYPE_BOOL; + params[1].buffer_length = sizeof(v.b[0]); + params[1].buffer = v.b; + params[1].length = t8_len; + params[1].is_null = is_null; + params[1].num = 10; + + params[2].buffer_type = TSDB_DATA_TYPE_TINYINT; + params[2].buffer_length = sizeof(v.v1[0]); + params[2].buffer = v.v1; + params[2].length = t8_len; + params[2].is_null = is_null; + params[2].num = 10; + + params[3].buffer_type = TSDB_DATA_TYPE_SMALLINT; + params[3].buffer_length = sizeof(v.v2[0]); + params[3].buffer = v.v2; + params[3].length = t16_len; + params[3].is_null = is_null; + params[3].num = 10; + + params[4].buffer_type = TSDB_DATA_TYPE_INT; + params[4].buffer_length = sizeof(v.v4[0]); + params[4].buffer = v.v4; + params[4].length = t32_len; + params[4].is_null = is_null; + params[4].num = 10; + + params[5].buffer_type = TSDB_DATA_TYPE_BIGINT; + params[5].buffer_length = sizeof(v.v8[0]); + params[5].buffer = v.v8; + params[5].length = t64_len; + params[5].is_null = is_null; + params[5].num = 10; + + params[6].buffer_type = TSDB_DATA_TYPE_FLOAT; + params[6].buffer_length = sizeof(v.f4[0]); + params[6].buffer = v.f4; + params[6].length = float_len; + params[6].is_null = is_null; + params[6].num = 10; + + params[7].buffer_type = TSDB_DATA_TYPE_DOUBLE; + params[7].buffer_length = sizeof(v.f8[0]); + params[7].buffer = v.f8; + params[7].length = double_len; + params[7].is_null = is_null; + params[7].num = 10; + + params[8].buffer_type = TSDB_DATA_TYPE_BINARY; + params[8].buffer_length = sizeof(v.bin[0]); + params[8].buffer = v.bin; + params[8].length = bin_len; + params[8].is_null = is_null; + params[8].num = 10; + + params[9].buffer_type = TSDB_DATA_TYPE_NCHAR; + params[9].buffer_length = sizeof(v.blob[0]); + params[9].buffer = v.blob; + params[9].length = blob_len; + params[9].is_null = is_null; + params[9].num = 10; + + params[10].buffer_type = TSDB_DATA_TYPE_UTINYINT; + params[10].buffer_length = sizeof(v.u1[0]); + params[10].buffer = v.u1; + params[10].length = u8_len; + params[10].is_null = is_null; + params[10].num = 10; + + params[11].buffer_type = TSDB_DATA_TYPE_USMALLINT; + params[11].buffer_length = sizeof(v.u2[0]); + params[11].buffer = v.u2; + params[11].length = u16_len; + params[11].is_null = is_null; + params[11].num = 10; + + params[12].buffer_type = TSDB_DATA_TYPE_UINT; + params[12].buffer_length = sizeof(v.u4[0]); + params[12].buffer = v.u4; + params[12].length = u32_len; + params[12].is_null = is_null; + params[12].num = 10; + + params[13].buffer_type = TSDB_DATA_TYPE_UBIGINT; + params[13].buffer_length = sizeof(v.u8[0]); + params[13].buffer = v.u8; + params[13].length = u64_len; + params[13].is_null = is_null; + params[13].num = 10; + +// verify table names for upper/lower case +#define VERIFY_CNT 5 + + typedef struct { + char setTbName[20]; + char showName[20]; + char describeName[20]; + char queryName[20]; + char dropName[20]; + } STbNames; + + /** + * @brief + * 0 - success expected + * NonZero - fail expected + */ + typedef struct { + int32_t setTbName; + int32_t showName; + int32_t describeName; + int32_t queryName; + int32_t dropName; + } STbNamesResult; + + STbNames tbName[VERIFY_CNT] = {0}; + STbNamesResult tbNameResult[VERIFY_CNT] = {0}; + + STbNames* pTbName = NULL; + STbNamesResult* pTbNameResult = NULL; + + pTbName = &tbName[0]; + pTbNameResult = &tbNameResult[0]; + strcpy(pTbName->setTbName, "Mn1"); + strcpy(pTbName->showName, "mn1"); + strcpy(pTbName->describeName, "mn1"); + strcpy(pTbName->queryName, "mn1"); + strcpy(pTbName->dropName, "mn1"); + + pTbName = &tbName[1]; + pTbNameResult = &tbNameResult[1]; + strcpy(pTbName->setTbName, "'Mn1'"); + strcpy(pTbName->showName, "'mn1'"); + strcpy(pTbName->describeName, "'mn1'"); + strcpy(pTbName->queryName, "'mn1'"); + strcpy(pTbName->dropName, "'mn1'"); + + pTbName = &tbName[2]; + pTbNameResult = &tbNameResult[2]; + strcpy(pTbName->setTbName, "\"Mn1\""); + strcpy(pTbName->showName, "\"mn1\""); + strcpy(pTbName->describeName, "\"mn1\""); + strcpy(pTbName->queryName, "\"mn1\""); + strcpy(pTbName->dropName, "\"mn1\""); + + pTbName = &tbName[3]; + pTbNameResult = &tbNameResult[3]; + strcpy(pTbName->setTbName, "\"Mn1\""); + strcpy(pTbName->showName, "'mn1'"); + strcpy(pTbName->describeName, "'mn1'"); + strcpy(pTbName->queryName, "mn1"); + strcpy(pTbName->dropName, "\"mn1\""); + + pTbName = &tbName[4]; + pTbNameResult = &tbNameResult[4]; + strcpy(pTbName->setTbName, "`Mn1`"); + strcpy(pTbName->showName, "`Mn1`"); + strcpy(pTbName->describeName, "`Mn1`"); + strcpy(pTbName->queryName, "`Mn1`"); + strcpy(pTbName->dropName, "`Mn1`"); + pTbNameResult->setTbName = -1; + pTbNameResult->showName = -1; + pTbNameResult->describeName = -1; + pTbNameResult->queryName = -1; + pTbNameResult->dropName = -1; + + TAOS_STMT* stmt = NULL; + + for (int n = 0; n < VERIFY_CNT; ++n) { + printf("\033[31m[%d] ===================================\033[0m\n", n); + pTbName = &tbName[n]; + pTbNameResult = &tbNameResult[n]; + char tmpStr[256] = {0}; + + // set table name + stmt = taos_stmt_init(taos); + if (!stmt) { + printf("\033[31m[%d] failed to execute taos_stmt_init. error:%s\033[0m\n", n); + exit(EXIT_FAILURE); + } + + sql = "insert into ? using st1 tags(?,?,?,?,?,?,?,?,?,?,?,?,?) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + code = taos_stmt_prepare(stmt, sql, 0); + if (code != 0) { + printf("\033[31mfailed to execute taos_stmt_prepare. error:%s\033[0m\n", taos_stmt_errstr(stmt)); + taos_stmt_close(stmt); + exit(EXIT_FAILURE); + } + + printf("[%d] taos_stmt_set_tbname_tags, tbname=%s\n", n, pTbName->setTbName); + code = taos_stmt_set_tbname_tags(stmt, pTbName->setTbName, tags); + if ((!pTbNameResult->setTbName && (0 != code)) || (pTbNameResult->setTbName && (0 == code))) { + printf("\033[31m[%d] failed to execute taos_stmt_set_tbname_tags. error:%s\033[0m\n", n, taos_stmt_errstr(stmt)); + taos_stmt_close(stmt); + exit(EXIT_FAILURE); + } + + if (code == 0) { + int64_t ts = 1591060628000 + 1000 * n; + for (int i = 0; i < 10; ++i) { + v.ts[i] = ts++; + is_null[i] = 0; + + v.b[i] = (int8_t)i % 2; + v.v1[i] = (int8_t)i; + v.v2[i] = (int16_t)(i * 2); + v.v4[i] = (int32_t)(i * 4); + v.v8[i] = (int64_t)(i * 8); + v.f4[i] = (float)(i * 40); + v.f8[i] = (double)(i * 80); + for (int j = 0; j < sizeof(v.bin[0]); ++j) { + v.bin[i][j] = (char)(i + '0'); + } + strcpy(v.blob[i], "一二三四五六七八九十"); + v.u1[i] = (uint8_t)i; + v.u2[i] = (uint16_t)(i * 2); + v.u4[i] = (uint32_t)(i * 4); + v.u8[i] = (uint64_t)(i * 8); + + t8_len[i] = sizeof(int8_t); + t16_len[i] = sizeof(int16_t); + t32_len[i] = sizeof(int32_t); + t64_len[i] = sizeof(int64_t); + float_len[i] = sizeof(float); + double_len[i] = sizeof(double); + bin_len[i] = sizeof(v.bin[0]); + blob_len[i] = (int32_t)strlen(v.blob[i]); + u8_len[i] = sizeof(uint8_t); + u16_len[i] = sizeof(uint16_t); + u32_len[i] = sizeof(uint32_t); + u64_len[i] = sizeof(uint64_t); + } + + taos_stmt_bind_param_batch(stmt, params); + taos_stmt_add_batch(stmt); + + if (taos_stmt_execute(stmt) != 0) { + printf("\033[31m[%d] failed to execute insert statement.error:%s\033[0m\n", n, taos_stmt_errstr(stmt)); + taos_stmt_close(stmt); + exit(EXIT_FAILURE); + } + } + taos_stmt_close(stmt); + + // show the table + printf("[%d] show tables, tbName = %s\n", n, pTbName->showName); + stmt = taos_stmt_init(taos); + sprintf(tmpStr, "show tables like %s", pTbName->showName); + taos_stmt_prepare(stmt, tmpStr, 0); + code = taos_stmt_execute(stmt); + if ((!pTbNameResult->showName && (0 != code)) || (pTbNameResult->showName && (0 == code))) { + printf("\033[31m[%d] failed to execute show tables like. error:%s\033[0m\n", n, taos_stmt_errstr(stmt)); + taos_stmt_close(stmt); + exit(EXIT_FAILURE); + } + taos_stmt_close(stmt); + + // describe the table + printf("[%d] describe tables, tbName = %s\n", n, pTbName->describeName); + stmt = taos_stmt_init(taos); + sprintf(tmpStr, "describe %s", pTbName->describeName); + taos_stmt_prepare(stmt, tmpStr, 0); + code = taos_stmt_execute(stmt); + if ((!pTbNameResult->describeName && (0 != code)) || (pTbNameResult->describeName && (0 == code))) { + printf("\033[31m[%d] failed to execute describe tables. error:%s\033[0m\n", n, taos_stmt_errstr(stmt)); + taos_stmt_close(stmt); + exit(EXIT_FAILURE); + } + taos_stmt_close(stmt); + + // query the records + printf("[%d] select statement, tbName = %s\n", n, pTbName->queryName); + stmt = taos_stmt_init(taos); + sprintf(tmpStr, "SELECT * FROM %s", pTbName->queryName); + taos_stmt_prepare(stmt, tmpStr, 0); + + TAOS_BIND qparams[2]; + + int8_t v1 = 5; + int16_t v2 = 15; + qparams[0].buffer_type = TSDB_DATA_TYPE_TINYINT; + qparams[0].buffer_length = sizeof(v1); + qparams[0].buffer = &v1; + qparams[0].length = &qparams[0].buffer_length; + qparams[0].is_null = NULL; + + qparams[1].buffer_type = TSDB_DATA_TYPE_SMALLINT; + qparams[1].buffer_length = sizeof(v2); + qparams[1].buffer = &v2; + qparams[1].length = &qparams[1].buffer_length; + qparams[1].is_null = NULL; + + taos_stmt_bind_param(stmt, qparams); + + code = taos_stmt_execute(stmt); + if ((!pTbNameResult->queryName && (0 != code)) || (pTbNameResult->queryName && (0 == code))) { + printf("\033[31m[%d] failed to execute select statement.error:%s\033[0m\n", n, taos_stmt_errstr(stmt)); + taos_stmt_close(stmt); + exit(EXIT_FAILURE); + } + + result = taos_stmt_use_result(stmt); + + TAOS_ROW row; + int rows = 0; + int num_fields = taos_num_fields(result); + TAOS_FIELD* fields = taos_fetch_fields(result); + + // fetch the records row by row + while ((row = taos_fetch_row(result))) { + char temp[256] = {0}; + rows++; + taos_print_row(temp, row, fields, num_fields); + printf("[%d] row = %s\n", n, temp); + } + + taos_free_result(result); + taos_stmt_close(stmt); + + // drop table + printf("[%d] drop table, tbName = %s\n", n, pTbName->dropName); + stmt = taos_stmt_init(taos); + sprintf(tmpStr, "drop table %s", pTbName->dropName); + taos_stmt_prepare(stmt, tmpStr, 0); + code = taos_stmt_execute(stmt); + if ((!pTbNameResult->dropName && (0 != code)) || (pTbNameResult->dropName && (0 == code))) { + printf("\033[31m[%d] failed to drop table. error:%s\033[0m\n", n, taos_stmt_errstr(stmt)); + taos_stmt_close(stmt); + exit(EXIT_FAILURE); + } + taos_stmt_close(stmt); + } + + free(t8_len); + free(t16_len); + free(t32_len); + free(t64_len); + free(float_len); + free(double_len); + free(bin_len); + free(blob_len); +} + int main(int argc, char* argv[]) { const char* host = "127.0.0.1"; const char* user = "root"; @@ -864,5 +1401,7 @@ int main(int argc, char* argv[]) { printf("************ verify prepare3 *************\n"); verify_prepare3(taos); printf("************ verify prepare4 *************\n"); + verify_prepare4(taos); + printf("************ verify end *************\n"); exit(EXIT_SUCCESS); } diff --git a/tests/pytest/query/queryLike.py b/tests/pytest/query/queryLike.py index 3c3b030f8f718371867f323f2496fb17b6b962e1..07e2786c12b8663679bb3fa315c08542d4af1339 100644 --- a/tests/pytest/query/queryLike.py +++ b/tests/pytest/query/queryLike.py @@ -36,6 +36,17 @@ class TDTestCase: tdSql.query("select * from test_cars where t1 like '%50 90 30 04 00 00%'") tdSql.checkRows(1) + tdSql.execute("create table stb(ts timestamp, c0 int) tags(t0 nchar(64))") + tdSql.execute("insert into tb1 using stb tags('测试ABCabc') values(now, 1)") + tdSql.query("select * from stb where t0 like '%试AB%'") + tdSql.checkRows(1) + + tdSql.query("select * from stb where t0 like '测试AB%'") + tdSql.checkRows(1) + + tdSql.query("select * from stb where t0 like '%ABCabc'") + tdSql.checkRows(1) + def stop(self): tdSql.close() tdLog.success("%s successfully executed" % __file__) diff --git a/tests/script/general/http/grafana.sim b/tests/script/general/http/grafana.sim index 414b859bd3dcaa78ab7d814afd660c9894857cc3..b47edce28cb170a67fe119f76965eae704c4ff43 100644 --- a/tests/script/general/http/grafana.sim +++ b/tests/script/general/http/grafana.sim @@ -50,6 +50,9 @@ sql insert into t3 values('2017-12-25 21:25:41', 3) sql insert into t3 values('2017-12-25 21:26:41', 3) sql insert into t3 values('2017-12-25 21:27:41', 3) +sql create table m3 (ts timestamp, col1 int, col2 float, txt binary(500)) +sql insert into m3 values(now, 1, 2.0, 'HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS') + print =============== step2 - login system_content curl 127.0.0.1:7111/grafana/ @@ -179,4 +182,10 @@ if $system_content != @[{"refId":"A","target":"{count(v1):3}","datapoints":[[15. return -1 endi -system sh/exec.sh -n dnode1 -s stop -x SIGINT \ No newline at end of file +system_content curl -H 'Authorization: Taosd /KfeAzX/f9na8qdtNZmtONryp201ma04bEl8LcvLUd7a8qdtNZmtONryp201ma04' -d '[{"refId":"A","alias":"taosd","sql":"select last(col1), last(col2), last(txt) from d1.m3 group by txt"}]' 127.0.0.1:7111/grafana/query +print 20-> $system_content +if $system_content != @[{"refId":"A","target":"taosd{last(col2):2.00000, last(txt):HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS}","datapoints":[[1,"-"]]}]@ then + return -1 +endi + +system sh/exec.sh -n dnode1 -s stop -x SIGINT