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.jdbctaos-jdbcdriver
- 2.0.34
+ 2.0.36jarJDBCDriver
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.0com.taosdata.jdbctaos-jdbcdriver
- 2.0.34
+ 2.0.36jarJDBCDriverhttps://github.com/taosdata/TDengine/tree/master/src/connector/jdbc
@@ -58,6 +58,7 @@
4.13.1test
+
@@ -70,6 +71,18 @@
+
+ org.apache.maven.plugins
+ maven-source-plugin
+
+
+ attach-sources
+
+ jar
+
+
+
+ org.apache.maven.pluginsmaven-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