提交 531bdc58 编写于 作者: A Alex Duan

Merge branch 'master' into fix/TS-445-M

...@@ -53,7 +53,7 @@ ELSEIF (TD_WINDOWS) ...@@ -53,7 +53,7 @@ ELSEIF (TD_WINDOWS)
#INSTALL(TARGETS taos RUNTIME DESTINATION driver) #INSTALL(TARGETS taos RUNTIME DESTINATION driver)
#INSTALL(TARGETS shell RUNTIME DESTINATION .) #INSTALL(TARGETS shell RUNTIME DESTINATION .)
IF (TD_MVN_INSTALLED) 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 () ENDIF ()
ELSEIF (TD_DARWIN) ELSEIF (TD_DARWIN)
SET(TD_MAKE_INSTALL_SH "${TD_COMMUNITY_DIR}/packaging/tools/make_install.sh") SET(TD_MAKE_INSTALL_SH "${TD_COMMUNITY_DIR}/packaging/tools/make_install.sh")
......
...@@ -41,6 +41,14 @@ JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_initImp ...@@ -41,6 +41,14 @@ JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_initImp
JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setOptions JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setOptions
(JNIEnv *, jclass, jint, jstring); (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 * Class: com_taosdata_jdbc_TSDBJNIConnector
* Method: getTsCharset * Method: getTsCharset
...@@ -231,6 +239,14 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_closeStmt(JNIEnv ...@@ -231,6 +239,14 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_closeStmt(JNIEnv
JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setTableNameTagsImp JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setTableNameTagsImp
(JNIEnv *, jobject, jlong, jstring, jint, jbyteArray, jbyteArray, jbyteArray, jbyteArray, jlong); (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 #ifdef __cplusplus
} }
#endif #endif
......
...@@ -200,6 +200,11 @@ JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_initImp(JNIEnv *e ...@@ -200,6 +200,11 @@ JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_initImp(JNIEnv *e
jniDebug("jni initialized successfully, config directory: %s", configDir); 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, JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setOptions(JNIEnv *env, jobject jobj, jint optionIndex,
jstring optionValue) { jstring optionValue) {
if (optionValue == NULL) { if (optionValue == NULL) {
...@@ -993,8 +998,8 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setTableNameTagsI ...@@ -993,8 +998,8 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setTableNameTagsI
return JNI_SUCCESS; return JNI_SUCCESS;
} }
JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_insertLinesImp(JNIEnv *env, jobject jobj, JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_insertLinesImp
jobjectArray lines, jlong conn) { (JNIEnv *env, jobject jobj, jobjectArray lines, jlong conn, jint protocol, jint precision){
TAOS *taos = (TAOS *)conn; TAOS *taos = (TAOS *)conn;
if (taos == NULL) { if (taos == NULL) {
jniError("jobj:%p, connection already closed", jobj); jniError("jobj:%p, connection already closed", jobj);
......
...@@ -1717,19 +1717,29 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags ...@@ -1717,19 +1717,29 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags
pStmt->last = STMT_SETTBNAME; 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) { if (uid != NULL) {
pStmt->mtb.currentUid = *uid; pStmt->mtb.currentUid = *uid;
STableDataBlocks** t1 = (STableDataBlocks**)taosHashGet(pStmt->mtb.pTableBlockHashList, (const char*)&pStmt->mtb.currentUid, sizeof(pStmt->mtb.currentUid)); STableDataBlocks** t1 = (STableDataBlocks**)taosHashGet(pStmt->mtb.pTableBlockHashList, (const char*)&pStmt->mtb.currentUid, sizeof(pStmt->mtb.currentUid));
if (t1 == NULL) { if (t1 == NULL) {
tscError("0x%"PRIx64" no table data block in hash list, uid:%" PRId64 , pSql->self, pStmt->mtb.currentUid); 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); STMT_RET(TSDB_CODE_TSC_APP_ERROR);
} }
if ((*t1)->pData == NULL) { if ((*t1)->pData == NULL) {
code = tscCreateDataBlockData(*t1, TSDB_PAYLOAD_SIZE, (*t1)->pTableMeta->tableInfo.rowSize, sizeof(SSubmitBlk)); code = tscCreateDataBlockData(*t1, TSDB_PAYLOAD_SIZE, (*t1)->pTableMeta->tableInfo.rowSize, sizeof(SSubmitBlk));
if (code != TSDB_CODE_SUCCESS) { if (code != TSDB_CODE_SUCCESS) {
tfree(tbname);
STMT_RET(code); STMT_RET(code);
} }
} }
...@@ -1744,7 +1754,8 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags ...@@ -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); 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); STMT_RET(TSDB_CODE_SUCCESS);
} }
...@@ -1756,8 +1767,8 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags ...@@ -1756,8 +1767,8 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags
SStrToken tname = {0}; SStrToken tname = {0};
tname.type = TK_STRING; tname.type = TK_STRING;
tname.z = (char *)name; tname.z = tbname;
tname.n = (uint32_t)strlen(name); tname.n = nameLen;
SName fullname = {0}; SName fullname = {0};
tscSetTableFullName(&fullname, &tname, pSql); tscSetTableFullName(&fullname, &tname, pSql);
...@@ -1765,6 +1776,7 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags ...@@ -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); code = tscGetTableMetaEx(pSql, pTableMetaInfo, false, true);
if (code != TSDB_CODE_SUCCESS) { if (code != TSDB_CODE_SUCCESS) {
tfree(tbname);
STMT_RET(code); STMT_RET(code);
} }
...@@ -1772,6 +1784,7 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags ...@@ -1772,6 +1784,7 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags
if (strcmp(sTableName, pTableMeta->sTableName)) { if (strcmp(sTableName, pTableMeta->sTableName)) {
tscError("0x%"PRIx64" only tables belongs to one stable is allowed", pSql->self); tscError("0x%"PRIx64" only tables belongs to one stable is allowed", pSql->self);
tfree(tbname);
STMT_RET(TSDB_CODE_TSC_APP_ERROR); 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 ...@@ -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(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.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); STMT_RET(TSDB_CODE_SUCCESS);
} }
if (pStmt->mtb.tagSet) { 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 { } else {
if (tags == NULL) { if (tags == NULL) {
tscError("No tags set"); tscError("No tags set");
tfree(tbname);
STMT_RET(invalidOperationMsg(tscGetErrorMsgPayload(&pStmt->pSql->cmd), "no tags set")); 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) { if (ret != TSDB_CODE_SUCCESS) {
tfree(tbname);
STMT_RET(ret); STMT_RET(ret);
} }
} }
...@@ -1846,15 +1861,16 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags ...@@ -1846,15 +1861,16 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags
pStmt->mtb.tbNum++; pStmt->mtb.tbNum++;
taosHashPut(pStmt->mtb.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));
if (pStmt->mtb.lastBlock == NULL) { if (pStmt->mtb.lastBlock == NULL) {
insertStmtGenLastBlock(&pStmt->mtb.lastBlock, pBlock); 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); STMT_RET(code);
} }
......
...@@ -8,7 +8,7 @@ IF (TD_MVN_INSTALLED) ...@@ -8,7 +8,7 @@ IF (TD_MVN_INSTALLED)
ADD_CUSTOM_COMMAND(OUTPUT ${JDBC_CMD_NAME} ADD_CUSTOM_COMMAND(OUTPUT ${JDBC_CMD_NAME}
POST_BUILD POST_BUILD
COMMAND mvn -Dmaven.test.skip=true install -f ${CMAKE_CURRENT_SOURCE_DIR}/pom.xml 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 COMMAND mvn -Dmaven.test.skip=true clean -f ${CMAKE_CURRENT_SOURCE_DIR}/pom.xml
COMMENT "build jdbc driver") COMMENT "build jdbc driver")
ADD_CUSTOM_TARGET(${JDBC_TARGET_NAME} ALL WORKING_DIRECTORY ${EXECUTABLE_OUTPUT_PATH} DEPENDS ${JDBC_CMD_NAME}) ADD_CUSTOM_TARGET(${JDBC_TARGET_NAME} ALL WORKING_DIRECTORY ${EXECUTABLE_OUTPUT_PATH} DEPENDS ${JDBC_CMD_NAME})
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
<groupId>com.taosdata.jdbc</groupId> <groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId> <artifactId>taos-jdbcdriver</artifactId>
<version>2.0.34</version> <version>2.0.36</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>JDBCDriver</name> <name>JDBCDriver</name>
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.taosdata.jdbc</groupId> <groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId> <artifactId>taos-jdbcdriver</artifactId>
<version>2.0.34</version> <version>2.0.36</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>JDBCDriver</name> <name>JDBCDriver</name>
<url>https://github.com/taosdata/TDengine/tree/master/src/connector/jdbc</url> <url>https://github.com/taosdata/TDengine/tree/master/src/connector/jdbc</url>
...@@ -58,6 +58,7 @@ ...@@ -58,6 +58,7 @@
<version>4.13.1</version> <version>4.13.1</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
...@@ -70,6 +71,18 @@ ...@@ -70,6 +71,18 @@
</resource> </resource>
</resources> </resources>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
...@@ -114,6 +127,7 @@ ...@@ -114,6 +127,7 @@
<excludes> <excludes>
<exclude>**/HttpClientPoolUtilTest.java</exclude> <exclude>**/HttpClientPoolUtilTest.java</exclude>
<exclude>**/AppMemoryLeakTest.java</exclude> <exclude>**/AppMemoryLeakTest.java</exclude>
<exclude>**/JDBCTypeAndTypeCompareTest.java</exclude>
<exclude>**/ConnectMultiTaosdByRestfulWithDifferentTokenTest.java</exclude> <exclude>**/ConnectMultiTaosdByRestfulWithDifferentTokenTest.java</exclude>
<exclude>**/DatetimeBefore1970Test.java</exclude> <exclude>**/DatetimeBefore1970Test.java</exclude>
<exclude>**/FailOverTest.java</exclude> <exclude>**/FailOverTest.java</exclude>
......
...@@ -107,16 +107,6 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti ...@@ -107,16 +107,6 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti
public void setCatalog(String catalog) throws SQLException { public void setCatalog(String catalog) throws SQLException {
if (isClosed()) if (isClosed())
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); 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; this.catalog = catalog;
} }
...@@ -392,7 +382,7 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti ...@@ -392,7 +382,7 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti
//true if the connection is valid, false otherwise //true if the connection is valid, false otherwise
if (isClosed()) if (isClosed())
return false; 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); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE);
ExecutorService executor = Executors.newCachedThreadPool(); ExecutorService executor = Executors.newCachedThreadPool();
...@@ -413,11 +403,9 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti ...@@ -413,11 +403,9 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti
status = future.get(); status = future.get();
else else
status = future.get(timeout, TimeUnit.SECONDS); status = future.get(timeout, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException ignored) {
e.printStackTrace();
} catch (TimeoutException e) { } catch (TimeoutException e) {
future.cancel(true); future.cancel(true);
status = false;
} finally { } finally {
executor.shutdownNow(); executor.shutdownNow();
} }
......
...@@ -562,25 +562,27 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da ...@@ -562,25 +562,27 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da
List<TSDBResultSetRowData> rowDataList = new ArrayList<>(); List<TSDBResultSetRowData> rowDataList = new ArrayList<>();
try (Statement stmt = connection.createStatement()) { try (Statement stmt = connection.createStatement()) {
stmt.execute("use " + catalog); stmt.execute("use " + catalog);
ResultSet tables = stmt.executeQuery("show tables"); try (ResultSet tables = stmt.executeQuery("show tables")) {
while (tables.next()) { while (tables.next()) {
TSDBResultSetRowData rowData = new TSDBResultSetRowData(10); TSDBResultSetRowData rowData = new TSDBResultSetRowData(10);
rowData.setStringValue(1, catalog); //TABLE_CAT rowData.setStringValue(1, catalog); //TABLE_CAT
rowData.setStringValue(2, null); //TABLE_SCHEM rowData.setStringValue(2, null); //TABLE_SCHEM
rowData.setStringValue(3, tables.getString("table_name")); //TABLE_NAME rowData.setStringValue(3, tables.getString("table_name")); //TABLE_NAME
rowData.setStringValue(4, "TABLE"); //TABLE_TYPE rowData.setStringValue(4, "TABLE"); //TABLE_TYPE
rowData.setStringValue(5, ""); //REMARKS rowData.setStringValue(5, ""); //REMARKS
rowDataList.add(rowData); rowDataList.add(rowData);
}
} }
ResultSet stables = stmt.executeQuery("show stables"); try (ResultSet stables = stmt.executeQuery("show stables")) {
while (stables.next()) { while (stables.next()) {
TSDBResultSetRowData rowData = new TSDBResultSetRowData(10); TSDBResultSetRowData rowData = new TSDBResultSetRowData(10);
rowData.setStringValue(1, catalog); //TABLE_CAT rowData.setStringValue(1, catalog); //TABLE_CAT
rowData.setStringValue(2, null); //TABLE_SCHEM rowData.setStringValue(2, null); //TABLE_SCHEM
rowData.setStringValue(3, stables.getString("name")); //TABLE_NAME rowData.setStringValue(3, stables.getString("name")); //TABLE_NAME
rowData.setStringValue(4, "TABLE"); //TABLE_TYPE rowData.setStringValue(4, "TABLE"); //TABLE_TYPE
rowData.setStringValue(5, "STABLE"); //REMARKS rowData.setStringValue(5, "STABLE"); //REMARKS
rowDataList.add(rowData); rowDataList.add(rowData);
}
} }
resultSet.setRowDataList(rowDataList); resultSet.setRowDataList(rowDataList);
} }
...@@ -595,7 +597,7 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da ...@@ -595,7 +597,7 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da
return col4; return col4;
} }
public ResultSet getSchemas() throws SQLException { public ResultSet getSchemas() {
return getEmptyResultSet(); return getEmptyResultSet();
} }
...@@ -627,7 +629,7 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da ...@@ -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; 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()) if (catalog == null || catalog.isEmpty())
return null; return null;
if (!isAvailableCatalog(conn, catalog)) if (!isAvailableCatalog(conn, catalog))
...@@ -638,8 +640,9 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da ...@@ -638,8 +640,9 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da
resultSet.setColumnMetaDataList(buildGetColumnsColumnMetaDataList()); resultSet.setColumnMetaDataList(buildGetColumnsColumnMetaDataList());
// set up rowDataList // set up rowDataList
List<TSDBResultSetRowData> rowDataList = new ArrayList<>(); List<TSDBResultSetRowData> rowDataList = new ArrayList<>();
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("describe " + catalog + "." + tableNamePattern); ResultSet rs = stmt.executeQuery("describe " + catalog + "." + tableNamePattern)) {
int rowIndex = 0; int rowIndex = 0;
while (rs.next()) { while (rs.next()) {
TSDBResultSetRowData rowData = new TSDBResultSetRowData(24); TSDBResultSetRowData rowData = new TSDBResultSetRowData(24);
...@@ -679,8 +682,6 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da ...@@ -679,8 +682,6 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da
rowIndex++; rowIndex++;
} }
resultSet.setRowDataList(rowDataList); resultSet.setRowDataList(rowDataList);
} catch (SQLException e) {
e.printStackTrace();
} }
return resultSet; return resultSet;
} }
...@@ -1147,9 +1148,9 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da ...@@ -1147,9 +1148,9 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da
columnMetaDataList.add(buildTableCatalogMeta(1)); // 1. TABLE_CAT columnMetaDataList.add(buildTableCatalogMeta(1)); // 1. TABLE_CAT
resultSet.setColumnMetaDataList(columnMetaDataList); resultSet.setColumnMetaDataList(columnMetaDataList);
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("show databases")) {
List<TSDBResultSetRowData> rowDataList = new ArrayList<>(); List<TSDBResultSetRowData> rowDataList = new ArrayList<>();
ResultSet rs = stmt.executeQuery("show databases");
while (rs.next()) { while (rs.next()) {
TSDBResultSetRowData rowData = new TSDBResultSetRowData(1); TSDBResultSetRowData rowData = new TSDBResultSetRowData(1);
rowData.setStringValue(1, rs.getString("name")); rowData.setStringValue(1, rs.getString("name"));
...@@ -1168,12 +1169,13 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da ...@@ -1168,12 +1169,13 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da
return new EmptyResultSet(); return new EmptyResultSet();
DatabaseMetaDataResultSet resultSet = new DatabaseMetaDataResultSet(); DatabaseMetaDataResultSet resultSet = new DatabaseMetaDataResultSet();
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("describe " + catalog + "." + table)) {
// set up ColumnMetaDataList // set up ColumnMetaDataList
resultSet.setColumnMetaDataList(buildGetPrimaryKeysMetadataList()); resultSet.setColumnMetaDataList(buildGetPrimaryKeysMetadataList());
// set rowData // set rowData
List<TSDBResultSetRowData> rowDataList = new ArrayList<>(); List<TSDBResultSetRowData> rowDataList = new ArrayList<>();
ResultSet rs = stmt.executeQuery("describe " + catalog + "." + table);
rs.next(); rs.next();
TSDBResultSetRowData rowData = new TSDBResultSetRowData(6); TSDBResultSetRowData rowData = new TSDBResultSetRowData(6);
rowData.setStringValue(1, catalog); rowData.setStringValue(1, catalog);
...@@ -1216,18 +1218,15 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da ...@@ -1216,18 +1218,15 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da
return col6; return col6;
} }
private boolean isAvailableCatalog(Connection connection, String catalog) { private boolean isAvailableCatalog(Connection connection, String catalog) throws SQLException {
try (Statement stmt = connection.createStatement()) { try (Statement stmt = connection.createStatement();
ResultSet databases = stmt.executeQuery("show databases"); ResultSet databases = stmt.executeQuery("show databases")) {
while (databases.next()) { while (databases.next()) {
String dbname = databases.getString("name"); String dbname = databases.getString("name");
this.precision = databases.getString("precision"); this.precision = databases.getString("precision");
if (dbname.equalsIgnoreCase(catalog)) if (dbname.equalsIgnoreCase(catalog))
return true; return true;
} }
databases.close();
} catch (SQLException e) {
e.printStackTrace();
} }
return false; return false;
} }
...@@ -1246,17 +1245,18 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da ...@@ -1246,17 +1245,18 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da
resultSet.setColumnMetaDataList(buildGetSuperTablesColumnMetaDataList()); resultSet.setColumnMetaDataList(buildGetSuperTablesColumnMetaDataList());
// set result set row data // set result set row data
stmt.execute("use " + catalog); stmt.execute("use " + catalog);
ResultSet rs = stmt.executeQuery("show tables like '" + tableNamePattern + "'"); try (ResultSet rs = stmt.executeQuery("show tables like '" + tableNamePattern + "'")) {
List<TSDBResultSetRowData> rowDataList = new ArrayList<>(); List<TSDBResultSetRowData> rowDataList = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
TSDBResultSetRowData rowData = new TSDBResultSetRowData(4); TSDBResultSetRowData rowData = new TSDBResultSetRowData(4);
rowData.setStringValue(1, catalog); rowData.setStringValue(1, catalog);
rowData.setStringValue(2, null); rowData.setStringValue(2, null);
rowData.setStringValue(3, rs.getString("table_name")); rowData.setStringValue(3, rs.getString("table_name"));
rowData.setStringValue(4, rs.getString("stable_name")); rowData.setStringValue(4, rs.getString("stable_name"));
rowDataList.add(rowData); rowDataList.add(rowData);
}
resultSet.setRowDataList(rowDataList);
} }
resultSet.setRowDataList(rowDataList);
} }
return resultSet; return resultSet;
} }
......
...@@ -11,6 +11,11 @@ import java.util.Map; ...@@ -11,6 +11,11 @@ import java.util.Map;
public abstract class AbstractResultSet extends WrapperImpl implements ResultSet { public abstract class AbstractResultSet extends WrapperImpl implements ResultSet {
private int fetchSize; private int fetchSize;
protected boolean wasNull; protected boolean wasNull;
protected int timestampPrecision;
public void setTimestampPrecision(int timestampPrecision) {
this.timestampPrecision = timestampPrecision;
}
protected void checkAvailability(int columnIndex, int bounds) throws SQLException { protected void checkAvailability(int columnIndex, int bounds) throws SQLException {
if (isClosed()) if (isClosed())
......
...@@ -9,6 +9,7 @@ public abstract class AbstractStatement extends WrapperImpl implements Statement ...@@ -9,6 +9,7 @@ public abstract class AbstractStatement extends WrapperImpl implements Statement
protected List<String> batchedArgs; protected List<String> batchedArgs;
private int fetchSize; private int fetchSize;
protected int affectedRows = -1;
@Override @Override
public abstract ResultSet executeQuery(String sql) throws SQLException; public abstract ResultSet executeQuery(String sql) throws SQLException;
...@@ -247,6 +248,7 @@ public abstract class AbstractStatement extends WrapperImpl implements Statement ...@@ -247,6 +248,7 @@ public abstract class AbstractStatement extends WrapperImpl implements Statement
public boolean getMoreResults(int current) throws SQLException { public boolean getMoreResults(int current) throws SQLException {
if (isClosed()) if (isClosed())
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED);
this.affectedRows = -1;
switch (current) { switch (current) {
case Statement.CLOSE_CURRENT_RESULT: case Statement.CLOSE_CURRENT_RESULT:
return false; return false;
......
...@@ -149,7 +149,7 @@ public class DatabaseMetaDataResultSet extends AbstractResultSet { ...@@ -149,7 +149,7 @@ public class DatabaseMetaDataResultSet extends AbstractResultSet {
public BigDecimal getBigDecimal(int columnIndex) throws SQLException { public BigDecimal getBigDecimal(int columnIndex) throws SQLException {
int colType = columnMetaDataList.get(columnIndex - 1).getColType(); int colType = columnMetaDataList.get(columnIndex - 1).getColType();
double value = rowCursor.getDouble(columnIndex, colType); double value = rowCursor.getDouble(columnIndex, colType);
return new BigDecimal(value); return BigDecimal.valueOf(value);
} }
@Override @Override
......
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<String> lines, SchemalessProtocolType protocolType, SchemalessTimestampType timestampType) throws SQLException {
String[] strings = lines.toArray(new String[0]);
write(strings, protocolType, timestampType);
}
}
/***************************************************************************
* Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
*
* 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 <http://www.gnu.org/licenses/>.
*****************************************************************************/
package com.taosdata.jdbc; package com.taosdata.jdbc;
import java.sql.*; import java.sql.*;
...@@ -66,7 +52,7 @@ public class TSDBConnection extends AbstractConnection { ...@@ -66,7 +52,7 @@ public class TSDBConnection extends AbstractConnection {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED); 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) { if (id == 0) {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_SUBSCRIBE_FAILED); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_SUBSCRIBE_FAILED);
} }
......
/***************************************************************************
* Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
*
* 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 <http://www.gnu.org/licenses/>.
*****************************************************************************/
package com.taosdata.jdbc; package com.taosdata.jdbc;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.Logger; import java.util.logging.Logger;
/** /**
...@@ -118,9 +103,6 @@ public class TSDBDriver extends AbstractDriver { ...@@ -118,9 +103,6 @@ public class TSDBDriver extends AbstractDriver {
} }
public Connection connect(String url, Properties info) throws SQLException { public Connection connect(String url, Properties info) throws SQLException {
if (url == null)
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_URL_NOT_SET);
if (!acceptsURL(url)) if (!acceptsURL(url))
return null; return null;
...@@ -135,16 +117,14 @@ public class TSDBDriver extends AbstractDriver { ...@@ -135,16 +117,14 @@ public class TSDBDriver extends AbstractDriver {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PASSWORD_IS_REQUIRED); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PASSWORD_IS_REQUIRED);
try { try {
TSDBJNIConnector.init((String) props.get(PROPERTY_KEY_CONFIG_DIR), (String) props.get(PROPERTY_KEY_LOCALE), TSDBJNIConnector.init(props);
(String) props.get(PROPERTY_KEY_CHARSET), (String) props.get(PROPERTY_KEY_TIME_ZONE));
return new TSDBConnection(props, this.dbMetaData); return new TSDBConnection(props, this.dbMetaData);
} catch (SQLWarning sqlWarning) { } catch (SQLWarning sqlWarning) {
sqlWarning.printStackTrace();
return new TSDBConnection(props, this.dbMetaData); return new TSDBConnection(props, this.dbMetaData);
} catch (SQLException sqlEx) { } catch (SQLException sqlEx) {
throw sqlEx; throw sqlEx;
} catch (Exception ex) { } 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 { ...@@ -157,7 +137,7 @@ public class TSDBDriver extends AbstractDriver {
public boolean acceptsURL(String url) throws SQLException { public boolean acceptsURL(String url) throws SQLException {
if (url == null) if (url == null)
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_URL_NOT_SET); 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 { public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
...@@ -205,6 +185,7 @@ public class TSDBDriver extends AbstractDriver { ...@@ -205,6 +185,7 @@ public class TSDBDriver extends AbstractDriver {
String dbProductName = url.substring(0, beginningOfSlashes); String dbProductName = url.substring(0, beginningOfSlashes);
dbProductName = dbProductName.substring(dbProductName.indexOf(":") + 1); dbProductName = dbProductName.substring(dbProductName.indexOf(":") + 1);
dbProductName = dbProductName.substring(0, dbProductName.indexOf(":")); dbProductName = dbProductName.substring(0, dbProductName.indexOf(":"));
urlProps.setProperty(TSDBDriver.PROPERTY_KEY_PRODUCT_NAME, dbProductName);
// parse database name // parse database name
url = url.substring(beginningOfSlashes + 2); url = url.substring(beginningOfSlashes + 2);
......
...@@ -35,6 +35,7 @@ public class TSDBError { ...@@ -35,6 +35,7 @@ public class TSDBError {
TSDBErrorMap.put(TSDBErrorNumbers.ERROR_UNKNOWN_TIMESTAMP_PRECISION, "unknown timestamp precision"); TSDBErrorMap.put(TSDBErrorNumbers.ERROR_UNKNOWN_TIMESTAMP_PRECISION, "unknown timestamp precision");
TSDBErrorMap.put(TSDBErrorNumbers.ERROR_USER_IS_REQUIRED, "user is required"); TSDBErrorMap.put(TSDBErrorNumbers.ERROR_USER_IS_REQUIRED, "user is required");
TSDBErrorMap.put(TSDBErrorNumbers.ERROR_PASSWORD_IS_REQUIRED, "password is required"); TSDBErrorMap.put(TSDBErrorNumbers.ERROR_PASSWORD_IS_REQUIRED, "password is required");
TSDBErrorMap.put(TSDBErrorNumbers.ERROR_INVALID_JSON_FORMAT, "invalid json format");
TSDBErrorMap.put(TSDBErrorNumbers.ERROR_UNKNOWN, "unknown error"); TSDBErrorMap.put(TSDBErrorNumbers.ERROR_UNKNOWN, "unknown error");
......
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
/**
* *************************************************************************
* Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ***************************************************************************
*/
package com.taosdata.jdbc; 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 com.taosdata.jdbc.utils.TaosInfo;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.SQLWarning; import java.sql.SQLWarning;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Properties;
/** /**
* JNI connector * JNI connector
*/ */
public class TSDBJNIConnector { 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 final TaosInfo taosInfo = TaosInfo.getInstance();
private long taos = TSDBConstants.JNI_NULL_POINTER; // Connection pointer used in C private long taos = TSDBConstants.JNI_NULL_POINTER; // Connection pointer used in C
...@@ -38,24 +29,27 @@ public class TSDBJNIConnector { ...@@ -38,24 +29,27 @@ public class TSDBJNIConnector {
System.loadLibrary("taos"); System.loadLibrary("taos");
} }
public boolean isClosed() { public static void init(Properties props) throws SQLWarning {
return this.taos == TSDBConstants.JNI_NULL_POINTER; synchronized (LOCK) {
} if (!isInitialized) {
public boolean isResultsetClosed() { JSONObject configJSON = new JSONObject();
return this.isResultsetClosed; 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 { initImp(props.getProperty(TSDBDriver.PROPERTY_KEY_CONFIG_DIR, null));
synchronized (isInitialized) {
if (!isInitialized) { String locale = props.getProperty(TSDBDriver.PROPERTY_KEY_LOCALE);
initImp(configDir);
if (setOptions(0, locale) < 0) { if (setOptions(0, locale) < 0) {
throw TSDBError.createSQLWarning("Failed to set locale: " + locale + ". System default will be used."); 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) { if (setOptions(1, charset) < 0) {
throw TSDBError.createSQLWarning("Failed to set charset: " + charset + ". System default will be used."); 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) { if (setOptions(2, timezone) < 0) {
throw TSDBError.createSQLWarning("Failed to set timezone: " + timezone + ". System default will be used."); throw TSDBError.createSQLWarning("Failed to set timezone: " + timezone + ". System default will be used.");
} }
...@@ -65,11 +59,13 @@ public class TSDBJNIConnector { ...@@ -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 { public boolean connect(String host, int port, String dbName, String user, String password) throws SQLException {
if (this.taos != TSDBConstants.JNI_NULL_POINTER) { if (this.taos != TSDBConstants.JNI_NULL_POINTER) {
...@@ -97,8 +93,7 @@ public class TSDBJNIConnector { ...@@ -97,8 +93,7 @@ public class TSDBJNIConnector {
try { try {
pSql = this.executeQueryImp(sql.getBytes(TaosGlobalConfig.getCharset()), this.taos); pSql = this.executeQueryImp(sql.getBytes(TaosGlobalConfig.getCharset()), this.taos);
taosInfo.stmt_count_increment(); taosInfo.stmt_count_increment();
} catch (Exception e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace();
this.freeResultSetImp(this.taos, pSql); this.freeResultSetImp(this.taos, pSql);
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_ENCODING); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_ENCODING);
} }
...@@ -159,6 +154,14 @@ public class TSDBJNIConnector { ...@@ -159,6 +154,14 @@ public class TSDBJNIConnector {
private native long isUpdateQueryImp(long connection, long pSql); 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 * Free result set operation from C to release result set pointer by JNI
*/ */
...@@ -243,8 +246,8 @@ public class TSDBJNIConnector { ...@@ -243,8 +246,8 @@ public class TSDBJNIConnector {
/** /**
* Create a subscription * Create a subscription
*/ */
long subscribe(String topic, String sql, boolean restart, int period) { long subscribe(String topic, String sql, boolean restart) {
return subscribeImp(this.taos, restart, topic, sql, period); return subscribeImp(this.taos, restart, topic, sql, 0);
} }
private native long subscribeImp(long connection, boolean restart, String topic, String sql, int period); private native long subscribeImp(long connection, boolean restart, String topic, String sql, int period);
...@@ -267,16 +270,6 @@ public class TSDBJNIConnector { ...@@ -267,16 +270,6 @@ public class TSDBJNIConnector {
private native void unsubscribeImp(long subscription, boolean isKeep); private native void unsubscribeImp(long subscription, boolean isKeep);
/**
* Validate if a <I>create table</I> 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 { public long prepareStmt(String sql) throws SQLException {
long stmt = prepareStmtImp(sql.getBytes(), this.taos); long stmt = prepareStmtImp(sql.getBytes(), this.taos);
...@@ -301,7 +294,7 @@ public class TSDBJNIConnector { ...@@ -301,7 +294,7 @@ public class TSDBJNIConnector {
public void setBindTableName(long stmt, String tableName) throws SQLException { public void setBindTableName(long stmt, String tableName) throws SQLException {
int code = setBindTableNameImp(stmt, tableName, this.taos); int code = setBindTableNameImp(stmt, tableName, this.taos);
if (code != TSDBConstants.JNI_SUCCESS) { 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 { ...@@ -343,12 +336,14 @@ public class TSDBJNIConnector {
private native int closeStmt(long stmt, long con); private native int closeStmt(long stmt, long con);
public void insertLines(String[] lines) throws SQLException { public void insertLines(String[] lines, SchemalessProtocolType protocolType, SchemalessTimestampType timestampType) throws SQLException {
int code = insertLinesImp(lines, this.taos); int code = insertLinesImp(lines, this.taos, protocolType.ordinal(), timestampType.ordinal());
if (code != TSDBConstants.JNI_SUCCESS) { 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);
} }
...@@ -36,15 +36,15 @@ import java.util.regex.Pattern; ...@@ -36,15 +36,15 @@ import java.util.regex.Pattern;
* compatibility needs. * compatibility needs.
*/ */
public class TSDBPreparedStatement extends TSDBStatement implements PreparedStatement { public class TSDBPreparedStatement extends TSDBStatement implements PreparedStatement {
// for jdbc preparedStatement interface
private String rawSql; private String rawSql;
private Object[] parameters; private Object[] parameters;
// for parameter binding
private ArrayList<ColumnInfo> colData; private long nativeStmtHandle = 0;
private String tableName;
private ArrayList<TableTagInfo> tableTags; private ArrayList<TableTagInfo> tableTags;
private int tagValueLength; private int tagValueLength;
private ArrayList<ColumnInfo> colData;
private String tableName;
private long nativeStmtHandle = 0;
TSDBPreparedStatement(TSDBConnection connection, String sql) { TSDBPreparedStatement(TSDBConnection connection, String sql) {
super(connection); super(connection);
...@@ -72,10 +72,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -72,10 +72,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
preprocessSql(); preprocessSql();
} }
/*
*
*/
/** /**
* Some of the SQLs sent by other popular frameworks or tools like Spark, contains syntax that cannot be parsed by * 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 * 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 ...@@ -250,13 +246,10 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
@Override @Override
public void setObject(int parameterIndex, Object x) throws SQLException { public void setObject(int parameterIndex, Object x) throws SQLException {
if (isClosed()) { if (isClosed())
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); 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); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE);
}
parameters[parameterIndex - 1] = x; parameters[parameterIndex - 1] = x;
} }
...@@ -335,7 +328,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -335,7 +328,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
if (isClosed()) if (isClosed())
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED);
// TODO:
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD);
} }
...@@ -419,7 +411,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -419,7 +411,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {
if (isClosed()) if (isClosed())
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED);
//TODO:
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD);
} }
...@@ -477,7 +468,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -477,7 +468,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
if (isClosed()) if (isClosed())
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED);
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD);
} }
@Override @Override
...@@ -496,7 +486,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -496,7 +486,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
/////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////
// NOTE: the following APIs are not JDBC compatible // NOTE: the following APIs are not JDBC compatible
// set the bind table name // parameter binding
private static class ColumnInfo { private static class ColumnInfo {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
private ArrayList data; private ArrayList data;
...@@ -539,7 +529,11 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -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; this.tableName = name;
} }
...@@ -617,7 +611,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -617,7 +611,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
try { try {
this.tagValueLength += value.getBytes(charset).length; this.tagValueLength += value.getBytes(charset).length;
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); throw new RuntimeException(e.getMessage());
} }
} }
...@@ -792,7 +786,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -792,7 +786,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
b = val.getBytes(charset); b = val.getBytes(charset);
} }
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); throw new RuntimeException(e.getMessage());
} }
tagDataList.put(b); tagDataList.put(b);
...@@ -927,7 +921,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -927,7 +921,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
b = val.getBytes(charset); b = val.getBytes(charset);
} }
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); throw new RuntimeException(e.getMessage());
} }
if (val.length() > col1.bytes) { if (val.length() > col1.bytes) {
...@@ -960,17 +954,22 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -960,17 +954,22 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
public void columnDataExecuteBatch() throws SQLException { public void columnDataExecuteBatch() throws SQLException {
TSDBJNIConnector connector = ((TSDBConnection) this.getConnection()).getConnector(); TSDBJNIConnector connector = ((TSDBConnection) this.getConnection()).getConnector();
connector.executeBatch(this.nativeStmtHandle); connector.executeBatch(this.nativeStmtHandle);
this.columnDataClearBatch(); this.columnDataClearBatchInternal();
} }
@Deprecated
public void columnDataClearBatch() { public void columnDataClearBatch() {
columnDataClearBatchInternal();
}
private void columnDataClearBatchInternal() {
int size = this.colData.size(); int size = this.colData.size();
this.colData.clear(); this.colData.clear();
this.colData.addAll(Collections.nCopies(size, null)); this.colData.addAll(Collections.nCopies(size, null));
this.tableName = null; // clear the table name this.tableName = null; // clear the table name
} }
public void columnDataCloseBatch() throws SQLException { public void columnDataCloseBatch() throws SQLException {
TSDBJNIConnector connector = ((TSDBConnection) this.getConnection()).getConnector(); TSDBJNIConnector connector = ((TSDBConnection) this.getConnection()).getConnector();
connector.closeBatch(this.nativeStmtHandle); connector.closeBatch(this.nativeStmtHandle);
...@@ -978,4 +977,13 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -978,4 +977,13 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
this.nativeStmtHandle = 0L; this.nativeStmtHandle = 0L;
this.tableName = null; this.tableName = null;
} }
@Override
public void close() throws SQLException {
if (this.nativeStmtHandle != 0L) {
this.columnDataClearBatchInternal();
this.columnDataCloseBatch();
}
super.close();
}
} }
...@@ -19,6 +19,7 @@ import com.google.common.primitives.Longs; ...@@ -19,6 +19,7 @@ import com.google.common.primitives.Longs;
import com.google.common.primitives.Shorts; import com.google.common.primitives.Shorts;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.sql.*; import java.sql.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
...@@ -73,9 +74,8 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { ...@@ -73,9 +74,8 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet {
public boolean next() throws SQLException { public boolean next() throws SQLException {
if (this.getBatchFetch()) { if (this.getBatchFetch()) {
if (this.blockData.forward()) { if (this.blockData.forward())
return true; return true;
}
int code = this.jniConnector.fetchBlock(this.resultSetPointer, this.blockData); int code = this.jniConnector.fetchBlock(this.resultSetPointer, this.blockData);
this.blockData.reset(); this.blockData.reset();
...@@ -213,7 +213,18 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { ...@@ -213,7 +213,18 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet {
if (!lastWasNull) { if (!lastWasNull) {
Object value = this.rowData.getObject(columnIndex); Object value = this.rowData.getObject(columnIndex);
if (value instanceof Timestamp) { 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 { } else {
int nativeType = this.columnMetaDataList.get(columnIndex - 1).getColType(); int nativeType = this.columnMetaDataList.get(columnIndex - 1).getColType();
res = this.rowData.getLong(columnIndex, nativeType); res = this.rowData.getLong(columnIndex, nativeType);
...@@ -256,7 +267,11 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { ...@@ -256,7 +267,11 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet {
public byte[] getBytes(int columnIndex) throws SQLException { public byte[] getBytes(int columnIndex) throws SQLException {
checkAvailability(columnIndex, this.columnMetaDataList.size()); checkAvailability(columnIndex, this.columnMetaDataList.size());
if (this.getBatchFetch())
return this.blockData.getString(columnIndex).getBytes();
Object value = this.rowData.getObject(columnIndex); Object value = this.rowData.getObject(columnIndex);
this.lastWasNull = value == null;
if (value == null) if (value == null)
return null; return null;
...@@ -331,25 +346,26 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { ...@@ -331,25 +346,26 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet {
return new BigDecimal(this.blockData.getLong(columnIndex - 1)); return new BigDecimal(this.blockData.getLong(columnIndex - 1));
this.lastWasNull = this.rowData.wasNull(columnIndex); this.lastWasNull = this.rowData.wasNull(columnIndex);
BigDecimal res = null; if (lastWasNull)
if (!lastWasNull) { return null;
int nativeType = this.columnMetaDataList.get(columnIndex - 1).getColType();
switch (nativeType) { BigDecimal res;
case TSDBConstants.TSDB_DATA_TYPE_TINYINT: int nativeType = this.columnMetaDataList.get(columnIndex - 1).getColType();
case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: switch (nativeType) {
case TSDBConstants.TSDB_DATA_TYPE_INT: case TSDBConstants.TSDB_DATA_TYPE_TINYINT:
case TSDBConstants.TSDB_DATA_TYPE_BIGINT: case TSDBConstants.TSDB_DATA_TYPE_SMALLINT:
res = new BigDecimal(Long.parseLong(this.rowData.getObject(columnIndex).toString())); case TSDBConstants.TSDB_DATA_TYPE_INT:
break; case TSDBConstants.TSDB_DATA_TYPE_BIGINT:
case TSDBConstants.TSDB_DATA_TYPE_FLOAT: res = new BigDecimal(Long.parseLong(this.rowData.getObject(columnIndex).toString()));
case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: break;
res = BigDecimal.valueOf(Double.parseDouble(this.rowData.getObject(columnIndex).toString())); case TSDBConstants.TSDB_DATA_TYPE_FLOAT:
break; case TSDBConstants.TSDB_DATA_TYPE_DOUBLE:
case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: res = BigDecimal.valueOf(Double.parseDouble(this.rowData.getObject(columnIndex).toString()));
return new BigDecimal(((Timestamp) this.rowData.getObject(columnIndex)).getTime()); break;
default: case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP:
res = new BigDecimal(this.rowData.getObject(columnIndex).toString()); return new BigDecimal(((Timestamp) this.rowData.getObject(columnIndex)).getTime());
} default:
res = new BigDecimal(this.rowData.getObject(columnIndex).toString());
} }
return res; return res;
} }
...@@ -465,12 +481,6 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { ...@@ -465,12 +481,6 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet {
public boolean isClosed() throws SQLException { public boolean isClosed() throws SQLException {
return isClosed; return isClosed;
// if (isClosed)
// return true;
// if (jniConnector != null) {
// isClosed = jniConnector.isResultsetClosed();
// }
// return isClosed;
} }
public String getNString(int columnIndex) throws SQLException { public String getNString(int columnIndex) throws SQLException {
......
...@@ -92,75 +92,71 @@ public class TSDBResultSetBlockData { ...@@ -92,75 +92,71 @@ public class TSDBResultSetBlockData {
} }
public void setByteArray(int col, int length, byte[] value) { public void setByteArray(int col, int length, byte[] value) {
try { switch (this.columnMetaDataList.get(col).getColType()) {
switch (this.columnMetaDataList.get(col).getColType()) { case TSDBConstants.TSDB_DATA_TYPE_BOOL: {
case TSDBConstants.TSDB_DATA_TYPE_BOOL: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); buf.order(ByteOrder.LITTLE_ENDIAN).asCharBuffer();
buf.order(ByteOrder.LITTLE_ENDIAN).asCharBuffer(); this.colData.set(col, buf);
this.colData.set(col, buf); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_UTINYINT:
case TSDBConstants.TSDB_DATA_TYPE_UTINYINT: case TSDBConstants.TSDB_DATA_TYPE_TINYINT: {
case TSDBConstants.TSDB_DATA_TYPE_TINYINT: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); buf.order(ByteOrder.LITTLE_ENDIAN);
buf.order(ByteOrder.LITTLE_ENDIAN); this.colData.set(col, buf);
this.colData.set(col, buf); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_USMALLINT:
case TSDBConstants.TSDB_DATA_TYPE_USMALLINT: case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: {
case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); ShortBuffer sb = buf.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
ShortBuffer sb = buf.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer(); this.colData.set(col, sb);
this.colData.set(col, sb); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_UINT:
case TSDBConstants.TSDB_DATA_TYPE_UINT: case TSDBConstants.TSDB_DATA_TYPE_INT: {
case TSDBConstants.TSDB_DATA_TYPE_INT: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); IntBuffer ib = buf.order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
IntBuffer ib = buf.order(ByteOrder.LITTLE_ENDIAN).asIntBuffer(); this.colData.set(col, ib);
this.colData.set(col, ib); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_UBIGINT:
case TSDBConstants.TSDB_DATA_TYPE_UBIGINT: case TSDBConstants.TSDB_DATA_TYPE_BIGINT: {
case TSDBConstants.TSDB_DATA_TYPE_BIGINT: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); LongBuffer lb = buf.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer();
LongBuffer lb = buf.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer(); this.colData.set(col, lb);
this.colData.set(col, lb); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_FLOAT: {
case TSDBConstants.TSDB_DATA_TYPE_FLOAT: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); FloatBuffer fb = buf.order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer();
FloatBuffer fb = buf.order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer(); this.colData.set(col, fb);
this.colData.set(col, fb); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: {
case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); DoubleBuffer db = buf.order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer();
DoubleBuffer db = buf.order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer(); this.colData.set(col, db);
this.colData.set(col, db); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_BINARY: {
case TSDBConstants.TSDB_DATA_TYPE_BINARY: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); buf.order(ByteOrder.LITTLE_ENDIAN);
buf.order(ByteOrder.LITTLE_ENDIAN); this.colData.set(col, buf);
this.colData.set(col, buf); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: {
case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); LongBuffer lb = buf.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer();
LongBuffer lb = buf.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer(); this.colData.set(col, lb);
this.colData.set(col, lb); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_NCHAR: {
case TSDBConstants.TSDB_DATA_TYPE_NCHAR: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); buf.order(ByteOrder.LITTLE_ENDIAN);
buf.order(ByteOrder.LITTLE_ENDIAN); this.colData.set(col, buf);
this.colData.set(col, buf); break;
break;
}
} }
} catch (Exception e) {
e.printStackTrace();
} }
} }
...@@ -283,14 +279,8 @@ public class TSDBResultSetBlockData { ...@@ -283,14 +279,8 @@ public class TSDBResultSetBlockData {
return 0; return 0;
} }
public Timestamp getTimestamp(int col) { public Timestamp getTimestamp(int col) throws SQLException {
try { return new Timestamp(getLong(col));
return new Timestamp(getLong(col));
} catch (SQLException e) {
e.printStackTrace();
}
return null;
} }
public double getDouble(int col) { public double getDouble(int col) {
...@@ -429,7 +419,7 @@ public class TSDBResultSetBlockData { ...@@ -429,7 +419,7 @@ public class TSDBResultSetBlockData {
String charset = TaosGlobalConfig.getCharset(); String charset = TaosGlobalConfig.getCharset();
return new String(dest, charset); return new String(dest, charset);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); throw new RuntimeException(e.getMessage());
} }
} }
} }
......
...@@ -16,6 +16,7 @@ package com.taosdata.jdbc; ...@@ -16,6 +16,7 @@ package com.taosdata.jdbc;
import com.taosdata.jdbc.utils.NullType; import com.taosdata.jdbc.utils.NullType;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Timestamp; import java.sql.Timestamp;
...@@ -49,7 +50,7 @@ public class TSDBResultSetRowData { ...@@ -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) { public void setBooleanValue(int col, boolean value) {
setBoolean(col - 1, value); setBoolean(col - 1, value);
...@@ -86,7 +87,7 @@ public class TSDBResultSetRowData { ...@@ -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) { public void setByteValue(int colIndex, byte value) {
setByte(colIndex - 1, value); setByte(colIndex - 1, value);
...@@ -100,7 +101,7 @@ public class TSDBResultSetRowData { ...@@ -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) { public void setShortValue(int colIndex, short value) {
setShort(colIndex - 1, value); setShort(colIndex - 1, value);
...@@ -114,7 +115,7 @@ public class TSDBResultSetRowData { ...@@ -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) { public void setIntValue(int colIndex, int value) {
setInt(colIndex - 1, value); setInt(colIndex - 1, value);
...@@ -189,12 +190,12 @@ public class TSDBResultSetRowData { ...@@ -189,12 +190,12 @@ public class TSDBResultSetRowData {
long value = (long) obj; long value = (long) obj;
if (value < 0) if (value < 0)
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_NUMERIC_VALUE_OUT_OF_RANGE); 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) { public void setLongValue(int colIndex, long value) {
setLong(colIndex - 1, value); setLong(colIndex - 1, value);
...@@ -262,7 +263,7 @@ public class TSDBResultSetRowData { ...@@ -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) { public void setFloatValue(int colIndex, float value) {
setFloat(colIndex - 1, value); setFloat(colIndex - 1, value);
...@@ -302,7 +303,7 @@ public class TSDBResultSetRowData { ...@@ -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) { public void setDoubleValue(int colIndex, double value) {
setDouble(colIndex - 1, value); setDouble(colIndex - 1, value);
...@@ -342,7 +343,7 @@ public class TSDBResultSetRowData { ...@@ -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) { public void setStringValue(int colIndex, String value) {
data.set(colIndex - 1, value); data.set(colIndex - 1, value);
...@@ -361,7 +362,7 @@ public class TSDBResultSetRowData { ...@@ -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) { public void setByteArrayValue(int colIndex, byte[] value) {
setByteArray(colIndex - 1, value); setByteArray(colIndex - 1, value);
...@@ -378,8 +379,8 @@ public class TSDBResultSetRowData { ...@@ -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 // this setByteArr(int, byte[]) to handle NCHAR value, we need to build a String with charsetEncoding by TaosGlobalConfig
try { try {
data.set(col, new String(value, TaosGlobalConfig.getCharset())); data.set(col, new String(value, TaosGlobalConfig.getCharset()));
} catch (Exception e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); throw new RuntimeException(e.getMessage());
} }
} }
...@@ -424,7 +425,7 @@ public class TSDBResultSetRowData { ...@@ -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) { public void setTimestampValue(int colIndex, long value) {
setTimestamp(colIndex - 1, value, 0); setTimestamp(colIndex - 1, value, 0);
......
...@@ -23,7 +23,7 @@ import java.util.Calendar; ...@@ -23,7 +23,7 @@ import java.util.Calendar;
import java.util.Map; 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 * standard JDBC API contains more or less some adjustments customized for certain
* compatibility needs. * compatibility needs.
*/ */
......
...@@ -23,7 +23,6 @@ public class TSDBStatement extends AbstractStatement { ...@@ -23,7 +23,6 @@ public class TSDBStatement extends AbstractStatement {
* Status of current statement * Status of current statement
*/ */
private boolean isClosed; private boolean isClosed;
private int affectedRows = -1;
private TSDBConnection connection; private TSDBConnection connection;
private TSDBResultSet resultSet; private TSDBResultSet resultSet;
...@@ -48,6 +47,8 @@ public class TSDBStatement extends AbstractStatement { ...@@ -48,6 +47,8 @@ public class TSDBStatement extends AbstractStatement {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEQUERY); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEQUERY);
} }
TSDBResultSet res = new TSDBResultSet(this, this.connection.getConnector(), pSql); TSDBResultSet res = new TSDBResultSet(this, this.connection.getConnector(), pSql);
int timestampPrecision = this.connection.getConnector().getResultTimePrecision(pSql);
res.setTimestampPrecision(timestampPrecision);
res.setBatchFetch(this.connection.getBatchFetch()); res.setBatchFetch(this.connection.getBatchFetch());
return res; return res;
} }
...@@ -80,7 +81,7 @@ public class TSDBStatement extends AbstractStatement { ...@@ -80,7 +81,7 @@ public class TSDBStatement extends AbstractStatement {
if (isClosed()) { if (isClosed()) {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED);
} }
// execute query // execute query
long pSql = this.connection.getConnector().executeQuery(sql); long pSql = this.connection.getConnector().executeQuery(sql);
// if pSql is create/insert/update/delete/alter SQL // if pSql is create/insert/update/delete/alter SQL
...@@ -99,7 +100,7 @@ public class TSDBStatement extends AbstractStatement { ...@@ -99,7 +100,7 @@ public class TSDBStatement extends AbstractStatement {
if (isClosed()) { if (isClosed()) {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED);
} }
return this.resultSet; return this.resultSet;
} }
...@@ -113,14 +114,14 @@ public class TSDBStatement extends AbstractStatement { ...@@ -113,14 +114,14 @@ public class TSDBStatement extends AbstractStatement {
if (isClosed()) { if (isClosed()) {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED);
} }
if (this.connection.getConnector() == null) { if (this.connection.getConnector() == null) {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL);
} }
return this.connection; return this.connection;
} }
public void setConnection(TSDBConnection connection) { public void setConnection(TSDBConnection connection) {
this.connection = connection; this.connection = connection;
} }
......
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);
}
}
package com.taosdata.jdbc.enums;
public enum SchemalessTimestampType {
// Let the database decide
NOT_CONFIGURED,
HOURS,
MINUTES,
SECONDS,
MILLI_SECONDS,
MICRO_SECONDS,
NANO_SECONDS,
;
}
package com.taosdata.jdbc.enums; package com.taosdata.jdbc.enums;
public enum TimestampPrecision { public class TimestampPrecision {
MS, public static final int MS = 0;
US, public static final int US = 1;
NS, public static final int NS = 2;
UNKNOWN
} }
...@@ -39,7 +39,7 @@ public class RestfulDriver extends AbstractDriver { ...@@ -39,7 +39,7 @@ public class RestfulDriver extends AbstractDriver {
String port = props.getProperty(TSDBDriver.PROPERTY_KEY_PORT, "6041"); 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 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 { try {
if (!props.containsKey(TSDBDriver.PROPERTY_KEY_USER)) if (!props.containsKey(TSDBDriver.PROPERTY_KEY_USER))
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_USER_IS_REQUIRED); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_USER_IS_REQUIRED);
...@@ -50,9 +50,13 @@ public class RestfulDriver extends AbstractDriver { ...@@ -50,9 +50,13 @@ public class RestfulDriver extends AbstractDriver {
String password = URLEncoder.encode(props.getProperty(TSDBDriver.PROPERTY_KEY_PASSWORD), StandardCharsets.UTF_8.displayName()); 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 + ""; loginUrl = "http://" + props.getProperty(TSDBDriver.PROPERTY_KEY_HOST) + ":" + props.getProperty(TSDBDriver.PROPERTY_KEY_PORT) + "/rest/login/" + user + "/" + password + "";
} catch (UnsupportedEncodingException e) { } 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); String result = HttpClientPoolUtil.execute(loginUrl);
JSONObject jsonResult = JSON.parseObject(result); JSONObject jsonResult = JSON.parseObject(result);
String status = jsonResult.getString("status"); String status = jsonResult.getString("status");
...@@ -64,9 +68,9 @@ public class RestfulDriver extends AbstractDriver { ...@@ -64,9 +68,9 @@ public class RestfulDriver extends AbstractDriver {
RestfulConnection conn = new RestfulConnection(host, port, props, database, url, token); RestfulConnection conn = new RestfulConnection(host, port, props, database, url, token);
if (database != null && !database.trim().replaceAll("\\s", "").isEmpty()) { if (database != null && !database.trim().replaceAll("\\s", "").isEmpty()) {
Statement stmt = conn.createStatement(); try (Statement stmt = conn.createStatement()) {
stmt.execute("use " + database); stmt.execute("use " + database);
stmt.close(); }
} }
return conn; return conn;
} }
...@@ -75,7 +79,7 @@ public class RestfulDriver extends AbstractDriver { ...@@ -75,7 +79,7 @@ public class RestfulDriver extends AbstractDriver {
public boolean acceptsURL(String url) throws SQLException { public boolean acceptsURL(String url) throws SQLException {
if (url == null) if (url == null)
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_URL_NOT_SET); 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 @Override
......
...@@ -14,13 +14,43 @@ import java.math.BigDecimal; ...@@ -14,13 +14,43 @@ import java.math.BigDecimal;
import java.sql.*; import java.sql.*;
import java.time.Instant; import java.time.Instant;
import java.time.ZoneOffset; 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.DateTimeParseException;
import java.time.format.ResolverStyle;
import java.time.temporal.ChronoField;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.List; import java.util.List;
public class RestfulResultSet extends AbstractResultSet implements ResultSet { 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; private final Statement statement;
// data // data
private final List<List<Object>> resultSet = new ArrayList<>(); private final List<List<Object>> resultSet = new ArrayList<>();
...@@ -168,35 +198,67 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -168,35 +198,67 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
case TIMESTAMP: { case TIMESTAMP: {
Long value = row.getLong(colIndex); Long value = row.getLong(colIndex);
//TODO: this implementation has bug if the timestamp bigger than 9999_9999_9999_9 //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); return new Timestamp(value);
long epochSec = value / 1000_000L; }
long nanoAdjustment = value % 1000_000L * 1000L; if (value >= 1_0000_0000_0000_0L && value < 1_000_000_000_000_000_0l) {
return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); 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: { case UTC: {
String value = row.getString(colIndex); String value = row.getString(colIndex);
long epochSec = Timestamp.valueOf(value.substring(0, 19).replace("T", " ")).getTime() / 1000; if (value.lastIndexOf(":") > 19) {
int fractionalSec = Integer.parseInt(value.substring(20, value.length() - 5)); ZonedDateTime parse = ZonedDateTime.parse(value, rfc3339Parser);
long nanoAdjustment; long nanoAdjustment;
if (value.length() > 31) { if (value.length() > 32) {
// ns timestamp: yyyy-MM-ddTHH:mm:ss.SSSSSSSSS+0x00 // ns timestamp: yyyy-MM-ddTHH:mm:ss.SSSSSSSSS+0x:00
nanoAdjustment = fractionalSec; this.timestampPrecision = TimestampPrecision.NS;
} else if (value.length() > 28) { } else if (value.length() > 29) {
// ms timestamp: yyyy-MM-ddTHH:mm:ss.SSSSSS+0x00 // ms timestamp: yyyy-MM-ddTHH:mm:ss.SSSSSS+0x:00
nanoAdjustment = fractionalSec * 1000L; 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 { } else {
// ms timestamp: yyyy-MM-ddTHH:mm:ss.SSS+0x00 long epochSec = Timestamp.valueOf(value.substring(0, 19).replace("T", " ")).getTime() / 1000;
nanoAdjustment = fractionalSec * 1000_000L; 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: case STRING:
default: { default: {
String value = row.getString(colIndex); String value = row.getString(colIndex);
TimestampPrecision precision = Utils.guessTimestampPrecision(value); int precision = Utils.guessTimestampPrecision(value);
this.timestampPrecision = precision;
if (precision == TimestampPrecision.MS) { if (precision == TimestampPrecision.MS) {
// ms timestamp: yyyy-MM-dd HH:mm:ss.SSS // ms timestamp: yyyy-MM-dd HH:mm:ss.SSS
return row.getTimestamp(colIndex); return row.getTimestamp(colIndex);
...@@ -255,6 +317,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -255,6 +317,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
checkAvailability(columnIndex, resultSet.get(pos).size()); checkAvailability(columnIndex, resultSet.get(pos).size());
Object value = resultSet.get(pos).get(columnIndex - 1); Object value = resultSet.get(pos).get(columnIndex - 1);
wasNull = value == null;
if (value == null) if (value == null)
return null; return null;
if (value instanceof byte[]) if (value instanceof byte[])
...@@ -267,11 +330,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -267,11 +330,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
checkAvailability(columnIndex, resultSet.get(pos).size()); checkAvailability(columnIndex, resultSet.get(pos).size());
Object value = resultSet.get(pos).get(columnIndex - 1); Object value = resultSet.get(pos).get(columnIndex - 1);
if (value == null) { wasNull = value == null;
wasNull = true; if (value == null)
return false; return false;
}
wasNull = false;
if (value instanceof Boolean) if (value instanceof Boolean)
return (boolean) value; return (boolean) value;
return Boolean.parseBoolean(value.toString()); return Boolean.parseBoolean(value.toString());
...@@ -282,11 +343,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -282,11 +343,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
checkAvailability(columnIndex, resultSet.get(pos).size()); checkAvailability(columnIndex, resultSet.get(pos).size());
Object value = resultSet.get(pos).get(columnIndex - 1); Object value = resultSet.get(pos).get(columnIndex - 1);
if (value == null) { wasNull = value == null;
wasNull = true; if (value == null)
return 0; return 0;
}
wasNull = false;
long valueAsLong = Long.parseLong(value.toString()); long valueAsLong = Long.parseLong(value.toString());
if (valueAsLong == Byte.MIN_VALUE) if (valueAsLong == Byte.MIN_VALUE)
return 0; return 0;
...@@ -306,11 +365,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -306,11 +365,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
checkAvailability(columnIndex, resultSet.get(pos).size()); checkAvailability(columnIndex, resultSet.get(pos).size());
Object value = resultSet.get(pos).get(columnIndex - 1); Object value = resultSet.get(pos).get(columnIndex - 1);
if (value == null) { wasNull = value == null;
wasNull = true; if (value == null)
return 0; return 0;
}
wasNull = false;
long valueAsLong = Long.parseLong(value.toString()); long valueAsLong = Long.parseLong(value.toString());
if (valueAsLong == Short.MIN_VALUE) if (valueAsLong == Short.MIN_VALUE)
return 0; return 0;
...@@ -324,11 +381,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -324,11 +381,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
checkAvailability(columnIndex, resultSet.get(pos).size()); checkAvailability(columnIndex, resultSet.get(pos).size());
Object value = resultSet.get(pos).get(columnIndex - 1); Object value = resultSet.get(pos).get(columnIndex - 1);
if (value == null) { wasNull = value == null;
wasNull = true; if (value == null)
return 0; return 0;
}
wasNull = false;
long valueAsLong = Long.parseLong(value.toString()); long valueAsLong = Long.parseLong(value.toString());
if (valueAsLong == Integer.MIN_VALUE) if (valueAsLong == Integer.MIN_VALUE)
return 0; return 0;
...@@ -342,14 +397,20 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -342,14 +397,20 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
checkAvailability(columnIndex, resultSet.get(pos).size()); checkAvailability(columnIndex, resultSet.get(pos).size());
Object value = resultSet.get(pos).get(columnIndex - 1); Object value = resultSet.get(pos).get(columnIndex - 1);
if (value == null) { wasNull = value == null;
wasNull = true; if (value == null)
return 0; return 0;
}
wasNull = false;
if (value instanceof Timestamp) { 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; long valueAsLong = 0;
try { try {
...@@ -367,11 +428,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -367,11 +428,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
checkAvailability(columnIndex, resultSet.get(pos).size()); checkAvailability(columnIndex, resultSet.get(pos).size());
Object value = resultSet.get(pos).get(columnIndex - 1); Object value = resultSet.get(pos).get(columnIndex - 1);
if (value == null) { wasNull = value == null;
wasNull = true; if (value == null)
return 0; return 0;
}
wasNull = false;
if (value instanceof Float) if (value instanceof Float)
return (float) value; return (float) value;
if (value instanceof Double) if (value instanceof Double)
...@@ -384,11 +443,10 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -384,11 +443,10 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
checkAvailability(columnIndex, resultSet.get(pos).size()); checkAvailability(columnIndex, resultSet.get(pos).size());
Object value = resultSet.get(pos).get(columnIndex - 1); Object value = resultSet.get(pos).get(columnIndex - 1);
wasNull = value == null;
if (value == null) { if (value == null) {
wasNull = true;
return 0; return 0;
} }
wasNull = false;
if (value instanceof Double || value instanceof Float) if (value instanceof Double || value instanceof Float)
return (double) value; return (double) value;
return Double.parseDouble(value.toString()); return Double.parseDouble(value.toString());
...@@ -399,6 +457,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -399,6 +457,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
checkAvailability(columnIndex, resultSet.get(pos).size()); checkAvailability(columnIndex, resultSet.get(pos).size());
Object value = resultSet.get(pos).get(columnIndex - 1); Object value = resultSet.get(pos).get(columnIndex - 1);
wasNull = value == null;
if (value == null) if (value == null)
return null; return null;
if (value instanceof byte[]) if (value instanceof byte[])
...@@ -425,6 +484,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -425,6 +484,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
checkAvailability(columnIndex, resultSet.get(pos).size()); checkAvailability(columnIndex, resultSet.get(pos).size());
Object value = resultSet.get(pos).get(columnIndex - 1); Object value = resultSet.get(pos).get(columnIndex - 1);
wasNull = value == null;
if (value == null) if (value == null)
return null; return null;
if (value instanceof Timestamp) if (value instanceof Timestamp)
...@@ -437,6 +497,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -437,6 +497,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
checkAvailability(columnIndex, resultSet.get(pos).size()); checkAvailability(columnIndex, resultSet.get(pos).size());
Object value = resultSet.get(pos).get(columnIndex - 1); Object value = resultSet.get(pos).get(columnIndex - 1);
wasNull = value == null;
if (value == null) if (value == null)
return null; return null;
if (value instanceof Timestamp) if (value instanceof Timestamp)
...@@ -454,6 +515,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -454,6 +515,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
checkAvailability(columnIndex, resultSet.get(pos).size()); checkAvailability(columnIndex, resultSet.get(pos).size());
Object value = resultSet.get(pos).get(columnIndex - 1); Object value = resultSet.get(pos).get(columnIndex - 1);
wasNull = value == null;
if (value == null) if (value == null)
return null; return null;
if (value instanceof Timestamp) if (value instanceof Timestamp)
...@@ -470,6 +532,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -470,6 +532,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
ret = Utils.parseTimestamp(value.toString()); ret = Utils.parseTimestamp(value.toString());
} catch (Exception e) { } catch (Exception e) {
ret = null; ret = null;
wasNull = true;
} }
return ret; return ret;
} }
...@@ -485,7 +548,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -485,7 +548,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
public Object getObject(int columnIndex) throws SQLException { public Object getObject(int columnIndex) throws SQLException {
checkAvailability(columnIndex, resultSet.get(pos).size()); 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 @Override
...@@ -504,9 +569,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -504,9 +569,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
checkAvailability(columnIndex, resultSet.get(pos).size()); checkAvailability(columnIndex, resultSet.get(pos).size());
Object value = resultSet.get(pos).get(columnIndex - 1); Object value = resultSet.get(pos).get(columnIndex - 1);
wasNull = value == null;
if (value == null) if (value == null)
return null; return null;
if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte) if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte)
return new BigDecimal(Long.parseLong(value.toString())); return new BigDecimal(Long.parseLong(value.toString()));
if (value instanceof Double || value instanceof Float) if (value instanceof Double || value instanceof Float)
...@@ -663,4 +728,4 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { ...@@ -663,4 +728,4 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
return isClosed; return isClosed;
} }
} }
\ No newline at end of file
...@@ -22,7 +22,6 @@ public class RestfulStatement extends AbstractStatement { ...@@ -22,7 +22,6 @@ public class RestfulStatement extends AbstractStatement {
private final RestfulConnection conn; private final RestfulConnection conn;
private volatile RestfulResultSet resultSet; private volatile RestfulResultSet resultSet;
private volatile int affectedRows;
public RestfulStatement(RestfulConnection conn, String database) { public RestfulStatement(RestfulConnection conn, String database) {
this.conn = conn; this.conn = conn;
...@@ -73,6 +72,7 @@ public class RestfulStatement extends AbstractStatement { ...@@ -73,6 +72,7 @@ public class RestfulStatement extends AbstractStatement {
} }
this.database = sql.trim().replace("use", "").trim(); this.database = sql.trim().replace("use", "").trim();
this.conn.setCatalog(this.database); this.conn.setCatalog(this.database);
this.conn.setClientInfo(TSDBDriver.PROPERTY_KEY_DBNAME, this.database);
result = false; result = false;
} else if (SqlSyntaxValidator.isDatabaseUnspecifiedQuery(sql)) { } else if (SqlSyntaxValidator.isDatabaseUnspecifiedQuery(sql)) {
executeOneQuery(sql); executeOneQuery(sql);
...@@ -122,7 +122,7 @@ public class RestfulStatement extends AbstractStatement { ...@@ -122,7 +122,7 @@ public class RestfulStatement extends AbstractStatement {
throw TSDBError.createSQLException(resultJson.getInteger("code"), "sql: " + sql + ", desc: " + resultJson.getString("desc")); throw TSDBError.createSQLException(resultJson.getInteger("code"), "sql: " + sql + ", desc: " + resultJson.getString("desc"));
} }
this.resultSet = new RestfulResultSet(database, this, resultJson); this.resultSet = new RestfulResultSet(database, this, resultJson);
this.affectedRows = 0; this.affectedRows = -1;
return resultSet; return resultSet;
} }
...@@ -142,8 +142,9 @@ public class RestfulStatement extends AbstractStatement { ...@@ -142,8 +142,9 @@ public class RestfulStatement extends AbstractStatement {
if (head.size() != 1 || !"affected_rows".equals(head.getString(0))) if (head.size() != 1 || !"affected_rows".equals(head.getString(0)))
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE, "invalid variable: [" + head.toJSONString() + "]"); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE, "invalid variable: [" + head.toJSONString() + "]");
JSONArray data = jsonObject.getJSONArray("data"); JSONArray data = jsonObject.getJSONArray("data");
if (data != null) if (data != null) {
return data.getJSONArray(0).getInteger(0); return data.getJSONArray(0).getInteger(0);
}
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE, "invalid variable: [" + jsonObject.toJSONString() + "]"); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE, "invalid variable: [" + jsonObject.toJSONString() + "]");
} }
......
...@@ -7,10 +7,10 @@ import org.apache.http.HeaderElementIterator; ...@@ -7,10 +7,10 @@ import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.NoHttpResponseException; import org.apache.http.NoHttpResponseException;
import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*; import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
...@@ -21,21 +21,20 @@ import org.apache.http.protocol.HTTP; ...@@ -21,21 +21,20 @@ import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLException;
import java.io.IOException; import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.concurrent.TimeUnit;
public class HttpClientPoolUtil { public class HttpClientPoolUtil {
private static final String DEFAULT_CONTENT_TYPE = "application/json"; private static final String DEFAULT_CONTENT_TYPE = "application/json";
private static final int DEFAULT_MAX_RETRY_COUNT = 5; private static final int DEFAULT_MAX_RETRY_COUNT = 5;
private static final int DEFAULT_MAX_TOTAL = 50; public static final String DEFAULT_HTTP_KEEP_ALIVE = "true";
private static final int DEFAULT_MAX_PER_ROUTE = 5; public static final String DEFAULT_MAX_PER_ROUTE = "20";
private static final int DEFAULT_HTTP_KEEP_TIME = -1; private static final int DEFAULT_HTTP_KEEP_TIME = -1;
private static String isKeepAlive;
private static final ConnectionKeepAliveStrategy DEFAULT_KEEP_ALIVE_STRATEGY = (response, context) -> { private static final ConnectionKeepAliveStrategy DEFAULT_KEEP_ALIVE_STRATEGY = (response, context) -> {
HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
...@@ -55,36 +54,39 @@ public class HttpClientPoolUtil { ...@@ -55,36 +54,39 @@ public class HttpClientPoolUtil {
private static CloseableHttpClient httpClient; private static CloseableHttpClient httpClient;
static { public static void init(Integer connPoolSize, boolean keepAlive) {
if (httpClient == null) {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); synchronized (HttpClientPoolUtil.class) {
connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL); if (httpClient == null) {
connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE); isKeepAlive = keepAlive ? HTTP.CONN_KEEP_ALIVE : HTTP.CONN_CLOSE;
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
httpClient = HttpClients.custom() connectionManager.setMaxTotal(connPoolSize * 10);
.setKeepAliveStrategy(DEFAULT_KEEP_ALIVE_STRATEGY) connectionManager.setDefaultMaxPerRoute(connPoolSize);
.setConnectionManager(connectionManager) httpClient = HttpClients.custom()
.setRetryHandler((exception, executionCount, httpContext) -> executionCount < DEFAULT_MAX_RETRY_COUNT) .setKeepAliveStrategy(DEFAULT_KEEP_ALIVE_STRATEGY)
.build(); .setConnectionManager(connectionManager)
.setRetryHandler((exception, executionCount, httpContext) -> executionCount < DEFAULT_MAX_RETRY_COUNT)
.build();
}
}
}
} }
/*** execute GET request ***/ /*** execute GET request ***/
public static String execute(String uri) throws SQLException { public static String execute(String uri) throws SQLException {
HttpEntity httpEntity = null; HttpEntity httpEntity = null;
String responseBody = ""; String responseBody = "";
try { HttpRequestBase method = getRequest(uri, HttpGet.METHOD_NAME);
HttpRequestBase method = getRequest(uri, HttpGet.METHOD_NAME); HttpContext context = HttpClientContext.create();
HttpContext context = HttpClientContext.create();
CloseableHttpResponse httpResponse = httpClient.execute(method, context); try (CloseableHttpResponse httpResponse = httpClient.execute(method, context)) {
httpEntity = httpResponse.getEntity(); httpEntity = httpResponse.getEntity();
if (httpEntity != null) { if (httpEntity != null) {
responseBody = EntityUtils.toString(httpEntity, StandardCharsets.UTF_8); responseBody = EntityUtils.toString(httpEntity, StandardCharsets.UTF_8);
} }
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
e.printStackTrace();
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_Protocol_Exception, e.getMessage()); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_Protocol_Exception, e.getMessage());
} catch (IOException exception) { } catch (IOException exception) {
exception.printStackTrace();
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_IOException, exception.getMessage()); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_IOException, exception.getMessage());
} finally { } finally {
if (httpEntity != null) { if (httpEntity != null) {
...@@ -94,30 +96,27 @@ public class HttpClientPoolUtil { ...@@ -94,30 +96,27 @@ public class HttpClientPoolUtil {
return responseBody; return responseBody;
} }
/*** execute POST request ***/ /*** execute POST request ***/
public static String execute(String uri, String data, String token) throws SQLException { 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; HttpEntity httpEntity = null;
String responseBody = ""; String responseBody = "";
try { try (CloseableHttpResponse httpResponse = httpClient.execute(method, context)) {
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);
httpEntity = httpResponse.getEntity(); httpEntity = httpResponse.getEntity();
if (httpEntity == null) { if (httpEntity == null) {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_HTTP_ENTITY_IS_NULL, "httpEntity is null, sql: " + data); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_HTTP_ENTITY_IS_NULL, "httpEntity is null, sql: " + data);
} }
responseBody = EntityUtils.toString(httpEntity, StandardCharsets.UTF_8); responseBody = EntityUtils.toString(httpEntity, StandardCharsets.UTF_8);
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
e.printStackTrace();
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_Protocol_Exception, e.getMessage()); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_Protocol_Exception, e.getMessage());
} catch (IOException exception) { } catch (IOException exception) {
exception.printStackTrace();
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_IOException, exception.getMessage()); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESTFul_Client_IOException, exception.getMessage());
} finally { } finally {
if (httpEntity != null) { if (httpEntity != null) {
...@@ -148,4 +147,12 @@ public class HttpClientPoolUtil { ...@@ -148,4 +147,12 @@ public class HttpClientPoolUtil {
return method; 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
...@@ -16,9 +16,8 @@ public class TaosInfo implements TaosInfoMBean { ...@@ -16,9 +16,8 @@ public class TaosInfo implements TaosInfoMBean {
MBeanServer server = ManagementFactory.getPlatformMBeanServer(); MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName("TaosInfoMBean:name=TaosInfo"); ObjectName name = new ObjectName("TaosInfoMBean:name=TaosInfo");
server.registerMBean(TaosInfo.getInstance(), name); server.registerMBean(TaosInfo.getInstance(), name);
} catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException ignored) {
} catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { throw new RuntimeException("registerMBean failed");
e.printStackTrace();
} }
} }
......
...@@ -49,14 +49,9 @@ public class Utils { ...@@ -49,14 +49,9 @@ public class Utils {
try { try {
return parseMicroSecTimestamp(timeStampStr); return parseMicroSecTimestamp(timeStampStr);
} catch (DateTimeParseException ee) { } catch (DateTimeParseException ee) {
try { return parseNanoSecTimestamp(timeStampStr);
return parseNanoSecTimestamp(timeStampStr);
} catch (DateTimeParseException eee) {
eee.printStackTrace();
}
} }
} }
return null;
} }
private static LocalDateTime parseMilliSecTimestamp(String timeStampStr) throws DateTimeParseException { private static LocalDateTime parseMilliSecTimestamp(String timeStampStr) throws DateTimeParseException {
...@@ -199,14 +194,14 @@ public class Utils { ...@@ -199,14 +194,14 @@ public class Utils {
return timestamp.toLocalDateTime().format(milliSecFormatter); return timestamp.toLocalDateTime().format(milliSecFormatter);
} }
public static TimestampPrecision guessTimestampPrecision(String value) { public static int guessTimestampPrecision(String value) {
if (isMilliSecFormat(value)) if (isMilliSecFormat(value))
return TimestampPrecision.MS; return TimestampPrecision.MS;
if (isMicroSecFormat(value)) if (isMicroSecFormat(value))
return TimestampPrecision.US; return TimestampPrecision.US;
if (isNanoSecFormat(value)) if (isNanoSecFormat(value))
return TimestampPrecision.NS; return TimestampPrecision.NS;
return TimestampPrecision.UNKNOWN; return TimestampPrecision.MS;
} }
private static boolean isMilliSecFormat(String timestampStr) { private static boolean isMilliSecFormat(String timestampStr) {
......
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();
}
}
}
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<Thread> 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<Long> timestampList = new ArrayList<>();
for (int j = 0; j < rowsEachTable; j++) {
timestampList.add(current + i * 1000 + j);
}
pstmt.setTimestamp(0, timestampList);
ArrayList<Integer> f1List = new ArrayList<>();
for (int j = 0; j < rowsEachTable; j++) {
f1List.add(random.nextInt(100));
}
pstmt.setInt(1, f1List);
ArrayList<Integer> 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();
}
}
}
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<String> 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();
}
}
}
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();
}
}
}
...@@ -30,42 +30,6 @@ public class TSDBConnectionTest { ...@@ -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 @Test
public void prepareStatement() throws SQLException { public void prepareStatement() throws SQLException {
PreparedStatement pstmt = conn.prepareStatement("select server_status()"); PreparedStatement pstmt = conn.prepareStatement("select server_status()");
...@@ -391,13 +355,9 @@ public class TSDBConnectionTest { ...@@ -391,13 +355,9 @@ public class TSDBConnectionTest {
} }
@Test @Test
public void unwrap() { public void unwrap() throws SQLException {
try { TSDBConnection tsdbConnection = conn.unwrap(TSDBConnection.class);
TSDBConnection tsdbConnection = conn.unwrap(TSDBConnection.class); Assert.assertNotNull(tsdbConnection);
Assert.assertNotNull(tsdbConnection);
} catch (SQLException e) {
e.printStackTrace();
}
} }
@Test @Test
...@@ -406,31 +366,25 @@ public class TSDBConnectionTest { ...@@ -406,31 +366,25 @@ public class TSDBConnectionTest {
} }
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() throws SQLException {
try { Properties properties = new Properties();
Class.forName("com.taosdata.jdbc.TSDBDriver"); properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
Properties properties = new Properties(); properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/log?user=root&password=taosdata", properties);
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); // create test database for test cases
conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/log?user=root&password=taosdata", properties); try (Statement stmt = conn.createStatement()) {
// create test database for test cases stmt.execute("create database if not exists test");
try (Statement stmt = conn.createStatement()) {
stmt.execute("create database if not exists test");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} }
} }
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() throws SQLException {
try { if (conn != null) {
if (conn != null) Statement statement = conn.createStatement();
conn.close(); statement.execute("drop database if exists test");
} catch (SQLException e) { statement.close();
e.printStackTrace(); conn.close();
} }
} }
......
package com.taosdata.jdbc; package com.taosdata.jdbc;
import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import java.sql.*; import java.sql.*;
...@@ -33,7 +32,6 @@ public class TSDBDriverTest { ...@@ -33,7 +32,6 @@ public class TSDBDriverTest {
conn = DriverManager.getConnection(url); conn = DriverManager.getConnection(url);
assertNotNull("failure - connection should not be null", conn); assertNotNull("failure - connection should not be null", conn);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace();
fail("failure - should not throw Exception"); fail("failure - should not throw Exception");
} }
} }
...@@ -49,7 +47,6 @@ public class TSDBDriverTest { ...@@ -49,7 +47,6 @@ public class TSDBDriverTest {
conn = DriverManager.getConnection(jdbcUrl, connProps); conn = DriverManager.getConnection(jdbcUrl, connProps);
assertNotNull("failure - connection should not be null", conn); assertNotNull("failure - connection should not be null", conn);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace();
fail("failure - should not throw Exception"); fail("failure - should not throw Exception");
} }
} }
...@@ -65,7 +62,6 @@ public class TSDBDriverTest { ...@@ -65,7 +62,6 @@ public class TSDBDriverTest {
conn = DriverManager.getConnection(jdbcUrl, connProps); conn = DriverManager.getConnection(jdbcUrl, connProps);
assertNotNull("failure - connection should not be null", conn); assertNotNull("failure - connection should not be null", conn);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace();
fail("failure - should not throw Exception"); fail("failure - should not throw Exception");
} }
} }
...@@ -157,16 +153,8 @@ public class TSDBDriverTest { ...@@ -157,16 +153,8 @@ public class TSDBDriverTest {
} }
@Test @Test
public void getParentLogger() throws SQLFeatureNotSupportedException { public void getParentLogger() {
assertNull(new TSDBDriver().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
package com.taosdata.jdbc; package com.taosdata.jdbc;
import com.taosdata.jdbc.enums.SchemalessProtocolType;
import com.taosdata.jdbc.enums.SchemalessTimestampType;
import org.junit.Test; import org.junit.Test;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
...@@ -8,6 +10,7 @@ import java.sql.SQLException; ...@@ -8,6 +10,7 @@ import java.sql.SQLException;
import java.sql.SQLWarning; import java.sql.SQLWarning;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Properties;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
...@@ -17,116 +20,111 @@ public class TSDBJNIConnectorTest { ...@@ -17,116 +20,111 @@ public class TSDBJNIConnectorTest {
private static TSDBResultSetRowData rowData; private static TSDBResultSetRowData rowData;
@Test @Test
public void test() { public void test() throws SQLException {
try { try {
//change sleepSeconds when debugging with attach to process to find PID
try { int sleepSeconds = -1;
//change sleepSeconds when debugging with attach to process to find PID if (sleepSeconds > 0) {
int sleepSeconds = -1; RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
if (sleepSeconds>0) { String jvmName = runtimeBean.getName();
RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); long pid = Long.valueOf(jvmName.split("@")[0]);
String jvmName = runtimeBean.getName(); System.out.println("JVM PID = " + pid);
long pid = Long.valueOf(jvmName.split("@")[0]);
System.out.println("JVM PID = " + pid); Thread.sleep(sleepSeconds * 1000);
Thread.sleep(sleepSeconds*1000);
}
}
catch (Exception e) {
e.printStackTrace();
} }
} catch (Exception e) {
e.printStackTrace();
}
// init // init
TSDBJNIConnector.init("/etc/taos", null, null, null); Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_CONFIG_DIR, "/etc/taos");
// connect TSDBJNIConnector.init(properties);
TSDBJNIConnector connector = new TSDBJNIConnector();
connector.connect("127.0.0.1", 6030, null, "root", "taosdata"); // connect
TSDBJNIConnector connector = new TSDBJNIConnector();
// setup connector.connect("127.0.0.1", 6030, null, "root", "taosdata");
String setupSqlStrs[] = {"create database if not exists d precision \"us\"",
"create table if not exists d.t(ts timestamp, f int)", // setup
"create database if not exists d2", String setupSqlStrs[] = {"create database if not exists d precision \"us\"",
"create table if not exists d2.t2(ts timestamp, f int)", "create table if not exists d.t(ts timestamp, f int)",
"insert into d.t values(now+100s, 100)", "create database if not exists d2",
"insert into d2.t2 values(now+200s, 200)" "create table if not exists d2.t2(ts timestamp, f int)",
}; "insert into d.t values(now+100s, 100)",
for (String setupSqlStr : setupSqlStrs) { "insert into d2.t2 values(now+200s, 200)"
long setupSql = connector.executeQuery(setupSqlStr); };
for (String setupSqlStr : setupSqlStrs) {
assertEquals(0, connector.getResultTimePrecision(setupSql)); long setupSql = connector.executeQuery(setupSqlStr);
if (connector.isUpdateQuery(setupSql)) {
connector.freeResultSet(setupSql); assertEquals(0, connector.getResultTimePrecision(setupSql));
} if (connector.isUpdateQuery(setupSql)) {
connector.freeResultSet(setupSql);
} }
}
{ {
long sqlObj1 = connector.executeQuery("select * from d2.t2"); long sqlObj1 = connector.executeQuery("select * from d2.t2");
assertEquals(0, connector.getResultTimePrecision(sqlObj1)); assertEquals(0, connector.getResultTimePrecision(sqlObj1));
List<ColumnMetaData> columnMetaDataList = new ArrayList<>(); List<ColumnMetaData> columnMetaDataList = new ArrayList<>();
int code = connector.getSchemaMetaData(sqlObj1, columnMetaDataList); int code = connector.getSchemaMetaData(sqlObj1, columnMetaDataList);
rowData = new TSDBResultSetRowData(columnMetaDataList.size()); rowData = new TSDBResultSetRowData(columnMetaDataList.size());
assertTrue(next(connector, sqlObj1)); assertTrue(next(connector, sqlObj1));
assertEquals(0, connector.getResultTimePrecision(sqlObj1)); assertEquals(0, connector.getResultTimePrecision(sqlObj1));
connector.freeResultSet(sqlObj1); connector.freeResultSet(sqlObj1);
} }
// executeQuery // executeQuery
long pSql = connector.executeQuery("select * from d.t"); long pSql = connector.executeQuery("select * from d.t");
if (connector.isUpdateQuery(pSql)) { if (connector.isUpdateQuery(pSql)) {
connector.freeResultSet(pSql); connector.freeResultSet(pSql);
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEQUERY); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEQUERY);
} }
assertEquals(1, connector.getResultTimePrecision(pSql)); assertEquals(1, connector.getResultTimePrecision(pSql));
// get schema // get schema
List<ColumnMetaData> columnMetaDataList = new ArrayList<>(); List<ColumnMetaData> columnMetaDataList = new ArrayList<>();
int code = connector.getSchemaMetaData(pSql, columnMetaDataList); int code = connector.getSchemaMetaData(pSql, columnMetaDataList);
if (code == TSDBConstants.JNI_CONNECTION_NULL) { if (code == TSDBConstants.JNI_CONNECTION_NULL) {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL);
} }
if (code == TSDBConstants.JNI_RESULT_SET_NULL) { if (code == TSDBConstants.JNI_RESULT_SET_NULL) {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_RESULT_SET_NULL); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_RESULT_SET_NULL);
} }
if (code == TSDBConstants.JNI_NUM_OF_FIELDS_0) { if (code == TSDBConstants.JNI_NUM_OF_FIELDS_0) {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_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)); 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 { private static boolean next(TSDBJNIConnector connector, long pSql) throws SQLException {
...@@ -140,11 +138,7 @@ public class TSDBJNIConnectorTest { ...@@ -140,11 +138,7 @@ public class TSDBJNIConnectorTest {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_RESULT_SET_NULL); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_RESULT_SET_NULL);
} else if (code == TSDBConstants.JNI_NUM_OF_FIELDS_0) { } else if (code == TSDBConstants.JNI_NUM_OF_FIELDS_0) {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_NUM_OF_FIELDS_0); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_NUM_OF_FIELDS_0);
} else if (code == TSDBConstants.JNI_FETCH_END) { } else return code != TSDBConstants.JNI_FETCH_END;
return false;
} else {
return true;
}
} }
} }
...@@ -17,6 +17,7 @@ public class TSDBParameterMetaDataTest { ...@@ -17,6 +17,7 @@ public class TSDBParameterMetaDataTest {
private static PreparedStatement pstmt_select; private static PreparedStatement pstmt_select;
private static ParameterMetaData parameterMetaData_insert; private static ParameterMetaData parameterMetaData_insert;
private static ParameterMetaData parameterMetaData_select; private static ParameterMetaData parameterMetaData_select;
private static final String dbname = "test_pstmt";
@Test @Test
public void getParameterCount() throws SQLException { public void getParameterCount() throws SQLException {
...@@ -152,9 +153,9 @@ public class TSDBParameterMetaDataTest { ...@@ -152,9 +153,9 @@ public class TSDBParameterMetaDataTest {
try { try {
conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata");
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.execute("drop database if exists test_pstmt"); stmt.execute("drop database if exists " + dbname);
stmt.execute("create database if not exists test_pstmt"); stmt.execute("create database if not exists " + dbname);
stmt.execute("use test_pstmt"); 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 weather(ts timestamp, f1 int, f2 bigint, f3 float, f4 double, f5 smallint, f6 tinyint, f7 bool, f8 binary(64), f9 nchar(64)) tags(loc nchar(64))");
stmt.execute("create table t1 using weather tags('beijing')"); stmt.execute("create table t1 using weather tags('beijing')");
} }
...@@ -190,8 +191,12 @@ public class TSDBParameterMetaDataTest { ...@@ -190,8 +191,12 @@ public class TSDBParameterMetaDataTest {
pstmt_insert.close(); pstmt_insert.close();
if (pstmt_select != null) if (pstmt_select != null)
pstmt_select.close(); pstmt_select.close();
if (conn != null) if (conn != null) {
Statement statement = conn.createStatement();
statement.execute("drop database if exists " + dbname);
statement.close();
conn.close(); conn.close();
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -1233,6 +1233,7 @@ public class TSDBPreparedStatementTest { ...@@ -1233,6 +1233,7 @@ public class TSDBPreparedStatementTest {
try { try {
Statement statement = conn.createStatement(); Statement statement = conn.createStatement();
statement.execute("drop database if exists " + dbname); statement.execute("drop database if exists " + dbname);
statement.execute("drop database if exists dbtest");
statement.close(); statement.close();
if (conn != null) if (conn != null)
conn.close(); conn.close();
......
...@@ -668,8 +668,12 @@ public class TSDBResultSetTest { ...@@ -668,8 +668,12 @@ public class TSDBResultSetTest {
rs.close(); rs.close();
if (stmt != null) if (stmt != null)
stmt.close(); stmt.close();
if (conn != null) if (conn != null) {
Statement statement = conn.createStatement();
statement.execute("drop database if exists restful_test");
statement.close();
conn.close(); conn.close();
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
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<CatalogMethod> 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<CatalogMethod> 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();
}
}
}
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<CatalogMethod> 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
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;
}
}
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
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 "";
}
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 "";
}
...@@ -2,7 +2,6 @@ package com.taosdata.jdbc.cases; ...@@ -2,7 +2,6 @@ package com.taosdata.jdbc.cases;
import com.taosdata.jdbc.TSDBErrorNumbers; import com.taosdata.jdbc.TSDBErrorNumbers;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
......
...@@ -19,16 +19,14 @@ public class BatchErrorIgnoreTest { ...@@ -19,16 +19,14 @@ public class BatchErrorIgnoreTest {
IntStream.range(1, 6).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + ")").forEach(sql -> { IntStream.range(1, 6).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + ")").forEach(sql -> {
try { try {
stmt.addBatch(sql); stmt.addBatch(sql);
} catch (SQLException e) { } catch (SQLException ignored) {
e.printStackTrace();
} }
}); });
stmt.addBatch("insert into t11 values(now, 11)"); 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 -> { IntStream.range(6, 11).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + "),(now + 1s, " + (10 * i) + ")").forEach(sql -> {
try { try {
stmt.addBatch(sql); stmt.addBatch(sql);
} catch (SQLException e) { } catch (SQLException ignored) {
e.printStackTrace();
} }
}); });
stmt.addBatch("select count(*) from test.weather"); stmt.addBatch("select count(*) from test.weather");
...@@ -57,23 +55,19 @@ public class BatchErrorIgnoreTest { ...@@ -57,23 +55,19 @@ public class BatchErrorIgnoreTest {
IntStream.range(1, 6).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + ")").forEach(sql -> { IntStream.range(1, 6).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + ")").forEach(sql -> {
try { try {
stmt.addBatch(sql); stmt.addBatch(sql);
} catch (SQLException e) { } catch (SQLException ignored) {
e.printStackTrace();
} }
}); });
stmt.addBatch("insert into t11 values(now, 11)"); 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 -> { IntStream.range(6, 11).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + "),(now + 1s, " + (10 * i) + ")").forEach(sql -> {
try { try {
stmt.addBatch(sql); stmt.addBatch(sql);
} catch (SQLException e) { } catch (SQLException ignored) {
e.printStackTrace();
} }
}); });
stmt.addBatch("select count(*) from test.weather"); stmt.addBatch("select count(*) from test.weather");
results = stmt.executeBatch(); results = stmt.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -94,10 +88,10 @@ public class BatchErrorIgnoreTest { ...@@ -94,10 +88,10 @@ public class BatchErrorIgnoreTest {
} }
@Before @Before
public void before() { public void before() throws SQLException {
try { try (Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata");
Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); Statement stmt = conn.createStatement();) {
Statement stmt = conn.createStatement();
stmt.execute("use test"); stmt.execute("use test");
stmt.execute("drop table if exists weather"); stmt.execute("drop table if exists weather");
stmt.execute("create table weather (ts timestamp, f1 float) tags(t1 int)"); stmt.execute("create table weather (ts timestamp, f1 float) tags(t1 int)");
...@@ -108,37 +102,25 @@ public class BatchErrorIgnoreTest { ...@@ -108,37 +102,25 @@ public class BatchErrorIgnoreTest {
e.printStackTrace(); e.printStackTrace();
} }
}); });
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() throws SQLException {
try { try (Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata");
Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); Statement stmt = conn.createStatement()) {
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists test"); stmt.execute("drop database if exists test");
stmt.execute("create database if not exists test"); stmt.execute("create database if not exists test");
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() throws SQLException {
try { try (Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata");
Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); Statement stmt = conn.createStatement()) {
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists test"); stmt.execute("drop database if exists test");
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} }
} }
} }
...@@ -20,22 +20,20 @@ public class ConnectMultiTaosdByRestfulWithDifferentTokenTest { ...@@ -20,22 +20,20 @@ public class ConnectMultiTaosdByRestfulWithDifferentTokenTest {
private Connection conn2; private Connection conn2;
@Test @Test
public void test() { public void test() throws SQLException {
//when //when
executeSelectStatus(conn1); executeSelectStatus(conn1);
executeSelectStatus(conn2); executeSelectStatus(conn2);
executeSelectStatus(conn1); executeSelectStatus(conn1);
} }
private void executeSelectStatus(Connection connection) { private void executeSelectStatus(Connection connection) throws SQLException {
try (Statement stmt = connection.createStatement()) { try (Statement stmt = connection.createStatement()) {
ResultSet rs = stmt.executeQuery("select server_status()"); ResultSet rs = stmt.executeQuery("select server_status()");
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
Assert.assertNotNull(meta); Assert.assertNotNull(meta);
while (rs.next()) { while (rs.next()) {
} }
} catch (SQLException e) {
e.printStackTrace();
} }
} }
......
...@@ -11,7 +11,7 @@ public class DatetimeBefore1970Test { ...@@ -11,7 +11,7 @@ public class DatetimeBefore1970Test {
private Connection conn; private Connection conn;
@Test @Test
public void test() { public void test() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
// given // given
stmt.executeUpdate("insert into weather(ts) values('1969-12-31 23:59:59.999')"); stmt.executeUpdate("insert into weather(ts) values('1969-12-31 23:59:59.999')");
...@@ -45,36 +45,25 @@ public class DatetimeBefore1970Test { ...@@ -45,36 +45,25 @@ public class DatetimeBefore1970Test {
// then // then
ts = rs.getTimestamp("ts"); ts = rs.getTimestamp("ts");
Assert.assertEquals("1970-01-01 07:59:59.999", TimestampUtil.longToDatetime(ts.getTime())); Assert.assertEquals("1970-01-01 07:59:59.999", TimestampUtil.longToDatetime(ts.getTime()));
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Before @Before
public void before() { public void before() throws SQLException {
try { conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata");
conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); Statement stmt = conn.createStatement();
Statement stmt = conn.createStatement(); stmt.execute("drop database if exists test_timestamp");
stmt.execute("drop database if exists test_timestamp"); stmt.execute("create database if not exists test_timestamp keep 36500");
stmt.execute("create database if not exists test_timestamp keep 36500"); stmt.execute("use test_timestamp");
stmt.execute("use test_timestamp"); stmt.execute("create table weather(ts timestamp,f1 float)");
stmt.execute("create table weather(ts timestamp,f1 float)"); stmt.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
@After @After
public void after() { public void after() throws SQLException {
try { Statement stmt = conn.createStatement();
Statement stmt = conn.createStatement(); stmt.execute("drop database if exists test_timestamp");
stmt.execute("drop database if exists test_timestamp"); if (conn != null)
if (conn != null) conn.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
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");
}
}
}
...@@ -17,29 +17,6 @@ public class ImportTest { ...@@ -17,29 +17,6 @@ public class ImportTest {
static String host = "127.0.0.1"; static String host = "127.0.0.1";
private static long ts; 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 @Test
public void case001_insertData() throws Exception { public void case001_insertData() throws Exception {
try (Statement stmt = connection.createStatement()) { try (Statement stmt = connection.createStatement()) {
...@@ -52,28 +29,25 @@ public class ImportTest { ...@@ -52,28 +29,25 @@ public class ImportTest {
} }
@Test @Test
public void case002_checkSum() { public void case002_checkSum() throws SQLException {
Assert.assertEquals(50, select()); Assert.assertEquals(50, select());
} }
private int select() { private int select() throws SQLException {
int count = 0; int count = 0;
try (Statement stmt = connection.createStatement()) { try (Statement stmt = connection.createStatement()) {
String sql = "select * from " + dbName + "." + tName; String sql = "select * from " + dbName + "." + tName;
ResultSet rs = stmt.executeQuery(sql); ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) { while (rs.next()) {
count++; count++;
} }
rs.close(); rs.close();
} catch (SQLException e) {
e.printStackTrace();
} }
return count; return count;
} }
@Test @Test
public void case003_importData() { public void case003_importData() throws SQLException {
// 避免时间重复 // 避免时间重复
try (Statement stmt = connection.createStatement()) { try (Statement stmt = connection.createStatement()) {
StringBuilder sqlBuilder = new StringBuilder("import into ").append(dbName).append(".").append(tName).append(" values "); StringBuilder sqlBuilder = new StringBuilder("import into ").append(dbName).append(".").append(tName).append(" values ");
...@@ -84,27 +58,40 @@ public class ImportTest { ...@@ -84,27 +58,40 @@ public class ImportTest {
} }
int rows = stmt.executeUpdate(sqlBuilder.toString()); int rows = stmt.executeUpdate(sqlBuilder.toString());
assertEquals(50, rows); assertEquals(50, rows);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void case004_checkSum() { public void case004_checkSum() throws SQLException {
Assert.assertEquals(100, select()); 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 @AfterClass
public static void close() { public static void close() throws SQLException {
try { if (connection != null) {
if (connection != null) { Statement statement = connection.createStatement();
Statement statement = connection.createStatement(); statement.executeUpdate("drop database " + dbName);
statement.executeUpdate("drop database " + dbName); statement.close();
statement.close(); connection.close();
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
} }
} }
} }
package com.taosdata.jdbc.cases; package com.taosdata.jdbc.cases;
import org.junit.Assert; import org.junit.*;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters; import org.junit.runners.MethodSorters;
import java.sql.*; import java.sql.*;
...@@ -16,36 +13,32 @@ public class InsertDbwithoutUseDbTest { ...@@ -16,36 +13,32 @@ public class InsertDbwithoutUseDbTest {
private static final String host = "127.0.0.1"; private static final String host = "127.0.0.1";
private static Properties properties; private static Properties properties;
private static final Random random = new Random(System.currentTimeMillis()); private static final Random random = new Random(System.currentTimeMillis());
private static final String dbname = "inWithoutDb";
@Test @Test
public void case001() throws SQLException { public void case001() throws SQLException {
// prepare schema // prepare schema
String url = "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata"; String url = "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata";
Connection conn = DriverManager.getConnection(url, properties); Connection conn = DriverManager.getConnection(url, properties);
try (Statement stmt = conn.createStatement()) { Statement stmt = conn.createStatement();
stmt.execute("drop database if exists inWithoutDb"); stmt.execute("drop database if exists " + dbname);
stmt.execute("create database if not exists inWithoutDb"); stmt.execute("create database if not exists " + dbname);
stmt.execute("create table inWithoutDb.weather(ts timestamp, f1 int)"); stmt.execute("create table " + dbname + ".weather(ts timestamp, f1 int)");
}
conn.close(); conn.close();
// execute insert // 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); conn = DriverManager.getConnection(url, properties);
try (Statement stmt = conn.createStatement()) { stmt = conn.createStatement();
int affectedRow = stmt.executeUpdate("insert into weather(ts, f1) values(now," + random.nextInt(100) + ")"); int affectedRow = stmt.executeUpdate("insert into weather(ts, f1) values(now," + random.nextInt(100) + ")");
Assert.assertEquals(1, affectedRow); Assert.assertEquals(1, affectedRow);
boolean flag = stmt.execute("insert into weather(ts, f1) values(now + 10s," + random.nextInt(100) + ")"); boolean flag = stmt.execute("insert into weather(ts, f1) values(now + 10s," + random.nextInt(100) + ")");
Assert.assertEquals(false, flag); Assert.assertEquals(false, flag);
ResultSet rs = stmt.executeQuery("select count(*) from weather"); ResultSet rs = stmt.executeQuery("select count(*) from weather");
rs.next(); rs.next();
int count = rs.getInt("count(*)"); int count = rs.getInt("count(*)");
Assert.assertEquals(2, count); Assert.assertEquals(2, count);
} catch (SQLException e) {
e.printStackTrace();
}
conn.close(); conn.close();
} }
...@@ -54,28 +47,25 @@ public class InsertDbwithoutUseDbTest { ...@@ -54,28 +47,25 @@ public class InsertDbwithoutUseDbTest {
// prepare the schema // prepare the schema
final String url = "jdbc:TAOS-RS://" + host + ":6041/inWithoutDb?user=root&password=taosdata"; final String url = "jdbc:TAOS-RS://" + host + ":6041/inWithoutDb?user=root&password=taosdata";
Connection conn = DriverManager.getConnection(url, properties); Connection conn = DriverManager.getConnection(url, properties);
try (Statement stmt = conn.createStatement()) { Statement stmt = conn.createStatement();
stmt.execute("drop database if exists inWithoutDb"); stmt.execute("drop database if exists " + dbname);
stmt.execute("create database if not exists inWithoutDb"); stmt.execute("create database if not exists " + dbname);
stmt.execute("create table inWithoutDb.weather(ts timestamp, f1 int)"); stmt.execute("create table " + dbname + ".weather(ts timestamp, f1 int)");
} stmt.close();
conn.close();
// execute // execute
conn = DriverManager.getConnection(url, properties); stmt = conn.createStatement();
try (Statement stmt = conn.createStatement()) { int affectedRow = stmt.executeUpdate("insert into weather(ts, f1) values(now," + random.nextInt(100) + ")");
int affectedRow = stmt.executeUpdate("insert into weather(ts, f1) values(now," + random.nextInt(100) + ")"); Assert.assertEquals(1, affectedRow);
Assert.assertEquals(1, affectedRow); boolean flag = stmt.execute("insert into weather(ts, f1) values(now + 10s," + random.nextInt(100) + ")");
boolean flag = stmt.execute("insert into weather(ts, f1) values(now + 10s," + random.nextInt(100) + ")"); Assert.assertEquals(false, flag);
Assert.assertEquals(false, flag); ResultSet rs = stmt.executeQuery("select count(*) from weather");
ResultSet rs = stmt.executeQuery("select count(*) from weather"); rs.next();
rs.next(); int count = rs.getInt("count(*)");
int count = rs.getInt("count(*)"); Assert.assertEquals(2, count);
Assert.assertEquals(2, count); stmt.execute("drop database if exists " + dbname);
stmt.close();
} catch (SQLException e) { conn.close();
e.printStackTrace();
}
} }
@BeforeClass @BeforeClass
......
...@@ -427,8 +427,12 @@ public class InsertSpecialCharacterJniTest { ...@@ -427,8 +427,12 @@ public class InsertSpecialCharacterJniTest {
@AfterClass @AfterClass
public static void afterClass() throws SQLException { 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(); conn.close();
}
} }
} }
...@@ -391,8 +391,12 @@ public class InsertSpecialCharacterRestfulTest { ...@@ -391,8 +391,12 @@ public class InsertSpecialCharacterRestfulTest {
@AfterClass @AfterClass
public static void afterClass() throws SQLException { 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(); conn.close();
}
} }
} }
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();
}
}
}
...@@ -47,7 +47,7 @@ public class MicroSecondPrecisionJNITest { ...@@ -47,7 +47,7 @@ public class MicroSecondPrecisionJNITest {
Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos);
ts = rs.getLong(1); ts = rs.getLong(1);
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp2, ts);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -79,8 +79,13 @@ public class MicroSecondPrecisionJNITest { ...@@ -79,8 +79,13 @@ public class MicroSecondPrecisionJNITest {
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() {
try { 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(); conn.close();
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -23,7 +23,7 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -23,7 +23,7 @@ public class MicroSecondPrecisionRestfulTest {
private static Connection conn3; private static Connection conn3;
@Test @Test
public void testCase1() { public void testCase1() throws SQLException {
try (Statement stmt = conn1.createStatement()) { try (Statement stmt = conn1.createStatement()) {
ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather"); ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather");
rs.next(); rs.next();
...@@ -31,13 +31,11 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -31,13 +31,11 @@ public class MicroSecondPrecisionRestfulTest {
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp1, ts);
ts = rs.getLong(1); ts = rs.getLong(1);
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp1, ts);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void testCase2() { public void testCase2() throws SQLException {
try (Statement stmt = conn1.createStatement()) { try (Statement stmt = conn1.createStatement()) {
ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather"); ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather");
rs.next(); rs.next();
...@@ -49,14 +47,12 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -49,14 +47,12 @@ public class MicroSecondPrecisionRestfulTest {
Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos);
ts = rs.getLong(1); ts = rs.getLong(1);
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp2, ts);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void testCase3() { public void testCase3() throws SQLException {
try (Statement stmt = conn2.createStatement()) { try (Statement stmt = conn2.createStatement()) {
ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather"); ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather");
rs.next(); rs.next();
...@@ -65,13 +61,11 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -65,13 +61,11 @@ public class MicroSecondPrecisionRestfulTest {
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp1, ts);
ts = rs.getLong(1); ts = rs.getLong(1);
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp1, ts);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void testCase4() { public void testCase4() throws SQLException {
try (Statement stmt = conn2.createStatement()) { try (Statement stmt = conn2.createStatement()) {
ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather"); ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather");
rs.next(); rs.next();
...@@ -83,14 +77,12 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -83,14 +77,12 @@ public class MicroSecondPrecisionRestfulTest {
Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos);
ts = rs.getLong(1); ts = rs.getLong(1);
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp2, ts);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void testCase5() { public void testCase5() throws SQLException {
try (Statement stmt = conn3.createStatement()) { try (Statement stmt = conn3.createStatement()) {
ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather"); ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather");
rs.next(); rs.next();
...@@ -99,13 +91,11 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -99,13 +91,11 @@ public class MicroSecondPrecisionRestfulTest {
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp1, ts);
ts = rs.getLong(1); ts = rs.getLong(1);
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp1, ts);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void testCase6() { public void testCase6() throws SQLException {
try (Statement stmt = conn3.createStatement()) { try (Statement stmt = conn3.createStatement()) {
ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather"); ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather");
rs.next(); rs.next();
...@@ -117,9 +107,7 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -117,9 +107,7 @@ public class MicroSecondPrecisionRestfulTest {
Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos);
ts = rs.getLong(1); ts = rs.getLong(1);
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp2, ts);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
...@@ -156,13 +144,18 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -156,13 +144,18 @@ public class MicroSecondPrecisionRestfulTest {
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() {
try { 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(); conn1.close();
}
if (conn2 != null) if (conn2 != null)
conn2.close(); conn2.close();
if (conn3 != null) if (conn3 != null)
conn3.close(); conn3.close();
} catch (SQLException e) { }catch (SQLException e){
e.printStackTrace(); e.printStackTrace();
} }
} }
......
package com.taosdata.jdbc.cases; package com.taosdata.jdbc.cases;
import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
...@@ -9,8 +10,7 @@ import java.util.concurrent.TimeUnit; ...@@ -9,8 +10,7 @@ import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import static org.junit.Assert.assertNotNull;
public class MultiConnectionWithDifferentDbTest { public class MultiConnectionWithDifferentDbTest {
...@@ -26,16 +26,17 @@ public class MultiConnectionWithDifferentDbTest { ...@@ -26,16 +26,17 @@ public class MultiConnectionWithDifferentDbTest {
@Override @Override
public void run() { public void run() {
for (int j = 0; j < 10; j++) { for (int j = 0; j < 10; j++) {
queryDb();
try { try {
queryDb();
TimeUnit.SECONDS.sleep(1); TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) { } catch (InterruptedException ignored) {
e.printStackTrace(); } 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"; String url = "jdbc:TAOS-RS://" + host + ":6041/db" + i + "?user=root&password=taosdata";
try (Connection connection = DriverManager.getConnection(url)) { try (Connection connection = DriverManager.getConnection(url)) {
Statement stmt = connection.createStatement(); Statement stmt = connection.createStatement();
...@@ -54,8 +55,6 @@ public class MultiConnectionWithDifferentDbTest { ...@@ -54,8 +55,6 @@ public class MultiConnectionWithDifferentDbTest {
assertEquals(loc, loc_actual); assertEquals(loc, loc_actual);
stmt.close(); stmt.close();
} catch (SQLException e) {
e.printStackTrace();
} }
} }
}, "thread-" + i)).collect(Collectors.toList()); }, "thread-" + i)).collect(Collectors.toList());
...@@ -73,12 +72,10 @@ public class MultiConnectionWithDifferentDbTest { ...@@ -73,12 +72,10 @@ public class MultiConnectionWithDifferentDbTest {
} }
@Before @Before
public void before() { public void before() throws SQLException {
ts = System.currentTimeMillis(); ts = System.currentTimeMillis();
try { try (Connection conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata")) {
Connection conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata");
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
stmt.execute("drop database if exists " + db1); stmt.execute("drop database if exists " + db1);
stmt.execute("create database if not exists " + db1); stmt.execute("create database if not exists " + db1);
...@@ -91,8 +88,16 @@ public class MultiConnectionWithDifferentDbTest { ...@@ -91,8 +88,16 @@ public class MultiConnectionWithDifferentDbTest {
stmt.execute("use " + db2); stmt.execute("use " + db2);
stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))"); 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)"); 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) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
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() {
}
}
package com.taosdata.jdbc.cases; package com.taosdata.jdbc.cases;
import org.junit.Assert; import org.junit.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.sql.*; import java.sql.*;
import java.time.Instant; import java.time.Instant;
...@@ -17,7 +14,7 @@ public class NanoSecondTimestampJNITest { ...@@ -17,7 +14,7 @@ public class NanoSecondTimestampJNITest {
private static Connection conn; private static Connection conn;
@Test @Test
public void insertUsingLongValue() { public void insertUsingLongValue() throws SQLException {
// given // given
long ms = System.currentTimeMillis(); long ms = System.currentTimeMillis();
long ns = ms * 1000_000 + random.nextInt(1000_000); long ns = ms * 1000_000 + random.nextInt(1000_000);
...@@ -26,8 +23,6 @@ public class NanoSecondTimestampJNITest { ...@@ -26,8 +23,6 @@ public class NanoSecondTimestampJNITest {
int ret = 0; int ret = 0;
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)");
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -35,15 +30,13 @@ public class NanoSecondTimestampJNITest { ...@@ -35,15 +30,13 @@ public class NanoSecondTimestampJNITest {
} }
@Test @Test
public void insertUsingStringValue() { public void insertUsingStringValue() throws SQLException {
// given // given
// when // when
int ret = 0; int ret = 0;
try (Statement stmt = conn.createStatement()) { 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)"); 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 // then
...@@ -51,7 +44,7 @@ public class NanoSecondTimestampJNITest { ...@@ -51,7 +44,7 @@ public class NanoSecondTimestampJNITest {
} }
@Test @Test
public void insertUsingTimestampValue() { public void insertUsingTimestampValue() throws SQLException {
// given // given
long epochSec = System.currentTimeMillis() / 1000; long epochSec = System.currentTimeMillis() / 1000;
long nanoAdjustment = random.nextInt(1000_000_000); long nanoAdjustment = random.nextInt(1000_000_000);
...@@ -65,8 +58,6 @@ public class NanoSecondTimestampJNITest { ...@@ -65,8 +58,6 @@ public class NanoSecondTimestampJNITest {
pstmt.setFloat(2, 12.34f); pstmt.setFloat(2, 12.34f);
pstmt.setInt(3, 55); pstmt.setInt(3, 55);
ret = pstmt.executeUpdate(); ret = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -85,15 +76,13 @@ public class NanoSecondTimestampJNITest { ...@@ -85,15 +76,13 @@ public class NanoSecondTimestampJNITest {
stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)");
rs = stmt.executeQuery("select * from weather"); rs = stmt.executeQuery("select * from weather");
rs.next(); rs.next();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
long actual = rs.getLong(1); long actual = rs.getLong(1);
Assert.assertEquals(ms, actual); Assert.assertEquals(ns, actual);
actual = rs.getLong("ts"); actual = rs.getLong("ts");
Assert.assertEquals(ms, actual); Assert.assertEquals(ns, actual);
} }
@Test @Test
...@@ -102,13 +91,11 @@ public class NanoSecondTimestampJNITest { ...@@ -102,13 +91,11 @@ public class NanoSecondTimestampJNITest {
String timestampStr = "2021-01-01 12:00:00.123456789"; String timestampStr = "2021-01-01 12:00:00.123456789";
// when // when
ResultSet rs = null; ResultSet rs;
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('" + timestampStr + "', 12.3, 4)"); stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('" + timestampStr + "', 12.3, 4)");
rs = stmt.executeQuery("select * from weather"); rs = stmt.executeQuery("select * from weather");
rs.next(); rs.next();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -133,8 +120,6 @@ public class NanoSecondTimestampJNITest { ...@@ -133,8 +120,6 @@ public class NanoSecondTimestampJNITest {
pstmt.setFloat(2, 12.34f); pstmt.setFloat(2, 12.34f);
pstmt.setInt(3, 55); pstmt.setInt(3, 55);
pstmt.executeUpdate(); pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} }
// when // when
...@@ -142,8 +127,6 @@ public class NanoSecondTimestampJNITest { ...@@ -142,8 +127,6 @@ public class NanoSecondTimestampJNITest {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
rs = stmt.executeQuery("select * from weather"); rs = stmt.executeQuery("select * from weather");
rs.next(); rs.next();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -156,25 +139,34 @@ public class NanoSecondTimestampJNITest { ...@@ -156,25 +139,34 @@ public class NanoSecondTimestampJNITest {
} }
@Before @Before
public void before() { public void before() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.execute("drop table if exists weather"); stmt.execute("drop table if exists weather");
stmt.execute("create table weather(ts timestamp, temperature float, humidity int)"); stmt.execute("create table weather(ts timestamp, temperature float, humidity int)");
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() throws SQLException {
final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
try { conn = DriverManager.getConnection(url);
conn = DriverManager.getConnection(url); try (Statement stmt = conn.createStatement()) {
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists " + dbname); stmt.execute("drop database if exists " + dbname);
stmt.execute("create database if not exists " + dbname + " precision 'ns'"); stmt.execute("create database if not exists " + dbname + " precision 'ns'");
stmt.execute("use " + dbname); 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(); e.printStackTrace();
} }
} }
......
package com.taosdata.jdbc.cases; package com.taosdata.jdbc.cases;
import org.junit.Assert; import org.junit.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.sql.*; import java.sql.*;
import java.time.Instant; import java.time.Instant;
...@@ -17,7 +14,7 @@ public class NanoSecondTimestampRestfulTest { ...@@ -17,7 +14,7 @@ public class NanoSecondTimestampRestfulTest {
private static Connection conn; private static Connection conn;
@Test @Test
public void insertUsingLongValue() { public void insertUsingLongValue() throws SQLException {
// given // given
long ms = System.currentTimeMillis(); long ms = System.currentTimeMillis();
long ns = ms * 1000_000 + random.nextInt(1000_000); long ns = ms * 1000_000 + random.nextInt(1000_000);
...@@ -26,8 +23,6 @@ public class NanoSecondTimestampRestfulTest { ...@@ -26,8 +23,6 @@ public class NanoSecondTimestampRestfulTest {
int ret = 0; int ret = 0;
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)");
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -35,15 +30,13 @@ public class NanoSecondTimestampRestfulTest { ...@@ -35,15 +30,13 @@ public class NanoSecondTimestampRestfulTest {
} }
@Test @Test
public void insertUsingStringValue() { public void insertUsingStringValue() throws SQLException {
// given // given
// when // when
int ret = 0; int ret = 0;
try (Statement stmt = conn.createStatement()) { 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)"); 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 // then
...@@ -51,7 +44,7 @@ public class NanoSecondTimestampRestfulTest { ...@@ -51,7 +44,7 @@ public class NanoSecondTimestampRestfulTest {
} }
@Test @Test
public void insertUsingTimestampValue() { public void insertUsingTimestampValue() throws SQLException {
// given // given
long epochSec = System.currentTimeMillis() / 1000; long epochSec = System.currentTimeMillis() / 1000;
long nanoAdjustment = random.nextInt(1000_000_000); long nanoAdjustment = random.nextInt(1000_000_000);
...@@ -65,8 +58,6 @@ public class NanoSecondTimestampRestfulTest { ...@@ -65,8 +58,6 @@ public class NanoSecondTimestampRestfulTest {
pstmt.setFloat(2, 12.34f); pstmt.setFloat(2, 12.34f);
pstmt.setInt(3, 55); pstmt.setInt(3, 55);
ret = pstmt.executeUpdate(); ret = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -80,20 +71,18 @@ public class NanoSecondTimestampRestfulTest { ...@@ -80,20 +71,18 @@ public class NanoSecondTimestampRestfulTest {
long ns = ms * 1000_000L + random.nextInt(1000_000); long ns = ms * 1000_000L + random.nextInt(1000_000);
// when // when
ResultSet rs = null; ResultSet rs;
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)");
rs = stmt.executeQuery("select * from weather"); rs = stmt.executeQuery("select * from weather");
rs.next(); rs.next();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
long actual = rs.getLong(1); long actual = rs.getLong(1);
Assert.assertEquals(ms, actual); Assert.assertEquals(ns, actual);
actual = rs.getLong("ts"); actual = rs.getLong("ts");
Assert.assertEquals(ms, actual); Assert.assertEquals(ns, actual);
} }
@Test @Test
...@@ -102,13 +91,11 @@ public class NanoSecondTimestampRestfulTest { ...@@ -102,13 +91,11 @@ public class NanoSecondTimestampRestfulTest {
String timestampStr = "2021-01-01 12:00:00.123456789"; String timestampStr = "2021-01-01 12:00:00.123456789";
// when // when
ResultSet rs = null; ResultSet rs;
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('" + timestampStr + "', 12.3, 4)"); stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('" + timestampStr + "', 12.3, 4)");
rs = stmt.executeQuery("select * from weather"); rs = stmt.executeQuery("select * from weather");
rs.next(); rs.next();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -133,8 +120,6 @@ public class NanoSecondTimestampRestfulTest { ...@@ -133,8 +120,6 @@ public class NanoSecondTimestampRestfulTest {
pstmt.setFloat(2, 12.34f); pstmt.setFloat(2, 12.34f);
pstmt.setInt(3, 55); pstmt.setInt(3, 55);
pstmt.executeUpdate(); pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} }
// when // when
...@@ -142,8 +127,6 @@ public class NanoSecondTimestampRestfulTest { ...@@ -142,8 +127,6 @@ public class NanoSecondTimestampRestfulTest {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
rs = stmt.executeQuery("select * from weather"); rs = stmt.executeQuery("select * from weather");
rs.next(); rs.next();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -156,26 +139,31 @@ public class NanoSecondTimestampRestfulTest { ...@@ -156,26 +139,31 @@ public class NanoSecondTimestampRestfulTest {
} }
@Before @Before
public void before() { public void before() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.execute("drop table if exists weather"); stmt.execute("drop table if exists weather");
stmt.execute("create table weather(ts timestamp, temperature float, humidity int)"); stmt.execute("create table weather(ts timestamp, temperature float, humidity int)");
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() throws SQLException {
final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
try { conn = DriverManager.getConnection(url);
conn = DriverManager.getConnection(url); try (Statement stmt = conn.createStatement()) {
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists " + dbname); stmt.execute("drop database if exists " + dbname);
stmt.execute("create database if not exists " + dbname + " precision 'ns'"); stmt.execute("create database if not exists " + dbname + " precision 'ns'");
stmt.execute("use " + dbname); 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();
} }
} }
......
...@@ -12,15 +12,13 @@ public class NullValueInResultSetJNITest { ...@@ -12,15 +12,13 @@ public class NullValueInResultSetJNITest {
Connection conn; Connection conn;
@Test @Test
public void test() { public void test() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from weather"); ResultSet rs = stmt.executeQuery("select * from weather");
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) { while (rs.next()) {
} }
} catch (SQLException e) {
e.printStackTrace();
} }
} }
...@@ -42,18 +40,16 @@ public class NullValueInResultSetJNITest { ...@@ -42,18 +40,16 @@ public class NullValueInResultSetJNITest {
stmt.executeUpdate("insert into weather(ts, f7) values(now+7s, true)"); 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, f8) values(now+8s, 'hello')");
stmt.executeUpdate("insert into weather(ts, f9) values(now+9s, '涛思数据')"); stmt.executeUpdate("insert into weather(ts, f9) values(now+9s, '涛思数据')");
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@After @After
public void after() { public void after() throws SQLException {
try { if (conn != null) {
if (conn != null) Statement statement = conn.createStatement();
conn.close(); statement.execute("drop database if exists test_null");
} catch (SQLException e) { statement.close();
e.printStackTrace(); conn.close();
} }
} }
} }
...@@ -12,7 +12,7 @@ public class NullValueInResultSetRestfulTest { ...@@ -12,7 +12,7 @@ public class NullValueInResultSetRestfulTest {
Connection conn; Connection conn;
@Test @Test
public void test() { public void test() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from weather"); ResultSet rs = stmt.executeQuery("select * from weather");
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
...@@ -21,9 +21,6 @@ public class NullValueInResultSetRestfulTest { ...@@ -21,9 +21,6 @@ public class NullValueInResultSetRestfulTest {
Object value = rs.getObject(i); Object value = rs.getObject(i);
} }
} }
} catch (SQLException e) {
e.printStackTrace();
} }
} }
...@@ -45,18 +42,16 @@ public class NullValueInResultSetRestfulTest { ...@@ -45,18 +42,16 @@ public class NullValueInResultSetRestfulTest {
stmt.executeUpdate("insert into weather(ts, f7) values(now+7s, true)"); 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, f8) values(now+8s, 'hello')");
stmt.executeUpdate("insert into weather(ts, f9) values(now+9s, '涛思数据')"); stmt.executeUpdate("insert into weather(ts, f9) values(now+9s, '涛思数据')");
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@After @After
public void after() { public void after() throws SQLException {
try { if (conn != null) {
if (conn != null) Statement statement = conn.createStatement();
conn.close(); statement.execute("drop database if exists test_null");
} catch (SQLException e) { statement.close();
e.printStackTrace(); conn.close();
} }
} }
} }
...@@ -85,7 +85,11 @@ public class NullValueInResultSetTest { ...@@ -85,7 +85,11 @@ public class NullValueInResultSetTest {
public static void afterClass() throws SQLException { public static void afterClass() throws SQLException {
if (conn_restful != null) if (conn_restful != null)
conn_restful.close(); 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(); conn_jni.close();
}
} }
} }
...@@ -20,7 +20,7 @@ public class PreparedStatementBatchInsertRestfulTest { ...@@ -20,7 +20,7 @@ public class PreparedStatementBatchInsertRestfulTest {
private Connection conn; private Connection conn;
@Test @Test
public void test() { public void test() throws SQLException {
// given // given
long ts = System.currentTimeMillis(); long ts = System.currentTimeMillis();
List<Object[]> rows = IntStream.range(0, 10).mapToObj(i -> { List<Object[]> rows = IntStream.range(0, 10).mapToObj(i -> {
...@@ -52,7 +52,6 @@ public class PreparedStatementBatchInsertRestfulTest { ...@@ -52,7 +52,6 @@ public class PreparedStatementBatchInsertRestfulTest {
} }
pstmt.executeBatch(); pstmt.executeBatch();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace();
Assert.fail(); Assert.fail();
} }
...@@ -64,35 +63,25 @@ public class PreparedStatementBatchInsertRestfulTest { ...@@ -64,35 +63,25 @@ public class PreparedStatementBatchInsertRestfulTest {
count++; count++;
} }
Assert.assertEquals(10, count); Assert.assertEquals(10, count);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Before @Before
public void before() { public void before() throws SQLException {
try { conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata");
conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); Statement stmt = conn.createStatement();
Statement stmt = conn.createStatement(); stmt.execute("drop database if exists " + dbname);
stmt.execute("drop database if exists " + dbname); stmt.execute("create database if not exists " + dbname);
stmt.execute("create database if not exists " + dbname); stmt.execute("use " + dbname);
stmt.execute("use " + dbname); stmt.execute("create table meters(ts timestamp, current float, voltage int, phase int) tags(groupId int)");
stmt.execute("create table meters(ts timestamp, current float, voltage int, phase int) tags(groupId int)");
} catch (SQLException e) {
e.printStackTrace();
}
} }
@After @After
public void after() { public void after() throws SQLException {
try { Statement stmt = conn.createStatement();
Statement stmt = conn.createStatement(); stmt.execute("drop database if exists " + dbname);
stmt.execute("drop database if exists " + dbname); stmt.close();
stmt.close(); conn.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
...@@ -19,26 +19,22 @@ public class QueryDataTest { ...@@ -19,26 +19,22 @@ public class QueryDataTest {
static String host = "127.0.0.1"; static String host = "127.0.0.1";
@Before @Before
public void createDatabase() { public void createDatabase() throws SQLException {
try { Properties properties = new Properties();
Properties properties = new Properties(); properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root");
properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root"); properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata");
properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata"); properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
statement = connection.createStatement();
statement = connection.createStatement(); statement.executeUpdate("drop database if exists " + dbName);
statement.executeUpdate("drop database if exists " + dbName); statement.executeUpdate("create database if not exists " + dbName);
statement.executeUpdate("create database if not exists " + dbName); statement.executeUpdate("use " + dbName);
statement.executeUpdate("use " + dbName);
String createTableSql = "create table " + stbName + "(ts timestamp, name binary(64))";
String createTableSql = "create table " + stbName + "(ts timestamp, name binary(64))"; statement.executeUpdate(createTableSql);
statement.executeUpdate(createTableSql);
} catch (SQLException e) {
e.printStackTrace();
}
} }
@Test @Test
...@@ -57,15 +53,11 @@ public class QueryDataTest { ...@@ -57,15 +53,11 @@ public class QueryDataTest {
} }
@After @After
public void close() { public void close() throws SQLException {
try { if (statement != null)
if (statement != null) statement.close();
statement.close(); if (connection != null)
if (connection != null) connection.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
\ No newline at end of file
...@@ -15,19 +15,15 @@ public class ResultSetMetaShouldNotBeNullRestfulTest { ...@@ -15,19 +15,15 @@ public class ResultSetMetaShouldNotBeNullRestfulTest {
private Connection connection; private Connection connection;
@Test @Test
public void testExecuteQuery() { public void testExecuteQuery() throws SQLException {
// given // given
ResultSetMetaData metaData = null; ResultSetMetaData metaData;
int columnCount = -1; int columnCount;
// when // when
try { Statement statement = connection.createStatement();
Statement statement = connection.createStatement(); metaData = statement.executeQuery("select * from weather").getMetaData();
metaData = statement.executeQuery("select * from weather").getMetaData(); columnCount = metaData.getColumnCount();
columnCount = metaData.getColumnCount();
} catch (SQLException e) {
e.printStackTrace();
}
// then // then
Assert.assertNotNull(metaData); Assert.assertNotNull(metaData);
...@@ -35,20 +31,17 @@ public class ResultSetMetaShouldNotBeNullRestfulTest { ...@@ -35,20 +31,17 @@ public class ResultSetMetaShouldNotBeNullRestfulTest {
} }
@Test @Test
public void testExecute() { public void testExecute() throws SQLException {
// given // given
ResultSetMetaData metaData = null; ResultSetMetaData metaData;
int columnCount = -1; int columnCount;
boolean execute = false; boolean execute;
// when // when
try { Statement statement = connection.createStatement();
Statement statement = connection.createStatement(); execute = statement.execute("select * from weather");
execute = statement.execute("select * from weather"); metaData = statement.getResultSet().getMetaData();
metaData = statement.getResultSet().getMetaData(); columnCount = metaData.getColumnCount();
columnCount = metaData.getColumnCount();
} catch (SQLException e) {
e.printStackTrace();
}
// then // then
Assert.assertEquals(true, execute); Assert.assertEquals(true, execute);
...@@ -57,30 +50,22 @@ public class ResultSetMetaShouldNotBeNullRestfulTest { ...@@ -57,30 +50,22 @@ public class ResultSetMetaShouldNotBeNullRestfulTest {
} }
@Before @Before
public void before() { public void before() throws SQLException {
try { connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata");
connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); Statement stmt = connection.createStatement();
Statement stmt = connection.createStatement(); stmt.execute("drop database if exists " + dbname);
stmt.execute("drop database if exists " + dbname); stmt.execute("create database if not exists " + dbname);
stmt.execute("create database if not exists " + dbname); stmt.execute("use " + dbname);
stmt.execute("use " + dbname); stmt.execute("create table weather (ts timestamp, temperature float)");
stmt.execute("create table weather (ts timestamp, temperature float)"); stmt.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
@After @After
public void after() { public void after() throws SQLException {
try { Statement stmt = connection.createStatement();
Statement stmt = connection.createStatement(); stmt.execute("drop database if exists " + dbname);
stmt.execute("drop database if exists " + dbname); stmt.close();
stmt.close(); connection.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
...@@ -17,25 +17,20 @@ public class SelectTest { ...@@ -17,25 +17,20 @@ public class SelectTest {
String host = "127.0.0.1"; String host = "127.0.0.1";
@Before @Before
public void createDatabaseAndTable() { public void createDatabaseAndTable() throws SQLException {
try { Properties properties = new Properties();
Properties properties = new Properties(); properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root");
properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root"); properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata");
properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata"); properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
Statement stmt = connection.createStatement();
stmt.execute("drop database if exists " + dbName);
stmt.execute("create database if not exists " + dbName);
stmt.execute("create table if not exists " + dbName + "." + tName + " (ts timestamp, k int, v int)");
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
Statement stmt = connection.createStatement();
stmt.execute("drop database if exists " + dbName);
stmt.execute("create database if not exists " + dbName);
stmt.execute("create table if not exists " + dbName + "." + tName + " (ts timestamp, k int, v int)");
stmt.close();
} }
@Test @Test
...@@ -65,16 +60,12 @@ public class SelectTest { ...@@ -65,16 +60,12 @@ public class SelectTest {
} }
@After @After
public void close() { public void close() throws SQLException {
try { if (connection != null) {
if (connection != null) { Statement stmt = connection.createStatement();
Statement stmt = connection.createStatement(); stmt.executeUpdate("drop database " + dbName);
stmt.executeUpdate("drop database " + dbName); stmt.close();
stmt.close(); connection.close();
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
} }
} }
} }
package com.taosdata.jdbc.cases;
import org.junit.Test;
import java.sql.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class TaosInfoMonitorTest {
@Test
public void testCreateTooManyConnection() throws ClassNotFoundException {
Class.forName("com.taosdata.jdbc.TSDBDriver");
final String url = "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata";
List<Connection> connectionList = IntStream.range(0, 100).mapToObj(i -> {
try {
TimeUnit.MILLISECONDS.sleep(100);
return DriverManager.getConnection(url);
} catch (SQLException | InterruptedException e) {
e.printStackTrace();
}
return null;
}).collect(Collectors.toList());
connectionList.forEach(conn -> {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("show databases");
while (rs.next()) {
}
TimeUnit.MILLISECONDS.sleep(100);
} catch (SQLException | InterruptedException e) {
e.printStackTrace();
}
});
connectionList.forEach(conn -> {
try {
conn.close();
TimeUnit.MILLISECONDS.sleep(100);
} catch (SQLException | InterruptedException e) {
e.printStackTrace();
}
});
}
}
...@@ -25,7 +25,7 @@ public class TimestampPrecisionInNanoInJniTest { ...@@ -25,7 +25,7 @@ public class TimestampPrecisionInNanoInJniTest {
private static final String date4 = format.format(new Date(timestamp1 + 10L)); private static final String date4 = format.format(new Date(timestamp1 + 10L));
private static final String date2 = date1 + "123455"; private static final String date2 = date1 + "123455";
private static final String date3 = date4 + "123456"; private static final String date3 = date4 + "123456";
private static Connection conn; private static Connection conn;
...@@ -43,7 +43,7 @@ public class TimestampPrecisionInNanoInJniTest { ...@@ -43,7 +43,7 @@ public class TimestampPrecisionInNanoInJniTest {
stmt.execute("drop database if exists " + ns_timestamp_db); stmt.execute("drop database if exists " + ns_timestamp_db);
stmt.execute("create database if not exists " + ns_timestamp_db + " precision 'ns'"); stmt.execute("create database if not exists " + ns_timestamp_db + " precision 'ns'");
stmt.execute("create table " + ns_timestamp_db + ".weather(ts timestamp, ts2 timestamp, f1 int)"); stmt.execute("create table " + ns_timestamp_db + ".weather(ts timestamp, ts2 timestamp, f1 int)");
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(\"" + date3 + "\", \"" + date3 + "\", 128)"); stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(\"" + date3 + "\", \"" + date3 + "\", 128)");
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp2 + "," + timestamp2 + ", 127)"); stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp2 + "," + timestamp2 + ", 127)");
stmt.close(); stmt.close();
} }
...@@ -54,7 +54,7 @@ public class TimestampPrecisionInNanoInJniTest { ...@@ -54,7 +54,7 @@ public class TimestampPrecisionInNanoInJniTest {
stmt.execute("drop database if exists " + ns_timestamp_db); stmt.execute("drop database if exists " + ns_timestamp_db);
stmt.execute("create database if not exists " + ns_timestamp_db + " precision 'ns'"); stmt.execute("create database if not exists " + ns_timestamp_db + " precision 'ns'");
stmt.execute("create table " + ns_timestamp_db + ".weather(ts timestamp, ts2 timestamp, f1 int)"); stmt.execute("create table " + ns_timestamp_db + ".weather(ts timestamp, ts2 timestamp, f1 int)");
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(\"" + date3 + "\", \"" + date3 + "\", 128)"); stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(\"" + date3 + "\", \"" + date3 + "\", 128)");
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp2 + "," + timestamp2 + ", 127)"); stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp2 + "," + timestamp2 + ", 127)");
stmt.close(); stmt.close();
} }
...@@ -62,8 +62,12 @@ public class TimestampPrecisionInNanoInJniTest { ...@@ -62,8 +62,12 @@ public class TimestampPrecisionInNanoInJniTest {
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() {
try { try {
if (conn != null) if (conn != null) {
Statement statement = conn.createStatement();
statement.execute("drop database if exists " + ns_timestamp_db);
statement.close();
conn.close(); conn.close();
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -83,7 +87,7 @@ public class TimestampPrecisionInNanoInJniTest { ...@@ -83,7 +87,7 @@ public class TimestampPrecisionInNanoInJniTest {
int nanos = rs.getTimestamp(1).getNanos(); int nanos = rs.getTimestamp(1).getNanos();
Assert.assertEquals(ts % 1000_000_000l, nanos); Assert.assertEquals(ts % 1000_000_000l, nanos);
long test_ts = rs.getLong(1); long test_ts = rs.getLong(1);
Assert.assertEquals(ts / 1000_000l, test_ts); Assert.assertEquals(ts, test_ts);
} }
@Test @Test
...@@ -105,7 +109,7 @@ public class TimestampPrecisionInNanoInJniTest { ...@@ -105,7 +109,7 @@ public class TimestampPrecisionInNanoInJniTest {
@Test @Test
public void canImportTimestampAndQueryByEqualToInDateTypeInBothFirstAndSecondCol() { public void canImportTimestampAndQueryByEqualToInDateTypeInBothFirstAndSecondCol() {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("import into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(\"" + date1 + "123123\", \"" + date1 + "123123\", 127)"); stmt.executeUpdate("import into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(\"" + date1 + "123123\", \"" + date1 + "123123\", 127)");
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date1 + "123123'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date1 + "123123'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + date1 + "123123'"); rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + date1 + "123123'");
...@@ -139,7 +143,7 @@ public class TimestampPrecisionInNanoInJniTest { ...@@ -139,7 +143,7 @@ public class TimestampPrecisionInNanoInJniTest {
public void canImportTimestampAndQueryByEqualToInNumberTypeInBothFirstAndSecondCol() { public void canImportTimestampAndQueryByEqualToInNumberTypeInBothFirstAndSecondCol() {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
long timestamp4 = timestamp1 * 1000_000 + 123123; long timestamp4 = timestamp1 * 1000_000 + 123123;
stmt.executeUpdate("import into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp4 + ", " + timestamp4 + ", 127)"); stmt.executeUpdate("import into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp4 + ", " + timestamp4 + ", 127)");
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + timestamp4 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + timestamp4 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + timestamp4 + "'"); rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + timestamp4 + "'");
...@@ -184,300 +188,248 @@ public class TimestampPrecisionInNanoInJniTest { ...@@ -184,300 +188,248 @@ public class TimestampPrecisionInNanoInJniTest {
} }
@Test @Test
public void canSelectFirstRowFromWeatherForSecondCol() { public void canSelectFirstRowFromWeatherForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select first(ts2) from " + ns_timestamp_db + ".weather"); ResultSet rs = stmt.executeQuery("select first(ts2) from " + ns_timestamp_db + ".weather");
checkTime(timestamp2, rs); checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLargerThanInDateTypeForFirstCol() { public void canQueryLargerThanInDateTypeForFirstCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts > '" + date2 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts > '" + date2 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts > '" + date2 + "'"); rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts > '" + date2 + "'");
checkTime(timestamp3, rs); checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLargerThanInDateTypeForSecondCol() { public void canQueryLargerThanInDateTypeForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 > '" + date2 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 > '" + date2 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 > '" + date2 + "'"); rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 > '" + date2 + "'");
checkTime(timestamp3, rs); checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLargerThanInNumberTypeForFirstCol() { public void canQueryLargerThanInNumberTypeForFirstCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts > '" + timestamp2 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts > '" + timestamp2 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts > '" + timestamp2 + "'"); rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts > '" + timestamp2 + "'");
checkTime(timestamp3, rs); checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLargerThanInNumberTypeForSecondCol() { public void canQueryLargerThanInNumberTypeForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 > '" + timestamp2 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 > '" + timestamp2 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 > '" + timestamp2 + "'"); rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 > '" + timestamp2 + "'");
checkTime(timestamp3, rs); checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLargerThanOrEqualToInDateTypeForFirstCol() { public void canQueryLargerThanOrEqualToInDateTypeForFirstCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts >= '" + date2 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts >= '" + date2 + "'");
checkCount(2l, rs); checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLargerThanOrEqualToInDateTypeForSecondCol() { public void canQueryLargerThanOrEqualToInDateTypeForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 >= '" + date2 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 >= '" + date2 + "'");
checkCount(2l, rs); checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLargerThanOrEqualToInNumberTypeForFirstCol() { public void canQueryLargerThanOrEqualToInNumberTypeForFirstCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts >= '" + timestamp2 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts >= '" + timestamp2 + "'");
checkCount(2l, rs); checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLargerThanOrEqualToInNumberTypeForSecondCol() { public void canQueryLargerThanOrEqualToInNumberTypeForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 >= '" + timestamp2 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 >= '" + timestamp2 + "'");
checkCount(2l, rs); checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLessThanInDateTypeForFirstCol() { public void canQueryLessThanInDateTypeForFirstCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts < '" + date3 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts < '" + date3 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts < '" + date3 + "'"); rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts < '" + date3 + "'");
checkTime(timestamp2, rs); checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLessThanInDateTypeForSecondCol() { public void canQueryLessThanInDateTypeForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 < '" + date3 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 < '" + date3 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 < '" + date3 + "'"); rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 < '" + date3 + "'");
checkTime(timestamp2, rs); checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLessThanInNumberTypeForFirstCol() { public void canQueryLessThanInNumberTypeForFirstCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts < '" + timestamp3 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts < '" + timestamp3 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts < '" + timestamp3 + "'"); rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts < '" + timestamp3 + "'");
checkTime(timestamp2, rs); checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLessThanInNumberTypeForSecondCol() { public void canQueryLessThanInNumberTypeForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 < '" + timestamp3 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 < '" + timestamp3 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 < '" + timestamp3 + "'"); rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 < '" + timestamp3 + "'");
checkTime(timestamp2, rs); checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLessThanOrEqualToInDateTypeForFirstCol() { public void canQueryLessThanOrEqualToInDateTypeForFirstCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + date3 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + date3 + "'");
checkCount(2l, rs); checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLessThanOrEqualToInDateTypeForSecondCol() { public void canQueryLessThanOrEqualToInDateTypeForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + date3 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + date3 + "'");
checkCount(2l, rs); checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLessThanOrEqualToInNumberTypeForFirstCol() { public void canQueryLessThanOrEqualToInNumberTypeForFirstCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + timestamp3 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + timestamp3 + "'");
checkCount(2l, rs); checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryLessThanOrEqualToInNumberTypeForSecondCol() { public void canQueryLessThanOrEqualToInNumberTypeForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + timestamp3 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + timestamp3 + "'");
checkCount(2l, rs); checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryBetweenAndInDateTypeForFirstCol() { public void canQueryBetweenAndInDateTypeForFirstCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + date3 + "' AND ts > '" + date2 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + date3 + "' AND ts > '" + date2 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts <= '" + date3 + "' AND ts > '" + date2 + "'"); rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts <= '" + date3 + "' AND ts > '" + date2 + "'");
checkTime(timestamp3, rs); checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryBetweenAndInDateTypeForSecondCol() { public void canQueryBetweenAndInDateTypeForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + date3 + "' AND ts2 > '" + date2 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + date3 + "' AND ts2 > '" + date2 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <= '" + date3 + "' AND ts2 > '" + date2 + "'"); rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <= '" + date3 + "' AND ts2 > '" + date2 + "'");
checkTime(timestamp3, rs); checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryBetweenAndInNumberTypeForFirstCol() { public void canQueryBetweenAndInNumberTypeForFirstCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + timestamp3 + "' AND ts > '" + timestamp2 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + timestamp3 + "' AND ts > '" + timestamp2 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts <= '" + timestamp3 + "' AND ts > '" + timestamp2 + "'"); rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts <= '" + timestamp3 + "' AND ts > '" + timestamp2 + "'");
checkTime(timestamp3, rs); checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryBetweenAndInNumberTypeForSecondCol() { public void canQueryBetweenAndInNumberTypeForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + timestamp3 + "' AND ts2 > '" + timestamp2 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + timestamp3 + "' AND ts2 > '" + timestamp2 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <= '" + timestamp3 + "' AND ts2 > '" + timestamp2 + "'"); rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <= '" + timestamp3 + "' AND ts2 > '" + timestamp2 + "'");
checkTime(timestamp3, rs); checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryNotEqualToInDateTypeForSecondCol() { public void canQueryNotEqualToInDateTypeForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <> '" + date3 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <> '" + date3 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <> '" + date3 + "'"); rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <> '" + date3 + "'");
checkTime(timestamp2, rs); checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryNotEqualToInNumberTypeForSecondCol() { public void canQueryNotEqualToInNumberTypeForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <> '" + timestamp3 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <> '" + timestamp3 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <> '" + timestamp3 + "'"); rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <> '" + timestamp3 + "'");
checkTime(timestamp2, rs); checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryNotEqualInDateTypeForSecondCol() { public void canQueryNotEqualInDateTypeForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 != '" + date3 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 != '" + date3 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 != '" + date3 + "'"); rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 != '" + date3 + "'");
checkTime(timestamp2, rs); checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canQueryNotEqualInNumberTypeForSecondCol() { public void canQueryNotEqualInNumberTypeForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 != '" + timestamp3 + "'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 != '" + timestamp3 + "'");
checkCount(1l, rs); checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 != '" + timestamp3 + "'"); rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 != '" + timestamp3 + "'");
checkTime(timestamp2, rs); checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canInsertTimestampWithNowAndNsOffsetInBothFirstAndSecondCol(){ public void canInsertTimestampWithNowAndNsOffsetInBothFirstAndSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(now + 1000b, now - 1000b, 128)"); stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(now + 1000b, now - 1000b, 128)");
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather");
checkCount(3l, rs); checkCount(3l, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canIntervalAndSlidingAcceptNsUnitForFirstCol(){ public void canIntervalAndSlidingAcceptNsUnitForFirstCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select sum(f1) from " + ns_timestamp_db + ".weather where ts >= '" + date2 + "' and ts <= '" + date3 + "' interval(10000000b) sliding(10000000b)"); ResultSet rs = stmt.executeQuery("select sum(f1) from " + ns_timestamp_db + ".weather where ts >= '" + date2 + "' and ts <= '" + date3 + "' interval(10000000b) sliding(10000000b)");
rs.next(); rs.next();
...@@ -486,13 +438,11 @@ public class TimestampPrecisionInNanoInJniTest { ...@@ -486,13 +438,11 @@ public class TimestampPrecisionInNanoInJniTest {
rs.next(); rs.next();
sum = rs.getLong(2); sum = rs.getLong(2);
Assert.assertEquals(128l, sum); Assert.assertEquals(128l, sum);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void canIntervalAndSlidingAcceptNsUnitForSecondCol(){ public void canIntervalAndSlidingAcceptNsUnitForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select sum(f1) from " + ns_timestamp_db + ".weather where ts2 >= '" + date2 + "' and ts <= '" + date3 + "' interval(10000000b) sliding(10000000b)"); ResultSet rs = stmt.executeQuery("select sum(f1) from " + ns_timestamp_db + ".weather where ts2 >= '" + date2 + "' and ts <= '" + date3 + "' interval(10000000b) sliding(10000000b)");
rs.next(); rs.next();
...@@ -501,8 +451,6 @@ public class TimestampPrecisionInNanoInJniTest { ...@@ -501,8 +451,6 @@ public class TimestampPrecisionInNanoInJniTest {
rs.next(); rs.next();
sum = rs.getLong(2); sum = rs.getLong(2);
Assert.assertEquals(128l, sum); Assert.assertEquals(128l, sum);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
...@@ -525,46 +473,38 @@ public class TimestampPrecisionInNanoInJniTest { ...@@ -525,46 +473,38 @@ public class TimestampPrecisionInNanoInJniTest {
} }
@Test @Test
public void willAutomaticallyFillToNsUnitWithZerosForFirstCol() { public void willAutomaticallyFillToNsUnitWithZerosForFirstCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "', '" + date1 + "', 127)"); stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "', '" + date1 + "', 127)");
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date1 + "000000'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date1 + "000000'");
checkCount(1l, rs); checkCount(1l, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void willAutomaticallyFillToNsUnitWithZerosForSecondCol() { public void willAutomaticallyFillToNsUnitWithZerosForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "', '" + date1 + "', 127)"); stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "', '" + date1 + "', 127)");
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "000000'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "000000'");
checkCount(1l, rs); checkCount(1l, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void willAutomaticallyDropDigitExceedNsDigitNumberForFirstCol() { public void willAutomaticallyDropDigitExceedNsDigitNumberForFirstCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "999999999', '" + date1 + "999999999', 127)"); stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "999999999', '" + date1 + "999999999', 127)");
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date1 + "999999'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date1 + "999999'");
checkCount(1l, rs); checkCount(1l, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void willAutomaticallyDropDigitExceedNsDigitNumberForSecondCol() { public void willAutomaticallyDropDigitExceedNsDigitNumberForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "999999999', '" + date1 + "999999999', 127)"); stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "999999999', '" + date1 + "999999999', 127)");
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "999999'"); ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "999999'");
checkCount(1l, rs); checkCount(1l, rs);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
} }
package com.taosdata.jdbc.cases;
import com.taosdata.jdbc.TSDBDriver;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.After;
import org.junit.Test;
import java.sql.*;
import java.util.Properties;
import java.text.Format;
import java.text.SimpleDateFormat;
public class TimestampPrecisonInNanoRestTest {
private static final String host = "127.0.0.1";
private static final String ns_timestamp_db = "ns_precision_test";
private static final long timestamp1 = System.currentTimeMillis();
private static final long timestamp2 = timestamp1 * 1000_000 + 123455;
private static final long timestamp3 = (timestamp1 + 10) * 1000_000 + 123456;
private static final Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
private static final String date1 = format.format(new Date(timestamp1));
private static final String date4 = format.format(new Date(timestamp1 + 10L));
private static final String date2 = date1 + "123455";
private static final String date3 = date4 + "123456";
private static Connection conn;
@BeforeClass
public static void beforeClass() throws SQLException {
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
conn = DriverManager.getConnection(url, properties);
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists " + ns_timestamp_db);
stmt.execute("create database if not exists " + ns_timestamp_db + " precision 'ns'");
stmt.execute("create table " + ns_timestamp_db + ".weather(ts timestamp, ts2 timestamp, f1 int)");
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(\"" + date3 + "\", \"" + date3 + "\", 128)");
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp2 + "," + timestamp2 + ", 127)");
stmt.close();
}
@After
public void afterEach() throws SQLException {
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists " + ns_timestamp_db);
stmt.execute("create database if not exists " + ns_timestamp_db + " precision 'ns'");
stmt.execute("create table " + ns_timestamp_db + ".weather(ts timestamp, ts2 timestamp, f1 int)");
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(\"" + date3 + "\", \"" + date3 + "\", 128)");
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp2 + "," + timestamp2 + ", 127)");
stmt.close();
}
@AfterClass
public static void afterClass() {
try {
if (conn != null) {
Statement statement = conn.createStatement();
statement.execute("drop database if exists " + ns_timestamp_db);
statement.close();
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void checkCount(long count, ResultSet rs) throws SQLException {
if (count == 0) {
Assert.fail();
}
rs.next();
long test_count = rs.getLong(1);
Assert.assertEquals(count, test_count);
}
private void checkTime(long ts, ResultSet rs) throws SQLException {
rs.next();
int nanos = rs.getTimestamp(1).getNanos();
Assert.assertEquals(ts % 1000_000_000l, nanos);
long test_ts = rs.getLong(1);
Assert.assertEquals(ts, test_ts);
}
@Test
public void canInsertTimestampAndQueryByEqualToInDateTypeInBothFirstAndSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date3 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + date3 + "'");
checkTime(timestamp3, rs);
rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date3 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 = '" + date3 + "'");
checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canImportTimestampAndQueryByEqualToInDateTypeInBothFirstAndSecondCol() {
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("import into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(\"" + date1 + "123123\", \"" + date1 + "123123\", 127)");
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date1 + "123123'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + date1 + "123123'");
checkTime(timestamp1 * 1000_000l + 123123l, rs);
rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "123123'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "123123'");
checkTime(timestamp1 * 1000_000l + 123123l, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canInsertTimestampAndQueryByEqualToInNumberTypeInBothFirstAndSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + timestamp2 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + timestamp2 + "'");
checkTime(timestamp2, rs);
rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + timestamp2 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 = '" + timestamp2 + "'");
checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canImportTimestampAndQueryByEqualToInNumberTypeInBothFirstAndSecondCol() {
try (Statement stmt = conn.createStatement()) {
long timestamp4 = timestamp1 * 1000_000 + 123123;
stmt.executeUpdate("import into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(" + timestamp4 + ", " + timestamp4 + ", 127)");
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + timestamp4 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts = '" + timestamp4 + "'");
checkTime(timestamp4, rs);
rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + timestamp4 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 = '" + timestamp4 + "'");
checkTime(timestamp4, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canSelectLastRowFromWeatherForFirstCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select last(ts) from " + ns_timestamp_db + ".weather");
checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canSelectLastRowFromWeatherForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select last(ts2) from " + ns_timestamp_db + ".weather");
checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canSelectFirstRowFromWeatherForFirstCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select first(ts) from " + ns_timestamp_db + ".weather");
checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canSelectFirstRowFromWeatherForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select first(ts2) from " + ns_timestamp_db + ".weather");
checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLargerThanInDateTypeForFirstCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts > '" + date2 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts > '" + date2 + "'");
checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLargerThanInDateTypeForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 > '" + date2 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 > '" + date2 + "'");
checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLargerThanInNumberTypeForFirstCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts > '" + timestamp2 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts > '" + timestamp2 + "'");
checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLargerThanInNumberTypeForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 > '" + timestamp2 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 > '" + timestamp2 + "'");
checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLargerThanOrEqualToInDateTypeForFirstCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts >= '" + date2 + "'");
checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLargerThanOrEqualToInDateTypeForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 >= '" + date2 + "'");
checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLargerThanOrEqualToInNumberTypeForFirstCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts >= '" + timestamp2 + "'");
checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLargerThanOrEqualToInNumberTypeForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 >= '" + timestamp2 + "'");
checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLessThanInDateTypeForFirstCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts < '" + date3 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts < '" + date3 + "'");
checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLessThanInDateTypeForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 < '" + date3 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 < '" + date3 + "'");
checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLessThanInNumberTypeForFirstCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts < '" + timestamp3 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts < '" + timestamp3 + "'");
checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLessThanInNumberTypeForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 < '" + timestamp3 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 < '" + timestamp3 + "'");
checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLessThanOrEqualToInDateTypeForFirstCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + date3 + "'");
checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLessThanOrEqualToInDateTypeForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + date3 + "'");
checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLessThanOrEqualToInNumberTypeForFirstCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + timestamp3 + "'");
checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryLessThanOrEqualToInNumberTypeForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + timestamp3 + "'");
checkCount(2l, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryBetweenAndInDateTypeForFirstCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + date3 + "' AND ts > '" + date2 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts <= '" + date3 + "' AND ts > '" + date2 + "'");
checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryBetweenAndInDateTypeForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + date3 + "' AND ts2 > '" + date2 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <= '" + date3 + "' AND ts2 > '" + date2 + "'");
checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryBetweenAndInNumberTypeForFirstCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts <= '" + timestamp3 + "' AND ts > '" + timestamp2 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts from " + ns_timestamp_db + ".weather where ts <= '" + timestamp3 + "' AND ts > '" + timestamp2 + "'");
checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryBetweenAndInNumberTypeForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <= '" + timestamp3 + "' AND ts2 > '" + timestamp2 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <= '" + timestamp3 + "' AND ts2 > '" + timestamp2 + "'");
checkTime(timestamp3, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryNotEqualToInDateTypeForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <> '" + date3 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <> '" + date3 + "'");
checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryNotEqualToInNumberTypeForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 <> '" + timestamp3 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 <> '" + timestamp3 + "'");
checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryNotEqualInDateTypeForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 != '" + date3 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 != '" + date3 + "'");
checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canQueryNotEqualInNumberTypeForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 != '" + timestamp3 + "'");
checkCount(1l, rs);
rs = stmt.executeQuery("select ts2 from " + ns_timestamp_db + ".weather where ts2 != '" + timestamp3 + "'");
checkTime(timestamp2, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canInsertTimestampWithNowAndNsOffsetInBothFirstAndSecondCol() {
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(now + 1000b, now - 1000b, 128)");
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather");
checkCount(3l, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canIntervalAndSlidingAcceptNsUnitForFirstCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select sum(f1) from " + ns_timestamp_db + ".weather where ts >= '" + date2 + "' and ts <= '" + date3 + "' interval(10000000b) sliding(10000000b)");
rs.next();
long sum = rs.getLong(2);
Assert.assertEquals(127l, sum);
rs.next();
sum = rs.getLong(2);
Assert.assertEquals(128l, sum);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void canIntervalAndSlidingAcceptNsUnitForSecondCol() {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select sum(f1) from " + ns_timestamp_db + ".weather where ts2 >= '" + date2 + "' and ts <= '" + date3 + "' interval(10000000b) sliding(10000000b)");
rs.next();
long sum = rs.getLong(2);
Assert.assertEquals(127l, sum);
rs.next();
sum = rs.getLong(2);
Assert.assertEquals(128l, sum);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test(expected = SQLException.class)
public void testDataOutOfRangeExceptionForFirstCol() throws SQLException {
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(123456789012345678, 1234567890123456789, 127)");
}
}
@Test(expected = SQLException.class)
public void testDataOutOfRangeExceptionForSecondCol() throws SQLException {
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values(1234567890123456789, 123456789012345678, 127)");
}
}
@Test
public void willAutomaticallyFillToNsUnitWithZerosForFirstCol() {
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "', '" + date1 + "', 127)");
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date1 + "000000'");
checkCount(1l, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void willAutomaticallyFillToNsUnitWithZerosForSecondCol() {
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "', '" + date1 + "', 127)");
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "000000'");
checkCount(1l, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void willAutomaticallyDropDigitExceedNsDigitNumberForFirstCol() {
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "999999999', '" + date1 + "999999999', 127)");
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts = '" + date1 + "999999'");
checkCount(1l, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void willAutomaticallyDropDigitExceedNsDigitNumberForSecondCol() {
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into " + ns_timestamp_db + ".weather(ts, ts2, f1) values('" + date1 + "999999999', '" + date1 + "999999999', 127)");
ResultSet rs = stmt.executeQuery("select count(*) from " + ns_timestamp_db + ".weather where ts2 = '" + date1 + "999999'");
checkCount(1l, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
...@@ -15,7 +15,7 @@ public class UnsignedNumberJniTest { ...@@ -15,7 +15,7 @@ public class UnsignedNumberJniTest {
private static long ts; private static long ts;
@Test @Test
public void testCase001() { public void testCase001() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from us_table"); ResultSet rs = stmt.executeQuery("select * from us_table");
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
...@@ -27,13 +27,11 @@ public class UnsignedNumberJniTest { ...@@ -27,13 +27,11 @@ public class UnsignedNumberJniTest {
Assert.assertEquals("2147483647", rs.getString(4)); Assert.assertEquals("2147483647", rs.getString(4));
Assert.assertEquals("9223372036854775807", rs.getString(5)); Assert.assertEquals("9223372036854775807", rs.getString(5));
} }
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void testCase002() { public void testCase002() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from us_table"); ResultSet rs = stmt.executeQuery("select * from us_table");
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
...@@ -46,8 +44,6 @@ public class UnsignedNumberJniTest { ...@@ -46,8 +44,6 @@ public class UnsignedNumberJniTest {
Assert.assertEquals(2147483647, rs.getInt(4)); Assert.assertEquals(2147483647, rs.getInt(4));
Assert.assertEquals(9223372036854775807L, rs.getLong(5)); Assert.assertEquals(9223372036854775807L, rs.getLong(5));
} }
} catch (SQLException e) {
e.printStackTrace();
} }
} }
...@@ -140,35 +136,31 @@ public class UnsignedNumberJniTest { ...@@ -140,35 +136,31 @@ public class UnsignedNumberJniTest {
} }
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() throws SQLException {
Properties properties = new Properties(); Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
ts = System.currentTimeMillis(); ts = System.currentTimeMillis();
try { final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; conn = DriverManager.getConnection(url, properties);
conn = DriverManager.getConnection(url, properties); Statement stmt = conn.createStatement();
Statement stmt = conn.createStatement(); stmt.execute("drop database if exists unsign_jni");
stmt.execute("drop database if exists unsign_jni"); stmt.execute("create database if not exists unsign_jni");
stmt.execute("create database if not exists unsign_jni"); stmt.execute("use unsign_jni");
stmt.execute("use unsign_jni"); stmt.execute("create table us_table(ts timestamp, f1 tinyint unsigned, f2 smallint unsigned, f3 int unsigned, f4 bigint unsigned)");
stmt.execute("create table us_table(ts timestamp, f1 tinyint unsigned, f2 smallint unsigned, f3 int unsigned, f4 bigint unsigned)"); stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + ts + ", 127, 32767,2147483647, 9223372036854775807)");
stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + ts + ", 127, 32767,2147483647, 9223372036854775807)"); stmt.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() throws SQLException {
try { if (conn != null) {
if (conn != null) Statement statement = conn.createStatement();
conn.close(); statement.execute("drop database if exists unsign_jni");
} catch (SQLException e) { statement.close();
e.printStackTrace(); conn.close();
} }
} }
......
...@@ -14,9 +14,10 @@ public class UnsignedNumberRestfulTest { ...@@ -14,9 +14,10 @@ public class UnsignedNumberRestfulTest {
private static final String host = "127.0.0.1"; private static final String host = "127.0.0.1";
private static Connection conn; private static Connection conn;
private static long ts; private static long ts;
private static final String dbname = "unsign_restful";
@Test @Test
public void testCase001() { public void testCase001() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from us_table"); ResultSet rs = stmt.executeQuery("select * from us_table");
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
...@@ -28,13 +29,11 @@ public class UnsignedNumberRestfulTest { ...@@ -28,13 +29,11 @@ public class UnsignedNumberRestfulTest {
Assert.assertEquals("2147483647", rs.getString(4)); Assert.assertEquals("2147483647", rs.getString(4));
Assert.assertEquals("9223372036854775807", rs.getString(5)); Assert.assertEquals("9223372036854775807", rs.getString(5));
} }
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void testCase002() { public void testCase002() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from us_table"); ResultSet rs = stmt.executeQuery("select * from us_table");
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
...@@ -47,8 +46,6 @@ public class UnsignedNumberRestfulTest { ...@@ -47,8 +46,6 @@ public class UnsignedNumberRestfulTest {
Assert.assertEquals(2147483647, rs.getInt(4)); Assert.assertEquals(2147483647, rs.getInt(4));
Assert.assertEquals(9223372036854775807L, rs.getLong(5)); Assert.assertEquals(9223372036854775807L, rs.getLong(5));
} }
} catch (SQLException e) {
e.printStackTrace();
} }
} }
...@@ -152,9 +149,9 @@ public class UnsignedNumberRestfulTest { ...@@ -152,9 +149,9 @@ public class UnsignedNumberRestfulTest {
final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
conn = DriverManager.getConnection(url, properties); conn = DriverManager.getConnection(url, properties);
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
stmt.execute("drop database if exists unsign_restful"); stmt.execute("drop database if exists " + dbname);
stmt.execute("create database if not exists unsign_restful"); stmt.execute("create database if not exists " + dbname);
stmt.execute("use unsign_restful"); stmt.execute("use " + dbname);
stmt.execute("create table us_table(ts timestamp, f1 tinyint unsigned, f2 smallint unsigned, f3 int unsigned, f4 bigint unsigned)"); stmt.execute("create table us_table(ts timestamp, f1 tinyint unsigned, f2 smallint unsigned, f3 int unsigned, f4 bigint unsigned)");
stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + ts + ", 127, 32767,2147483647, 9223372036854775807)"); stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + ts + ", 127, 32767,2147483647, 9223372036854775807)");
stmt.close(); stmt.close();
...@@ -166,8 +163,12 @@ public class UnsignedNumberRestfulTest { ...@@ -166,8 +163,12 @@ public class UnsignedNumberRestfulTest {
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() {
try { try {
if (conn != null) if (conn != null) {
Statement statement = conn.createStatement();
statement.execute("drop database if exists " + dbname);
statement.close();
conn.close(); conn.close();
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
package com.taosdata.jdbc.cases;
import org.junit.AfterClass;
import org.junit.Test;
import java.sql.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class UseNowInsertTimestampTest {
private static String url = "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata";
@Test
public void millisec() throws SQLException {
try (Connection conn = DriverManager.getConnection(url)) {
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists test");
stmt.execute("create database if not exists test precision 'ms'");
stmt.execute("use test");
stmt.execute("create table weather(ts timestamp, f1 int)");
stmt.execute("insert into weather values(now, 1)");
ResultSet rs = stmt.executeQuery("select * from weather");
rs.next();
Timestamp ts = rs.getTimestamp("ts");
assertEquals(13, Long.toString(ts.getTime()).length());
int nanos = ts.getNanos();
assertEquals(0, nanos % 1000_000);
stmt.execute("drop database if exists test");
}
}
@Test
public void microsec() throws SQLException {
try (Connection conn = DriverManager.getConnection(url)) {
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists test");
stmt.execute("create database if not exists test precision 'us'");
stmt.execute("use test");
stmt.execute("create table weather(ts timestamp, f1 int)");
stmt.execute("insert into weather values(now, 1)");
ResultSet rs = stmt.executeQuery("select * from weather");
rs.next();
Timestamp ts = rs.getTimestamp("ts");
int nanos = ts.getNanos();
assertEquals(0, nanos % 1000);
stmt.execute("drop database if exists test");
}
}
@Test
public void nanosec() throws SQLException {
long now_time = System.currentTimeMillis() * 1000_000L + System.nanoTime() % 1000_000L;
try (Connection conn = DriverManager.getConnection(url)) {
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists test");
stmt.execute("create database if not exists test precision 'ns'");
stmt.execute("use test");
stmt.execute("create table weather(ts timestamp, f1 int)");
stmt.execute("insert into weather values(" + now_time + ", 1)");
ResultSet rs = stmt.executeQuery("select * from weather");
rs.next();
Timestamp ts = rs.getTimestamp("ts");
int nanos = ts.getNanos();
assertTrue(nanos % 1000 != 0);
stmt.execute("drop database if exists test");
}
}
@AfterClass
public static void afterClass() {
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
stmt.execute("drop database if exists test");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package com.taosdata.jdbc.cases; package com.taosdata.jdbc.confprops;
import com.taosdata.jdbc.TSDBDriver; import com.taosdata.jdbc.TSDBDriver;
...@@ -19,26 +19,22 @@ public class BadLocaleSettingTest { ...@@ -19,26 +19,22 @@ public class BadLocaleSettingTest {
private static Connection conn; private static Connection conn;
@Test @Test
public void canSetLocale() { public void canSetLocale() throws SQLException {
try { Properties properties = new Properties();
Properties properties = new Properties(); properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; conn = DriverManager.getConnection(url, properties);
conn = DriverManager.getConnection(url, properties); Statement stmt = conn.createStatement();
Statement stmt = conn.createStatement(); stmt.execute("drop database if exists " + dbName);
stmt.execute("drop database if exists " + dbName); stmt.execute("create database if not exists " + dbName);
stmt.execute("create database if not exists " + dbName); stmt.execute("use " + dbName);
stmt.execute("use " + dbName); stmt.execute("drop table if exists weather");
stmt.execute("drop table if exists weather"); stmt.execute("create table weather(ts timestamp, temperature float, humidity int)");
stmt.execute("create table weather(ts timestamp, temperature float, humidity int)"); stmt.executeUpdate("insert into weather values(1624071506435, 12.3, 4)");
stmt.executeUpdate("insert into weather values(1624071506435, 12.3, 4)"); stmt.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
@BeforeClass @BeforeClass
...@@ -48,12 +44,12 @@ public class BadLocaleSettingTest { ...@@ -48,12 +44,12 @@ public class BadLocaleSettingTest {
} }
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() throws SQLException {
try { if (conn != null) {
if (conn != null) Statement statement = conn.createStatement();
conn.close(); statement.execute("drop database " + dbName);
} catch (SQLException e) { statement.close();
e.printStackTrace(); conn.close();
} }
} }
} }
\ No newline at end of file
package com.taosdata.jdbc.confprops;
import org.junit.*;
import org.junit.runners.MethodSorters;
import java.sql.*;
import java.util.Random;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class BatchFetchTest {
private static String host = "127.0.0.1";
private long rowFetchCost, batchFetchCost;
@Test
public void case01_rowFetch() throws SQLException {
String url = "jdbc:TAOS://" + host + ":6030/test?user=root&password=taosdata";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
boolean batchfetch = Boolean.parseBoolean(conn.getClientInfo("batchfetch"));
Assert.assertFalse(batchfetch);
long start = System.currentTimeMillis();
ResultSet rs = stmt.executeQuery("select * from weather");
while (rs.next()) {
}
long end = System.currentTimeMillis();
rowFetchCost = end - start;
}
}
@Test
public void case02_batchFetch() throws SQLException {
String url = "jdbc:TAOS://" + host + ":6030/test?user=root&password=taosdata&batchfetch=true";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
boolean batchfetch = Boolean.parseBoolean(conn.getClientInfo("batchfetch"));
Assert.assertTrue(batchfetch);
long start = System.currentTimeMillis();
ResultSet rs = stmt.executeQuery("select * from weather");
while (rs.next()) {
}
long end = System.currentTimeMillis();
batchFetchCost = end - start;
}
}
@Test
public void case03_batchFetchFastThanRowFetch() {
Assert.assertTrue(rowFetchCost - batchFetchCost >= 0);
}
@BeforeClass
public static void beforeClass() throws SQLException {
String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
stmt.execute("drop database if exists test");
stmt.execute("create database if not exists test");
stmt.execute("use test");
stmt.execute("create table weather(ts timestamp, f int) tags(t int)");
for (int i = 0; i < 1000; i++) {
stmt.execute(generateSql(100, 100));
}
}
}
private static String generateSql(int tableSize, int valueSize) {
Random random = new Random(System.currentTimeMillis());
StringBuilder builder = new StringBuilder("insert into ");
for (int i = 0; i < tableSize; i++) {
builder.append("t" + i).append(" using weather tags(").append(random.nextInt(100)).append(") values");
for (int j = 0; j < valueSize; j++) {
builder.append(" (now + ").append(i).append("s, ").append(random.nextInt(100)).append(")");
}
}
return builder.toString();
}
@AfterClass
public static void afterClass(){
String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
stmt.execute("drop database if exists test");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package com.taosdata.jdbc.confprops;
import com.taosdata.jdbc.TSDBDriver;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Test;
import java.sql.*;
import java.util.Properties;
public class CharsetTest {
private static final String host = "127.0.0.1";
@Test
public void test() throws SQLException {
// given
String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
Properties props = new Properties();
props.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
try (Connection conn = DriverManager.getConnection(url, props);
Statement stmt = conn.createStatement()) {
// when
stmt.execute("drop database if exists test");
stmt.execute("create database if not exists test");
stmt.execute("use test");
stmt.execute("create table weather(ts timestamp, temperature nchar(10))");
stmt.execute("insert into weather values(now, '北京')");
// then
ResultSet rs = stmt.executeQuery("select * from weather");
while (rs.next()) {
Object value = rs.getObject("temperature");
Assert.assertTrue(value instanceof String);
Assert.assertEquals("北京", value.toString());
}
}
}
@AfterClass
public static void afterClass(){
String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
Properties props = new Properties();
props.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
try (Connection conn = DriverManager.getConnection(url, props);
Statement stmt = conn.createStatement()) {
stmt.execute("drop database if exists test");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package com.taosdata.jdbc.confprops;
import org.junit.Assert;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class HttpKeepAliveTest {
private static final String host = "127.0.0.1";
@Test
public void test() throws SQLException {
//given
int multi = 4000;
AtomicInteger exceptionCount = new AtomicInteger();
//when
Properties props = new Properties();
props.setProperty("httpKeepAlive", "false");
props.setProperty("httpPoolSize", "20");
Connection connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata", props);
List<Thread> threads = IntStream.range(0, multi).mapToObj(i -> new Thread(
() -> {
try (Statement stmt = connection.createStatement()) {
stmt.execute("insert into log.tb_not_exists values(now, 1)");
stmt.execute("select last(*) from log.dn");
} catch (SQLException throwables) {
exceptionCount.getAndIncrement();
}
}
)).collect(Collectors.toList());
threads.forEach(Thread::start);
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//then
Assert.assertEquals(multi, exceptionCount.get());
}
}
package com.taosdata.jdbc.confprops;
import org.junit.Assert;
import org.junit.Test;
import java.sql.*;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class TaosInfoMonitorTest {
private static final String host = "127.0.0.1";
private Random random = new Random(System.currentTimeMillis());
@Test
public void testCreateTooManyConnection() throws InterruptedException {
List<Thread> threads = IntStream.range(1, 11).mapToObj(i -> new Thread(() -> {
final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
int connSize = random.nextInt(10);
for (int j = 0; j < connSize; j++) {
try {
Connection conn = DriverManager.getConnection(url);
TimeUnit.MILLISECONDS.sleep(random.nextInt(3000));
int stmtSize = random.nextInt(100);
for (int k = 0; k < stmtSize; k++) {
Statement stmt = conn.createStatement();
TimeUnit.MILLISECONDS.sleep(random.nextInt(3000));
ResultSet rs = stmt.executeQuery("show databases");
while (rs.next()) {
}
rs.close();
stmt.close();
}
} catch (SQLException | InterruptedException throwables) {
Assert.fail();
}
}
}, "thread-" + i)).collect(Collectors.toList());
threads.forEach(Thread::start);
for (Thread thread : threads) {
thread.join();
}
}
}
package com.taosdata.jdbc.cases; package com.taosdata.jdbc.confprops;
import com.taosdata.jdbc.TSDBDriver; import com.taosdata.jdbc.TSDBDriver;
import org.junit.Test; import org.junit.Test;
...@@ -29,7 +29,7 @@ public class TimeZoneTest { ...@@ -29,7 +29,7 @@ public class TimeZoneTest {
} }
@Test @Test
public void taosTimeZone() { public void taosTimeZone() throws SQLException {
// given // given
Properties props = new Properties(); Properties props = new Properties();
props.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); props.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
...@@ -39,7 +39,7 @@ public class TimeZoneTest { ...@@ -39,7 +39,7 @@ public class TimeZoneTest {
Statement stmt = connection.createStatement(); Statement stmt = connection.createStatement();
stmt.execute("drop database if exists timezone_test"); stmt.execute("drop database if exists timezone_test");
stmt.execute("create database if not exists timezone_test keep 365000"); stmt.execute("create database if not exists timezone_test keep 36500");
stmt.execute("use timezone_test"); stmt.execute("use timezone_test");
stmt.execute("create table weather(ts timestamp, temperature float)"); stmt.execute("create table weather(ts timestamp, temperature float)");
...@@ -51,7 +51,7 @@ public class TimeZoneTest { ...@@ -51,7 +51,7 @@ public class TimeZoneTest {
System.out.println("ts: " + ts.getTime() + "," + ts); System.out.println("ts: " + ts.getTime() + "," + ts);
} }
stmt.execute("insert into timezone_test.weather(ts, temperature, humidity) values('1970-01-02 00:00:00', 1.0, 2.0)"); stmt.execute("insert into timezone_test.weather(ts, temperature) values('1970-01-02 00:00:00', 1.0)");
rs = stmt.executeQuery("select * from timezone_test.weather"); rs = stmt.executeQuery("select * from timezone_test.weather");
while (rs.next()) { while (rs.next()) {
...@@ -63,8 +63,6 @@ public class TimeZoneTest { ...@@ -63,8 +63,6 @@ public class TimeZoneTest {
stmt.execute("drop database if exists timezone_test"); stmt.execute("drop database if exists timezone_test");
stmt.close(); stmt.close();
} catch (SQLException e) {
e.printStackTrace();
} }
} }
......
package com.taosdata.jdbc.confprops;
import com.taosdata.jdbc.TSDBDriver;
import org.junit.*;
import java.sql.*;
import java.time.Instant;
import java.util.Calendar;
import java.util.Properties;
public class TimestampFormatTest {
private static final String host = "127.0.0.1";
private long ts = Instant.now().toEpochMilli();
private Connection conn;
@Test
public void string() throws SQLException {
// given
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
// when
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
// then
String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT);
Assert.assertEquals("STRING", actual);
ResultSet rs = stmt.executeQuery("select * from test.weather");
while (rs.next()) {
String value = rs.getString("ts");
String expect = new Timestamp(ts).toString();
Assert.assertEquals(expect, value);
}
}
}
@Test
public void stringInProperties() throws SQLException {
// given
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
// when
String timestampFormat = "STRING";
Properties props = new Properties();
props.setProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, timestampFormat);
try (Connection conn = DriverManager.getConnection(url, props);
Statement stmt = conn.createStatement()) {
// then
String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT);
Assert.assertEquals(timestampFormat, actual);
ResultSet rs = stmt.executeQuery("select * from test.weather");
while (rs.next()) {
String value = rs.getString("ts");
String expect = new Timestamp(ts).toString();
Assert.assertEquals(expect, value);
}
}
}
@Test
public void timestampInUrl() throws SQLException {
// given
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata&timestampFormat=";
String timestampFormat = "TIMESTAMP";
// when
try (Connection conn = DriverManager.getConnection(url + timestampFormat);
Statement stmt = conn.createStatement()) {
// then
String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT);
Assert.assertEquals(timestampFormat, actual);
ResultSet rs = stmt.executeQuery("select * from test.weather");
while (rs.next()) {
Object value = rs.getObject("ts");
String expect = new Timestamp(ts).toString();
Assert.assertEquals(expect, value.toString());
}
}
}
@Test
public void timestampInProperties() throws SQLException {
// given
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
String timestampFormat = "TIMESTAMP";
// when
Properties props = new Properties();
props.setProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, timestampFormat);
try (Connection conn = DriverManager.getConnection(url, props);
Statement stmt = conn.createStatement()) {
// then
String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT);
Assert.assertEquals(timestampFormat, actual);
ResultSet rs = stmt.executeQuery("select * from test.weather");
while (rs.next()) {
Object value = rs.getObject("ts");
String expect = new Timestamp(ts).toString();
Assert.assertEquals(expect, value.toString());
}
}
}
@Test
public void utcInUrl() throws SQLException {
// given
String timestampFormat = "UTC";
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata&timestampFormat=" + timestampFormat;
// when & then
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT);
Assert.assertEquals(timestampFormat, actual);
ResultSet rs = stmt.executeQuery("select * from test.weather");
while (rs.next()) {
Object value = rs.getObject("ts");
Assert.assertTrue(value instanceof Timestamp);
String expect = new Timestamp(ts).toString();
Assert.assertEquals(expect, value.toString());
}
}
}
@Test
public void utcInProperties() throws SQLException {
// given
String timestampFormat = "UTC";
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
// when
Properties props = new Properties();
props.setProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, timestampFormat);
try (Connection conn = DriverManager.getConnection(url, props);
Statement stmt = conn.createStatement()) {
// then
String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT);
Assert.assertEquals(timestampFormat, actual);
ResultSet rs = stmt.executeQuery("select * from test.weather");
while (rs.next()) {
Object value = rs.getObject("ts");
Assert.assertTrue(value instanceof Timestamp);
String expect = new Timestamp(ts).toString();
Assert.assertEquals(expect, value.toString());
}
}
}
@Before
public void before() throws SQLException {
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists test");
stmt.execute("create database if not exists test");
stmt.execute("use test");
stmt.execute("create table weather(ts timestamp, temperature nchar(10))");
stmt.execute("insert into weather values(" + ts + ", '北京')");
stmt.close();
}
@After
public void after() {
try {
if (null != conn) {
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists test");
stmt.close();
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
...@@ -33,7 +33,6 @@ public class DatabaseSpecifiedTest { ...@@ -33,7 +33,6 @@ public class DatabaseSpecifiedTest {
String loc = rs.getString("loc"); String loc = rs.getString("loc");
assertEquals("beijing", loc); assertEquals("beijing", loc);
} }
connection.close();
} }
@Before @Before
...@@ -59,8 +58,12 @@ public class DatabaseSpecifiedTest { ...@@ -59,8 +58,12 @@ public class DatabaseSpecifiedTest {
@After @After
public void after() { public void after() {
try { try {
if (connection != null) if (connection != null) {
Statement statement = connection.createStatement();
statement.execute("drop database if exists " + dbname);
statement.close();
connection.close(); connection.close();
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -23,14 +23,12 @@ public class RestfulConnectionTest { ...@@ -23,14 +23,12 @@ public class RestfulConnectionTest {
} }
@Test @Test
public void createStatement() { public void createStatement() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select server_status()"); ResultSet rs = stmt.executeQuery("select server_status()");
rs.next(); rs.next();
int status = rs.getInt("server_status()"); int status = rs.getInt("server_status()");
assertEquals(1, status); assertEquals(1, status);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
...@@ -359,13 +357,9 @@ public class RestfulConnectionTest { ...@@ -359,13 +357,9 @@ public class RestfulConnectionTest {
} }
@Test @Test
public void unwrap() { public void unwrap() throws SQLException {
try { RestfulConnection restfulConnection = conn.unwrap(RestfulConnection.class);
RestfulConnection restfulConnection = conn.unwrap(RestfulConnection.class); Assert.assertNotNull(restfulConnection);
Assert.assertNotNull(restfulConnection);
} catch (SQLException e) {
e.printStackTrace();
}
} }
@Test @Test
...@@ -388,12 +382,12 @@ public class RestfulConnectionTest { ...@@ -388,12 +382,12 @@ public class RestfulConnectionTest {
} }
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() throws SQLException {
try { if (conn != null) {
if (conn != null) Statement statement = conn.createStatement();
conn.close(); statement.execute("drop database if exists test");
} catch (SQLException e) { statement.close();
e.printStackTrace(); conn.close();
} }
} }
......
...@@ -1085,30 +1085,26 @@ public class RestfulDatabaseMetaDataTest { ...@@ -1085,30 +1085,26 @@ public class RestfulDatabaseMetaDataTest {
} }
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() throws SQLException {
try { Properties properties = new Properties();
Class.forName("com.taosdata.jdbc.rs.RestfulDriver"); properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
Properties properties = new Properties(); properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); connection = DriverManager.getConnection(url, properties);
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); Statement stmt = connection.createStatement();
connection = DriverManager.getConnection(url, properties); stmt.execute("drop database if exists log");
metaData = connection.getMetaData().unwrap(RestfulDatabaseMetaData.class); stmt.execute("create database if not exists log precision 'us'");
} catch (ClassNotFoundException e) { stmt.execute("use log");
e.printStackTrace(); stmt.execute("create table dn (ts TIMESTAMP,cpu_taosd FLOAT,cpu_system FLOAT,cpu_cores INT,mem_taosd FLOAT,mem_system FLOAT,mem_total INT,disk_used FLOAT,disk_total INT,band_speed FLOAT,io_read FLOAT,io_write FLOAT,req_http INT,req_select INT,req_insert INT) TAGS (dnodeid INT,fqdn BINARY(128))");
} catch (SQLException e) { stmt.execute("insert into dn1 using dn tags(1,'a') (ts) values(now)");
e.printStackTrace();
} metaData = connection.getMetaData().unwrap(RestfulDatabaseMetaData.class);
} }
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() throws SQLException {
try { if (connection != null)
if (connection != null) connection.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
\ No newline at end of file
...@@ -12,25 +12,26 @@ public class RestfulJDBCTest { ...@@ -12,25 +12,26 @@ public class RestfulJDBCTest {
private static final String host = "127.0.0.1"; private static final String host = "127.0.0.1";
private static final Random random = new Random(System.currentTimeMillis()); private static final Random random = new Random(System.currentTimeMillis());
private static Connection connection; private static Connection connection;
private static final String dbname = "restful_test";
@Test @Test
public void testCase001() throws SQLException { public void testCase001() throws SQLException {
// given // given
String sql = "drop database if exists restful_test"; String sql = "drop database if exists " + dbname;
// when // when
boolean execute = execute(connection, sql); boolean execute = execute(connection, sql);
// then // then
Assert.assertFalse(execute); Assert.assertFalse(execute);
// given // given
sql = "create database if not exists restful_test"; sql = "create database if not exists " + dbname;
// when // when
execute = execute(connection, sql); execute = execute(connection, sql);
// then // then
Assert.assertFalse(execute); Assert.assertFalse(execute);
// given // given
sql = "use restful_test"; sql = "use " + dbname;
// when // when
execute = execute(connection, sql); execute = execute(connection, sql);
// then // then
...@@ -40,7 +41,7 @@ public class RestfulJDBCTest { ...@@ -40,7 +41,7 @@ public class RestfulJDBCTest {
@Test @Test
public void testCase002() throws SQLException { public void testCase002() throws SQLException {
// given // given
String sql = "create table weather(ts timestamp, temperature float, humidity int) tags(location nchar(64), groupId int)"; String sql = "create table " + dbname + ".weather(ts timestamp, temperature float, humidity int) tags(location nchar(64), groupId int)";
// when // when
boolean execute = execute(connection, sql); boolean execute = execute(connection, sql);
// then // then
...@@ -51,7 +52,7 @@ public class RestfulJDBCTest { ...@@ -51,7 +52,7 @@ public class RestfulJDBCTest {
public void testCase004() throws SQLException { public void testCase004() throws SQLException {
for (int i = 1; i <= 100; i++) { for (int i = 1; i <= 100; i++) {
// given // given
String sql = "create table t" + i + " using weather tags('beijing', '" + i + "')"; String sql = "create table " + dbname + ".t" + i + " using " + dbname + ".weather tags('beijing', '" + i + "')";
// when // when
boolean execute = execute(connection, sql); boolean execute = execute(connection, sql);
// then // then
...@@ -67,7 +68,7 @@ public class RestfulJDBCTest { ...@@ -67,7 +68,7 @@ public class RestfulJDBCTest {
// given // given
long currentTimeMillis = System.currentTimeMillis(); long currentTimeMillis = System.currentTimeMillis();
String sql = "insert into t" + j + " values(" + currentTimeMillis + "," + (random.nextFloat() * 50) + "," + random.nextInt(100) + ")"; String sql = "insert into " + dbname + ".t" + j + " values(" + currentTimeMillis + "," + (random.nextFloat() * 50) + "," + random.nextInt(100) + ")";
// when // when
int affectRows = executeUpdate(connection, sql); int affectRows = executeUpdate(connection, sql);
// then // then
...@@ -82,7 +83,7 @@ public class RestfulJDBCTest { ...@@ -82,7 +83,7 @@ public class RestfulJDBCTest {
@Test @Test
public void testCase006() throws SQLException { public void testCase006() throws SQLException {
// given // given
String sql = "select * from weather"; String sql = "select * from " + dbname + ".weather";
// when // when
ResultSet rs = executeQuery(connection, sql); ResultSet rs = executeQuery(connection, sql);
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
...@@ -101,7 +102,7 @@ public class RestfulJDBCTest { ...@@ -101,7 +102,7 @@ public class RestfulJDBCTest {
@Test @Test
public void testCase007() throws SQLException { public void testCase007() throws SQLException {
// given // given
String sql = "drop database restful_test"; String sql = "drop database " + dbname;
// when // when
boolean execute = execute(connection, sql); boolean execute = execute(connection, sql);
...@@ -142,7 +143,7 @@ public class RestfulJDBCTest { ...@@ -142,7 +143,7 @@ public class RestfulJDBCTest {
public static void afterClass() throws SQLException { public static void afterClass() throws SQLException {
if (connection != null) { if (connection != null) {
Statement stmt = connection.createStatement(); Statement stmt = connection.createStatement();
stmt.execute("drop database if exists restful_test"); stmt.execute("drop database if exists " + dbname);
stmt.close(); stmt.close();
connection.close(); connection.close();
} }
......
...@@ -18,6 +18,7 @@ public class RestfulParameterMetaDataTest { ...@@ -18,6 +18,7 @@ public class RestfulParameterMetaDataTest {
private static PreparedStatement pstmt_select; private static PreparedStatement pstmt_select;
private static ParameterMetaData parameterMetaData_insert; private static ParameterMetaData parameterMetaData_insert;
private static ParameterMetaData parameterMetaData_select; private static ParameterMetaData parameterMetaData_select;
private static final String dbname = "test_pstmt";
@Test @Test
public void getParameterCount() throws SQLException { public void getParameterCount() throws SQLException {
...@@ -148,9 +149,9 @@ public class RestfulParameterMetaDataTest { ...@@ -148,9 +149,9 @@ public class RestfulParameterMetaDataTest {
Class.forName("com.taosdata.jdbc.rs.RestfulDriver"); Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata");
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.execute("drop database if exists test_pstmt"); stmt.execute("drop database if exists " + dbname);
stmt.execute("create database if not exists test_pstmt"); stmt.execute("create database if not exists " + dbname);
stmt.execute("use test_pstmt"); 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 weather(ts timestamp, f1 int, f2 bigint, f3 float, f4 double, f5 smallint, f6 tinyint, f7 bool, f8 binary(64), f9 nchar(64)) tags(loc nchar(64))");
stmt.execute("create table t1 using weather tags('beijing')"); stmt.execute("create table t1 using weather tags('beijing')");
} }
...@@ -186,8 +187,12 @@ public class RestfulParameterMetaDataTest { ...@@ -186,8 +187,12 @@ public class RestfulParameterMetaDataTest {
pstmt_insert.close(); pstmt_insert.close();
if (pstmt_select != null) if (pstmt_select != null)
pstmt_select.close(); pstmt_select.close();
if (conn != null) if (conn != null) {
Statement statement = conn.createStatement();
statement.execute("drop database if exists " + dbname);
statement.close();
conn.close(); conn.close();
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -400,8 +400,12 @@ public class RestfulPreparedStatementTest { ...@@ -400,8 +400,12 @@ public class RestfulPreparedStatementTest {
pstmt_select.close(); pstmt_select.close();
if (pstmt_without_parameters != null) if (pstmt_without_parameters != null)
pstmt_without_parameters.close(); pstmt_without_parameters.close();
if (conn != null) if (conn != null) {
Statement statement = conn.createStatement();
statement.execute("drop database if exists test_pstmt");
statement.close();
conn.close(); conn.close();
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -15,6 +15,7 @@ public class RestfulResultSetMetaDataTest { ...@@ -15,6 +15,7 @@ public class RestfulResultSetMetaDataTest {
private static Statement stmt; private static Statement stmt;
private static ResultSet rs; private static ResultSet rs;
private static ResultSetMetaData meta; private static ResultSetMetaData meta;
private static final String dbname = "restful_test";
@Test @Test
public void getColumnCount() throws SQLException { public void getColumnCount() throws SQLException {
...@@ -206,8 +207,12 @@ public class RestfulResultSetMetaDataTest { ...@@ -206,8 +207,12 @@ public class RestfulResultSetMetaDataTest {
rs.close(); rs.close();
if (stmt != null) if (stmt != null)
stmt.close(); stmt.close();
if (conn != null) if (conn != null) {
Statement statement = conn.createStatement();
statement.execute("drop database if exists " + dbname);
statement.close();
conn.close(); conn.close();
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -22,6 +22,20 @@ public class RestfulResultSetTest { ...@@ -22,6 +22,20 @@ public class RestfulResultSetTest {
private static Statement stmt; private static Statement stmt;
private static ResultSet rs; private static ResultSet rs;
@BeforeClass
public static void beforeClass() throws SQLException {
conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata");
stmt = conn.createStatement();
stmt.execute("drop database if exists restful_test");
stmt.execute("create database if not exists restful_test");
stmt.execute("use restful_test");
stmt.execute("drop table if exists weather");
stmt.execute("create table if not exists weather(f1 timestamp, f2 int, f3 bigint, f4 float, f5 double, f6 binary(64), f7 smallint, f8 tinyint, f9 bool, f10 nchar(64))");
stmt.execute("insert into restful_test.weather values('2021-01-01 00:00:00.000', 1, 100, 3.1415, 3.1415926, 'abc', 10, 10, true, '涛思数据')");
rs = stmt.executeQuery("select * from restful_test.weather");
rs.next();
}
@Test @Test
public void wasNull() throws SQLException { public void wasNull() throws SQLException {
Assert.assertFalse(rs.wasNull()); Assert.assertFalse(rs.wasNull());
...@@ -657,20 +671,6 @@ public class RestfulResultSetTest { ...@@ -657,20 +671,6 @@ public class RestfulResultSetTest {
Assert.assertTrue(rs.isWrapperFor(RestfulResultSet.class)); Assert.assertTrue(rs.isWrapperFor(RestfulResultSet.class));
} }
@BeforeClass
public static void beforeClass() throws SQLException {
conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata");
stmt = conn.createStatement();
stmt.execute("drop database if exists restful_test");
stmt.execute("create database if not exists restful_test");
stmt.execute("use restful_test");
stmt.execute("drop table if exists weather");
stmt.execute("create table if not exists weather(f1 timestamp, f2 int, f3 bigint, f4 float, f5 double, f6 binary(64), f7 smallint, f8 tinyint, f9 bool, f10 nchar(64))");
stmt.execute("insert into restful_test.weather values('2021-01-01 00:00:00.000', 1, 100, 3.1415, 3.1415926, 'abc', 10, 10, true, '涛思数据')");
rs = stmt.executeQuery("select * from restful_test.weather");
rs.next();
}
@AfterClass @AfterClass
public static void afterClass() throws SQLException { public static void afterClass() throws SQLException {
if (rs != null) if (rs != null)
......
...@@ -17,46 +17,32 @@ public class RestfulStatementTest { ...@@ -17,46 +17,32 @@ public class RestfulStatementTest {
private static Statement stmt; private static Statement stmt;
@Test @Test
public void executeQuery() { public void executeQuery() throws SQLException {
try { ResultSet rs = stmt.executeQuery("show databases");
ResultSet rs = stmt.executeQuery("show databases"); Assert.assertNotNull(rs);
Assert.assertNotNull(rs); ResultSetMetaData meta = rs.getMetaData();
ResultSetMetaData meta = rs.getMetaData(); int columnCount = meta.getColumnCount();
int columnCount = meta.getColumnCount(); Assert.assertTrue(columnCount > 1);
Assert.assertTrue(columnCount > 1); while (rs.next()) {
while (rs.next()) { Assert.assertEquals("name", meta.getColumnLabel(1));
Assert.assertEquals("name", meta.getColumnLabel(1)); Assert.assertNotNull(rs.getString("name"));
Assert.assertNotNull(rs.getString("name"));
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} }
rs.close();
} }
@Test @Test
public void executeUpdate() { public void executeUpdate() throws SQLException {
final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32);
try { int affectRows = stmt.executeUpdate("create database " + dbName);
int affectRows = stmt.executeUpdate("create database " + dbName); Assert.assertEquals(0, affectRows);
Assert.assertEquals(0, affectRows); affectRows = stmt.executeUpdate("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))");
affectRows = stmt.executeUpdate("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); Assert.assertEquals(0, affectRows);
Assert.assertEquals(0, affectRows); affectRows = stmt.executeUpdate("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)");
affectRows = stmt.executeUpdate("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); Assert.assertEquals(1, affectRows);
Assert.assertEquals(1, affectRows); affectRows = stmt.executeUpdate("drop database " + dbName);
affectRows = stmt.executeUpdate("drop database " + dbName); Assert.assertEquals(0, affectRows);
Assert.assertEquals(0, affectRows);
} catch (SQLException e) {
e.printStackTrace();
}
} }
@Test
public void close() {
// test in AfterClass method
}
@Test @Test
public void getMaxFieldSize() throws SQLException { public void getMaxFieldSize() throws SQLException {
Assert.assertEquals(16 * 1024, stmt.getMaxFieldSize()); Assert.assertEquals(16 * 1024, stmt.getMaxFieldSize());
...@@ -64,7 +50,6 @@ public class RestfulStatementTest { ...@@ -64,7 +50,6 @@ public class RestfulStatementTest {
@Test(expected = SQLException.class) @Test(expected = SQLException.class)
public void setMaxFieldSize() throws SQLException { public void setMaxFieldSize() throws SQLException {
stmt.setMaxFieldSize(0); stmt.setMaxFieldSize(0);
stmt.setMaxFieldSize(-1); stmt.setMaxFieldSize(-1);
} }
...@@ -118,83 +103,70 @@ public class RestfulStatementTest { ...@@ -118,83 +103,70 @@ public class RestfulStatementTest {
} }
@Test @Test
public void execute() { public void execute() throws SQLException {
final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32);
try { boolean isSelect = stmt.execute("create database if not exists " + dbName);
boolean isSelect = stmt.execute("create database if not exists " + dbName); Assert.assertEquals(false, isSelect);
Assert.assertEquals(false, isSelect); int affectedRows = stmt.getUpdateCount();
int affectedRows = stmt.getUpdateCount(); Assert.assertEquals(0, affectedRows);
Assert.assertEquals(0, affectedRows);
isSelect = stmt.execute("create table if not exists " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))");
isSelect = stmt.execute("create table if not exists " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); Assert.assertEquals(false, isSelect);
Assert.assertEquals(false, isSelect); affectedRows = stmt.getUpdateCount();
affectedRows = stmt.getUpdateCount(); Assert.assertEquals(0, affectedRows);
Assert.assertEquals(0, affectedRows);
isSelect = stmt.execute("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)");
isSelect = stmt.execute("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); Assert.assertEquals(false, isSelect);
Assert.assertEquals(false, isSelect); affectedRows = stmt.getUpdateCount();
affectedRows = stmt.getUpdateCount(); Assert.assertEquals(1, affectedRows);
Assert.assertEquals(1, affectedRows);
isSelect = stmt.execute("select * from " + dbName + ".weather");
isSelect = stmt.execute("select * from " + dbName + ".weather"); Assert.assertEquals(true, isSelect);
Assert.assertEquals(true, isSelect);
isSelect = stmt.execute("drop database " + dbName);
isSelect = stmt.execute("drop database " + dbName); Assert.assertEquals(false, isSelect);
Assert.assertEquals(false, isSelect); affectedRows = stmt.getUpdateCount();
affectedRows = stmt.getUpdateCount(); Assert.assertEquals(0, affectedRows);
Assert.assertEquals(0, affectedRows);
} catch (SQLException e) {
e.printStackTrace();
}
} }
@Test @Test
public void getResultSet() { public void getResultSet() throws SQLException {
final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32);
try { boolean isSelect = stmt.execute("create database if not exists " + dbName);
boolean isSelect = stmt.execute("create database if not exists " + dbName); Assert.assertEquals(false, isSelect);
Assert.assertEquals(false, isSelect); int affectedRows = stmt.getUpdateCount();
int affectedRows = stmt.getUpdateCount(); Assert.assertEquals(0, affectedRows);
Assert.assertEquals(0, affectedRows);
isSelect = stmt.execute("create table if not exists " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))");
isSelect = stmt.execute("create table if not exists " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); Assert.assertEquals(false, isSelect);
Assert.assertEquals(false, isSelect); affectedRows = stmt.getUpdateCount();
affectedRows = stmt.getUpdateCount(); Assert.assertEquals(0, affectedRows);
Assert.assertEquals(0, affectedRows);
isSelect = stmt.execute("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)");
isSelect = stmt.execute("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); Assert.assertEquals(false, isSelect);
Assert.assertEquals(false, isSelect); affectedRows = stmt.getUpdateCount();
affectedRows = stmt.getUpdateCount(); Assert.assertEquals(1, affectedRows);
Assert.assertEquals(1, affectedRows);
isSelect = stmt.execute("select * from " + dbName + ".weather");
isSelect = stmt.execute("select * from " + dbName + ".weather"); Assert.assertEquals(true, isSelect);
Assert.assertEquals(true, isSelect); ResultSet rs = stmt.getResultSet();
ResultSet rs = stmt.getResultSet(); Assert.assertNotNull(rs);
Assert.assertNotNull(rs); ResultSetMetaData meta = rs.getMetaData();
ResultSetMetaData meta = rs.getMetaData(); Assert.assertEquals(3, meta.getColumnCount());
Assert.assertEquals(3, meta.getColumnCount()); int count = 0;
int count = 0; while (rs.next()) {
while (rs.next()) { Assert.assertEquals("ts", meta.getColumnLabel(1));
Assert.assertEquals("ts", meta.getColumnLabel(1)); Assert.assertNotNull(rs.getTimestamp(1));
Assert.assertNotNull(rs.getTimestamp(1)); Assert.assertEquals("temperature", meta.getColumnLabel(2));
Assert.assertEquals("temperature", meta.getColumnLabel(2)); Assert.assertEquals(22.33, rs.getFloat(2), 0.001f);
Assert.assertEquals(22.33, rs.getFloat(2), 0.001f); count++;
count++;
}
Assert.assertEquals(1, count);
isSelect = stmt.execute("drop database " + dbName);
Assert.assertEquals(false, isSelect);
affectedRows = stmt.getUpdateCount();
Assert.assertEquals(0, affectedRows);
} catch (SQLException e) {
e.printStackTrace();
} }
} Assert.assertEquals(1, count);
@Test isSelect = stmt.execute("drop database " + dbName);
public void getUpdateCount() { Assert.assertEquals(false, isSelect);
// already test in execute method affectedRows = stmt.getUpdateCount();
Assert.assertEquals(0, affectedRows);
} }
@Test @Test
...@@ -239,64 +211,48 @@ public class RestfulStatementTest { ...@@ -239,64 +211,48 @@ public class RestfulStatementTest {
} }
@Test @Test
public void addBatch() { public void addBatch() throws SQLException {
final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32);
try { stmt.addBatch("create database " + dbName);
stmt.addBatch("create database " + dbName); stmt.addBatch("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))");
stmt.addBatch("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); stmt.addBatch("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)");
stmt.addBatch("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); stmt.addBatch("select * from " + dbName + ".weather");
stmt.addBatch("select * from " + dbName + ".weather"); stmt.addBatch("drop database " + dbName);
stmt.addBatch("drop database " + dbName);
} catch (SQLException e) {
e.printStackTrace();
}
} }
@Test @Test
public void clearBatch() { public void clearBatch() throws SQLException {
final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32);
try { stmt.clearBatch();
stmt.clearBatch(); stmt.addBatch("create database " + dbName);
stmt.addBatch("create database " + dbName); stmt.addBatch("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))");
stmt.addBatch("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); stmt.addBatch("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)");
stmt.addBatch("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); stmt.addBatch("select * from " + dbName + ".weather");
stmt.addBatch("select * from " + dbName + ".weather"); stmt.addBatch("drop database " + dbName);
stmt.addBatch("drop database " + dbName); stmt.clearBatch();
stmt.clearBatch();
} catch (SQLException e) {
e.printStackTrace();
}
} }
@Test @Test
public void executeBatch() { public void executeBatch() throws SQLException {
final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32); final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32);
try { stmt.addBatch("create database " + dbName);
stmt.addBatch("create database " + dbName); stmt.addBatch("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))");
stmt.addBatch("create table " + dbName + ".weather(ts timestamp, temperature float) tags(loc nchar(64))"); stmt.addBatch("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)");
stmt.addBatch("insert into " + dbName + ".t1 using " + dbName + ".weather tags('北京') values(now, 22.33)"); stmt.addBatch("select * from " + dbName + ".weather");
stmt.addBatch("select * from " + dbName + ".weather"); stmt.addBatch("drop database " + dbName);
stmt.addBatch("drop database " + dbName); int[] results = stmt.executeBatch();
int[] results = stmt.executeBatch(); Assert.assertEquals(0, results[0]);
Assert.assertEquals(0, results[0]); Assert.assertEquals(0, results[1]);
Assert.assertEquals(0, results[1]); Assert.assertEquals(1, results[2]);
Assert.assertEquals(1, results[2]); Assert.assertEquals(Statement.SUCCESS_NO_INFO, results[3]);
Assert.assertEquals(Statement.SUCCESS_NO_INFO, results[3]); Assert.assertEquals(0, results[4]);
Assert.assertEquals(0, results[4]);
} catch (SQLException e) {
e.printStackTrace();
}
} }
@Test @Test
public void getConnection() { public void getConnection() throws SQLException {
try { Connection connection = stmt.getConnection();
Connection connection = stmt.getConnection(); Assert.assertNotNull(connection);
Assert.assertNotNull(connection); Assert.assertTrue(this.conn == connection);
Assert.assertTrue(this.conn == connection);
} catch (SQLException e) {
e.printStackTrace();
}
} }
@Test(expected = SQLFeatureNotSupportedException.class) @Test(expected = SQLFeatureNotSupportedException.class)
...@@ -346,12 +302,8 @@ public class RestfulStatementTest { ...@@ -346,12 +302,8 @@ public class RestfulStatementTest {
} }
@Test @Test
public void isClosed() { public void isClosed() throws SQLException {
try { Assert.assertEquals(false, stmt.isClosed());
Assert.assertEquals(false, stmt.isClosed());
} catch (SQLException e) {
e.printStackTrace();
}
} }
@Test @Test
...@@ -387,29 +339,21 @@ public class RestfulStatementTest { ...@@ -387,29 +339,21 @@ public class RestfulStatementTest {
} }
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() throws SQLException {
try { Properties properties = new Properties();
Properties properties = new Properties(); properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata", properties);
conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata", properties); stmt = conn.createStatement();
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
} }
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() throws SQLException {
try { if (stmt != null)
if (stmt != null) stmt.close();
stmt.close(); if (conn != null)
if (conn != null) conn.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
...@@ -543,15 +543,6 @@ public class SQLTest { ...@@ -543,15 +543,6 @@ public class SQLTest {
Assert.assertNotNull(rs); Assert.assertNotNull(rs);
} }
@Test
public void testCase053() {
String sql = "select avg(cpu_taosd), avg(cpu_system), max(cpu_cores), avg(mem_taosd), avg(mem_system), max(mem_total), avg(disk_used), max(disk_total), avg(band_speed), avg(io_read), avg(io_write), sum(req_http), sum(req_select), sum(req_insert) from log.dn1 where ts> now - 60m and ts<= now interval(1m) fill(value, 0)";
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
private boolean execute(Connection connection, String sql) { private boolean execute(Connection connection, String sql) {
try (Statement statement = connection.createStatement()) { try (Statement statement = connection.createStatement()) {
return statement.execute(sql); return statement.execute(sql);
......
package com.taosdata.jdbc.rs;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.sql.*;
public class WasNullTest {
private static final String host = "127.0.0.1";
private Connection conn;
@Test
public void testGetTimestamp() throws SQLException {
try (Statement stmt = conn.createStatement()) {
stmt.execute("drop table if exists weather");
stmt.execute("create table if not exists weather(f1 timestamp, f2 timestamp, f3 int)");
stmt.execute("insert into restful_test.weather values('2021-01-01 00:00:00.000', NULL, 100)");
ResultSet rs = stmt.executeQuery("select * from restful_test.weather");
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
if (i == 2) {
Object value = rs.getTimestamp(i);
boolean wasNull = rs.wasNull();
Assert.assertNull(value);
Assert.assertTrue(wasNull);
} else {
Object value = rs.getObject(i);
boolean wasNull = rs.wasNull();
Assert.assertNotNull(value);
Assert.assertFalse(wasNull);
}
}
}
}
}
@Test
public void testGetObject() throws SQLException {
try (Statement stmt = conn.createStatement()) {
stmt.execute("drop table if exists weather");
stmt.execute("create table if not exists weather(f1 timestamp, f2 int, f3 bigint, f4 float, f5 double, f6 binary(64), f7 smallint, f8 tinyint, f9 bool, f10 nchar(64))");
stmt.execute("insert into restful_test.weather values('2021-01-01 00:00:00.000', 1, 100, 3.1415, 3.1415926, NULL, 10, 10, true, '涛思数据')");
ResultSet rs = stmt.executeQuery("select * from restful_test.weather");
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
Object value = rs.getObject(i);
boolean wasNull = rs.wasNull();
if (i == 6) {
Assert.assertNull(value);
Assert.assertTrue(wasNull);
} else {
Assert.assertNotNull(value);
Assert.assertFalse(wasNull);
}
}
}
}
}
@Before
public void before() throws SQLException {
conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata");
try (Statement stmt = conn.createStatement()) {
stmt.execute("drop database if exists restful_test");
stmt.execute("create database if not exists restful_test");
stmt.execute("use restful_test");
}
}
@After
public void after() throws SQLException {
if (conn != null) {
Statement statement = conn.createStatement();
statement.execute("drop database if exists restful_test");
conn.close();
}
}
}
...@@ -2,8 +2,6 @@ package com.taosdata.jdbc.utils; ...@@ -2,8 +2,6 @@ package com.taosdata.jdbc.utils;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.taosdata.jdbc.TSDBDriver;
import com.taosdata.jdbc.TSDBError;
import org.junit.Test; import org.junit.Test;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
...@@ -11,7 +9,6 @@ import java.net.URLEncoder; ...@@ -11,7 +9,6 @@ import java.net.URLEncoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
...@@ -20,18 +17,20 @@ public class HttpClientPoolUtilTest { ...@@ -20,18 +17,20 @@ public class HttpClientPoolUtilTest {
String user = "root"; String user = "root";
String password = "taosdata"; String password = "taosdata";
String host = "127.0.0.1"; String host = "127.0.0.1";
String dbname = "log";
@Test @Test
public void test() { public void useLog() {
// given // given
List<Thread> threads = IntStream.range(0, 4000).mapToObj(i -> new Thread(() -> { int multi = 10;
useDB();
// try { // when
// TimeUnit.SECONDS.sleep(10); List<Thread> threads = IntStream.range(0, multi).mapToObj(i -> new Thread(() -> {
// } catch (InterruptedException e) { try {
// e.printStackTrace(); String token = login(multi);
// } executeOneSql("use log", token);
} catch (SQLException | UnsupportedEncodingException e) {
e.printStackTrace();
}
})).collect(Collectors.toList()); })).collect(Collectors.toList());
threads.forEach(Thread::start); threads.forEach(Thread::start);
...@@ -43,34 +42,62 @@ public class HttpClientPoolUtilTest { ...@@ -43,34 +42,62 @@ public class HttpClientPoolUtilTest {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
private void useDB() { @Test
try { public void tableNotExist() {
user = URLEncoder.encode(user, StandardCharsets.UTF_8.displayName()); // given
password = URLEncoder.encode(password, StandardCharsets.UTF_8.displayName()); int multi = 20;
String loginUrl = "http://" + host + ":" + 6041 + "/rest/login/" + user + "/" + password + "";
String result = HttpClientPoolUtil.execute(loginUrl); // when
JSONObject jsonResult = JSON.parseObject(result); List<Thread> threads = IntStream.range(0, multi * 25).mapToObj(i -> new Thread(() -> {
String status = jsonResult.getString("status"); try {
String token = jsonResult.getString("desc"); // String token = "/KfeAzX/f9na8qdtNZmtONryp201ma04bEl8LcvLUd7a8qdtNZmtONryp201ma04";
if (!status.equals("succ")) { String token = login(multi);
throw new SQLException(jsonResult.getString("desc")); executeOneSql("insert into log.tb_not_exist values(now, 1)", token);
executeOneSql("select last(*) from log.dn", token);
} catch (SQLException | UnsupportedEncodingException e) {
e.printStackTrace();
} }
})).collect(Collectors.toList());
String url = "http://" + host + ":6041/rest/sql"; threads.forEach(Thread::start);
String sql = "use " + dbname;
result = HttpClientPoolUtil.execute(url, sql, token);
JSONObject resultJson = JSON.parseObject(result); for (Thread thread : threads) {
if (resultJson.getString("status").equals("error")) { try {
throw TSDBError.createSQLException(resultJson.getInteger("code"), resultJson.getString("desc")); thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
} }
} catch (UnsupportedEncodingException | SQLException e) {
e.printStackTrace();
} }
} }
private String login(int connPoolSize) throws SQLException, UnsupportedEncodingException {
user = URLEncoder.encode(user, StandardCharsets.UTF_8.displayName());
password = URLEncoder.encode(password, StandardCharsets.UTF_8.displayName());
String loginUrl = "http://" + host + ":" + 6041 + "/rest/login/" + user + "/" + password + "";
HttpClientPoolUtil.init(connPoolSize, false);
String result = HttpClientPoolUtil.execute(loginUrl);
JSONObject jsonResult = JSON.parseObject(result);
String status = jsonResult.getString("status");
String token = jsonResult.getString("desc");
if (!status.equals("succ")) {
throw new SQLException(jsonResult.getString("desc"));
}
return token;
}
private boolean executeOneSql(String sql, String token) throws SQLException {
String url = "http://" + host + ":6041/rest/sql";
String result = HttpClientPoolUtil.execute(url, sql, token);
JSONObject resultJson = JSON.parseObject(result);
if (resultJson.getString("status").equals("error")) {
// HttpClientPoolUtil.reset();
// throw TSDBError.createSQLException(resultJson.getInteger("code"), resultJson.getString("desc"));
return false;
}
return true;
}
} }
\ No newline at end of file
#org.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
org.apache.commons.logging.simplelog.defaultlog=TRACE
org.apache.commons.logging.simplelog.showlogname=true
org.apache.commons.logging.simplelog.showShortLogname=restful
org.apache.commons.logging.simplelog.showdatetime=true
org.apache.commons.logging.simplelog.dateTimeFormat=yyyy-mm-dd hh:MM:ss.SSS
\ No newline at end of file
...@@ -37,7 +37,7 @@ ...@@ -37,7 +37,7 @@
#define HTTP_BUFFER_SIZE 8388608 #define HTTP_BUFFER_SIZE 8388608
#define HTTP_STEP_SIZE 4096 //http message get process step by step #define HTTP_STEP_SIZE 4096 //http message get process step by step
#define HTTP_METHOD_SCANNER_SIZE 7 //http method fp size #define HTTP_METHOD_SCANNER_SIZE 7 //http method fp size
#define HTTP_GC_TARGET_SIZE 512 #define HTTP_GC_TARGET_SIZE 16384
#define HTTP_WRITE_RETRY_TIMES 500 #define HTTP_WRITE_RETRY_TIMES 500
#define HTTP_WRITE_WAIT_TIME_MS 5 #define HTTP_WRITE_WAIT_TIME_MS 5
#define HTTP_PASSWORD_LEN TSDB_UNI_LEN #define HTTP_PASSWORD_LEN TSDB_UNI_LEN
......
...@@ -130,14 +130,34 @@ bool gcBuildQueryJson(HttpContext *pContext, HttpSqlCmd *cmd, TAOS_RES *result, ...@@ -130,14 +130,34 @@ bool gcBuildQueryJson(HttpContext *pContext, HttpSqlCmd *cmd, TAOS_RES *result,
// for group by // for group by
if (groupFields != -1) { if (groupFields != -1) {
char target[HTTP_GC_TARGET_SIZE] = {0}; char target[HTTP_GC_TARGET_SIZE] = {0};
int32_t len; int32_t len = 0, cur = 0;
len = snprintf(target, HTTP_GC_TARGET_SIZE, "%s{", aliasBuffer); cur = snprintf(target, HTTP_GC_TARGET_SIZE, "%s{", aliasBuffer);
if (cur < 0 || cur >= HTTP_GC_TARGET_SIZE) {
httpError("context:%p, fd:%d, too long alias: %s", pContext, pContext->fd, aliasBuffer);
return false;
}
len += cur;
for (int32_t i = dataFields + 1; i < num_fields; i++) { for (int32_t i = dataFields + 1; i < num_fields; i++) {
// -2 means the last '}' and '\0'
#define HTTP_GC_CHECK_SIZE(name) if (cur < 0 || cur >= HTTP_GC_TARGET_SIZE - len - 2) { \
if (cur < 0) { \
httpError("context:%p, fd:%d, failed to snprintf for: %s", pContext, pContext->fd, name); \
} else { \
httpError("context:%p, fd:%d, snprintf overflow for: %s", pContext, pContext->fd, name); \
target[len] = '\0'; \
} \
break; \
} else { \
len += cur; \
}
if (row[i] == NULL) { if (row[i] == NULL) {
len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:nil", fields[i].name); cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:nil", fields[i].name);
HTTP_GC_CHECK_SIZE(fields[i].name)
if (i < num_fields - 1) { if (i < num_fields - 1) {
len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, ", "); cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, ", ");
HTTP_GC_CHECK_SIZE(fields[i].name)
} }
continue; continue;
...@@ -146,40 +166,49 @@ bool gcBuildQueryJson(HttpContext *pContext, HttpSqlCmd *cmd, TAOS_RES *result, ...@@ -146,40 +166,49 @@ bool gcBuildQueryJson(HttpContext *pContext, HttpSqlCmd *cmd, TAOS_RES *result,
switch (fields[i].type) { switch (fields[i].type) {
case TSDB_DATA_TYPE_BOOL: case TSDB_DATA_TYPE_BOOL:
case TSDB_DATA_TYPE_TINYINT: case TSDB_DATA_TYPE_TINYINT:
len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:%d", fields[i].name, *((int8_t *)row[i])); cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:%d", fields[i].name, *((int8_t *)row[i]));
HTTP_GC_CHECK_SIZE(fields[i].name)
break; break;
case TSDB_DATA_TYPE_SMALLINT: case TSDB_DATA_TYPE_SMALLINT:
len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:%d", fields[i].name, *((int16_t *)row[i])); cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:%d", fields[i].name, *((int16_t *)row[i]));
HTTP_GC_CHECK_SIZE(fields[i].name)
break; break;
case TSDB_DATA_TYPE_INT: case TSDB_DATA_TYPE_INT:
len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:%d,", fields[i].name, *((int32_t *)row[i])); cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:%d,", fields[i].name, *((int32_t *)row[i]));
HTTP_GC_CHECK_SIZE(fields[i].name)
break; break;
case TSDB_DATA_TYPE_BIGINT: case TSDB_DATA_TYPE_BIGINT:
len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:%" PRId64, fields[i].name, *((int64_t *)row[i])); cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:%" PRId64, fields[i].name, *((int64_t *)row[i]));
HTTP_GC_CHECK_SIZE(fields[i].name)
break; break;
case TSDB_DATA_TYPE_FLOAT: case TSDB_DATA_TYPE_FLOAT:
len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:%.5f", fields[i].name, GET_FLOAT_VAL(row[i])); cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:%.5f", fields[i].name, GET_FLOAT_VAL(row[i]));
HTTP_GC_CHECK_SIZE(fields[i].name)
break; break;
case TSDB_DATA_TYPE_DOUBLE: case TSDB_DATA_TYPE_DOUBLE:
len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:%.9f", fields[i].name, GET_DOUBLE_VAL(row[i])); cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:%.9f", fields[i].name, GET_DOUBLE_VAL(row[i]));
HTTP_GC_CHECK_SIZE(fields[i].name)
break; break;
case TSDB_DATA_TYPE_BINARY: case TSDB_DATA_TYPE_BINARY:
case TSDB_DATA_TYPE_NCHAR: case TSDB_DATA_TYPE_NCHAR:
if (row[i] != NULL) { if (row[i] != NULL) {
len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:", fields[i].name); cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:", fields[i].name);
memcpy(target + len, (char *)row[i], length[i]); HTTP_GC_CHECK_SIZE(fields[i].name)
memcpy(target + len, (char *)row[i], MIN(length[i], HTTP_GC_TARGET_SIZE - len - 3));
len = (int32_t)strlen(target); len = (int32_t)strlen(target);
} }
break; break;
default: default:
len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "%s:%s", fields[i].name, "-"); cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, "%s:%s", fields[i].name, "-");
HTTP_GC_CHECK_SIZE(fields[i].name)
break; break;
} }
if (i < num_fields - 1) { if (i < num_fields - 1) {
len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, ", "); cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 2, ", ");
HTTP_GC_CHECK_SIZE(fields[i].name)
} }
} }
len += snprintf(target + len, HTTP_GC_TARGET_SIZE - len, "}"); cur = snprintf(target + len, HTTP_GC_TARGET_SIZE - len - 1, "}");
if (strcmp(target, targetBuffer) != 0) { if (strcmp(target, targetBuffer) != 0) {
// first target not write this section // first target not write this section
......
...@@ -183,7 +183,7 @@ bool likeOperator(SColumnFilterElem *pFilter, const char *minval, const char *ma ...@@ -183,7 +183,7 @@ bool likeOperator(SColumnFilterElem *pFilter, const char *minval, const char *ma
return patternMatch((char *)pFilter->filterInfo.pz, varDataVal(minval), varDataLen(minval), &info) == TSDB_PATTERN_MATCH; return patternMatch((char *)pFilter->filterInfo.pz, varDataVal(minval), varDataLen(minval), &info) == TSDB_PATTERN_MATCH;
} else if (type == TSDB_DATA_TYPE_NCHAR) { } else if (type == TSDB_DATA_TYPE_NCHAR) {
SPatternCompareInfo info = PATTERN_COMPARE_INFO_INITIALIZER; SPatternCompareInfo info = PATTERN_COMPARE_INFO_INITIALIZER;
return WCSPatternMatch((wchar_t*)pFilter->filterInfo.pz, varDataVal(minval), varDataLen(minval)/TSDB_NCHAR_SIZE, &info) == TSDB_PATTERN_MATCH; return WCSPatternMatch((uint32_t *) pFilter->filterInfo.pz, (uint32_t *) varDataVal(minval), varDataLen(minval)/TSDB_NCHAR_SIZE, &info) == TSDB_PATTERN_MATCH;
} else { } else {
return false; return false;
} }
......
...@@ -43,7 +43,7 @@ typedef struct SPatternCompareInfo { ...@@ -43,7 +43,7 @@ typedef struct SPatternCompareInfo {
int patternMatch(const char *pattern, const char *str, size_t size, const SPatternCompareInfo *pInfo); int patternMatch(const char *pattern, const char *str, size_t size, const SPatternCompareInfo *pInfo);
int WCSPatternMatch(const wchar_t *pattern, const wchar_t *str, size_t size, const SPatternCompareInfo *pInfo); int WCSPatternMatch(const uint32_t *pattern, const uint32_t *str, size_t size, const SPatternCompareInfo *pInfo);
int32_t doCompare(const char* a, const char* b, int32_t type, size_t size); int32_t doCompare(const char* a, const char* b, int32_t type, size_t size);
......
...@@ -275,29 +275,94 @@ int patternMatch(const char *patterStr, const char *str, size_t size, const SPat ...@@ -275,29 +275,94 @@ int patternMatch(const char *patterStr, const char *str, size_t size, const SPat
return (str[j] == 0 || j >= size) ? TSDB_PATTERN_MATCH : TSDB_PATTERN_NOMATCH; return (str[j] == 0 || j >= size) ? TSDB_PATTERN_MATCH : TSDB_PATTERN_NOMATCH;
} }
int WCSPatternMatch(const wchar_t *patterStr, const wchar_t *str, size_t size, const SPatternCompareInfo *pInfo) { static uint32_t *
wchar_t c, c1; taosWcschr (const uint32_t *wcs, const uint32_t wc)
wchar_t matchOne = L'_'; // "_" {
wchar_t matchAll = L'%'; // "%" const uint32_t *wcs2 = wcs + 1;
if (*wcs == wc)
return (uint32_t *) wcs;
if (*wcs == L'\0')
return NULL;
do
{
wcs += 2;
if (*wcs2 == wc)
return (uint32_t *) wcs2;
if (*wcs2 == L'\0')
return NULL;
wcs2 += 2;
if (*wcs == wc)
return (uint32_t *) wcs;
if (*wcs == L'\0')
return NULL;
wcs += 2;
if (*wcs2 == wc)
return (uint32_t *) wcs2;
if (*wcs2 == L'\0')
return NULL;
wcs2 += 2;
if (*wcs == wc)
return (uint32_t *) wcs;
if (*wcs == L'\0')
return NULL;
wcs += 2;
if (*wcs2 == wc)
return (uint32_t *) wcs2;
if (*wcs2 == L'\0')
return NULL;
wcs2 += 2;
if (*wcs == wc)
return (uint32_t *) wcs;
if (*wcs == L'\0')
return NULL;
wcs += 2;
if (*wcs2 == wc)
return (uint32_t *) wcs2;
if (*wcs2 == L'\0')
return NULL;
wcs2 += 2;
if (*wcs == wc)
return (uint32_t *) wcs;
}
while (*wcs != L'\0');
return NULL;
}
static size_t
taosWcscspn (const uint32_t *wcs, const uint32_t *reject)
{
size_t count = 0;
while (*wcs != L'\0')
if (taosWcschr (reject, *wcs++) == NULL)
++count;
else
return count;
return count;
}
int WCSPatternMatch(const uint32_t *patterStr, const uint32_t *str, size_t size, const SPatternCompareInfo *pInfo) {
uint32_t c, c1;
uint32_t matchOne = (uint32_t) L'_'; // "_"
uint32_t matchAll = (uint32_t) L'%'; // "%"
int32_t i = 0; int32_t i = 0;
int32_t j = 0; int32_t j = 0;
while ((c = patterStr[i++]) != 0) { while ((c = patterStr[i++]) != 0) {
if (c == matchAll) { /* Match "%" */ if (c == matchAll) { /* Match "%" */
while ((c = patterStr[i++]) == matchAll || c == matchOne) { while ((c = patterStr[i++]) == matchAll || c == matchOne) {
if (c == matchOne && (j > size || str[j++] == 0)) { if (c == matchOne && (j > size || str[j++] == 0)) {
return TSDB_PATTERN_NOWILDCARDMATCH; return TSDB_PATTERN_NOWILDCARDMATCH;
} }
} }
if (c == 0) { if (c == 0) {
return TSDB_PATTERN_MATCH; return TSDB_PATTERN_MATCH;
} }
wchar_t utl_accept[3] = {towupper(c), towlower(c), 0}; uint32_t utl_accept[3] = {towupper(c), towlower(c), 0};
while (1) { while (1) {
size_t n = wcscspn(str, utl_accept); size_t n = taosWcscspn((uint32_t *)str, utl_accept);
str += n; str += n;
if (str[0] == 0 || (n >= size)) { if (str[0] == 0 || (n >= size)) {
...@@ -368,7 +433,7 @@ int32_t compareWStrPatternComp(const void* pLeft, const void* pRight) { ...@@ -368,7 +433,7 @@ int32_t compareWStrPatternComp(const void* pLeft, const void* pRight) {
memcpy(pattern, varDataVal(pRight), varDataLen(pRight)); memcpy(pattern, varDataVal(pRight), varDataLen(pRight));
memcpy(str, varDataVal(pLeft), size * sizeof(wchar_t)); memcpy(str, varDataVal(pLeft), size * sizeof(wchar_t));
int32_t ret = WCSPatternMatch(pattern, str, size, &pInfo); int32_t ret = WCSPatternMatch((uint32_t *)pattern, (uint32_t *)str, size, &pInfo);
free(pattern); free(pattern);
free(str); free(str);
......
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
<dependency> <dependency>
<groupId>com.taosdata.jdbc</groupId> <groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId> <artifactId>taos-jdbcdriver</artifactId>
<version>2.0.34</version> <version>2.0.36</version>
</dependency> </dependency>
</dependencies> </dependencies>
......
...@@ -841,6 +841,543 @@ void verify_prepare3(TAOS* taos) { ...@@ -841,6 +841,543 @@ void verify_prepare3(TAOS* taos) {
free(blob_len); free(blob_len);
} }
/**
* @brief Verify the upper/lower case of tableName for create(by setTableName)/query/show/describe/drop.
* https://jira.taosdata.com:18080/browse/TS-904
* https://jira.taosdata.com:18090/pages/viewpage.action?pageId=129140555
* @param taos
*/
void verify_prepare4(TAOS* taos) {
printf("Verify the upper/lower case of tableName for create(by setTableName)/query/show/describe/drop etc.\n");
TAOS_RES* result = taos_query(taos, "drop database if exists test;");
taos_free_result(result);
usleep(100000);
result = taos_query(taos, "create database test;");
int code = taos_errno(result);
if (code != 0) {
printf("\033[31mfailed to create database, reason:%s\033[0m\n", taos_errstr(result));
taos_free_result(result);
exit(EXIT_FAILURE);
}
taos_free_result(result);
usleep(100000);
taos_select_db(taos, "test");
// create table
const char* sql =
"create stable st1 (ts timestamp, b bool, v1 tinyint, v2 smallint, v4 int, v8 bigint, f4 float, f8 double, bin "
"binary(40), blob nchar(10), u1 tinyint unsigned, u2 smallint unsigned, u4 int unsigned, u8 bigint unsigned) "
"tags "
"(b_tag bool, v1_tag tinyint, v2_tag smallint, v4_tag int, v8_tag bigint, f4_tag float, f8_tag double, bin_tag "
"binary(40), blob_tag nchar(10), u1_tag tinyint unsigned, u2_tag smallint unsigned, u4_tag int unsigned, u8_tag "
"bigint "
"unsigned)";
result = taos_query(taos, sql);
code = taos_errno(result);
if (code != 0) {
printf("\033[31mfailed to create table, reason:%s\033[0m\n", taos_errstr(result));
taos_free_result(result);
exit(EXIT_FAILURE);
}
taos_free_result(result);
TAOS_BIND tags[13];
struct {
int8_t b;
int8_t v1;
int16_t v2;
int32_t v4;
int64_t v8;
float f4;
double f8;
char bin[40];
char blob[80];
uint8_t u1;
uint16_t u2;
uint32_t u4;
uint64_t u8;
} id = {0};
id.b = (int8_t)1;
id.v1 = (int8_t)1;
id.v2 = (int16_t)2;
id.v4 = (int32_t)4;
id.v8 = (int64_t)8;
id.f4 = (float)40;
id.f8 = (double)80;
for (int j = 0; j < sizeof(id.bin); ++j) {
id.bin[j] = (char)('1' + '0');
}
strcpy(id.blob, "一二三四五六七八九十");
id.u1 = (uint8_t)1;
id.u2 = (uint16_t)2;
id.u4 = (uint32_t)4;
id.u8 = (uint64_t)8;
tags[0].buffer_type = TSDB_DATA_TYPE_BOOL;
tags[0].buffer_length = sizeof(id.b);
tags[0].buffer = &id.b;
tags[0].length = &tags[0].buffer_length;
tags[0].is_null = NULL;
tags[1].buffer_type = TSDB_DATA_TYPE_TINYINT;
tags[1].buffer_length = sizeof(id.v1);
tags[1].buffer = &id.v1;
tags[1].length = &tags[1].buffer_length;
tags[1].is_null = NULL;
tags[2].buffer_type = TSDB_DATA_TYPE_SMALLINT;
tags[2].buffer_length = sizeof(id.v2);
tags[2].buffer = &id.v2;
tags[2].length = &tags[2].buffer_length;
tags[2].is_null = NULL;
tags[3].buffer_type = TSDB_DATA_TYPE_INT;
tags[3].buffer_length = sizeof(id.v4);
tags[3].buffer = &id.v4;
tags[3].length = &tags[3].buffer_length;
tags[3].is_null = NULL;
tags[4].buffer_type = TSDB_DATA_TYPE_BIGINT;
tags[4].buffer_length = sizeof(id.v8);
tags[4].buffer = &id.v8;
tags[4].length = &tags[4].buffer_length;
tags[4].is_null = NULL;
tags[5].buffer_type = TSDB_DATA_TYPE_FLOAT;
tags[5].buffer_length = sizeof(id.f4);
tags[5].buffer = &id.f4;
tags[5].length = &tags[5].buffer_length;
tags[5].is_null = NULL;
tags[6].buffer_type = TSDB_DATA_TYPE_DOUBLE;
tags[6].buffer_length = sizeof(id.f8);
tags[6].buffer = &id.f8;
tags[6].length = &tags[6].buffer_length;
tags[6].is_null = NULL;
tags[7].buffer_type = TSDB_DATA_TYPE_BINARY;
tags[7].buffer_length = sizeof(id.bin);
tags[7].buffer = &id.bin;
tags[7].length = &tags[7].buffer_length;
tags[7].is_null = NULL;
tags[8].buffer_type = TSDB_DATA_TYPE_NCHAR;
tags[8].buffer_length = strlen(id.blob);
tags[8].buffer = &id.blob;
tags[8].length = &tags[8].buffer_length;
tags[8].is_null = NULL;
tags[9].buffer_type = TSDB_DATA_TYPE_UTINYINT;
tags[9].buffer_length = sizeof(id.u1);
tags[9].buffer = &id.u1;
tags[9].length = &tags[9].buffer_length;
tags[9].is_null = NULL;
tags[10].buffer_type = TSDB_DATA_TYPE_USMALLINT;
tags[10].buffer_length = sizeof(id.u2);
tags[10].buffer = &id.u2;
tags[10].length = &tags[10].buffer_length;
tags[10].is_null = NULL;
tags[11].buffer_type = TSDB_DATA_TYPE_UINT;
tags[11].buffer_length = sizeof(id.u4);
tags[11].buffer = &id.u4;
tags[11].length = &tags[11].buffer_length;
tags[11].is_null = NULL;
tags[12].buffer_type = TSDB_DATA_TYPE_UBIGINT;
tags[12].buffer_length = sizeof(id.u8);
tags[12].buffer = &id.u8;
tags[12].length = &tags[12].buffer_length;
tags[12].is_null = NULL;
// insert 10 records
struct {
int64_t ts[10];
int8_t b[10];
int8_t v1[10];
int16_t v2[10];
int32_t v4[10];
int64_t v8[10];
float f4[10];
double f8[10];
char bin[10][40];
char blob[10][80];
uint8_t u1[10];
uint16_t u2[10];
uint32_t u4[10];
uint64_t u8[10];
} v;
int32_t* t8_len = malloc(sizeof(int32_t) * 10);
int32_t* t16_len = malloc(sizeof(int32_t) * 10);
int32_t* t32_len = malloc(sizeof(int32_t) * 10);
int32_t* t64_len = malloc(sizeof(int32_t) * 10);
int32_t* float_len = malloc(sizeof(int32_t) * 10);
int32_t* double_len = malloc(sizeof(int32_t) * 10);
int32_t* bin_len = malloc(sizeof(int32_t) * 10);
int32_t* blob_len = malloc(sizeof(int32_t) * 10);
int32_t* u8_len = malloc(sizeof(int32_t) * 10);
int32_t* u16_len = malloc(sizeof(int32_t) * 10);
int32_t* u32_len = malloc(sizeof(int32_t) * 10);
int32_t* u64_len = malloc(sizeof(int32_t) * 10);
TAOS_MULTI_BIND params[14];
char is_null[10] = {0};
params[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP;
params[0].buffer_length = sizeof(v.ts[0]);
params[0].buffer = v.ts;
params[0].length = t64_len;
params[0].is_null = is_null;
params[0].num = 10;
params[1].buffer_type = TSDB_DATA_TYPE_BOOL;
params[1].buffer_length = sizeof(v.b[0]);
params[1].buffer = v.b;
params[1].length = t8_len;
params[1].is_null = is_null;
params[1].num = 10;
params[2].buffer_type = TSDB_DATA_TYPE_TINYINT;
params[2].buffer_length = sizeof(v.v1[0]);
params[2].buffer = v.v1;
params[2].length = t8_len;
params[2].is_null = is_null;
params[2].num = 10;
params[3].buffer_type = TSDB_DATA_TYPE_SMALLINT;
params[3].buffer_length = sizeof(v.v2[0]);
params[3].buffer = v.v2;
params[3].length = t16_len;
params[3].is_null = is_null;
params[3].num = 10;
params[4].buffer_type = TSDB_DATA_TYPE_INT;
params[4].buffer_length = sizeof(v.v4[0]);
params[4].buffer = v.v4;
params[4].length = t32_len;
params[4].is_null = is_null;
params[4].num = 10;
params[5].buffer_type = TSDB_DATA_TYPE_BIGINT;
params[5].buffer_length = sizeof(v.v8[0]);
params[5].buffer = v.v8;
params[5].length = t64_len;
params[5].is_null = is_null;
params[5].num = 10;
params[6].buffer_type = TSDB_DATA_TYPE_FLOAT;
params[6].buffer_length = sizeof(v.f4[0]);
params[6].buffer = v.f4;
params[6].length = float_len;
params[6].is_null = is_null;
params[6].num = 10;
params[7].buffer_type = TSDB_DATA_TYPE_DOUBLE;
params[7].buffer_length = sizeof(v.f8[0]);
params[7].buffer = v.f8;
params[7].length = double_len;
params[7].is_null = is_null;
params[7].num = 10;
params[8].buffer_type = TSDB_DATA_TYPE_BINARY;
params[8].buffer_length = sizeof(v.bin[0]);
params[8].buffer = v.bin;
params[8].length = bin_len;
params[8].is_null = is_null;
params[8].num = 10;
params[9].buffer_type = TSDB_DATA_TYPE_NCHAR;
params[9].buffer_length = sizeof(v.blob[0]);
params[9].buffer = v.blob;
params[9].length = blob_len;
params[9].is_null = is_null;
params[9].num = 10;
params[10].buffer_type = TSDB_DATA_TYPE_UTINYINT;
params[10].buffer_length = sizeof(v.u1[0]);
params[10].buffer = v.u1;
params[10].length = u8_len;
params[10].is_null = is_null;
params[10].num = 10;
params[11].buffer_type = TSDB_DATA_TYPE_USMALLINT;
params[11].buffer_length = sizeof(v.u2[0]);
params[11].buffer = v.u2;
params[11].length = u16_len;
params[11].is_null = is_null;
params[11].num = 10;
params[12].buffer_type = TSDB_DATA_TYPE_UINT;
params[12].buffer_length = sizeof(v.u4[0]);
params[12].buffer = v.u4;
params[12].length = u32_len;
params[12].is_null = is_null;
params[12].num = 10;
params[13].buffer_type = TSDB_DATA_TYPE_UBIGINT;
params[13].buffer_length = sizeof(v.u8[0]);
params[13].buffer = v.u8;
params[13].length = u64_len;
params[13].is_null = is_null;
params[13].num = 10;
// verify table names for upper/lower case
#define VERIFY_CNT 5
typedef struct {
char setTbName[20];
char showName[20];
char describeName[20];
char queryName[20];
char dropName[20];
} STbNames;
/**
* @brief
* 0 - success expected
* NonZero - fail expected
*/
typedef struct {
int32_t setTbName;
int32_t showName;
int32_t describeName;
int32_t queryName;
int32_t dropName;
} STbNamesResult;
STbNames tbName[VERIFY_CNT] = {0};
STbNamesResult tbNameResult[VERIFY_CNT] = {0};
STbNames* pTbName = NULL;
STbNamesResult* pTbNameResult = NULL;
pTbName = &tbName[0];
pTbNameResult = &tbNameResult[0];
strcpy(pTbName->setTbName, "Mn1");
strcpy(pTbName->showName, "mn1");
strcpy(pTbName->describeName, "mn1");
strcpy(pTbName->queryName, "mn1");
strcpy(pTbName->dropName, "mn1");
pTbName = &tbName[1];
pTbNameResult = &tbNameResult[1];
strcpy(pTbName->setTbName, "'Mn1'");
strcpy(pTbName->showName, "'mn1'");
strcpy(pTbName->describeName, "'mn1'");
strcpy(pTbName->queryName, "'mn1'");
strcpy(pTbName->dropName, "'mn1'");
pTbName = &tbName[2];
pTbNameResult = &tbNameResult[2];
strcpy(pTbName->setTbName, "\"Mn1\"");
strcpy(pTbName->showName, "\"mn1\"");
strcpy(pTbName->describeName, "\"mn1\"");
strcpy(pTbName->queryName, "\"mn1\"");
strcpy(pTbName->dropName, "\"mn1\"");
pTbName = &tbName[3];
pTbNameResult = &tbNameResult[3];
strcpy(pTbName->setTbName, "\"Mn1\"");
strcpy(pTbName->showName, "'mn1'");
strcpy(pTbName->describeName, "'mn1'");
strcpy(pTbName->queryName, "mn1");
strcpy(pTbName->dropName, "\"mn1\"");
pTbName = &tbName[4];
pTbNameResult = &tbNameResult[4];
strcpy(pTbName->setTbName, "`Mn1`");
strcpy(pTbName->showName, "`Mn1`");
strcpy(pTbName->describeName, "`Mn1`");
strcpy(pTbName->queryName, "`Mn1`");
strcpy(pTbName->dropName, "`Mn1`");
pTbNameResult->setTbName = -1;
pTbNameResult->showName = -1;
pTbNameResult->describeName = -1;
pTbNameResult->queryName = -1;
pTbNameResult->dropName = -1;
TAOS_STMT* stmt = NULL;
for (int n = 0; n < VERIFY_CNT; ++n) {
printf("\033[31m[%d] ===================================\033[0m\n", n);
pTbName = &tbName[n];
pTbNameResult = &tbNameResult[n];
char tmpStr[256] = {0};
// set table name
stmt = taos_stmt_init(taos);
if (!stmt) {
printf("\033[31m[%d] failed to execute taos_stmt_init. error:%s\033[0m\n", n);
exit(EXIT_FAILURE);
}
sql = "insert into ? using st1 tags(?,?,?,?,?,?,?,?,?,?,?,?,?) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
code = taos_stmt_prepare(stmt, sql, 0);
if (code != 0) {
printf("\033[31mfailed to execute taos_stmt_prepare. error:%s\033[0m\n", taos_stmt_errstr(stmt));
taos_stmt_close(stmt);
exit(EXIT_FAILURE);
}
printf("[%d] taos_stmt_set_tbname_tags, tbname=%s\n", n, pTbName->setTbName);
code = taos_stmt_set_tbname_tags(stmt, pTbName->setTbName, tags);
if ((!pTbNameResult->setTbName && (0 != code)) || (pTbNameResult->setTbName && (0 == code))) {
printf("\033[31m[%d] failed to execute taos_stmt_set_tbname_tags. error:%s\033[0m\n", n, taos_stmt_errstr(stmt));
taos_stmt_close(stmt);
exit(EXIT_FAILURE);
}
if (code == 0) {
int64_t ts = 1591060628000 + 1000 * n;
for (int i = 0; i < 10; ++i) {
v.ts[i] = ts++;
is_null[i] = 0;
v.b[i] = (int8_t)i % 2;
v.v1[i] = (int8_t)i;
v.v2[i] = (int16_t)(i * 2);
v.v4[i] = (int32_t)(i * 4);
v.v8[i] = (int64_t)(i * 8);
v.f4[i] = (float)(i * 40);
v.f8[i] = (double)(i * 80);
for (int j = 0; j < sizeof(v.bin[0]); ++j) {
v.bin[i][j] = (char)(i + '0');
}
strcpy(v.blob[i], "一二三四五六七八九十");
v.u1[i] = (uint8_t)i;
v.u2[i] = (uint16_t)(i * 2);
v.u4[i] = (uint32_t)(i * 4);
v.u8[i] = (uint64_t)(i * 8);
t8_len[i] = sizeof(int8_t);
t16_len[i] = sizeof(int16_t);
t32_len[i] = sizeof(int32_t);
t64_len[i] = sizeof(int64_t);
float_len[i] = sizeof(float);
double_len[i] = sizeof(double);
bin_len[i] = sizeof(v.bin[0]);
blob_len[i] = (int32_t)strlen(v.blob[i]);
u8_len[i] = sizeof(uint8_t);
u16_len[i] = sizeof(uint16_t);
u32_len[i] = sizeof(uint32_t);
u64_len[i] = sizeof(uint64_t);
}
taos_stmt_bind_param_batch(stmt, params);
taos_stmt_add_batch(stmt);
if (taos_stmt_execute(stmt) != 0) {
printf("\033[31m[%d] failed to execute insert statement.error:%s\033[0m\n", n, taos_stmt_errstr(stmt));
taos_stmt_close(stmt);
exit(EXIT_FAILURE);
}
}
taos_stmt_close(stmt);
// show the table
printf("[%d] show tables, tbName = %s\n", n, pTbName->showName);
stmt = taos_stmt_init(taos);
sprintf(tmpStr, "show tables like %s", pTbName->showName);
taos_stmt_prepare(stmt, tmpStr, 0);
code = taos_stmt_execute(stmt);
if ((!pTbNameResult->showName && (0 != code)) || (pTbNameResult->showName && (0 == code))) {
printf("\033[31m[%d] failed to execute show tables like. error:%s\033[0m\n", n, taos_stmt_errstr(stmt));
taos_stmt_close(stmt);
exit(EXIT_FAILURE);
}
taos_stmt_close(stmt);
// describe the table
printf("[%d] describe tables, tbName = %s\n", n, pTbName->describeName);
stmt = taos_stmt_init(taos);
sprintf(tmpStr, "describe %s", pTbName->describeName);
taos_stmt_prepare(stmt, tmpStr, 0);
code = taos_stmt_execute(stmt);
if ((!pTbNameResult->describeName && (0 != code)) || (pTbNameResult->describeName && (0 == code))) {
printf("\033[31m[%d] failed to execute describe tables. error:%s\033[0m\n", n, taos_stmt_errstr(stmt));
taos_stmt_close(stmt);
exit(EXIT_FAILURE);
}
taos_stmt_close(stmt);
// query the records
printf("[%d] select statement, tbName = %s\n", n, pTbName->queryName);
stmt = taos_stmt_init(taos);
sprintf(tmpStr, "SELECT * FROM %s", pTbName->queryName);
taos_stmt_prepare(stmt, tmpStr, 0);
TAOS_BIND qparams[2];
int8_t v1 = 5;
int16_t v2 = 15;
qparams[0].buffer_type = TSDB_DATA_TYPE_TINYINT;
qparams[0].buffer_length = sizeof(v1);
qparams[0].buffer = &v1;
qparams[0].length = &qparams[0].buffer_length;
qparams[0].is_null = NULL;
qparams[1].buffer_type = TSDB_DATA_TYPE_SMALLINT;
qparams[1].buffer_length = sizeof(v2);
qparams[1].buffer = &v2;
qparams[1].length = &qparams[1].buffer_length;
qparams[1].is_null = NULL;
taos_stmt_bind_param(stmt, qparams);
code = taos_stmt_execute(stmt);
if ((!pTbNameResult->queryName && (0 != code)) || (pTbNameResult->queryName && (0 == code))) {
printf("\033[31m[%d] failed to execute select statement.error:%s\033[0m\n", n, taos_stmt_errstr(stmt));
taos_stmt_close(stmt);
exit(EXIT_FAILURE);
}
result = taos_stmt_use_result(stmt);
TAOS_ROW row;
int rows = 0;
int num_fields = taos_num_fields(result);
TAOS_FIELD* fields = taos_fetch_fields(result);
// fetch the records row by row
while ((row = taos_fetch_row(result))) {
char temp[256] = {0};
rows++;
taos_print_row(temp, row, fields, num_fields);
printf("[%d] row = %s\n", n, temp);
}
taos_free_result(result);
taos_stmt_close(stmt);
// drop table
printf("[%d] drop table, tbName = %s\n", n, pTbName->dropName);
stmt = taos_stmt_init(taos);
sprintf(tmpStr, "drop table %s", pTbName->dropName);
taos_stmt_prepare(stmt, tmpStr, 0);
code = taos_stmt_execute(stmt);
if ((!pTbNameResult->dropName && (0 != code)) || (pTbNameResult->dropName && (0 == code))) {
printf("\033[31m[%d] failed to drop table. error:%s\033[0m\n", n, taos_stmt_errstr(stmt));
taos_stmt_close(stmt);
exit(EXIT_FAILURE);
}
taos_stmt_close(stmt);
}
free(t8_len);
free(t16_len);
free(t32_len);
free(t64_len);
free(float_len);
free(double_len);
free(bin_len);
free(blob_len);
}
int main(int argc, char* argv[]) { int main(int argc, char* argv[]) {
const char* host = "127.0.0.1"; const char* host = "127.0.0.1";
const char* user = "root"; const char* user = "root";
...@@ -864,5 +1401,7 @@ int main(int argc, char* argv[]) { ...@@ -864,5 +1401,7 @@ int main(int argc, char* argv[]) {
printf("************ verify prepare3 *************\n"); printf("************ verify prepare3 *************\n");
verify_prepare3(taos); verify_prepare3(taos);
printf("************ verify prepare4 *************\n"); printf("************ verify prepare4 *************\n");
verify_prepare4(taos);
printf("************ verify end *************\n");
exit(EXIT_SUCCESS); exit(EXIT_SUCCESS);
} }
...@@ -36,6 +36,17 @@ class TDTestCase: ...@@ -36,6 +36,17 @@ class TDTestCase:
tdSql.query("select * from test_cars where t1 like '%50 90 30 04 00 00%'") tdSql.query("select * from test_cars where t1 like '%50 90 30 04 00 00%'")
tdSql.checkRows(1) tdSql.checkRows(1)
tdSql.execute("create table stb(ts timestamp, c0 int) tags(t0 nchar(64))")
tdSql.execute("insert into tb1 using stb tags('测试ABCabc') values(now, 1)")
tdSql.query("select * from stb where t0 like '%试AB%'")
tdSql.checkRows(1)
tdSql.query("select * from stb where t0 like '测试AB%'")
tdSql.checkRows(1)
tdSql.query("select * from stb where t0 like '%ABCabc'")
tdSql.checkRows(1)
def stop(self): def stop(self):
tdSql.close() tdSql.close()
tdLog.success("%s successfully executed" % __file__) tdLog.success("%s successfully executed" % __file__)
......
...@@ -50,6 +50,9 @@ sql insert into t3 values('2017-12-25 21:25:41', 3) ...@@ -50,6 +50,9 @@ sql insert into t3 values('2017-12-25 21:25:41', 3)
sql insert into t3 values('2017-12-25 21:26:41', 3) sql insert into t3 values('2017-12-25 21:26:41', 3)
sql insert into t3 values('2017-12-25 21:27:41', 3) sql insert into t3 values('2017-12-25 21:27:41', 3)
sql create table m3 (ts timestamp, col1 int, col2 float, txt binary(500))
sql insert into m3 values(now, 1, 2.0, 'HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS')
print =============== step2 - login print =============== step2 - login
system_content curl 127.0.0.1:7111/grafana/ system_content curl 127.0.0.1:7111/grafana/
...@@ -179,4 +182,10 @@ if $system_content != @[{"refId":"A","target":"{count(v1):3}","datapoints":[[15. ...@@ -179,4 +182,10 @@ if $system_content != @[{"refId":"A","target":"{count(v1):3}","datapoints":[[15.
return -1 return -1
endi endi
system sh/exec.sh -n dnode1 -s stop -x SIGINT system_content curl -H 'Authorization: Taosd /KfeAzX/f9na8qdtNZmtONryp201ma04bEl8LcvLUd7a8qdtNZmtONryp201ma04' -d '[{"refId":"A","alias":"taosd","sql":"select last(col1), last(col2), last(txt) from d1.m3 group by txt"}]' 127.0.0.1:7111/grafana/query
\ No newline at end of file print 20-> $system_content
if $system_content != @[{"refId":"A","target":"taosd{last(col2):2.00000, last(txt):HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS HELLO TAOS}","datapoints":[[1,"-"]]}]@ then
return -1
endi
system sh/exec.sh -n dnode1 -s stop -x SIGINT
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册