diff --git a/.drone.yml b/.drone.yml index 4009b563b4cfd7e42ca58f07014245400f7e5f6d..e7ae6ebbdaed1b2446e99e3f0365907ff44754d0 100644 --- a/.drone.yml +++ b/.drone.yml @@ -7,27 +7,19 @@ platform: arch: amd64 steps: -- name: build - image: gcc - commands: - - apt-get update - - apt-get install -y cmake build-essential git - - mkdir debug - - cd debug - - cmake .. - - make - when: - branch: - - develop - - master - - name: smoke_test image: python:3.8 commands: + - apt-get update + - apt-get install -y cmake build-essential gcc - pip3 install psutil - pip3 install guppy3 - pip3 install src/connector/python/linux/python3/ - - cd tests + - mkdir debug + - cd debug + - cmake .. + - make + - cd ../tests - ./test-all.sh smoke when: branch: @@ -82,7 +74,7 @@ platform: steps: - name: build - image: gcc + image: arm32v7/ubuntu:bionic commands: - apt-get update - apt-get install -y cmake build-essential diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 0617d759768251fcf09aa2316f3556f20c1718d8..0000000000000000000000000000000000000000 --- a/.travis.yml +++ /dev/null @@ -1,296 +0,0 @@ -# -# Configuration -# -# -# Build Matrix -# -branches: - only: - - master - - develop - - coverity_scan - - /^.*ci-.*$/ - -matrix: - - os: linux - dist: focal - language: c - - git: - - depth: 1 - - compiler: gcc - env: DESC="linux/gcc build and test" - - addons: - apt: - packages: - - build-essential - - cmake - - net-tools - - python3-pip - - python3-setuptools - - valgrind - - psmisc - - unixodbc - - unixodbc-dev - - mono-complete - - before_script: - - export TZ=Asia/Harbin - - date - - cd ${TRAVIS_BUILD_DIR} - - mkdir debug - - cd debug - - script: - - cmake .. > /dev/null - - make > /dev/null - - after_success: - - travis_wait 20 - - |- - case $TRAVIS_OS_NAME in - linux) - cd ${TRAVIS_BUILD_DIR}/debug - make install > /dev/null || travis_terminate $? - - py3ver=`python3 --version|awk '{print $2}'|cut -d "." -f 1,2` && apt install python$py3ver-dev - pip3 install psutil - pip3 install guppy3 - pip3 install --user ${TRAVIS_BUILD_DIR}/src/connector/python/linux/python3/ - - cd ${TRAVIS_BUILD_DIR}/tests/examples/C#/taosdemo - mcs -out:taosdemo *.cs || travis_terminate $? - pkill -TERM -x taosd - fuser -k -n tcp 6030 - sleep 1 - ${TRAVIS_BUILD_DIR}/debug/build/bin/taosd -c ${TRAVIS_BUILD_DIR}/debug/test/cfg > /dev/null & - sleep 5 - mono taosdemo -Q DEFAULT -y || travis_terminate $? - pkill -KILL -x taosd - fuser -k -n tcp 6030 - sleep 1 - - cd ${TRAVIS_BUILD_DIR}/tests - ./test-all.sh smoke || travis_terminate $? - sleep 1 - - cd ${TRAVIS_BUILD_DIR}/tests/pytest - pkill -TERM -x taosd - fuser -k -n tcp 6030 - sleep 1 - ./crash_gen.sh -a -p -t 4 -s 2000|| travis_terminate $? - sleep 1 - - cd ${TRAVIS_BUILD_DIR}/tests/pytest - ./valgrind-test.sh 2>&1 > mem-error-out.log - sleep 1 - - - # Color setting - RED='\033[0;31m' - GREEN='\033[1;32m' - GREEN_DARK='\033[0;32m' - GREEN_UNDERLINE='\033[4;32m' - NC='\033[0m' - - grep 'start to execute\|ERROR SUMMARY' mem-error-out.log|grep -v 'grep'|uniq|tee uniq-mem-error-out.log - - for memError in `grep 'ERROR SUMMARY' uniq-mem-error-out.log | awk '{print $4}'` - do - if [ -n "$memError" ]; then - if [ "$memError" -gt 12 ]; then - echo -e "${RED} ## Memory errors number valgrind reports is $memError.\ - More than our threshold! ## ${NC}" - travis_terminate $memError - fi - fi - done - - grep 'start to execute\|definitely lost:' mem-error-out.log|grep -v 'grep'|uniq|tee uniq-definitely-lost-out.log - for defiMemError in `grep 'definitely lost:' uniq-definitely-lost-out.log | awk '{print $7}'` - do - if [ -n "$defiMemError" ]; then - if [ "$defiMemError" -gt 13 ]; then - echo -e "${RED} ## Memory errors number valgrind reports \ - Definitely lost is $defiMemError. More than our threshold! ## ${NC}" - travis_terminate $defiMemError - fi - fi - done - - ;; - esac - - - os: linux - dist: bionic - language: c - compiler: gcc - env: COVERITY_SCAN=true - git: - - depth: 1 - - script: - - echo "this job is for coverity scan" - - addons: - coverity_scan: - # GitHub project metadata - # ** specific to your project ** - project: - name: TDengine - version: 2.x - description: TDengine - - # Where email notification of build analysis results will be sent - notification_email: sdsang@taosdata.com, slguan@taosdata.com - - # Commands to prepare for build_command - # ** likely specific to your build ** - build_command_prepend: cmake . > /dev/null - - # The command that will be added as an argument to "cov-build" to compile your project for analysis, - # ** likely specific to your build ** - build_command: make - - # Pattern to match selecting branches that will run analysis. We recommend leaving this set to 'coverity_scan'. - # Take care in resource usage, and consider the build frequency allowances per - # https://scan.coverity.com/faq#frequency - branch_pattern: coverity_scan - - - os: linux - dist: trusty - language: c - git: - - depth: 1 - - addons: - apt: - packages: - - build-essential - - cmake - - binutils-2.26 - - unixodbc - - unixodbc-dev - env: - - DESC="trusty/gcc-4.8/bintuils-2.26 build" - - before_script: - - export TZ=Asia/Harbin - - date - - cd ${TRAVIS_BUILD_DIR} - - mkdir debug - - cd debug - - script: - - cmake .. > /dev/null - - export PATH=/usr/lib/binutils-2.26/bin:$PATH && make - - - os: linux - dist: bionic - language: c - compiler: clang - env: DESC="linux/clang build" - git: - - depth: 1 - - addons: - apt: - packages: - - build-essential - - cmake - - unixodbc - - unixodbc-dev - - before_script: - - export TZ=Asia/Harbin - - date - - cd ${TRAVIS_BUILD_DIR} - - mkdir debug - - cd debug - - script: - - cmake .. > /dev/null - - make > /dev/null - - - os: linux - arch: arm64 - dist: bionic - language: c - compiler: clang - env: DESC="arm64 linux/clang build" - git: - - depth: 1 - - addons: - apt: - packages: - - build-essential - - cmake - - before_script: - - export TZ=Asia/Harbin - - date - - cd ${TRAVIS_BUILD_DIR} - - mkdir debug - - cd debug - - script: - - if [ "${TRAVIS_CPU_ARCH}" == "arm64" ]; then - cmake .. -DCPUTYPE=aarch64 > /dev/null; - else - cmake .. > /dev/null; - fi - - make > /dev/null - - - os: linux - arch: arm64 - dist: xenial - language: c - git: - - depth: 1 - - addons: - apt: - packages: - - build-essential - - cmake - - unixodbc - - unixodbc-dev - env: - - DESC="arm64 xenial build" - - before_script: - - export TZ=Asia/Harbin - - date - - cd ${TRAVIS_BUILD_DIR} - - mkdir debug - - cd debug - - script: - - if [ "${TRAVIS_CPU_ARCH}" == "arm64" ]; then - cmake .. -DCPUTYPE=aarch64 > /dev/null; - else - cmake .. > /dev/null; - fi - - make > /dev/null - - - os: osx - osx_image: xcode11.4 - language: c - compiler: clang - env: DESC="mac/clang build" - git: - - depth: 1 - addons: - homebrew: - - cmake - - unixodbc - - script: - - cd ${TRAVIS_BUILD_DIR} - - mkdir debug - - cd debug - - cmake .. > /dev/null - - make > /dev/null diff --git a/Jenkinsfile b/Jenkinsfile index dfe9ed4389933b710ed422e6ffc7e0673e0157dc..33ce784bce134134bbb78ffffb9d58b71dbd17f7 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -94,6 +94,7 @@ def pre_test(){ make > /dev/null make install > /dev/null cd ${WKC}/tests + pip3 install ${WKC}/src/connector/python/linux/python3/ ''' return 1 } diff --git a/cmake/install.inc b/cmake/install.inc index 5823ef743ed5b5b57f3915a82aa9e1e21f850d2f..9e325531d51c7ebb315fb01ccbd0cbb06ffcd5d5 100755 --- a/cmake/install.inc +++ b/cmake/install.inc @@ -32,7 +32,7 @@ ELSEIF (TD_WINDOWS) #INSTALL(TARGETS taos RUNTIME DESTINATION driver) #INSTALL(TARGETS shell RUNTIME DESTINATION .) IF (TD_MVN_INSTALLED) - INSTALL(FILES ${LIBRARY_OUTPUT_PATH}/taos-jdbcdriver-2.0.25-dist.jar DESTINATION connector/jdbc) + INSTALL(FILES ${LIBRARY_OUTPUT_PATH}/taos-jdbcdriver-2.0.28-dist.jar DESTINATION connector/jdbc) ENDIF () ELSEIF (TD_DARWIN) SET(TD_MAKE_INSTALL_SH "${TD_COMMUNITY_DIR}/packaging/tools/make_install.sh") diff --git a/cmake/version.inc b/cmake/version.inc index 8035b31cc7a9a391becaacbff22d708177536ce2..a560c7f5988b10cee040078e070316302d5584b7 100755 --- a/cmake/version.inc +++ b/cmake/version.inc @@ -4,7 +4,7 @@ PROJECT(TDengine) IF (DEFINED VERNUMBER) SET(TD_VER_NUMBER ${VERNUMBER}) ELSE () - SET(TD_VER_NUMBER "2.0.20.0") + SET(TD_VER_NUMBER "2.0.20.2") ENDIF () IF (DEFINED VERCOMPATIBLE) diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml index 31343ed293c2617a56da57e3893a36b5d3289faf..9c7400c6165f88fec22ac1e811c2b204a3e103ba 100644 --- a/snap/snapcraft.yaml +++ b/snap/snapcraft.yaml @@ -1,6 +1,6 @@ name: tdengine base: core18 -version: '2.0.20.0' +version: '2.0.20.2' icon: snap/gui/t-dengine.svg summary: an open-source big data platform designed and optimized for IoT. description: | @@ -72,7 +72,7 @@ parts: - usr/bin/taosd - usr/bin/taos - usr/bin/taosdemo - - usr/lib/libtaos.so.2.0.20.0 + - usr/lib/libtaos.so.2.0.20.2 - usr/lib/libtaos.so.1 - usr/lib/libtaos.so diff --git a/src/client/inc/tscUtil.h b/src/client/inc/tscUtil.h index 0eda49b1f40876f695594e80874c60407e1ca45c..b80dcfb5774b96aa94e36429de3113d1690feeb4 100644 --- a/src/client/inc/tscUtil.h +++ b/src/client/inc/tscUtil.h @@ -168,7 +168,8 @@ void tscFieldInfoClear(SFieldInfo* pFieldInfo); static FORCE_INLINE int32_t tscNumOfFields(SQueryInfo* pQueryInfo) { return pQueryInfo->fieldsInfo.numOfOutput; } -int32_t tscFieldInfoCompare(const SFieldInfo* pFieldInfo1, const SFieldInfo* pFieldInfo2); +int32_t tscFieldInfoCompare(const SFieldInfo* pFieldInfo1, const SFieldInfo* pFieldInfo2, int32_t *diffSize); +int32_t tscFieldInfoSetSize(const SFieldInfo* pFieldInfo1, const SFieldInfo* pFieldInfo2); void addExprParams(SSqlExpr* pExpr, char* argument, int32_t type, int32_t bytes); @@ -297,7 +298,7 @@ STableMeta* createSuperTableMeta(STableMetaMsg* pChild); uint32_t tscGetTableMetaSize(STableMeta* pTableMeta); CChildTableMeta* tscCreateChildMeta(STableMeta* pTableMeta); uint32_t tscGetTableMetaMaxSize(); -int32_t tscCreateTableMetaFromCChildMeta(STableMeta* pChild, const char* name); +int32_t tscCreateTableMetaFromCChildMeta(STableMeta* pChild, const char* name, void* buf); STableMeta* tscTableMetaDup(STableMeta* pTableMeta); diff --git a/src/client/inc/tsclient.h b/src/client/inc/tsclient.h index c91943e232864ccba69150325bb12c08eb5dee5d..6d94d270a774cad67b08d072c210fb80bc164647 100644 --- a/src/client/inc/tsclient.h +++ b/src/client/inc/tsclient.h @@ -83,6 +83,7 @@ typedef struct STableMeta { typedef struct STableMetaInfo { STableMeta *pTableMeta; // table meta, cached in client side and acquired by name + uint32_t tableMetaSize; SVgroupsInfo *vgroupList; SArray *pVgroupTables; // SArray diff --git a/src/client/src/tscParseInsert.c b/src/client/src/tscParseInsert.c index 79ceb81cbcd999066655526085588d5681bb5753..f17afa0f780f14f2ec6a140b01858677803f2969 100644 --- a/src/client/src/tscParseInsert.c +++ b/src/client/src/tscParseInsert.c @@ -705,19 +705,11 @@ static int32_t doParseInsertStatement(SSqlCmd* pCmd, char **str, STableDataBlock } code = TSDB_CODE_TSC_INVALID_SQL; - char *tmpTokenBuf = calloc(1, 16*1024); // used for deleting Escape character: \\, \', \" - if (NULL == tmpTokenBuf) { - return TSDB_CODE_TSC_OUT_OF_MEMORY; - } + char tmpTokenBuf[16*1024] = {0}; // used for deleting Escape character: \\, \', \" int32_t numOfRows = 0; code = tsParseValues(str, dataBuf, maxNumOfRows, pCmd, &numOfRows, tmpTokenBuf); - free(tmpTokenBuf); - if (code != TSDB_CODE_SUCCESS) { - return code; - } - for (uint32_t i = 0; i < dataBuf->numOfParams; ++i) { SParamInfo *param = dataBuf->params + i; if (param->idx == -1) { diff --git a/src/client/src/tscSQLParser.c b/src/client/src/tscSQLParser.c index 751c4bf39fca595b4bfddb1b553e4e70c0078843..4251695d7bab65c8b86e3b9f19bf951f107bcdf7 100644 --- a/src/client/src/tscSQLParser.c +++ b/src/client/src/tscSQLParser.c @@ -64,7 +64,7 @@ static char* getAccountId(SSqlObj* pSql); static bool has(SArray* pFieldList, int32_t startIdx, const char* name); static char* cloneCurrentDBName(SSqlObj* pSql); -static bool hasSpecifyDB(SStrToken* pTableName); +static int32_t getDelimiterIndex(SStrToken* pTableName); static bool validateTableColumnInfo(SArray* pFieldList, SSqlCmd* pCmd); static bool validateTagParams(SArray* pTagsList, SArray* pFieldList, SSqlCmd* pCmd); @@ -426,17 +426,11 @@ int32_t tscToSQLCmd(SSqlObj* pSql, struct SSqlInfo* pInfo) { case TSDB_SQL_DESCRIBE_TABLE: { const char* msg1 = "invalid table name"; - const char* msg2 = "table name too long"; SStrToken* pToken = taosArrayGet(pInfo->pMiscInfo->a, 0); if (tscValidateName(pToken) != TSDB_CODE_SUCCESS) { return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1); } - - if (!tscValidateTableNameLength(pToken->n)) { - return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2); - } - // additional msg has been attached already code = tscSetTableFullName(pTableMetaInfo, pToken, pSql); if (code != TSDB_CODE_SUCCESS) { @@ -447,17 +441,12 @@ int32_t tscToSQLCmd(SSqlObj* pSql, struct SSqlInfo* pInfo) { } case TSDB_SQL_SHOW_CREATE_TABLE: { const char* msg1 = "invalid table name"; - const char* msg2 = "table name is too long"; SStrToken* pToken = taosArrayGet(pInfo->pMiscInfo->a, 0); if (tscValidateName(pToken) != TSDB_CODE_SUCCESS) { return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1); } - if (!tscValidateTableNameLength(pToken->n)) { - return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2); - } - code = tscSetTableFullName(pTableMetaInfo, pToken, pSql); if (code != TSDB_CODE_SUCCESS) { return code; @@ -642,17 +631,25 @@ int32_t tscToSQLCmd(SSqlObj* pSql, struct SSqlInfo* pInfo) { // set the command/global limit parameters from the first subclause to the sqlcmd object SQueryInfo* pQueryInfo1 = tscGetQueryInfoDetail(pCmd, 0); pCmd->command = pQueryInfo1->command; - + int32_t diffSize = 0; + // if there is only one element, the limit of clause is the limit of global result. for (int32_t i = 1; i < pCmd->numOfClause; ++i) { SQueryInfo* pQueryInfo2 = tscGetQueryInfoDetail(pCmd, i); - int32_t ret = tscFieldInfoCompare(&pQueryInfo1->fieldsInfo, &pQueryInfo2->fieldsInfo); + int32_t ret = tscFieldInfoCompare(&pQueryInfo1->fieldsInfo, &pQueryInfo2->fieldsInfo, &diffSize); if (ret != 0) { return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1); } } + if (diffSize) { + for (int32_t i = 1; i < pCmd->numOfClause; ++i) { + SQueryInfo* pQueryInfo2 = tscGetQueryInfoDetail(pCmd, i); + tscFieldInfoSetSize(&pQueryInfo1->fieldsInfo, &pQueryInfo2->fieldsInfo); + } + } + pCmd->parseFinished = 1; return TSDB_CODE_SUCCESS; // do not build query message here } @@ -979,11 +976,13 @@ int32_t tscSetTableFullName(STableMetaInfo* pTableMetaInfo, SStrToken* pTableNam const char* msg1 = "name too long"; const char* msg2 = "acctId too long"; const char* msg3 = "no acctId"; + const char* msg4 = "db name too long"; + const char* msg5 = "table name too long"; SSqlCmd* pCmd = &pSql->cmd; int32_t code = TSDB_CODE_SUCCESS; - - if (hasSpecifyDB(pTableName)) { // db has been specified in sql string so we ignore current db path + int32_t idx = getDelimiterIndex(pTableName); + if (idx != -1) { // db has been specified in sql string so we ignore current db path char* acctId = getAccountId(pSql); if (acctId == NULL || strlen(acctId) <= 0) { return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3); @@ -993,6 +992,13 @@ int32_t tscSetTableFullName(STableMetaInfo* pTableMetaInfo, SStrToken* pTableNam if (code != 0) { return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2); } + if (idx >= TSDB_DB_NAME_LEN) { + return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg4); + } + if (pTableName->n - 1 - idx >= TSDB_TABLE_NAME_LEN) { + return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg5); + } + char name[TSDB_TABLE_FNAME_LEN] = {0}; strncpy(name, pTableName->z, pTableName->n); @@ -1337,14 +1343,13 @@ static char* cloneCurrentDBName(SSqlObj* pSql) { } /* length limitation, strstr cannot be applied */ -static bool hasSpecifyDB(SStrToken* pTableName) { - for (uint32_t i = 0; i < pTableName->n; ++i) { - if (pTableName->z[i] == TS_PATH_DELIMITER[0]) { - return true; +static int32_t getDelimiterIndex(SStrToken* pTableName) { + for (uint32_t i = 0; i < pTableName->n; ++i) { + if (pTableName->z[i] == TS_PATH_DELIMITER[0]) { + return i; } } - - return false; + return -1; } int32_t setObjFullName(char* fullName, const char* account, SStrToken* pDB, SStrToken* tableName, int32_t* xlen) { @@ -1606,6 +1611,22 @@ bool isValidDistinctSql(SQueryInfo* pQueryInfo) { return false; } +static bool hasNoneUserDefineExpr(SQueryInfo* pQueryInfo) { + size_t numOfExprs = taosArrayGetSize(pQueryInfo->exprList); + for (int32_t i = 0; i < numOfExprs; ++i) { + SSqlExpr* pExpr = taosArrayGetP(pQueryInfo->exprList, i); + + if (TSDB_COL_IS_UD_COL(pExpr->colInfo.flag)) { + continue; + } + + return true; + } + + return false; +} + + int32_t parseSelectClause(SSqlCmd* pCmd, int32_t clauseIndex, SArray* pSelectList, bool isSTable, bool joinQuery, bool timeWindowQuery) { assert(pSelectList != NULL && pCmd != NULL); const char* msg1 = "too many columns in selection clause"; @@ -1670,7 +1691,7 @@ int32_t parseSelectClause(SSqlCmd* pCmd, int32_t clauseIndex, SArray* pSelectLis // there is only one user-defined column in the final result field, add the timestamp column. size_t numOfSrcCols = taosArrayGetSize(pQueryInfo->colList); - if (numOfSrcCols <= 0 && !tscQueryTags(pQueryInfo) && !tscQueryBlockInfo(pQueryInfo)) { + if ((numOfSrcCols <= 0 || !hasNoneUserDefineExpr(pQueryInfo)) && !tscQueryTags(pQueryInfo) && !tscQueryBlockInfo(pQueryInfo)) { addPrimaryTsColIntoResult(pQueryInfo); } @@ -7459,11 +7480,3 @@ bool hasNormalColumnFilter(SQueryInfo* pQueryInfo) { return false; } - - - - - - - - diff --git a/src/client/src/tscServer.c b/src/client/src/tscServer.c index 194c7a0eca8597f78611e27c642baa5ef623c612..33325c7fd7adbb8c8c4262340554b945224ae49e 100644 --- a/src/client/src/tscServer.c +++ b/src/client/src/tscServer.c @@ -1973,6 +1973,8 @@ int tscProcessTableMetaRsp(SSqlObj *pSql) { return TSDB_CODE_TSC_INVALID_VALUE; } + assert(pTableMeta->tableType == TSDB_SUPER_TABLE || pTableMeta->tableType == TSDB_CHILD_TABLE || pTableMeta->tableType == TSDB_NORMAL_TABLE || pTableMeta->tableType == TSDB_STREAM_TABLE); + if (pTableMeta->tableType == TSDB_CHILD_TABLE) { // check if super table hashmap or not int32_t len = (int32_t) strnlen(pTableMeta->sTableName, TSDB_TABLE_FNAME_LEN); @@ -2530,10 +2532,23 @@ static int32_t getTableMetaFromMnode(SSqlObj *pSql, STableMetaInfo *pTableMetaIn int32_t tscGetTableMeta(SSqlObj *pSql, STableMetaInfo *pTableMetaInfo) { assert(tIsValidName(&pTableMetaInfo->name)); - tfree(pTableMetaInfo->pTableMeta); - uint32_t size = tscGetTableMetaMaxSize(); - pTableMetaInfo->pTableMeta = calloc(1, size); + if (pTableMetaInfo->pTableMeta == NULL) { + pTableMetaInfo->pTableMeta = calloc(1, size); + pTableMetaInfo->tableMetaSize = size; + } else if (pTableMetaInfo->tableMetaSize < size) { + char *tmp = realloc(pTableMetaInfo->pTableMeta, size); + if (tmp == NULL) { + return TSDB_CODE_TSC_OUT_OF_MEMORY; + } + pTableMetaInfo->pTableMeta = (STableMeta *)tmp; + memset(pTableMetaInfo->pTableMeta, 0, size); + pTableMetaInfo->tableMetaSize = size; + } else { + //uint32_t s = tscGetTableMetaSize(pTableMetaInfo->pTableMeta); + memset(pTableMetaInfo->pTableMeta, 0, size); + pTableMetaInfo->tableMetaSize = size; + } pTableMetaInfo->pTableMeta->tableType = -1; pTableMetaInfo->pTableMeta->tableInfo.numOfColumns = -1; @@ -2545,10 +2560,13 @@ int32_t tscGetTableMeta(SSqlObj *pSql, STableMetaInfo *pTableMetaInfo) { taosHashGetClone(tscTableMetaInfo, name, len, NULL, pTableMetaInfo->pTableMeta, -1); // TODO resize the tableMeta + char buf[80*1024] = {0}; + assert(size < 80*1024); + STableMeta* pMeta = pTableMetaInfo->pTableMeta; if (pMeta->id.uid > 0) { if (pMeta->tableType == TSDB_CHILD_TABLE) { - int32_t code = tscCreateTableMetaFromCChildMeta(pTableMetaInfo->pTableMeta, name); + int32_t code = tscCreateTableMetaFromCChildMeta(pTableMetaInfo->pTableMeta, name, buf); if (code != TSDB_CODE_SUCCESS) { return getTableMetaFromMnode(pSql, pTableMetaInfo); } diff --git a/src/client/src/tscUtil.c b/src/client/src/tscUtil.c index fa9e53b0a6c962104a09bef63cc113ccc5ee5dd8..37875790dd4fcfba8957345156a06c783c424c46 100644 --- a/src/client/src/tscUtil.c +++ b/src/client/src/tscUtil.c @@ -693,7 +693,8 @@ int32_t tscCopyDataBlockToPayload(SSqlObj* pSql, STableDataBlocks* pDataBlock) { tfree(pTableMetaInfo->pTableMeta); } - pTableMetaInfo->pTableMeta = tscTableMetaDup(pDataBlock->pTableMeta); + pTableMetaInfo->pTableMeta = tscTableMetaDup(pDataBlock->pTableMeta); + pTableMetaInfo->tableMetaSize = tscGetTableMetaSize(pDataBlock->pTableMeta); } /* @@ -1098,7 +1099,7 @@ int16_t tscFieldInfoGetOffset(SQueryInfo* pQueryInfo, int32_t index) { return pInfo->pSqlExpr->offset; } -int32_t tscFieldInfoCompare(const SFieldInfo* pFieldInfo1, const SFieldInfo* pFieldInfo2) { +int32_t tscFieldInfoCompare(const SFieldInfo* pFieldInfo1, const SFieldInfo* pFieldInfo2, int32_t *diffSize) { assert(pFieldInfo1 != NULL && pFieldInfo2 != NULL); if (pFieldInfo1->numOfOutput != pFieldInfo2->numOfOutput) { @@ -1110,15 +1111,36 @@ int32_t tscFieldInfoCompare(const SFieldInfo* pFieldInfo1, const SFieldInfo* pFi TAOS_FIELD* pField2 = tscFieldInfoGetField((SFieldInfo*) pFieldInfo2, i); if (pField1->type != pField2->type || - pField1->bytes != pField2->bytes || strcasecmp(pField1->name, pField2->name) != 0) { return 1; } + + if (pField1->bytes != pField2->bytes) { + *diffSize = 1; + + if (pField2->bytes > pField1->bytes) { + pField1->bytes = pField2->bytes; + } + } + } + + return 0; +} + +int32_t tscFieldInfoSetSize(const SFieldInfo* pFieldInfo1, const SFieldInfo* pFieldInfo2) { + assert(pFieldInfo1 != NULL && pFieldInfo2 != NULL); + + for (int32_t i = 0; i < pFieldInfo1->numOfOutput; ++i) { + TAOS_FIELD* pField1 = tscFieldInfoGetField((SFieldInfo*) pFieldInfo1, i); + TAOS_FIELD* pField2 = tscFieldInfoGetField((SFieldInfo*) pFieldInfo2, i); + + pField2->bytes = pField1->bytes; } return 0; } + int32_t tscGetResRowLength(SArray* pExprList) { size_t num = taosArrayGetSize(pExprList); if (num == 0) { @@ -2057,6 +2079,11 @@ STableMetaInfo* tscAddTableMetaInfo(SQueryInfo* pQueryInfo, SName* name, STableM } pTableMetaInfo->pTableMeta = pTableMeta; + if (pTableMetaInfo->pTableMeta == NULL) { + pTableMetaInfo->tableMetaSize = 0; + } else { + pTableMetaInfo->tableMetaSize = tscGetTableMetaSize(pTableMeta); + } if (vgroupList != NULL) { pTableMetaInfo->vgroupList = tscVgroupInfoClone(vgroupList); @@ -2331,6 +2358,7 @@ SSqlObj* createSubqueryObj(SSqlObj* pSql, int16_t tableIndex, __async_cb_func_t pFinalInfo = tscAddTableMetaInfo(pNewQueryInfo, &pTableMetaInfo->name, pTableMeta, pTableMetaInfo->vgroupList, pTableMetaInfo->tagColList, pTableMetaInfo->pVgroupTables); + } else { // transfer the ownership of pTableMeta to the newly create sql object. STableMetaInfo* pPrevInfo = tscGetTableMetaInfoFromCmd(&pPrevSql->cmd, pPrevSql->cmd.clauseIndex, 0); if (pPrevInfo->pTableMeta && pPrevInfo->pTableMeta->tableType < 0) { @@ -2682,7 +2710,13 @@ void tscTryQueryNextClause(SSqlObj* pSql, __async_cb_func_t fp) { //backup the total number of result first int64_t num = pRes->numOfTotal + pRes->numOfClauseTotal; + + + // DON't free final since it may be recoreded and used later in APP + TAOS_FIELD* finalBk = pRes->final; + pRes->final = NULL; tscFreeSqlResult(pSql); + pRes->final = finalBk; pRes->numOfTotal = num; @@ -2915,11 +2949,11 @@ CChildTableMeta* tscCreateChildMeta(STableMeta* pTableMeta) { return cMeta; } -int32_t tscCreateTableMetaFromCChildMeta(STableMeta* pChild, const char* name) { - assert(pChild != NULL); +int32_t tscCreateTableMetaFromCChildMeta(STableMeta* pChild, const char* name, void* buf) { + assert(pChild != NULL && buf != NULL); - uint32_t size = tscGetTableMetaMaxSize(); - STableMeta* p = calloc(1, size); +// uint32_t size = tscGetTableMetaMaxSize(); + STableMeta* p = buf;//calloc(1, size); taosHashGetClone(tscTableMetaInfo, pChild->sTableName, strnlen(pChild->sTableName, TSDB_TABLE_FNAME_LEN), NULL, p, -1); if (p->id.uid > 0) { // tableMeta exists, build child table meta and return @@ -2931,12 +2965,12 @@ int32_t tscCreateTableMetaFromCChildMeta(STableMeta* pChild, const char* name) { memcpy(pChild->schema, p->schema, sizeof(SSchema) *total); - tfree(p); +// tfree(p); return TSDB_CODE_SUCCESS; } else { // super table has been removed, current tableMeta is also expired. remove it here taosHashRemove(tscTableMetaInfo, name, strnlen(name, TSDB_TABLE_FNAME_LEN)); - tfree(p); +// tfree(p); return -1; } } diff --git a/src/connector/jdbc/CMakeLists.txt b/src/connector/jdbc/CMakeLists.txt index eb158b1f769f97482a314f2797ec247f756b3b39..de4b8f6bfb92d2de0810dab50c70452f7d47b7a8 100644 --- a/src/connector/jdbc/CMakeLists.txt +++ b/src/connector/jdbc/CMakeLists.txt @@ -8,7 +8,7 @@ IF (TD_MVN_INSTALLED) ADD_CUSTOM_COMMAND(OUTPUT ${JDBC_CMD_NAME} POST_BUILD COMMAND mvn -Dmaven.test.skip=true install -f ${CMAKE_CURRENT_SOURCE_DIR}/pom.xml - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/target/taos-jdbcdriver-2.0.25-dist.jar ${LIBRARY_OUTPUT_PATH} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/target/taos-jdbcdriver-2.0.28-dist.jar ${LIBRARY_OUTPUT_PATH} COMMAND mvn -Dmaven.test.skip=true clean -f ${CMAKE_CURRENT_SOURCE_DIR}/pom.xml COMMENT "build jdbc driver") ADD_CUSTOM_TARGET(${JDBC_TARGET_NAME} ALL WORKING_DIRECTORY ${EXECUTABLE_OUTPUT_PATH} DEPENDS ${JDBC_CMD_NAME}) diff --git a/src/connector/jdbc/deploy-pom.xml b/src/connector/jdbc/deploy-pom.xml index eb8c92575c4b9953e5b8155d2bf2b1ded4772a26..a31796ffdeeb4b76835e4b04d40720dda149fddc 100755 --- a/src/connector/jdbc/deploy-pom.xml +++ b/src/connector/jdbc/deploy-pom.xml @@ -5,7 +5,7 @@ com.taosdata.jdbc taos-jdbcdriver - 2.0.25 + 2.0.28 jar JDBCDriver diff --git a/src/connector/jdbc/pom.xml b/src/connector/jdbc/pom.xml index 1f75754b0c46ec0afced88743c5aba1d308c24ec..3400a82e73640c79f6157fafd2bbe8c7520145dd 100755 --- a/src/connector/jdbc/pom.xml +++ b/src/connector/jdbc/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.taosdata.jdbc taos-jdbcdriver - 2.0.25 + 2.0.28 jar JDBCDriver https://github.com/taosdata/TDengine/tree/master/src/connector/jdbc diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractConnection.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractConnection.java index 976078da95c387110a2e5e55076a42a2c320ca18..2970f6c2d37d73476ee0d8831a68128569766fb4 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractConnection.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractConnection.java @@ -4,13 +4,23 @@ import java.sql.*; import java.util.Enumeration; import java.util.Map; import java.util.Properties; +import java.util.Set; import java.util.concurrent.*; public abstract class AbstractConnection extends WrapperImpl implements Connection { protected volatile boolean isClosed; protected volatile String catalog; - protected volatile Properties clientInfoProps = new Properties(); + protected final Properties clientInfoProps = new Properties(); + + protected AbstractConnection(Properties properties) { + Set propNames = properties.stringPropertyNames(); + for (String propName : propNames) { + clientInfoProps.setProperty(propName, properties.getProperty(propName)); + } + String timestampFormat = properties.getProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, "STRING"); + clientInfoProps.setProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, timestampFormat); + } @Override public abstract Statement createStatement() throws SQLException; @@ -35,7 +45,6 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti } - @Override public void setAutoCommit(boolean autoCommit) throws SQLException { if (isClosed()) @@ -441,9 +450,8 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti if (isClosed) throw (SQLClientInfoException) TSDBError.createSQLException(TSDBErrorNumbers.ERROR_SQLCLIENT_EXCEPTION_ON_CONNECTION_CLOSED); - if (clientInfoProps == null) - clientInfoProps = new Properties(); - clientInfoProps.setProperty(name, value); + if (clientInfoProps != null) + clientInfoProps.setProperty(name, value); } @Override diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractResultSet.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractResultSet.java index abd348e68c3ebac0d940b4c9789a85ddd68e238e..4b5b88d93bdf14b2387708a3e24229d0fd5d74d7 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractResultSet.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractResultSet.java @@ -10,6 +10,7 @@ import java.util.Map; public abstract class AbstractResultSet extends WrapperImpl implements ResultSet { private int fetchSize; + protected boolean wasNull; protected void checkAvailability(int columnIndex, int bounds) throws SQLException { if (isClosed()) @@ -28,7 +29,7 @@ public abstract class AbstractResultSet extends WrapperImpl implements ResultSet @Override public boolean wasNull() throws SQLException { - return false; + return wasNull; } @Override diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConnection.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConnection.java index 5b4615485dd21b7d5e41e513f48116edf53594d0..c8ab9fb15ae0ece504ff825dbbe16e12408aede0 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConnection.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConnection.java @@ -28,6 +28,7 @@ public class TSDBConnection extends AbstractConnection { } public TSDBConnection(Properties info, TSDBDatabaseMetaData meta) throws SQLException { + super(info); this.databaseMetaData = meta; connect(info.getProperty(TSDBDriver.PROPERTY_KEY_HOST), Integer.parseInt(info.getProperty(TSDBDriver.PROPERTY_KEY_PORT, "0")), diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBDriver.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBDriver.java index 5f599df1300b3d6959e9a7b58c00a720d722e07b..55533bd28cc4027c2e4a258cf2a36fd5b72d12f2 100755 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBDriver.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBDriver.java @@ -95,11 +95,16 @@ public class TSDBDriver extends AbstractDriver { */ public static final String PROPERTY_KEY_BATCH_LOAD = "batchfetch"; + /** + * timestamp format for JDBC-RESTful,should one of the options: string or timestamp or utc + */ + public static final String PROPERTY_KEY_TIMESTAMP_FORMAT = "timestampFormat"; + private TSDBDatabaseMetaData dbMetaData = null; static { try { - java.sql.DriverManager.registerDriver(new TSDBDriver()); + DriverManager.registerDriver(new TSDBDriver()); } catch (SQLException e) { throw TSDBError.createRuntimeException(TSDBErrorNumbers.ERROR_CANNOT_REGISTER_JNI_DRIVER, e); } diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBPreparedStatement.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBPreparedStatement.java index 728b537f715e69b4c79e3e67d2b9672c2e3d0714..56f971a35e72c60608fcc294298a2f3ca7fbc292 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBPreparedStatement.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBPreparedStatement.java @@ -14,11 +14,12 @@ *****************************************************************************/ package com.taosdata.jdbc; +import com.taosdata.jdbc.utils.Utils; + import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; -import java.nio.charset.Charset; import java.sql.*; import java.util.ArrayList; import java.util.Calendar; @@ -33,17 +34,9 @@ import java.util.regex.Pattern; public class TSDBPreparedStatement extends TSDBStatement implements PreparedStatement { private String rawSql; - private String sql; - // private ArrayList parameters = new ArrayList<>(); private Object[] parameters; private boolean isPrepared; - //start with insert or import and is case-insensitive - private static Pattern savePattern = Pattern.compile("(?i)^\\s*(insert|import)"); - // is insert or import - private boolean isSaved; - - // private SavedPreparedStatement savedPreparedStatement; private volatile TSDBParameterMetaData parameterMetaData; TSDBPreparedStatement(TSDBConnection connection, TSDBJNIConnector connecter, String sql) { @@ -65,35 +58,11 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat private void init(String sql) { this.rawSql = sql; preprocessSql(); -// this.isSaved = isSavedSql(this.rawSql); -// if (this.isSaved) { -// try { -// this.savedPreparedStatement = new SavedPreparedStatement(this.rawSql, this); -// } catch (SQLException e) { -// e.printStackTrace(); -// } -// } - - } - - /** - * if the precompiled sql is insert or import - * - * @param sql - * @return - */ - private boolean isSavedSql(String sql) { - Matcher matcher = savePattern.matcher(sql); - return matcher.find(); } @Override public int[] executeBatch() throws SQLException { -// if (isSaved) { -// return this.savedPreparedStatement.executeBatch(); -// } else { return super.executeBatch(); -// } } /* @@ -157,152 +126,64 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat * * @return a string of the native sql statement for TSDB */ -// private String getNativeSql(String rawSql) { -// for (int i = 0; i < parameters.length; i++) { -// Object para = parameters[i]; -// if (para != null) { -// String paraStr = para.toString(); -// if (para instanceof Timestamp || para instanceof String) { -// paraStr = "'" + paraStr + "'"; -// } -// this.sql = this.sql.replaceFirst("[?]", paraStr); -// } else { -// this.sql = this.sql.replaceFirst("[?]", "NULL"); -// } -// } -// parameters = new Object[parameters.length]; -// return sql; -// } - private String getNativeSql(String rawSql) throws SQLException { - String sql = rawSql; - for (int i = 0; i < parameters.length; ++i) { - Object para = parameters[i]; - if (para != null) { - String paraStr; - if (para instanceof byte[]) { - paraStr = new String((byte[]) para, Charset.forName("UTF-8")); - } else { - paraStr = para.toString(); - } - // if para is timestamp or String or byte[] need to translate ' character - if (para instanceof Timestamp || para instanceof String || para instanceof byte[]) { - paraStr = paraStr.replaceAll("'", "\\\\\\\\'"); - paraStr = "'" + paraStr + "'"; - } - sql = sql.replaceFirst("[?]", paraStr); - } else { - sql = sql.replaceFirst("[?]", "NULL"); - } - } - clearParameters(); - return sql; + return Utils.getNativeSql(rawSql, this.parameters); } @Override public ResultSet executeQuery() throws SQLException { -// if (isSaved) { -// this.savedPreparedStatement.executeBatchInternal(); -// return null; -// } else { - if (!isPrepared) return executeQuery(this.rawSql); final String sql = getNativeSql(this.rawSql); return executeQuery(sql); -// } } @Override public int executeUpdate() throws SQLException { -// if (isSaved) { -// return this.savedPreparedStatement.executeBatchInternal(); -// } else { if (!isPrepared) return executeUpdate(this.rawSql); String sql = getNativeSql(this.rawSql); return executeUpdate(sql); -// } - } - - private boolean isSupportedSQLType(int sqlType) { - switch (sqlType) { - case Types.TIMESTAMP: - case Types.INTEGER: - case Types.BIGINT: - case Types.FLOAT: - case Types.DOUBLE: - case Types.SMALLINT: - case Types.TINYINT: - case Types.BOOLEAN: - case Types.BINARY: - case Types.NCHAR: - return true; - default: - return false; - } } @Override public void setNull(int parameterIndex, int sqlType) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - if (!isSupportedSQLType(sqlType) || parameterIndex < 0) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); -// if (parameterIndex >= parameters.size()) -// throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_BOUNDARY); - - setObject(parameterIndex, "NULL"); + setObject(parameterIndex, null); } @Override public void setBoolean(int parameterIndex, boolean x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - setObject(parameterIndex, x); } @Override public void setByte(int parameterIndex, byte x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - setObject(parameterIndex,x); + setObject(parameterIndex, x); } @Override public void setShort(int parameterIndex, short x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); setObject(parameterIndex, x); } @Override public void setInt(int parameterIndex, int x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); setObject(parameterIndex, x); } @Override public void setLong(int parameterIndex, long x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); setObject(parameterIndex, x); } @Override public void setFloat(int parameterIndex, float x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); setObject(parameterIndex, x); } @Override public void setDouble(int parameterIndex, double x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); setObject(parameterIndex, x); } @@ -315,17 +196,12 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat @Override public void setString(int parameterIndex, String x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); setObject(parameterIndex, x); } @Override public void setBytes(int parameterIndex, byte[] x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - setObject(parameterIndex,x); + setObject(parameterIndex, x); } @Override @@ -344,8 +220,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat @Override public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); setObject(parameterIndex, x); } @@ -360,7 +234,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { if (isClosed()) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); } @@ -375,8 +248,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat public void clearParameters() throws SQLException { if (isClosed()) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - -// parameters.clear(); parameters = new Object[parameters.length]; } @@ -384,43 +255,29 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { if (isClosed()) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); + setObject(parameterIndex, x); } @Override public void setObject(int parameterIndex, Object x) throws SQLException { -// if (isSaved) { -// this.savedPreparedStatement.setParam(parameterIndex, x); -// } else { + if (isClosed()) + throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); if (parameterIndex < 1 && parameterIndex >= parameters.length) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_PARAMETER_INDEX_OUT_RANGE); - parameters[parameterIndex - 1] = x; -// parameters.add(x); -// } } @Override public boolean execute() throws SQLException { -// if (isSaved) { -// int result = this.savedPreparedStatement.executeBatchInternal(); -// return result > 0; -// } else { if (!isPrepared) return execute(this.rawSql); final String sql = getNativeSql(this.rawSql); - return execute(sql); -// } } @Override public void addBatch() throws SQLException { -// if (isSaved) { -// this.savedPreparedStatement.addBatch(); -// } else { if (this.batchedArgs == null) { batchedArgs = new ArrayList<>(); } @@ -431,7 +288,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat String sql = this.getConnection().nativeSQL(this.rawSql); addBatch(sql); } -// } } @Override @@ -475,7 +331,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat public ResultSetMetaData getMetaData() throws SQLException { if (isClosed()) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); -// return this.getResultSet().getMetaData(); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD); } diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSet.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSet.java index a20ddaa836535b2249ecc1a05e74a7903b9caeeb..2576a25f0d40e15efbb958706f672a40fbd2ee2e 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSet.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSet.java @@ -203,7 +203,11 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { this.lastWasNull = this.rowData.wasNull(columnIndex - 1); if (!lastWasNull) { - res = this.rowData.getLong(columnIndex - 1, this.columnMetaDataList.get(columnIndex - 1).getColType()); + Object value = this.rowData.get(columnIndex - 1); + if (value instanceof Timestamp) + res = ((Timestamp) value).getTime(); + else + res = this.rowData.getLong(columnIndex - 1, this.columnMetaDataList.get(columnIndex - 1).getColType()); } return res; } @@ -273,7 +277,6 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, this.columnMetaDataList.size()); Timestamp res = null; - if (this.getBatchFetch()) return this.blockData.getTimestamp(columnIndex - 1); diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java index 7cf5f0d79a89d0e6ed21d6b18136b92dc2c0b131..34470fbc4e5c06caa117737923612478d7039a90 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java @@ -17,6 +17,7 @@ package com.taosdata.jdbc; import java.math.BigDecimal; import java.sql.SQLException; import java.sql.Timestamp; +import java.time.Instant; import java.util.ArrayList; import java.util.Collections; @@ -299,7 +300,19 @@ public class TSDBResultSetRowData { } public void setTimestamp(int col, long ts) { - data.set(col, new Timestamp(ts)); + //TODO: this implementation contains logical error + // when precision is us the (long ts) is 16 digital number + // when precision is ms, the (long ts) is 13 digital number + // we need a JNI function like this: + // public void setTimestamp(int col, long epochSecond, long nanoAdjustment) + if (ts < 1_0000_0000_0000_0L) { + data.set(col, new Timestamp(ts)); + } else { + long epochSec = ts / 1000_000l; + long nanoAdjustment = ts % 1000_000l * 1000l; + Timestamp timestamp = Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); + data.set(col, timestamp); + } } public Timestamp getTimestamp(int col) { diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulConnection.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulConnection.java index 1f3ed2d144a88b10c0b1a8947e70def2c3db42a9..b810f9aeb59247ef618451b542a678d6c951ad3f 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulConnection.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulConnection.java @@ -22,6 +22,7 @@ public class RestfulConnection extends AbstractConnection { private final DatabaseMetaData metadata; public RestfulConnection(String host, String port, Properties props, String database, String url) { + super(props); this.host = host; this.port = Integer.parseInt(port); this.database = database; diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDriver.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDriver.java index 6efe13561d9509ee00d453e731bbc1ae4e3f0a75..a94cfa6e07c62ee9b163823aaad03bcc402bbffc 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDriver.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDriver.java @@ -17,7 +17,7 @@ public class RestfulDriver extends AbstractDriver { static { try { - java.sql.DriverManager.registerDriver(new RestfulDriver()); + DriverManager.registerDriver(new RestfulDriver()); } catch (SQLException e) { throw TSDBError.createRuntimeException(TSDBErrorNumbers.ERROR_URL_NOT_SET, e); } diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulPreparedStatement.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulPreparedStatement.java index f82955ca9dae5e3712da511a576aee64528061b5..f58e3f8cd2406e6372900c2f7b2547a450fb7fe9 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulPreparedStatement.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulPreparedStatement.java @@ -2,12 +2,12 @@ package com.taosdata.jdbc.rs; import com.taosdata.jdbc.TSDBError; import com.taosdata.jdbc.TSDBErrorNumbers; +import com.taosdata.jdbc.utils.Utils; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; -import java.nio.charset.Charset; import java.sql.*; import java.util.Calendar; @@ -21,6 +21,7 @@ public class RestfulPreparedStatement extends RestfulStatement implements Prepar public RestfulPreparedStatement(RestfulConnection conn, String database, String sql) { super(conn, database); this.rawSql = sql; + if (sql.contains("?")) { int parameterCnt = 0; for (int i = 0; i < sql.length(); i++) { @@ -58,29 +59,14 @@ public class RestfulPreparedStatement extends RestfulStatement implements Prepar return executeUpdate(sql); } - private String getNativeSql(String rawSql) throws SQLException { - String sql = rawSql; - for (int i = 0; i < parameters.length; ++i) { - Object para = parameters[i]; - if (para != null) { - String paraStr; - if (para instanceof byte[]) { - paraStr = new String((byte[]) para, Charset.forName("UTF-8")); - } else { - paraStr = para.toString(); - } - // if para is timestamp or String or byte[] need to translate ' character - if (para instanceof Timestamp || para instanceof String || para instanceof byte[]) { - paraStr = paraStr.replaceAll("'", "\\\\\\\\'"); - paraStr = "'" + paraStr + "'"; - } - sql = sql.replaceFirst("[?]", paraStr); - } else { - sql = sql.replaceFirst("[?]", "NULL"); - } - } - clearParameters(); - return sql; + /**** + * 将rawSql转换成一条可执行的sql语句,使用属性parameters中的变脸进行替换 + * 对于insert into ?.? (?,?,?) using ?.? (?,?,?) tags(?, ?, ?) values(?, ?, ?) + * @param rawSql,可能是insert、select或其他,使用?做占位符 + * @return + */ + private String getNativeSql(String rawSql) { + return Utils.getNativeSql(rawSql, this.parameters); } @Override @@ -220,8 +206,8 @@ public class RestfulPreparedStatement extends RestfulStatement implements Prepar public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { if (isClosed()) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - setObject(parameterIndex,x); + + setObject(parameterIndex, x); } @Override diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSet.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSet.java index 5c2d4c45b079974672843b232e38fcd9d010b0c4..db635f5f79f187dab98cb9fdfdc50369ca682fa9 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSet.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSet.java @@ -5,13 +5,12 @@ import com.alibaba.fastjson.JSONObject; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import com.google.common.primitives.Shorts; -import com.taosdata.jdbc.AbstractResultSet; -import com.taosdata.jdbc.TSDBConstants; -import com.taosdata.jdbc.TSDBError; -import com.taosdata.jdbc.TSDBErrorNumbers; +import com.taosdata.jdbc.*; import java.math.BigDecimal; import java.sql.*; +import java.time.Instant; +import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Calendar; @@ -19,6 +18,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { private volatile boolean isClosed; private int pos = -1; + private final String database; private final Statement statement; // data @@ -65,7 +65,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { } } - private Object parseColumnData(JSONArray row, int colIndex, int taosType) { + private Object parseColumnData(JSONArray row, int colIndex, int taosType) throws SQLException { switch (taosType) { case TSDBConstants.TSDB_DATA_TYPE_BOOL: return row.getBoolean(colIndex); @@ -81,8 +81,44 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { return row.getFloat(colIndex); case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: return row.getDouble(colIndex); - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: - return new Timestamp(row.getDate(colIndex).getTime()); + case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { + if (row.get(colIndex) == null) + return null; + String timestampFormat = this.statement.getConnection().getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT); + if ("TIMESTAMP".equalsIgnoreCase(timestampFormat)) { + Long value = row.getLong(colIndex); + //TODO: this implementation has bug if the timestamp bigger than 9999_9999_9999_9 + if (value < 1_0000_0000_0000_0L) + return new Timestamp(value); + long epochSec = value / 1000_000l; + long nanoAdjustment = value % 1000_000l * 1000l; + return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); + } + if ("UTC".equalsIgnoreCase(timestampFormat)) { + String value = row.getString(colIndex); + long epochSec = Timestamp.valueOf(value.substring(0, 19).replace("T", " ")).getTime() / 1000; + int fractionalSec = Integer.parseInt(value.substring(20, value.length() - 5)); + long nanoAdjustment = 0; + if (value.length() > 28) { + // ms timestamp: yyyy-MM-ddTHH:mm:ss.SSSSSS+0x00 + nanoAdjustment = fractionalSec * 1000l; + } else { + // ms timestamp: yyyy-MM-ddTHH:mm:ss.SSS+0x00 + nanoAdjustment = fractionalSec * 1000_000l; + } + ZoneOffset zoneOffset = ZoneOffset.of(value.substring(value.length() - 5)); + Instant instant = Instant.ofEpochSecond(epochSec, nanoAdjustment).atOffset(zoneOffset).toInstant(); + return Timestamp.from(instant); + } + String value = row.getString(colIndex); + if (value.length() <= 23) // ms timestamp: yyyy-MM-dd HH:mm:ss.SSS + return row.getTimestamp(colIndex); + // us timestamp: yyyy-MM-dd HH:mm:ss.SSSSSS + long epochSec = Timestamp.valueOf(value.substring(0, 19)).getTime() / 1000; + long nanoAdjustment = Integer.parseInt(value.substring(20)) * 1000l; + Timestamp timestamp = Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); + return timestamp; + } case TSDBConstants.TSDB_DATA_TYPE_BINARY: return row.getString(colIndex) == null ? null : row.getString(colIndex).getBytes(); case TSDBConstants.TSDB_DATA_TYPE_NCHAR: @@ -126,12 +162,12 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { } } - @Override - public boolean wasNull() throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); - return resultSet.isEmpty(); - } +// @Override +// public boolean wasNull() throws SQLException { +// if (isClosed()) +// throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED); +// return resultSet.isEmpty(); +// } @Override public String getString(int columnIndex) throws SQLException { @@ -150,8 +186,11 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, resultSet.get(pos).size()); Object value = resultSet.get(pos).get(columnIndex - 1); - if (value == null) + if (value == null) { + wasNull = true; return false; + } + wasNull = false; if (value instanceof Boolean) return (boolean) value; return Boolean.valueOf(value.toString()); @@ -162,8 +201,11 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, resultSet.get(pos).size()); Object value = resultSet.get(pos).get(columnIndex - 1); - if (value == null) + if (value == null) { + wasNull = true; return 0; + } + wasNull = false; long valueAsLong = Long.parseLong(value.toString()); if (valueAsLong == Byte.MIN_VALUE) return 0; @@ -183,8 +225,11 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, resultSet.get(pos).size()); Object value = resultSet.get(pos).get(columnIndex - 1); - if (value == null) + if (value == null) { + wasNull = true; return 0; + } + wasNull = false; long valueAsLong = Long.parseLong(value.toString()); if (valueAsLong == Short.MIN_VALUE) return 0; @@ -198,8 +243,11 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, resultSet.get(pos).size()); Object value = resultSet.get(pos).get(columnIndex - 1); - if (value == null) + if (value == null) { + wasNull = true; return 0; + } + wasNull = false; long valueAsLong = Long.parseLong(value.toString()); if (valueAsLong == Integer.MIN_VALUE) return 0; @@ -213,9 +261,14 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, resultSet.get(pos).size()); Object value = resultSet.get(pos).get(columnIndex - 1); - if (value == null) + if (value == null) { + wasNull = true; return 0; - + } + wasNull = false; + if (value instanceof Timestamp) { + return ((Timestamp) value).getTime(); + } long valueAsLong = 0; try { valueAsLong = Long.parseLong(value.toString()); @@ -232,8 +285,11 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, resultSet.get(pos).size()); Object value = resultSet.get(pos).get(columnIndex - 1); - if (value == null) + if (value == null) { + wasNull = true; return 0; + } + wasNull = false; if (value instanceof Float || value instanceof Double) return (float) value; return Float.parseFloat(value.toString()); @@ -244,8 +300,11 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, resultSet.get(pos).size()); Object value = resultSet.get(pos).get(columnIndex - 1); - if (value == null) + if (value == null) { + wasNull = true; return 0; + } + wasNull = false; if (value instanceof Double || value instanceof Float) return (double) value; return Double.parseDouble(value.toString()); @@ -307,6 +366,13 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { return null; if (value instanceof Timestamp) return (Timestamp) value; +// if (value instanceof Long) { +// if (1_0000_0000_0000_0L > (long) value) +// return Timestamp.from(Instant.ofEpochMilli((long) value)); +// long epochSec = (long) value / 1000_000L; +// long nanoAdjustment = (long) ((long) value % 1000_000L * 1000); +// return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); +// } return Timestamp.valueOf(value.toString()); } diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulStatement.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulStatement.java index 9071c046726a0ef7df3f712ac3ddbb10d3afafba..fbc3a50a27a18db069a25ea86fe37027dca42f1f 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulStatement.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulStatement.java @@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.taosdata.jdbc.AbstractStatement; +import com.taosdata.jdbc.TSDBDriver; import com.taosdata.jdbc.TSDBError; import com.taosdata.jdbc.TSDBErrorNumbers; import com.taosdata.jdbc.utils.HttpClientPoolUtil; @@ -34,14 +35,11 @@ public class RestfulStatement extends AbstractStatement { if (!SqlSyntaxValidator.isValidForExecuteQuery(sql)) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_FOR_EXECUTE_QUERY, "not a valid sql for executeQuery: " + sql); - final String url = "http://" + conn.getHost() + ":" + conn.getPort() + "/rest/sql"; if (SqlSyntaxValidator.isDatabaseUnspecifiedQuery(sql)) { - return executeOneQuery(url, sql); + return executeOneQuery(sql); } -// if (this.database != null && !this.database.trim().replaceAll("\\s","").isEmpty()) -// HttpClientPoolUtil.execute(url, "use " + this.database); - return executeOneQuery(url, sql); + return executeOneQuery(sql); } @Override @@ -56,8 +54,6 @@ public class RestfulStatement extends AbstractStatement { return executeOneUpdate(url, sql); } -// if (this.database != null && !this.database.trim().replaceAll("\\s", "").isEmpty()) -// HttpClientPoolUtil.execute(url, "use " + this.database); return executeOneUpdate(url, sql); } @@ -78,14 +74,21 @@ public class RestfulStatement extends AbstractStatement { //如果执行了use操作应该将当前Statement的catalog设置为新的database boolean result = true; - final String url = "http://" + conn.getHost() + ":" + conn.getPort() + "/rest/sql"; + String url = "http://" + conn.getHost() + ":" + conn.getPort() + "/rest/sql"; + if (conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT).equals("TIMESTAMP")) { + url = "http://" + conn.getHost() + ":" + conn.getPort() + "/rest/sqlt"; + } + if (conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT).equals("UTC")) { + url = "http://" + conn.getHost() + ":" + conn.getPort() + "/rest/sqlutc"; + } + if (SqlSyntaxValidator.isUseSql(sql)) { HttpClientPoolUtil.execute(url, sql); this.database = sql.trim().replace("use", "").trim(); this.conn.setCatalog(this.database); result = false; } else if (SqlSyntaxValidator.isDatabaseUnspecifiedQuery(sql)) { - executeOneQuery(url, sql); + executeOneQuery(sql); } else if (SqlSyntaxValidator.isDatabaseUnspecifiedUpdate(sql)) { executeOneUpdate(url, sql); result = false; @@ -101,11 +104,18 @@ public class RestfulStatement extends AbstractStatement { return result; } - private ResultSet executeOneQuery(String url, String sql) throws SQLException { + private ResultSet executeOneQuery(String sql) throws SQLException { if (!SqlSyntaxValidator.isValidForExecuteQuery(sql)) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_FOR_EXECUTE_QUERY, "not a valid sql for executeQuery: " + sql); // row data + String url = "http://" + conn.getHost() + ":" + conn.getPort() + "/rest/sql"; + String timestampFormat = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT); + if ("TIMESTAMP".equalsIgnoreCase(timestampFormat)) + url = "http://" + conn.getHost() + ":" + conn.getPort() + "/rest/sqlt"; + if ("UTC".equalsIgnoreCase(timestampFormat)) + url = "http://" + conn.getHost() + ":" + conn.getPort() + "/rest/sqlutc"; + String result = HttpClientPoolUtil.execute(url, sql); JSONObject resultJson = JSON.parseObject(result); if (resultJson.getString("status").equals("error")) { @@ -126,21 +136,21 @@ public class RestfulStatement extends AbstractStatement { throw TSDBError.createSQLException(jsonObject.getInteger("code"), jsonObject.getString("desc")); } this.resultSet = null; - this.affectedRows = checkJsonResultSet(jsonObject); + this.affectedRows = getAffectedRows(jsonObject); return this.affectedRows; } - private int checkJsonResultSet(JSONObject jsonObject) { + private int getAffectedRows(JSONObject jsonObject) throws SQLException { // create ... SQLs should return 0 , and Restful result is this: // {"status": "succ", "head": ["affected_rows"], "data": [[0]], "rows": 1} JSONArray head = jsonObject.getJSONArray("head"); + if (head.size() != 1 || !"affected_rows".equals(head.getString(0))) + throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); JSONArray data = jsonObject.getJSONArray("data"); - int rows = Integer.parseInt(jsonObject.getString("rows")); - if (head.size() == 1 && "affected_rows".equals(head.getString(0)) - && data.size() == 1 && data.getJSONArray(0).getInteger(0) == 0 && rows == 1) { - return 0; - } - return rows; + if (data != null) + return data.getJSONArray(0).getInteger(0); + + throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); } @Override diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/UtcTimestampUtil.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/UtcTimestampUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..04a11a2beb00832a20d9d2d887a8ce5a68e5cf54 --- /dev/null +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/UtcTimestampUtil.java @@ -0,0 +1,12 @@ +package com.taosdata.jdbc.utils; + +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; + +public class UtcTimestampUtil { + public static final DateTimeFormatter formatter = new DateTimeFormatterBuilder() + .appendPattern("yyyy-MM-ddTHH:mm:ss.SSS+") +// .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true) + .toFormatter(); + +} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/Utils.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/Utils.java new file mode 100644 index 0000000000000000000000000000000000000000..0ce4bd3dc1dc991683a217e70995ef861d82cbd7 --- /dev/null +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/Utils.java @@ -0,0 +1,135 @@ +package com.taosdata.jdbc.utils; + +import com.google.common.collect.Range; +import com.google.common.collect.RangeSet; +import com.google.common.collect.TreeRangeSet; + +import java.nio.charset.Charset; +import java.sql.Timestamp; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class Utils { + + private static Pattern ptn = Pattern.compile(".*?'"); + + public static String escapeSingleQuota(String origin) { + Matcher m = ptn.matcher(origin); + StringBuffer sb = new StringBuffer(); + int end = 0; + while (m.find()) { + end = m.end(); + String seg = origin.substring(m.start(), end); + int len = seg.length(); + if (len == 1) { + if ('\'' == seg.charAt(0)) { + sb.append("\\'"); + } else { + sb.append(seg); + } + } else { // len > 1 + sb.append(seg.substring(0, seg.length() - 2)); + char lastcSec = seg.charAt(seg.length() - 2); + if (lastcSec == '\\') { + sb.append("\\'"); + } else { + sb.append(lastcSec); + sb.append("\\'"); + } + } + } + + if (end < origin.length()) { + sb.append(origin.substring(end)); + } + return sb.toString(); + } + + public static String getNativeSql(String rawSql, Object[] parameters) { + // toLowerCase + String preparedSql = rawSql.trim().toLowerCase(); + + String[] clause = new String[0]; + if (SqlSyntaxValidator.isInsertSql(preparedSql)) { + // insert or import + clause = new String[]{"values\\s*\\(.*?\\)", "tags\\s*\\(.*?\\)"}; + } + if (SqlSyntaxValidator.isSelectSql(preparedSql)) { + // select + clause = new String[]{"where\\s*.*"}; + } + Map placeholderPositions = new HashMap<>(); + RangeSet clauseRangeSet = TreeRangeSet.create(); + findPlaceholderPosition(preparedSql, placeholderPositions); + findClauseRangeSet(preparedSql, clause, clauseRangeSet); + + return transformSql(rawSql, parameters, placeholderPositions, clauseRangeSet); + } + + private static void findClauseRangeSet(String preparedSql, String[] regexArr, RangeSet clauseRangeSet) { + clauseRangeSet.clear(); + for (String regex : regexArr) { + Matcher matcher = Pattern.compile(regex).matcher(preparedSql); + while (matcher.find()) { + int start = matcher.start(); + int end = matcher.end(); + clauseRangeSet.add(Range.closed(start, end)); + } + } + } + + private static void findPlaceholderPosition(String preparedSql, Map placeholderPosition) { + placeholderPosition.clear(); + Matcher matcher = Pattern.compile("\\?").matcher(preparedSql); + int index = 0; + while (matcher.find()) { + int pos = matcher.start(); + placeholderPosition.put(index, pos); + index++; + } + } + + /*** + * + * @param rawSql + * @param paramArr + * @param placeholderPosition + * @param clauseRangeSet + * @return + */ + private static String transformSql(String rawSql, Object[] paramArr, Map placeholderPosition, RangeSet clauseRangeSet) { + String[] sqlArr = rawSql.split("\\?"); + return IntStream.range(0, sqlArr.length).mapToObj(index -> { + if (index == paramArr.length) + return sqlArr[index]; + + Object para = paramArr[index]; + String paraStr; + if (para != null) { + if (para instanceof byte[]) { + paraStr = new String((byte[]) para, Charset.forName("UTF-8")); + } else { + paraStr = para.toString(); + } + // if para is timestamp or String or byte[] need to translate ' character + if (para instanceof Timestamp || para instanceof String || para instanceof byte[]) { + paraStr = Utils.escapeSingleQuota(paraStr); + + Integer pos = placeholderPosition.get(index); + boolean contains = clauseRangeSet.contains(pos); + if (contains) { + paraStr = "'" + paraStr + "'"; + } + } + } else { + paraStr = "NULL"; + } + return sqlArr[index] + paraStr; + }).collect(Collectors.joining()); + } + +} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SubscribeTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SubscribeTest.java index 11c3de305280a48b690ccdacd2df9751f4b718a9..3a223ed981a7f465386319c3a671782c92bf334f 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SubscribeTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/SubscribeTest.java @@ -12,6 +12,7 @@ import java.util.Properties; import java.util.concurrent.TimeUnit; public class SubscribeTest { + Connection connection; Statement statement; String dbName = "test"; @@ -19,62 +20,53 @@ public class SubscribeTest { String host = "127.0.0.1"; String topic = "test"; - @Before - public void createDatabase() { - try { - Class.forName("com.taosdata.jdbc.TSDBDriver"); - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties); - - statement = connection.createStatement(); - statement.execute("drop database if exists " + dbName); - statement.execute("create database if not exists " + dbName); - statement.execute("create table if not exists " + dbName + "." + tName + " (ts timestamp, k int, v int)"); - long ts = System.currentTimeMillis(); - for (int i = 0; i < 2; i++) { - ts += i; - String sql = "insert into " + dbName + "." + tName + " values (" + ts + ", " + (100 + i) + ", " + i + ")"; - statement.executeUpdate(sql); - } - - } catch (ClassNotFoundException | SQLException e) { - return; - } - } - @Test public void subscribe() { try { String rawSql = "select * from " + dbName + "." + tName + ";"; - System.out.println(rawSql); -// TSDBSubscribe subscribe = ((TSDBConnection) connection).subscribe(topic, rawSql, false); + TSDBConnection conn = connection.unwrap(TSDBConnection.class); + TSDBSubscribe subscribe = conn.subscribe(topic, rawSql, false); + + int a = 0; + while (true) { + TimeUnit.MILLISECONDS.sleep(1000); + TSDBResultSet resSet = subscribe.consume(); + while (resSet.next()) { + for (int i = 1; i <= resSet.getMetaData().getColumnCount(); i++) { + System.out.printf(i + ": " + resSet.getString(i) + "\t"); + } + System.out.println("\n======" + a + "=========="); + } + a++; + if (a >= 2) { + break; + } + resSet.close(); + } -// int a = 0; -// while (true) { -// TimeUnit.MILLISECONDS.sleep(1000); -// TSDBResultSet resSet = subscribe.consume(); -// while (resSet.next()) { -// for (int i = 1; i <= resSet.getMetaData().getColumnCount(); i++) { -// System.out.printf(i + ": " + resSet.getString(i) + "\t"); -// } -// System.out.println("\n======" + a + "=========="); -// } -// a++; -// if (a >= 2) { -// break; -// } -// resSet.close(); -// } -// -// subscribe.close(true); + subscribe.close(true); } catch (Exception e) { e.printStackTrace(); } } + @Before + public void createDatabase() throws SQLException { + Properties properties = new Properties(); + properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); + properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); + properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); + connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties); + + statement = connection.createStatement(); + statement.execute("drop database if exists " + dbName); + statement.execute("create database if not exists " + dbName); + statement.execute("create table if not exists " + dbName + "." + tName + " (ts timestamp, k int, v int)"); + long ts = System.currentTimeMillis(); + statement.executeUpdate("insert into " + dbName + "." + tName + " values (" + ts + ", 100, 1)"); + statement.executeUpdate("insert into " + dbName + "." + tName + " values (" + (ts + 1) + ", 101, 2)"); + } + @After public void close() { try { @@ -86,6 +78,5 @@ public class SubscribeTest { } catch (SQLException e) { e.printStackTrace(); } - } } \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBPreparedStatementTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBPreparedStatementTest.java index 434095efa284b8bae0fafef2795714573e2f76e0..dc6fd4c5016bd67eb8e5dcf0e9d497f4f2f97612 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBPreparedStatementTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBPreparedStatementTest.java @@ -50,6 +50,51 @@ public class TSDBPreparedStatementTest { pstmt_insert.setNull(2, Types.INTEGER); int result = pstmt_insert.executeUpdate(); Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(3, Types.BIGINT); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(4, Types.FLOAT); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(5, Types.DOUBLE); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(6, Types.SMALLINT); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(7, Types.TINYINT); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(8, Types.BOOLEAN); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(9, Types.BINARY); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(10, Types.NCHAR); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(10, Types.OTHER); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); } @Test @@ -129,7 +174,7 @@ public class TSDBPreparedStatementTest { Assert.assertFalse(pstmt_insert.execute()); } - class Person implements Serializable { + class Person { String name; int age; boolean sex; diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBResultSetTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBResultSetTest.java index 374b1335fc88e4eefcfd02f90ed5c2e36ede38e1..c5c6f7bca5226ca87441e0d080b269231f0167c0 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBResultSetTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBResultSetTest.java @@ -160,6 +160,7 @@ public class TSDBResultSetTest { @Test public void getTime() throws SQLException { Time f1 = rs.getTime("f1"); + Assert.assertNotNull(f1); Assert.assertEquals("00:00:00", f1.toString()); } diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DriverAutoloadTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DriverAutoloadTest.java index 9826e6ed764f8319c70a8a2c1edf7b2444b4f21d..6c8aed1b066236371496813301f77db32fb4e0f9 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DriverAutoloadTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/DriverAutoloadTest.java @@ -20,6 +20,7 @@ public class DriverAutoloadTest { final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; Connection conn = DriverManager.getConnection(url, properties); Assert.assertNotNull(conn); + conn.close(); } @Test @@ -27,6 +28,7 @@ public class DriverAutoloadTest { final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; Connection conn = DriverManager.getConnection(url, properties); Assert.assertNotNull(conn); + conn.close(); } diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertSpecialCharacterJniTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertSpecialCharacterJniTest.java new file mode 100644 index 0000000000000000000000000000000000000000..9014e82a9ece395fd3319d00563b9956691e8e8e --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertSpecialCharacterJniTest.java @@ -0,0 +1,400 @@ +package com.taosdata.jdbc.cases; + +import org.junit.*; + +import java.sql.*; + +public class InsertSpecialCharacterJniTest { + + private static final String host = "127.0.0.1"; + private static Connection conn; + private static String dbName = "spec_char_test"; + private static String tbname1 = "test"; + private static String tbname2 = "weather"; + private static String special_character_str_1 = "$asd$$fsfsf$"; + private static String special_character_str_2 = "\\asdfsfsf\\\\"; + private static String special_character_str_3 = "\\\\asdfsfsf\\"; + private static String special_character_str_4 = "?asd??fsf?sf?"; + private static String special_character_str_5 = "?#sd@$f(('<(s[P)>\"){]}f?s[]{}%vaew|\"fsfs^a&d*jhg)(j))(f@~!?$"; + + @Test + public void testCase01() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setTimestamp(1, new Timestamp(now)); + pstmt.setBytes(2, special_character_str_1.getBytes()); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query + final String query = "select * from ?"; + try (PreparedStatement pstmt = conn.prepareStatement(query)) { + pstmt.setString(1, tbname1); + + ResultSet rs = pstmt.executeQuery(); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_1, f1); + String f2 = rs.getString(3); + Assert.assertNull(f2); + } + } + + + @Test + public void testCase02() throws SQLException { + //TODO: + // Expected :\asdfsfsf\\ + // Actual :\asdfsfsf\ + + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setTimestamp(1, new Timestamp(now)); + pstmt.setBytes(2, special_character_str_2.getBytes()); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query + final String query = "select * from " + tbname1; + try (PreparedStatement pstmt = conn.prepareStatement(query)) { + ResultSet rs = pstmt.executeQuery(); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + //TODO: bug to be fixed +// Assert.assertEquals(special_character_str_2, f1); + Assert.assertEquals(special_character_str_2.substring(0, special_character_str_1.length() - 2), f1); + String f2 = rs.getString(3); + Assert.assertNull(f2); + } + } + + @Test(expected = SQLException.class) + public void testCase03() throws SQLException { + //TODO: + // TDengine ERROR (216): Syntax error in SQL + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setTimestamp(1, new Timestamp(now)); + pstmt.setBytes(2, special_character_str_3.getBytes()); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query + final String query = "select * from " + tbname1; + try (PreparedStatement pstmt = conn.prepareStatement(query)) { + ResultSet rs = pstmt.executeQuery(); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_3, f1); + String f2 = rs.getString(3); + Assert.assertNull(f2); + } + } + + @Test + public void testCase04() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setTimestamp(1, new Timestamp(now)); + pstmt.setBytes(2, special_character_str_4.getBytes()); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query + final String query = "select * from " + tbname1; + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery(query); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_4, f1); + String f2 = rs.getString(3); + Assert.assertNull(f2); + } + } + + @Test + public void testCase05() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setTimestamp(1, new Timestamp(now)); + pstmt.setBytes(2, special_character_str_5.getBytes()); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query + final String query = "select * from " + tbname1; + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery(query); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_5, f1); + String f2 = rs.getString(3); + Assert.assertNull(f2); + } + } + + @Test + public void testCase06() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into t? using " + tbname2 + " tags(?) values(?, ?, ?)"; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setInt(1, 1); + pstmt.setString(2, special_character_str_4); + pstmt.setTimestamp(3, new Timestamp(now)); + pstmt.setBytes(4, special_character_str_4.getBytes()); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query t1 + final String query = "select * from t1"; + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery(query); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_4, f1); + String f2 = rs.getString(3); + Assert.assertNull(f2); + } + } + + @Test + public void testCase07() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into " + tbname1 + "(ts, f1, f2) values(?, ?, ?) ; "; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setTimestamp(1, new Timestamp(now)); + pstmt.setBytes(2, special_character_str_4.getBytes()); + pstmt.setString(3, special_character_str_4); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query + final String query = "select * from " + tbname1; + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery(query); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_4, f1); + String f2 = rs.getString(3); + Assert.assertEquals(special_character_str_4, f2); + } + } + + @Test(expected = SQLException.class) + public void testCase08() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into t? using " + tbname2 + " tags(?) values(?, ?, ?) ? "; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setInt(1, 1); + pstmt.setString(2, special_character_str_5); + pstmt.setTimestamp(3, new Timestamp(now)); + pstmt.setBytes(4, special_character_str_5.getBytes()); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + } + + @Test + public void testCase09() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into ?.t? using " + tbname2 + " tags(?) values(?, ?, ?) t? using weather tags(?) values(?,?,?) "; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + // t1 + pstmt.setString(1, dbName); + pstmt.setInt(2, 1); + pstmt.setString(3, special_character_str_5); + pstmt.setTimestamp(4, new Timestamp(now)); + pstmt.setBytes(5, special_character_str_5.getBytes()); + // t2 + pstmt.setInt(7, 2); + pstmt.setString(8, special_character_str_5); + pstmt.setTimestamp(9, new Timestamp(now)); + pstmt.setString(11, special_character_str_5); + + int ret = pstmt.executeUpdate(); + Assert.assertEquals(2, ret); + } + // query t1 + String query = "select * from t?"; + try (PreparedStatement pstmt = conn.prepareStatement(query)) { + pstmt.setInt(1, 1); + + ResultSet rs = pstmt.executeQuery(); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_5, f1); + String f2 = rs.getString(3); + Assert.assertNull(f2); + } + // query t2 + query = "select * from t2"; + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery(query); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + byte[] f1 = rs.getBytes(2); + Assert.assertNull(f1); + String f2 = new String(rs.getBytes(3)); + Assert.assertEquals(special_character_str_5, f2); + } + } + + @Test + public void testCase10() throws SQLException { + final long now = System.currentTimeMillis(); + + // insert + final String sql = "insert into t? using ? tags(?) values(?, ?, ?) t? using " + tbname2 + " tags(?) values(?,?,?) "; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + // t1 + pstmt.setInt(1, 1); + pstmt.setString(2, tbname2); + pstmt.setString(3, special_character_str_5); + pstmt.setTimestamp(4, new Timestamp(now)); + pstmt.setBytes(5, special_character_str_5.getBytes()); + // t2 + pstmt.setInt(7, 2); + pstmt.setString(8, special_character_str_5); + pstmt.setTimestamp(9, new Timestamp(now)); + pstmt.setString(11, special_character_str_5); + + int ret = pstmt.executeUpdate(); + Assert.assertEquals(2, ret); + } + //query t1 + String query = "select * from ?.t? where ts < ? and ts >= ? and ? is not null"; + try (PreparedStatement pstmt = conn.prepareStatement(query)) { + pstmt.setString(1, dbName); + pstmt.setInt(2, 1); + pstmt.setTimestamp(3, new Timestamp(System.currentTimeMillis())); + pstmt.setTimestamp(4, new Timestamp(0)); + pstmt.setString(5, "f1"); + + ResultSet rs = pstmt.executeQuery(); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_5, f1); + byte[] f2 = rs.getBytes(3); + Assert.assertNull(f2); + } + // query t2 + query = "select * from t? where ts < ? and ts >= ? and ? is not null"; + try (PreparedStatement pstmt = conn.prepareStatement(query)) { + pstmt.setInt(1, 2); + pstmt.setTimestamp(2, new Timestamp(System.currentTimeMillis())); + pstmt.setTimestamp(3, new Timestamp(0)); + pstmt.setString(4, "f2"); + + ResultSet rs = pstmt.executeQuery(); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + byte[] f1 = rs.getBytes(2); + Assert.assertNull(f1); + String f2 = new String(rs.getBytes(3)); + Assert.assertEquals(special_character_str_5, f2); + } + } + + @Test(expected = SQLException.class) + public void testCase11() throws SQLException { + final String speicalCharacterStr = "?#sd@$f(((s[P)){]}f?s[]{}%vs^a&d*jhg)(j))(f@~!?$"; + final long now = System.currentTimeMillis(); + + final String sql = "insert into t? using " + tbname2 + " values(?, ?, 'abc?abc') "; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setInt(1, 1); + pstmt.setTimestamp(2, new Timestamp(now)); + pstmt.setBytes(3, speicalCharacterStr.getBytes()); + + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + } + + @Test + public void testCase12() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into " + tbname1 + "(ts, f1, f2) values(?, 'HelloTDengine', ?) ; "; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setTimestamp(1, new Timestamp(now)); + pstmt.setString(2, special_character_str_4); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query + final String query = "select * from " + tbname1; + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery(query); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals("HelloTDengine", f1); + String f2 = rs.getString(3); + Assert.assertEquals(special_character_str_4, f2); + } + } + + @Before + public void before() throws SQLException { + try (Statement stmt = conn.createStatement()) { + stmt.execute("drop table if exists " + tbname1 + ""); + stmt.execute("create table " + tbname1 + "(ts timestamp,f1 binary(64),f2 nchar(64))"); + stmt.execute("drop table if exists " + tbname2); + stmt.execute("create table " + tbname2 + "(ts timestamp, f1 binary(64), f2 nchar(64)) tags(loc nchar(64))"); + } + } + + @BeforeClass + public static void beforeClass() throws SQLException { + String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; + conn = DriverManager.getConnection(url); + try (Statement stmt = conn.createStatement()) { + stmt.execute("drop database if exists " + dbName); + stmt.execute("create database if not exists " + dbName); + stmt.execute("use " + dbName); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + if (conn != null) + conn.close(); + } + +} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertSpecialCharacterRestfulTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertSpecialCharacterRestfulTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0cbbe76716f7f057f79ad7011e20efa838401e95 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/InsertSpecialCharacterRestfulTest.java @@ -0,0 +1,401 @@ +package com.taosdata.jdbc.cases; + +import org.junit.*; + +import java.sql.*; + +public class InsertSpecialCharacterRestfulTest { + + private static final String host = "127.0.0.1"; + // private static final String host = "master"; + private static Connection conn; + private static String dbName = "spec_char_test"; + private static String tbname1 = "test"; + private static String tbname2 = "weather"; + private static String special_character_str_1 = "$asd$$fsfsf$"; + private static String special_character_str_2 = "\\asdfsfsf\\\\"; + private static String special_character_str_3 = "\\\\asdfsfsf\\"; + private static String special_character_str_4 = "?asd??fsf?sf?"; + private static String special_character_str_5 = "?#sd@$f(('<(s[P)>\"){]}f?s[]{}%vaew|\"fsfs^a&d*jhg)(j))(f@~!?$"; + + @Test + public void testCase01() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setTimestamp(1, new Timestamp(now)); + pstmt.setBytes(2, special_character_str_1.getBytes()); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query + final String query = "select * from ?"; + try (PreparedStatement pstmt = conn.prepareStatement(query)) { + pstmt.setString(1, tbname1); + + ResultSet rs = pstmt.executeQuery(); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_1, f1); + String f2 = rs.getString(3); + Assert.assertNull(f2); + } + } + + + @Test + public void testCase02() throws SQLException { + //TODO: + // Expected :\asdfsfsf\\ + // Actual :\asdfsfsf\ + + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setTimestamp(1, new Timestamp(now)); + pstmt.setBytes(2, special_character_str_2.getBytes()); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query + final String query = "select * from " + tbname1; + try (PreparedStatement pstmt = conn.prepareStatement(query)) { + ResultSet rs = pstmt.executeQuery(); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + //TODO: bug to be fixed +// Assert.assertEquals(special_character_str_2, f1); + Assert.assertEquals(special_character_str_2.substring(0, special_character_str_1.length() - 2), f1); + String f2 = rs.getString(3); + Assert.assertNull(f2); + } + } + + @Test(expected = SQLException.class) + public void testCase03() throws SQLException { + //TODO: + // TDengine ERROR (216): Syntax error in SQL + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setTimestamp(1, new Timestamp(now)); + pstmt.setBytes(2, special_character_str_3.getBytes()); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query + final String query = "select * from " + tbname1; + try (PreparedStatement pstmt = conn.prepareStatement(query)) { + ResultSet rs = pstmt.executeQuery(); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_3, f1); + String f2 = rs.getString(3); + Assert.assertNull(f2); + } + } + + @Test + public void testCase04() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setTimestamp(1, new Timestamp(now)); + pstmt.setBytes(2, special_character_str_4.getBytes()); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query + final String query = "select * from " + tbname1; + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery(query); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_4, f1); + String f2 = rs.getString(3); + Assert.assertNull(f2); + } + } + + @Test + public void testCase05() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into " + tbname1 + "(ts, f1) values(?, ?)"; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setTimestamp(1, new Timestamp(now)); + pstmt.setBytes(2, special_character_str_5.getBytes()); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query + final String query = "select * from " + tbname1; + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery(query); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_5, f1); + String f2 = rs.getString(3); + Assert.assertNull(f2); + } + } + + @Test + public void testCase06() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into t? using " + tbname2 + " tags(?) values(?, ?, ?)"; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setInt(1, 1); + pstmt.setString(2, special_character_str_4); + pstmt.setTimestamp(3, new Timestamp(now)); + pstmt.setBytes(4, special_character_str_4.getBytes()); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query t1 + final String query = "select * from t1"; + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery(query); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_4, f1); + String f2 = rs.getString(3); + Assert.assertNull(f2); + } + } + + @Test + public void testCase07() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into " + tbname1 + "(ts, f1, f2) values(?, ?, ?) ; "; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setTimestamp(1, new Timestamp(now)); + pstmt.setBytes(2, special_character_str_4.getBytes()); + pstmt.setString(3, special_character_str_4); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query + final String query = "select * from " + tbname1; + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery(query); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_4, f1); + String f2 = rs.getString(3); + Assert.assertEquals(special_character_str_4, f2); + } + } + + @Test(expected = SQLException.class) + public void testCase08() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into t? using " + tbname2 + " tags(?) values(?, ?, ?) ? "; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setInt(1, 1); + pstmt.setString(2, special_character_str_5); + pstmt.setTimestamp(3, new Timestamp(now)); + pstmt.setBytes(4, special_character_str_5.getBytes()); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + } + + @Test + public void testCase09() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into ?.t? using " + tbname2 + " tags(?) values(?, ?, ?) t? using weather tags(?) values(?,?,?) "; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + // t1 + pstmt.setString(1, dbName); + pstmt.setInt(2, 1); + pstmt.setString(3, special_character_str_5); + pstmt.setTimestamp(4, new Timestamp(now)); + pstmt.setBytes(5, special_character_str_5.getBytes()); + // t2 + pstmt.setInt(7, 2); + pstmt.setString(8, special_character_str_5); + pstmt.setTimestamp(9, new Timestamp(now)); + pstmt.setString(11, special_character_str_5); + + int ret = pstmt.executeUpdate(); + Assert.assertEquals(2, ret); + } + // query t1 + String query = "select * from t?"; + try (PreparedStatement pstmt = conn.prepareStatement(query)) { + pstmt.setInt(1, 1); + + ResultSet rs = pstmt.executeQuery(); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_5, f1); + String f2 = rs.getString(3); + Assert.assertNull(f2); + } + // query t2 + query = "select * from t2"; + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery(query); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + byte[] f1 = rs.getBytes(2); + Assert.assertNull(f1); + String f2 = new String(rs.getBytes(3)); + Assert.assertEquals(special_character_str_5, f2); + } + } + + @Test + public void testCase10() throws SQLException { + final long now = System.currentTimeMillis(); + + // insert + final String sql = "insert into t? using ? tags(?) values(?, ?, ?) t? using " + tbname2 + " tags(?) values(?,?,?) "; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + // t1 + pstmt.setInt(1, 1); + pstmt.setString(2, tbname2); + pstmt.setString(3, special_character_str_5); + pstmt.setTimestamp(4, new Timestamp(now)); + pstmt.setBytes(5, special_character_str_5.getBytes()); + // t2 + pstmt.setInt(7, 2); + pstmt.setString(8, special_character_str_5); + pstmt.setTimestamp(9, new Timestamp(now)); + pstmt.setString(11, special_character_str_5); + + int ret = pstmt.executeUpdate(); + Assert.assertEquals(2, ret); + } + //query t1 + String query = "select * from ?.t? where ts < ? and ts >= ? and ? is not null"; + try (PreparedStatement pstmt = conn.prepareStatement(query)) { + pstmt.setString(1, dbName); + pstmt.setInt(2, 1); + pstmt.setTimestamp(3, new Timestamp(System.currentTimeMillis())); + pstmt.setTimestamp(4, new Timestamp(0)); + pstmt.setString(5, "f1"); + + ResultSet rs = pstmt.executeQuery(); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals(special_character_str_5, f1); + byte[] f2 = rs.getBytes(3); + Assert.assertNull(f2); + } + // query t2 + query = "select * from t? where ts < ? and ts >= ? and ? is not null"; + try (PreparedStatement pstmt = conn.prepareStatement(query)) { + pstmt.setInt(1, 2); + pstmt.setTimestamp(2, new Timestamp(System.currentTimeMillis())); + pstmt.setTimestamp(3, new Timestamp(0)); + pstmt.setString(4, "f2"); + + ResultSet rs = pstmt.executeQuery(); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + byte[] f1 = rs.getBytes(2); + Assert.assertNull(f1); + String f2 = new String(rs.getBytes(3)); + Assert.assertEquals(special_character_str_5, f2); + } + } + + @Test(expected = SQLException.class) + public void testCase11() throws SQLException { + final String speicalCharacterStr = "?#sd@$f(((s[P)){]}f?s[]{}%vs^a&d*jhg)(j))(f@~!?$"; + final long now = System.currentTimeMillis(); + + final String sql = "insert into t? using " + tbname2 + " values(?, ?, 'abc?abc') "; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setInt(1, 1); + pstmt.setTimestamp(2, new Timestamp(now)); + pstmt.setBytes(3, speicalCharacterStr.getBytes()); + + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + } + + @Test + public void testCase12() throws SQLException { + final long now = System.currentTimeMillis(); + // insert + final String sql = "insert into " + tbname1 + "(ts, f1, f2) values(?, 'HelloTDengine', ?) ; "; + try (PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setTimestamp(1, new Timestamp(now)); + pstmt.setString(2, special_character_str_4); + int ret = pstmt.executeUpdate(); + Assert.assertEquals(1, ret); + } + // query + final String query = "select * from " + tbname1; + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery(query); + rs.next(); + long timestamp = rs.getTimestamp(1).getTime(); + Assert.assertEquals(now, timestamp); + String f1 = new String(rs.getBytes(2)); + Assert.assertEquals("HelloTDengine", f1); + String f2 = rs.getString(3); + Assert.assertEquals(special_character_str_4, f2); + } + } + + @Before + public void before() throws SQLException { + try (Statement stmt = conn.createStatement()) { + stmt.execute("drop table if exists " + tbname1 + ""); + stmt.execute("create table " + tbname1 + "(ts timestamp,f1 binary(64),f2 nchar(64))"); + stmt.execute("drop table if exists " + tbname2); + stmt.execute("create table " + tbname2 + "(ts timestamp, f1 binary(64), f2 nchar(64)) tags(loc nchar(64))"); + } + } + + @BeforeClass + public static void beforeClass() throws SQLException { + String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; + conn = DriverManager.getConnection(url); + try (Statement stmt = conn.createStatement()) { + stmt.execute("drop database if exists " + dbName); + stmt.execute("create database if not exists " + dbName); + stmt.execute("use " + dbName); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + if (conn != null) + conn.close(); + } + +} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NullValueInResultSetForJdbcJniTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NullValueInResultSetForJdbcJniTest.java new file mode 100644 index 0000000000000000000000000000000000000000..782125144c4fbe8dcc4bdfd4769e95e5119ea32f --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NullValueInResultSetForJdbcJniTest.java @@ -0,0 +1,64 @@ +package com.taosdata.jdbc.cases; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.sql.*; + +public class NullValueInResultSetForJdbcJniTest { + + private static final String host = "127.0.0.1"; + Connection conn; + + @Test + public void test() { + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery("select * from weather"); + ResultSetMetaData meta = rs.getMetaData(); + while (rs.next()) { + for (int i = 1; i <= meta.getColumnCount(); i++) { + Object value = rs.getObject(i); + System.out.print(meta.getColumnLabel(i) + ": " + value + "\t"); + } + System.out.println(); + } + + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Before + public void before() throws SQLException { + final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; + conn = DriverManager.getConnection(url); + try (Statement stmt = conn.createStatement()) { + stmt.execute("drop database if exists test_null"); + stmt.execute("create database if not exists test_null"); + stmt.execute("use test_null"); + stmt.execute("create table weather(ts timestamp, f1 int, f2 bigint, f3 float, f4 double, f5 smallint, f6 tinyint, f7 bool, f8 binary(64), f9 nchar(64))"); + stmt.executeUpdate("insert into weather(ts, f1) values(now+1s, 1)"); + stmt.executeUpdate("insert into weather(ts, f2) values(now+2s, 2)"); + stmt.executeUpdate("insert into weather(ts, f3) values(now+3s, 3.0)"); + stmt.executeUpdate("insert into weather(ts, f4) values(now+4s, 4.0)"); + stmt.executeUpdate("insert into weather(ts, f5) values(now+5s, 5)"); + stmt.executeUpdate("insert into weather(ts, f6) values(now+6s, 6)"); + stmt.executeUpdate("insert into weather(ts, f7) values(now+7s, true)"); + stmt.executeUpdate("insert into weather(ts, f8) values(now+8s, 'hello')"); + stmt.executeUpdate("insert into weather(ts, f9) values(now+9s, '涛思数据')"); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @After + public void after() { + try { + if (conn != null) + conn.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } +} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TD3841Test.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TD3841Test.java new file mode 100644 index 0000000000000000000000000000000000000000..c6fba81eb24b9b8c08fd553ca57b1e1d68bb81e0 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TD3841Test.java @@ -0,0 +1,91 @@ +package com.taosdata.jdbc.cases; + +import com.taosdata.jdbc.TSDBDriver; +import com.taosdata.jdbc.utils.TimestampUtil; +import org.junit.*; + +import java.sql.*; +import java.util.Properties; + +public class TD3841Test { + private static final String host = "127.0.0.1"; + private static Properties properties; + private static Connection conn_restful; + private static Connection conn_jni; + + @Test + public void testRestful() throws SQLException { + String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; + conn_restful = DriverManager.getConnection(url, properties); + + try (Statement stmt = conn_restful.createStatement()) { + stmt.execute("drop database if exists test_null"); + stmt.execute("create database if not exists test_null"); + stmt.execute("use test_null"); + stmt.execute("create table weather(ts timestamp, f1 timestamp, f2 int, f3 bigint, f4 float, f5 double, f6 smallint, f7 tinyint, f8 bool, f9 binary(64), f10 nchar(64))"); + stmt.executeUpdate("insert into weather(ts, f1) values(now+1s, " + TimestampUtil.datetimeToLong("2021-04-21 12:00:00.000") + ")"); + ResultSet rs = stmt.executeQuery("select * from weather"); + rs.next(); + + Assert.assertEquals("2021-04-21 12:00:00.000", TimestampUtil.longToDatetime(rs.getTimestamp(2).getTime())); + Assert.assertEquals(true, rs.getInt(3) == 0 && rs.wasNull()); + Assert.assertEquals(true, rs.getLong(4) == 0 && rs.wasNull()); + Assert.assertEquals(true, rs.getFloat(5) == 0.0f && rs.wasNull()); + Assert.assertEquals(true, rs.getDouble(6) == 0.0f && rs.wasNull()); + Assert.assertEquals(true, rs.getByte(7) == 0 && rs.wasNull()); + Assert.assertEquals(true, rs.getShort(8) == 0 && rs.wasNull()); + Assert.assertEquals(null, rs.getBytes(9)); + Assert.assertEquals(null, rs.getString(10)); + + rs.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Test + public void testJNI() throws SQLException { + final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; + conn_jni = DriverManager.getConnection(url, properties); + + try (Statement stmt = conn_jni.createStatement()) { + stmt.execute("drop database if exists test_null"); + stmt.execute("create database if not exists test_null"); + stmt.execute("use test_null"); + stmt.execute("create table weather(ts timestamp, f1 timestamp, f2 int, f3 bigint, f4 float, f5 double, f6 smallint, f7 tinyint, f8 bool, f9 binary(64), f10 nchar(64))"); + stmt.executeUpdate("insert into weather(ts, f1) values(now+1s, " + TimestampUtil.datetimeToLong("2021-04-21 12:00:00.000") + ")"); + ResultSet rs = stmt.executeQuery("select * from weather"); + rs.next(); + + Assert.assertEquals("2021-04-21 12:00:00.000", TimestampUtil.longToDatetime(rs.getTimestamp(2).getTime())); + Assert.assertEquals(true, rs.getInt(3) == 0 && rs.wasNull()); + Assert.assertEquals(true, rs.getLong(4) == 0 && rs.wasNull()); + Assert.assertEquals(true, rs.getFloat(5) == 0.0f && rs.wasNull()); + Assert.assertEquals(true, rs.getDouble(6) == 0.0f && rs.wasNull()); + Assert.assertEquals(true, rs.getByte(7) == 0 && rs.wasNull()); + Assert.assertEquals(true, rs.getShort(8) == 0 && rs.wasNull()); + Assert.assertEquals(null, rs.getBytes(9)); + Assert.assertEquals(null, rs.getString(10)); + + rs.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @BeforeClass + public static void beforeClass() { + properties = new Properties(); + properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); + properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); + properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); + } + + @AfterClass + public static void afterClass() throws SQLException { + if (conn_restful != null) + conn_restful.close(); + if (conn_jni != null) + conn_jni.close(); + } +} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TwoTypeTimestampPercisionInJniTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TwoTypeTimestampPercisionInJniTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f9b111bb12f189a7a42c7944237aa01ebb008d25 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TwoTypeTimestampPercisionInJniTest.java @@ -0,0 +1,89 @@ +package com.taosdata.jdbc.cases; + + +import com.taosdata.jdbc.TSDBDriver; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.sql.*; +import java.util.Properties; + +public class TwoTypeTimestampPercisionInJniTest { + + private static final String host = "127.0.0.1"; + private static final String ms_timestamp_db = "ms_precision_test"; + private static final String us_timestamp_db = "us_precision_test"; + private static final long timestamp1 = System.currentTimeMillis(); + private static final long timestamp2 = timestamp1 * 1000 + 123; + + private static Connection conn; + + @Test + public void testCase1() { + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather"); + rs.next(); + long ts = rs.getTimestamp(1).getTime(); + Assert.assertEquals(timestamp1, ts); + ts = rs.getLong(1); + Assert.assertEquals(timestamp1, ts); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Test + public void testCase2() { + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather"); + rs.next(); + + Timestamp timestamp = rs.getTimestamp(1); + System.out.println(timestamp); + long ts = timestamp.getTime(); + Assert.assertEquals(timestamp1, ts); + int nanos = timestamp.getNanos(); + Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); + + ts = rs.getLong(1); + Assert.assertEquals(timestamp1, ts); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @BeforeClass + public static void beforeClass() throws SQLException { + Properties properties = new Properties(); + properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); + properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); + properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); + + String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; + conn = DriverManager.getConnection(url, properties); + + Statement stmt = conn.createStatement(); + stmt.execute("drop database if exists " + ms_timestamp_db); + stmt.execute("create database if not exists " + ms_timestamp_db + " precision 'ms'"); + stmt.execute("create table " + ms_timestamp_db + ".weather(ts timestamp, f1 int)"); + stmt.executeUpdate("insert into " + ms_timestamp_db + ".weather(ts,f1) values(" + timestamp1 + ", 127)"); + + stmt.execute("drop database if exists " + us_timestamp_db); + stmt.execute("create database if not exists " + us_timestamp_db + " precision 'us'"); + stmt.execute("create table " + us_timestamp_db + ".weather(ts timestamp, f1 int)"); + stmt.executeUpdate("insert into " + us_timestamp_db + ".weather(ts,f1) values(" + timestamp2 + ", 127)"); + stmt.close(); + } + + @AfterClass + public static void afterClass() { + try { + if (conn != null) + conn.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } +} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TwoTypeTimestampPercisionInRestfulTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TwoTypeTimestampPercisionInRestfulTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ed4f979ef33354595bfeb707678e3b9797aba686 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/TwoTypeTimestampPercisionInRestfulTest.java @@ -0,0 +1,168 @@ +package com.taosdata.jdbc.cases; + + +import com.taosdata.jdbc.TSDBDriver; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.sql.*; +import java.util.Properties; + +public class TwoTypeTimestampPercisionInRestfulTest { + + private static final String host = "127.0.0.1"; + private static final String ms_timestamp_db = "ms_precision_test"; + private static final String us_timestamp_db = "us_precision_test"; + private static final long timestamp1 = System.currentTimeMillis(); + private static final long timestamp2 = timestamp1 * 1000 + 123; + + private static Connection conn1; + private static Connection conn2; + private static Connection conn3; + + @Test + public void testCase1() { + try (Statement stmt = conn1.createStatement()) { + ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather"); + rs.next(); + long ts = rs.getTimestamp(1).getTime(); + Assert.assertEquals(timestamp1, ts); + ts = rs.getLong(1); + Assert.assertEquals(timestamp1, ts); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Test + public void testCase2() { + try (Statement stmt = conn1.createStatement()) { + ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather"); + rs.next(); + + Timestamp timestamp = rs.getTimestamp(1); + long ts = timestamp.getTime(); + Assert.assertEquals(timestamp1, ts); + int nanos = timestamp.getNanos(); + Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); + + ts = rs.getLong(1); + Assert.assertEquals(timestamp1, ts); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Test + public void testCase3() { + try (Statement stmt = conn2.createStatement()) { + ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather"); + rs.next(); + Timestamp rsTimestamp = rs.getTimestamp(1); + long ts = rsTimestamp.getTime(); + Assert.assertEquals(timestamp1, ts); + ts = rs.getLong(1); + Assert.assertEquals(timestamp1, ts); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Test + public void testCase4() { + try (Statement stmt = conn2.createStatement()) { + ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather"); + rs.next(); + + Timestamp timestamp = rs.getTimestamp(1); + long ts = timestamp.getTime(); + Assert.assertEquals(timestamp1, ts); + int nanos = timestamp.getNanos(); + Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); + + ts = rs.getLong(1); + Assert.assertEquals(timestamp1, ts); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Test + public void testCase5() { + try (Statement stmt = conn3.createStatement()) { + ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather"); + rs.next(); + long ts = rs.getTimestamp(1).getTime(); + Assert.assertEquals(timestamp1, ts); + ts = rs.getLong(1); + Assert.assertEquals(timestamp1, ts); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Test + public void testCase6() { + try (Statement stmt = conn3.createStatement()) { + ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather"); + rs.next(); + + Timestamp timestamp = rs.getTimestamp(1); + long ts = timestamp.getTime(); + Assert.assertEquals(timestamp1, ts); + int nanos = timestamp.getNanos(); + Assert.assertEquals(timestamp2 % 1000_000l * 1000, nanos); + + ts = rs.getLong(1); + Assert.assertEquals(timestamp1, ts); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @BeforeClass + public static void beforeClass() throws SQLException { + Properties properties = new Properties(); + properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); + properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); + properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); +// properties.setProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, "TIMESTAMP"); + + String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; + conn1 = DriverManager.getConnection(url, properties); + + url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata×tampFormat=timestamp"; + conn2 = DriverManager.getConnection(url, properties); + + url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata×tampFormat=utc"; + conn3 = DriverManager.getConnection(url, properties); + + Statement stmt = conn1.createStatement(); + stmt.execute("drop database if exists " + ms_timestamp_db); + stmt.execute("create database if not exists " + ms_timestamp_db + " precision 'ms'"); + stmt.execute("create table " + ms_timestamp_db + ".weather(ts timestamp, f1 int)"); + stmt.executeUpdate("insert into " + ms_timestamp_db + ".weather(ts,f1) values(" + timestamp1 + ", 127)"); + + stmt.execute("drop database if exists " + us_timestamp_db); + stmt.execute("create database if not exists " + us_timestamp_db + " precision 'us'"); + stmt.execute("create table " + us_timestamp_db + ".weather(ts timestamp, f1 int)"); + stmt.executeUpdate("insert into " + us_timestamp_db + ".weather(ts,f1) values(" + timestamp2 + ", 127)"); + stmt.close(); + } + + @AfterClass + public static void afterClass() { + try { + if (conn1 != null) + conn1.close(); + if (conn2 != null) + conn2.close(); + if (conn3 != null) + conn3.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } +} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulPreparedStatementTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulPreparedStatementTest.java index 094dff8c8de0667110e4911a32a8479e21d6fc71..e4dd6384f9cc2f22d6c9cbcd04ae9b0f67dc477b 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulPreparedStatementTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulPreparedStatementTest.java @@ -6,11 +6,11 @@ import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; -import java.io.Serializable; import java.sql.*; public class RestfulPreparedStatementTest { private static final String host = "127.0.0.1"; + // private static final String host = "master"; private static Connection conn; private static final String sql_insert = "insert into t1 values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; private static PreparedStatement pstmt_insert; @@ -50,6 +50,51 @@ public class RestfulPreparedStatementTest { pstmt_insert.setNull(2, Types.INTEGER); int result = pstmt_insert.executeUpdate(); Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(3, Types.BIGINT); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(4, Types.FLOAT); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(5, Types.DOUBLE); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(6, Types.SMALLINT); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(7, Types.TINYINT); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(8, Types.BOOLEAN); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(9, Types.BINARY); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(10, Types.NCHAR); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); + + pstmt_insert.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + pstmt_insert.setNull(10, Types.OTHER); + result = pstmt_insert.executeUpdate(); + Assert.assertEquals(1, result); } @Test @@ -129,7 +174,7 @@ public class RestfulPreparedStatementTest { Assert.assertFalse(pstmt_insert.execute()); } - class Person implements Serializable { + private class Person { String name; int age; boolean sex; diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetTest.java index d6b2a58127d0440cf1c3a730439ccbeb94a77bdd..9bfe9a04ffb33f1ecf9466b2aba85121da85e846 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetTest.java @@ -160,6 +160,7 @@ public class RestfulResultSetTest { @Test public void getTime() throws SQLException { Time f1 = rs.getTime("f1"); + Assert.assertNotNull(f1); Assert.assertEquals("00:00:00", f1.toString()); } diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/UtilsTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/UtilsTest.java new file mode 100644 index 0000000000000000000000000000000000000000..c861ef296607b244e4564423ad4024ea1f13df5d --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/utils/UtilsTest.java @@ -0,0 +1,24 @@ +package com.taosdata.jdbc.utils; + +import org.junit.Assert; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class UtilsTest { + + @Test + public void escapeSingleQuota() { + String s = "'''''a\\'"; + String news = Utils.escapeSingleQuota(s); + Assert.assertEquals("\\'\\'\\'\\'\\'a\\'", news); + + s = "\'''''a\\'"; + news = Utils.escapeSingleQuota(s); + Assert.assertEquals("\\'\\'\\'\\'\\'a\\'", news); + + s = "\'\'\'\''a\\'"; + news = Utils.escapeSingleQuota(s); + Assert.assertEquals("\\'\\'\\'\\'\\'a\\'", news); + } +} \ No newline at end of file diff --git a/src/connector/python/linux/python2/setup.py b/src/connector/python/linux/python2/setup.py index ff2d90fcb3dff5965572452672a7491dd4aa44d1..3f065e03485bb0436d7b0356c2508d5913273eb5 100644 --- a/src/connector/python/linux/python2/setup.py +++ b/src/connector/python/linux/python2/setup.py @@ -5,7 +5,7 @@ with open("README.md", "r") as fh: setuptools.setup( name="taos", - version="2.0.8", + version="2.0.9", author="Taosdata Inc.", author_email="support@taosdata.com", description="TDengine python client package", diff --git a/src/connector/python/linux/python2/taos/cinterface.py b/src/connector/python/linux/python2/taos/cinterface.py index 4367947341edad7b0a9bdbcaec69a7de9801e267..3d0ecd290156b71e2d738fe7d3693763e0047338 100644 --- a/src/connector/python/linux/python2/taos/cinterface.py +++ b/src/connector/python/linux/python2/taos/cinterface.py @@ -21,11 +21,17 @@ def _crow_timestamp_to_python(data, num_of_rows, nbytes=None, micro=False): _timestamp_converter = _convert_microsecond_to_datetime if num_of_rows > 0: - return list(map(_timestamp_converter, ctypes.cast( - data, ctypes.POINTER(ctypes.c_int64))[:abs(num_of_rows)])) + return [ + None if ele == FieldType.C_BIGINT_NULL else _timestamp_converter(ele) for ele in ctypes.cast( + data, ctypes.POINTER( + ctypes.c_int64))[ + :abs(num_of_rows)]] else: - return list(map(_timestamp_converter, ctypes.cast( - data, ctypes.POINTER(ctypes.c_int64))[:abs(num_of_rows)])) + return [ + None if ele == FieldType.C_BIGINT_NULL else _timestamp_converter(ele) for ele in ctypes.cast( + data, ctypes.POINTER( + ctypes.c_int64))[ + :abs(num_of_rows)]] def _crow_bool_to_python(data, num_of_rows, nbytes=None, micro=False): diff --git a/src/connector/python/linux/python3/setup.py b/src/connector/python/linux/python3/setup.py index 296e79b973fde7c86493565940d63f64e7c6fca3..0bd7d51b6a3699acc6c923de2533cd85393f6ae3 100644 --- a/src/connector/python/linux/python3/setup.py +++ b/src/connector/python/linux/python3/setup.py @@ -5,7 +5,7 @@ with open("README.md", "r") as fh: setuptools.setup( name="taos", - version="2.0.7", + version="2.0.9", author="Taosdata Inc.", author_email="support@taosdata.com", description="TDengine python client package", diff --git a/src/connector/python/linux/python3/taos/cinterface.py b/src/connector/python/linux/python3/taos/cinterface.py index 4367947341edad7b0a9bdbcaec69a7de9801e267..3d0ecd290156b71e2d738fe7d3693763e0047338 100644 --- a/src/connector/python/linux/python3/taos/cinterface.py +++ b/src/connector/python/linux/python3/taos/cinterface.py @@ -21,11 +21,17 @@ def _crow_timestamp_to_python(data, num_of_rows, nbytes=None, micro=False): _timestamp_converter = _convert_microsecond_to_datetime if num_of_rows > 0: - return list(map(_timestamp_converter, ctypes.cast( - data, ctypes.POINTER(ctypes.c_int64))[:abs(num_of_rows)])) + return [ + None if ele == FieldType.C_BIGINT_NULL else _timestamp_converter(ele) for ele in ctypes.cast( + data, ctypes.POINTER( + ctypes.c_int64))[ + :abs(num_of_rows)]] else: - return list(map(_timestamp_converter, ctypes.cast( - data, ctypes.POINTER(ctypes.c_int64))[:abs(num_of_rows)])) + return [ + None if ele == FieldType.C_BIGINT_NULL else _timestamp_converter(ele) for ele in ctypes.cast( + data, ctypes.POINTER( + ctypes.c_int64))[ + :abs(num_of_rows)]] def _crow_bool_to_python(data, num_of_rows, nbytes=None, micro=False): diff --git a/src/connector/python/osx/python3/setup.py b/src/connector/python/osx/python3/setup.py index 9bce1a976febcec457c2b3f8ade0bc6d546307c4..4c865676c9145846e61ee789cb503b84ad424bf1 100644 --- a/src/connector/python/osx/python3/setup.py +++ b/src/connector/python/osx/python3/setup.py @@ -5,7 +5,7 @@ with open("README.md", "r") as fh: setuptools.setup( name="taos", - version="2.0.7", + version="2.0.9", author="Taosdata Inc.", author_email="support@taosdata.com", description="TDengine python client package", diff --git a/src/connector/python/osx/python3/taos/cinterface.py b/src/connector/python/osx/python3/taos/cinterface.py index dca9bd42e8733616f34654542ba8c2c3ea3ece9d..720fbef6f5111c2ec85394498ec862c85aafbc99 100644 --- a/src/connector/python/osx/python3/taos/cinterface.py +++ b/src/connector/python/osx/python3/taos/cinterface.py @@ -21,11 +21,17 @@ def _crow_timestamp_to_python(data, num_of_rows, nbytes=None, micro=False): _timestamp_converter = _convert_microsecond_to_datetime if num_of_rows > 0: - return list(map(_timestamp_converter, ctypes.cast( - data, ctypes.POINTER(ctypes.c_int64))[:abs(num_of_rows)])) + return [ + None if ele == FieldType.C_BIGINT_NULL else _timestamp_converter(ele) for ele in ctypes.cast( + data, ctypes.POINTER( + ctypes.c_int64))[ + :abs(num_of_rows)]] else: - return list(map(_timestamp_converter, ctypes.cast( - data, ctypes.POINTER(ctypes.c_int64))[:abs(num_of_rows)])) + return [ + None if ele == FieldType.C_BIGINT_NULL else _timestamp_converter(ele) for ele in ctypes.cast( + data, ctypes.POINTER( + ctypes.c_int64))[ + :abs(num_of_rows)]] def _crow_bool_to_python(data, num_of_rows, nbytes=None, micro=False): diff --git a/src/connector/python/windows/python2/setup.py b/src/connector/python/windows/python2/setup.py index 47d374fe67673172596824f68ed495f68941bb51..24d75f937cdb2a61cd2330138c0575e4ccbe2875 100644 --- a/src/connector/python/windows/python2/setup.py +++ b/src/connector/python/windows/python2/setup.py @@ -5,7 +5,7 @@ with open("README.md", "r") as fh: setuptools.setup( name="taos", - version="2.0.7", + version="2.0.9", author="Taosdata Inc.", author_email="support@taosdata.com", description="TDengine python client package", diff --git a/src/connector/python/windows/python2/taos/cinterface.py b/src/connector/python/windows/python2/taos/cinterface.py index ec72474df93a4d13aa13256611044c5bc140f2d3..65cb183f26978dc83553b3e88a5c6599ccc1dd48 100644 --- a/src/connector/python/windows/python2/taos/cinterface.py +++ b/src/connector/python/windows/python2/taos/cinterface.py @@ -21,11 +21,17 @@ def _crow_timestamp_to_python(data, num_of_rows, nbytes=None, micro=False): _timestamp_converter = _convert_microsecond_to_datetime if num_of_rows > 0: - return list(map(_timestamp_converter, ctypes.cast( - data, ctypes.POINTER(ctypes.c_int64))[:abs(num_of_rows)])) + return [ + None if ele == FieldType.C_BIGINT_NULL else _timestamp_converter(ele) for ele in ctypes.cast( + data, ctypes.POINTER( + ctypes.c_int64))[ + :abs(num_of_rows)]] else: - return list(map(_timestamp_converter, ctypes.cast( - data, ctypes.POINTER(ctypes.c_int64))[:abs(num_of_rows)])) + return [ + None if ele == FieldType.C_BIGINT_NULL else _timestamp_converter(ele) for ele in ctypes.cast( + data, ctypes.POINTER( + ctypes.c_int64))[ + :abs(num_of_rows)]] def _crow_bool_to_python(data, num_of_rows, nbytes=None, micro=False): diff --git a/src/connector/python/windows/python3/setup.py b/src/connector/python/windows/python3/setup.py index cdcec62a218e72adbda949c0fd666b5ec4abc340..2659c493aad8c3059095f0d4c98c61b69ed834f2 100644 --- a/src/connector/python/windows/python3/setup.py +++ b/src/connector/python/windows/python3/setup.py @@ -5,7 +5,7 @@ with open("README.md", "r") as fh: setuptools.setup( name="taos", - version="2.0.7", + version="2.0.9", author="Taosdata Inc.", author_email="support@taosdata.com", description="TDengine python client package", diff --git a/src/connector/python/windows/python3/taos/cinterface.py b/src/connector/python/windows/python3/taos/cinterface.py index ec72474df93a4d13aa13256611044c5bc140f2d3..65cb183f26978dc83553b3e88a5c6599ccc1dd48 100644 --- a/src/connector/python/windows/python3/taos/cinterface.py +++ b/src/connector/python/windows/python3/taos/cinterface.py @@ -21,11 +21,17 @@ def _crow_timestamp_to_python(data, num_of_rows, nbytes=None, micro=False): _timestamp_converter = _convert_microsecond_to_datetime if num_of_rows > 0: - return list(map(_timestamp_converter, ctypes.cast( - data, ctypes.POINTER(ctypes.c_int64))[:abs(num_of_rows)])) + return [ + None if ele == FieldType.C_BIGINT_NULL else _timestamp_converter(ele) for ele in ctypes.cast( + data, ctypes.POINTER( + ctypes.c_int64))[ + :abs(num_of_rows)]] else: - return list(map(_timestamp_converter, ctypes.cast( - data, ctypes.POINTER(ctypes.c_int64))[:abs(num_of_rows)])) + return [ + None if ele == FieldType.C_BIGINT_NULL else _timestamp_converter(ele) for ele in ctypes.cast( + data, ctypes.POINTER( + ctypes.c_int64))[ + :abs(num_of_rows)]] def _crow_bool_to_python(data, num_of_rows, nbytes=None, micro=False): diff --git a/src/inc/taoserror.h b/src/inc/taoserror.h index eff4eecbc1baaea7f96a6560757bd2000eeab1bf..ce6f7c4f22e0dd7b63e70b67b44ac95984a7dc26 100644 --- a/src/inc/taoserror.h +++ b/src/inc/taoserror.h @@ -218,6 +218,7 @@ int32_t* taosGetErrno(); #define TSDB_CODE_VND_NOT_SYNCED TAOS_DEF_ERROR_CODE(0, 0x0511) //"Database suspended") #define TSDB_CODE_VND_NO_WRITE_AUTH TAOS_DEF_ERROR_CODE(0, 0x0512) //"Database write operation denied") #define TSDB_CODE_VND_IS_SYNCING TAOS_DEF_ERROR_CODE(0, 0x0513) //"Database is syncing") +#define TSDB_CODE_VND_INVALID_TSDB_STATE TAOS_DEF_ERROR_CODE(0, 0x0514) //"Invalid tsdb state") // tsdb #define TSDB_CODE_TDB_INVALID_TABLE_ID TAOS_DEF_ERROR_CODE(0, 0x0600) //"Invalid table ID") diff --git a/src/kit/taosdemo/taosdemo.c b/src/kit/taosdemo/taosdemo.c index e6d7fb6a096d26206381cdfef68fc27158a2e0fd..99befbaf315c665f00f0f438cf5a3c36a3165569 100644 --- a/src/kit/taosdemo/taosdemo.c +++ b/src/kit/taosdemo/taosdemo.c @@ -81,7 +81,7 @@ enum QUERY_MODE { #define MAX_DB_NAME_SIZE 64 #define MAX_HOSTNAME_SIZE 64 #define MAX_TB_NAME_SIZE 64 -#define MAX_DATA_SIZE (16*1024) +#define MAX_DATA_SIZE (16*1024)+20 // max record len: 16*1024, timestamp string and ,('') need extra space #define MAX_NUM_DATATYPE 10 #define OPT_ABORT 1 /* –abort */ #define STRING_LEN 60000 @@ -188,7 +188,7 @@ typedef struct { /* Used by main to communicate with parse_opt. */ typedef struct SArguments_S { char * metaFile; - int test_mode; + uint32_t test_mode; char * host; uint16_t port; char * user; @@ -205,31 +205,31 @@ typedef struct SArguments_S { bool verbose_print; bool performance_print; char * output_file; - int query_mode; + uint32_t query_mode; char * datatype[MAX_NUM_DATATYPE + 1]; - int len_of_binary; - int num_of_CPR; - int num_of_threads; - int64_t insert_interval; + uint32_t len_of_binary; + uint32_t num_of_CPR; + uint32_t num_of_threads; + uint64_t insert_interval; int64_t query_times; - int64_t interlace_rows; - int64_t num_of_RPR; // num_of_records_per_req - int64_t max_sql_len; - int64_t num_of_tables; - int64_t num_of_DPT; + uint64_t interlace_rows; + uint64_t num_of_RPR; // num_of_records_per_req + uint64_t max_sql_len; + uint64_t num_of_tables; + uint64_t num_of_DPT; int abort; int disorderRatio; // 0: no disorder, >0: x% int disorderRange; // ms or us by database precision - int method_of_delete; + uint32_t method_of_delete; char ** arg_list; - int64_t totalInsertRows; - int64_t totalAffectedRows; + uint64_t totalInsertRows; + uint64_t totalAffectedRows; } SArguments; typedef struct SColumn_S { - char field[TSDB_COL_NAME_LEN + 1]; - char dataType[MAX_TB_NAME_SIZE]; - int dataLen; + char field[TSDB_COL_NAME_LEN + 1]; + char dataType[MAX_TB_NAME_SIZE]; + uint32_t dataLen; char note[128]; } StrColumn; @@ -237,50 +237,50 @@ typedef struct SSuperTable_S { char sTblName[MAX_TB_NAME_SIZE+1]; int64_t childTblCount; bool childTblExists; // 0: no, 1: yes - int64_t batchCreateTableNum; // 0: no batch, > 0: batch table number in one sql - int8_t autoCreateTable; // 0: create sub table, 1: auto create sub table + uint64_t batchCreateTableNum; // 0: no batch, > 0: batch table number in one sql + uint8_t autoCreateTable; // 0: create sub table, 1: auto create sub table char childTblPrefix[MAX_TB_NAME_SIZE]; char dataSource[MAX_TB_NAME_SIZE+1]; // rand_gen or sample - char insertMode[MAX_TB_NAME_SIZE]; // taosc, restful + char insertMode[MAX_TB_NAME_SIZE]; // taosc, rest int64_t childTblLimit; - int64_t childTblOffset; + uint64_t childTblOffset; // int multiThreadWriteOneTbl; // 0: no, 1: yes - int64_t interlaceRows; // + uint64_t interlaceRows; // int disorderRatio; // 0: no disorder, >0: x% int disorderRange; // ms or us by database precision - int64_t maxSqlLen; // + uint64_t maxSqlLen; // - int64_t insertInterval; // insert interval, will override global insert interval - int64_t insertRows; + uint64_t insertInterval; // insert interval, will override global insert interval + uint64_t insertRows; int64_t timeStampStep; char startTimestamp[MAX_TB_NAME_SIZE]; char sampleFormat[MAX_TB_NAME_SIZE]; // csv, json char sampleFile[MAX_FILE_NAME_LEN+1]; char tagsFile[MAX_FILE_NAME_LEN+1]; - int columnCount; + uint32_t columnCount; StrColumn columns[MAX_COLUMN_COUNT]; - int tagCount; + uint32_t tagCount; StrColumn tags[MAX_TAG_COUNT]; char* childTblName; char* colsOfCreateChildTable; - int64_t lenOfOneRow; - int64_t lenOfTagOfOneRow; + uint64_t lenOfOneRow; + uint64_t lenOfTagOfOneRow; char* sampleDataBuf; //int sampleRowCount; //int sampleUsePos; - int tagSource; // 0: rand, 1: tag sample + uint32_t tagSource; // 0: rand, 1: tag sample char* tagDataBuf; - int tagSampleCount; - int tagUsePos; + uint32_t tagSampleCount; + uint32_t tagUsePos; // statistics - int64_t totalInsertRows; - int64_t totalAffectedRows; + uint64_t totalInsertRows; + uint64_t totalAffectedRows; } SSuperTable; typedef struct { @@ -307,8 +307,8 @@ typedef struct { typedef struct SDbCfg_S { // int maxtablesPerVnode; - int minRows; - int maxRows; + uint32_t minRows; // 0 means default + uint32_t maxRows; // 0 means default int comp; int walLevel; int cacheLast; @@ -327,13 +327,15 @@ typedef struct SDataBase_S { char dbName[MAX_DB_NAME_SIZE]; bool drop; // 0: use exists, 1: if exists, drop then new create SDbCfg dbCfg; - int64_t superTblCount; + uint64_t superTblCount; SSuperTable superTbls[MAX_SUPER_TABLE_COUNT]; } SDataBase; typedef struct SDbs_S { char cfgDir[MAX_FILE_NAME_LEN+1]; char host[MAX_HOSTNAME_SIZE]; + struct sockaddr_in serv_addr; + uint16_t port; char user[MAX_USERNAME_SIZE]; char password[MAX_PASSWORD_SIZE]; @@ -343,104 +345,105 @@ typedef struct SDbs_S { bool do_aggreFunc; bool queryMode; - int threadCount; - int threadCountByCreateTbl; - int dbCount; + uint32_t threadCount; + uint32_t threadCountByCreateTbl; + uint32_t dbCount; SDataBase db[MAX_DB_COUNT]; // statistics - int64_t totalInsertRows; - int64_t totalAffectedRows; + uint64_t totalInsertRows; + uint64_t totalAffectedRows; } SDbs; typedef struct SpecifiedQueryInfo_S { - int64_t queryInterval; // 0: unlimit > 0 loop/s - int64_t concurrent; - int64_t sqlCount; - int mode; // 0: sync, 1: async - int64_t subscribeInterval; // ms - int64_t queryTimes; + uint64_t queryInterval; // 0: unlimit > 0 loop/s + uint64_t concurrent; + uint64_t sqlCount; + uint32_t mode; // 0: sync, 1: async + uint64_t subscribeInterval; // ms + uint64_t queryTimes; int subscribeRestart; int subscribeKeepProgress; char sql[MAX_QUERY_SQL_COUNT][MAX_QUERY_SQL_LENGTH+1]; char result[MAX_QUERY_SQL_COUNT][MAX_FILE_NAME_LEN+1]; TAOS_SUB* tsub[MAX_QUERY_SQL_COUNT]; - int64_t totalQueried; + uint64_t totalQueried; } SpecifiedQueryInfo; typedef struct SuperQueryInfo_S { char sTblName[MAX_TB_NAME_SIZE+1]; - int64_t queryInterval; // 0: unlimit > 0 loop/s - int threadCnt; - int mode; // 0: sync, 1: async - int64_t subscribeInterval; // ms + uint64_t queryInterval; // 0: unlimit > 0 loop/s + uint32_t threadCnt; + uint32_t mode; // 0: sync, 1: async + uint64_t subscribeInterval; // ms int subscribeRestart; int subscribeKeepProgress; - int64_t queryTimes; - int64_t childTblCount; + uint64_t queryTimes; + uint64_t childTblCount; char childTblPrefix[MAX_TB_NAME_SIZE]; - int64_t sqlCount; + uint64_t sqlCount; char sql[MAX_QUERY_SQL_COUNT][MAX_QUERY_SQL_LENGTH+1]; char result[MAX_QUERY_SQL_COUNT][MAX_FILE_NAME_LEN+1]; TAOS_SUB* tsub[MAX_QUERY_SQL_COUNT]; char* childTblName; - int64_t totalQueried; + uint64_t totalQueried; } SuperQueryInfo; typedef struct SQueryMetaInfo_S { char cfgDir[MAX_FILE_NAME_LEN+1]; char host[MAX_HOSTNAME_SIZE]; uint16_t port; + struct sockaddr_in serv_addr; char user[MAX_USERNAME_SIZE]; char password[MAX_PASSWORD_SIZE]; char dbName[MAX_DB_NAME_SIZE+1]; - char queryMode[MAX_TB_NAME_SIZE]; // taosc, restful + char queryMode[MAX_TB_NAME_SIZE]; // taosc, rest SpecifiedQueryInfo specifiedQueryInfo; SuperQueryInfo superQueryInfo; - int64_t totalQueried; + uint64_t totalQueried; } SQueryMetaInfo; typedef struct SThreadInfo_S { - TAOS *taos; - int threadID; - char db_name[MAX_DB_NAME_SIZE+1]; - uint32_t time_precision; - char fp[4096]; - char tb_prefix[MAX_TB_NAME_SIZE]; - int64_t start_table_from; - int64_t end_table_to; - int64_t ntables; - int64_t data_of_rate; - int64_t start_time; - char* cols; - bool use_metric; + TAOS * taos; + int threadID; + char db_name[MAX_DB_NAME_SIZE+1]; + uint32_t time_precision; + char fp[4096]; + char tb_prefix[MAX_TB_NAME_SIZE]; + uint64_t start_table_from; + uint64_t end_table_to; + uint64_t ntables; + uint64_t data_of_rate; + int64_t start_time; + char* cols; + bool use_metric; SSuperTable* superTblInfo; // for async insert - tsem_t lock_sem; - int64_t counter; + tsem_t lock_sem; + int64_t counter; uint64_t st; uint64_t et; - int64_t lastTs; + uint64_t lastTs; // sample data - int64_t samplePos; + int64_t samplePos; // statistics - int64_t totalInsertRows; - int64_t totalAffectedRows; + uint64_t totalInsertRows; + uint64_t totalAffectedRows; // insert delay statistics - int64_t cntDelay; - int64_t totalDelay; - int64_t avgDelay; - int64_t maxDelay; - int64_t minDelay; + uint64_t cntDelay; + uint64_t totalDelay; + uint64_t avgDelay; + uint64_t maxDelay; + uint64_t minDelay; // query - int64_t querySeq; // sequence number of sql command + uint64_t querySeq; // sequence number of sql command } threadInfo; #ifdef WINDOWS @@ -566,7 +569,7 @@ SArguments g_args = { 1, // query_times 0, // interlace_rows; 30000, // num_of_RPR - 1024000, // max_sql_len + (1024*1024), // max_sql_len 10000, // num_of_tables 10000, // num_of_DPT 0, // abort @@ -663,11 +666,11 @@ static void printHelp() { printf("%s%s%s%s\n", indent, "-q", indent, "Query mode -- 0: SYNC, 1: ASYNC. Default is SYNC."); printf("%s%s%s%s\n", indent, "-b", indent, - "The data_type of columns, default: TINYINT,SMALLINT,INT,BIGINT,FLOAT,DOUBLE,BINARY,NCHAR,BOOL,TIMESTAMP."); + "The data_type of columns, default: INT,INT,INT,INT."); printf("%s%s%s%s\n", indent, "-w", indent, "The length of data_type 'BINARY' or 'NCHAR'. Default is 16"); printf("%s%s%s%s\n", indent, "-l", indent, - "The number of columns per record. Default is 10."); + "The number of columns per record. Default is 4."); printf("%s%s%s%s\n", indent, "-T", indent, "The number of threads. Default is 10."); printf("%s%s%s%s\n", indent, "-i", indent, @@ -722,7 +725,7 @@ static void parse_args(int argc, char *argv[], SArguments *arguments) { errorPrint("%s", "\n\t-c need a valid path following!\n"); exit(EXIT_FAILURE); } - tstrncpy(configDir, argv[++i], MAX_FILE_NAME_LEN); + tstrncpy(configDir, argv[++i], TSDB_FILENAME_LEN); } else if (strcmp(argv[i], "-h") == 0) { if (argc == i+1) { @@ -768,48 +771,49 @@ static void parse_args(int argc, char *argv[], SArguments *arguments) { } arguments->sqlFile = argv[++i]; } else if (strcmp(argv[i], "-q") == 0) { - if ((argc == i+1) || - (!isStringNumber(argv[i+1]))) { + if ((argc == i+1) + || (!isStringNumber(argv[i+1]))) { printHelp(); errorPrint("%s", "\n\t-q need a number following!\nQuery mode -- 0: SYNC, 1: ASYNC. Default is SYNC.\n"); exit(EXIT_FAILURE); } arguments->query_mode = atoi(argv[++i]); } else if (strcmp(argv[i], "-T") == 0) { - if ((argc == i+1) || - (!isStringNumber(argv[i+1]))) { + if ((argc == i+1) + || (!isStringNumber(argv[i+1]))) { printHelp(); errorPrint("%s", "\n\t-T need a number following!\n"); exit(EXIT_FAILURE); } arguments->num_of_threads = atoi(argv[++i]); } else if (strcmp(argv[i], "-i") == 0) { - if ((argc == i+1) || - (!isStringNumber(argv[i+1]))) { + if ((argc == i+1) + || (!isStringNumber(argv[i+1]))) { printHelp(); errorPrint("%s", "\n\t-i need a number following!\n"); exit(EXIT_FAILURE); } arguments->insert_interval = atoi(argv[++i]); } else if (strcmp(argv[i], "-qt") == 0) { - if ((argc == i+1) || - (!isStringNumber(argv[i+1]))) { + if ((argc == i+1) + || (!isStringNumber(argv[i+1])) + || (atoi(argv[i+1]) <= 0)) { printHelp(); - errorPrint("%s", "\n\t-qt need a number following!\n"); + errorPrint("%s", "\n\t-qt need a valid (>0) number following!\n"); exit(EXIT_FAILURE); } arguments->query_times = atoi(argv[++i]); } else if (strcmp(argv[i], "-B") == 0) { - if ((argc == i+1) || - (!isStringNumber(argv[i+1]))) { + if ((argc == i+1) + || (!isStringNumber(argv[i+1]))) { printHelp(); errorPrint("%s", "\n\t-B need a number following!\n"); exit(EXIT_FAILURE); } arguments->interlace_rows = atoi(argv[++i]); } else if (strcmp(argv[i], "-r") == 0) { - if ((argc == i+1) || - (!isStringNumber(argv[i+1]))) { + if ((argc == i+1) + || (!isStringNumber(argv[i+1]))) { printHelp(); errorPrint("%s", "\n\t-r need a number following!\n"); exit(EXIT_FAILURE); @@ -964,9 +968,9 @@ static void parse_args(int argc, char *argv[], SArguments *arguments) { } } else if (strcmp(argv[i], "-D") == 0) { arguments->method_of_delete = atoi(argv[++i]); - if (arguments->method_of_delete < 0 - || arguments->method_of_delete > 3) { - arguments->method_of_delete = 0; + if (arguments->method_of_delete > 3) { + errorPrint("%s", "\n\t-D need a valud (0~3) number following!\n"); + exit(EXIT_FAILURE); } } else if ((strcmp(argv[i], "--version") == 0) || (strcmp(argv[i], "-V") == 0)){ @@ -1001,17 +1005,17 @@ static void parse_args(int argc, char *argv[], SArguments *arguments) { break; printf("\n"); } - printf("# Insertion interval: %"PRId64"\n", + printf("# Insertion interval: %"PRIu64"\n", arguments->insert_interval); - printf("# Number of records per req: %"PRId64"\n", + printf("# Number of records per req: %"PRIu64"\n", arguments->num_of_RPR); - printf("# Max SQL length: %"PRId64"\n", + printf("# Max SQL length: %"PRIu64"\n", arguments->max_sql_len); printf("# Length of Binary: %d\n", arguments->len_of_binary); printf("# Number of Threads: %d\n", arguments->num_of_threads); - printf("# Number of Tables: %"PRId64"\n", + printf("# Number of Tables: %"PRIu64"\n", arguments->num_of_tables); - printf("# Number of Data per Table: %"PRId64"\n", + printf("# Number of Data per Table: %"PRIu64"\n", arguments->num_of_DPT); printf("# Database name: %s\n", arguments->database); printf("# Table prefix: %s\n", arguments->tb_prefix); @@ -1069,7 +1073,7 @@ static int queryDbExec(TAOS *taos, char *command, QUERY_TYPE type, bool quiet) { if (code != 0) { if (!quiet) { debugPrint("%s() LN%d - command: %s\n", __func__, __LINE__, command); - errorPrint("Failed to run %s, reason: %s\n", command, taos_errstr(res)); + errorPrint("Failed to execute %s, reason: %s\n", command, taos_errstr(res)); } taos_free_result(res); //taos_close(taos); @@ -1188,13 +1192,31 @@ static float rand_float(){ return randfloat[cursor]; } +#if 0 +static const char charNum[] = "0123456789"; + +static void nonrand_string(char *, int) __attribute__ ((unused)); // reserve for debugging purpose +static void nonrand_string(char *str, int size) +{ + str[0] = 0; + if (size > 0) { + int n; + for (n = 0; n < size; n++) { + str[n] = charNum[n % 10]; + } + str[n] = 0; + } +} +#endif + static const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; + static void rand_string(char *str, int size) { str[0] = 0; if (size > 0) { //--size; int n; - for (n = 0; n < size - 1; n++) { + for (n = 0; n < size; n++) { int key = abs(rand_tinyint()) % (int)(sizeof(charset) - 1); str[n] = charset[key]; } @@ -1249,11 +1271,11 @@ static int printfInsertMeta() { printf("resultFile: \033[33m%s\033[0m\n", g_Dbs.resultFile); printf("thread num of insert data: \033[33m%d\033[0m\n", g_Dbs.threadCount); printf("thread num of create table: \033[33m%d\033[0m\n", g_Dbs.threadCountByCreateTbl); - printf("top insert interval: \033[33m%"PRId64"\033[0m\n", + printf("top insert interval: \033[33m%"PRIu64"\033[0m\n", g_args.insert_interval); - printf("number of records per req: \033[33m%"PRId64"\033[0m\n", + printf("number of records per req: \033[33m%"PRIu64"\033[0m\n", g_args.num_of_RPR); - printf("max sql length: \033[33m%"PRId64"\033[0m\n", + printf("max sql length: \033[33m%"PRIu64"\033[0m\n", g_args.max_sql_len); printf("database count: \033[33m%d\033[0m\n", g_Dbs.dbCount); @@ -1315,10 +1337,10 @@ static int printfInsertMeta() { } } - printf(" super table count: \033[33m%"PRId64"\033[0m\n", + printf(" super table count: \033[33m%"PRIu64"\033[0m\n", g_Dbs.db[i].superTblCount); - for (int64_t j = 0; j < g_Dbs.db[i].superTblCount; j++) { - printf(" super table[\033[33m%"PRId64"\033[0m]:\n", j); + for (uint64_t j = 0; j < g_Dbs.db[i].superTblCount; j++) { + printf(" super table[\033[33m%"PRIu64"\033[0m]:\n", j); printf(" stbName: \033[33m%s\033[0m\n", g_Dbs.db[i].superTbls[j].sTblName); @@ -1339,7 +1361,7 @@ static int printfInsertMeta() { printf(" childTblExists: \033[33m%s\033[0m\n", "error"); } - printf(" childTblCount: \033[33m%"PRId64"\033[0m\n", + printf(" childTblCount: \033[33m%"PRIu64"\033[0m\n", g_Dbs.db[i].superTbls[j].childTblCount); printf(" childTblPrefix: \033[33m%s\033[0m\n", g_Dbs.db[i].superTbls[j].childTblPrefix); @@ -1351,11 +1373,11 @@ static int printfInsertMeta() { printf(" childTblLimit: \033[33m%"PRId64"\033[0m\n", g_Dbs.db[i].superTbls[j].childTblLimit); } - if (g_Dbs.db[i].superTbls[j].childTblOffset >= 0) { - printf(" childTblOffset: \033[33m%"PRId64"\033[0m\n", + if (g_Dbs.db[i].superTbls[j].childTblOffset > 0) { + printf(" childTblOffset: \033[33m%"PRIu64"\033[0m\n", g_Dbs.db[i].superTbls[j].childTblOffset); } - printf(" insertRows: \033[33m%"PRId64"\033[0m\n", + printf(" insertRows: \033[33m%"PRIu64"\033[0m\n", g_Dbs.db[i].superTbls[j].insertRows); /* if (0 == g_Dbs.db[i].superTbls[j].multiThreadWriteOneTbl) { @@ -1364,11 +1386,11 @@ static int printfInsertMeta() { printf(" multiThreadWriteOneTbl: \033[33myes\033[0m\n"); } */ - printf(" interlaceRows: \033[33m%"PRId64"\033[0m\n", + printf(" interlaceRows: \033[33m%"PRIu64"\033[0m\n", g_Dbs.db[i].superTbls[j].interlaceRows); if (g_Dbs.db[i].superTbls[j].interlaceRows > 0) { - printf(" stable insert interval: \033[33m%"PRId64"\033[0m\n", + printf(" stable insert interval: \033[33m%"PRIu64"\033[0m\n", g_Dbs.db[i].superTbls[j].insertInterval); } @@ -1376,7 +1398,7 @@ static int printfInsertMeta() { g_Dbs.db[i].superTbls[j].disorderRange); printf(" disorderRatio: \033[33m%d\033[0m\n", g_Dbs.db[i].superTbls[j].disorderRatio); - printf(" maxSqlLen: \033[33m%"PRId64"\033[0m\n", + printf(" maxSqlLen: \033[33m%"PRIu64"\033[0m\n", g_Dbs.db[i].superTbls[j].maxSqlLen); printf(" timeStampStep: \033[33m%"PRId64"\033[0m\n", g_Dbs.db[i].superTbls[j].timeStampStep); @@ -1442,8 +1464,8 @@ static void printfInsertMetaToFile(FILE* fp) { fprintf(fp, "resultFile: %s\n", g_Dbs.resultFile); fprintf(fp, "thread num of insert data: %d\n", g_Dbs.threadCount); fprintf(fp, "thread num of create table: %d\n", g_Dbs.threadCountByCreateTbl); - fprintf(fp, "number of records per req: %"PRId64"\n", g_args.num_of_RPR); - fprintf(fp, "max sql length: %"PRId64"\n", g_args.max_sql_len); + fprintf(fp, "number of records per req: %"PRIu64"\n", g_args.num_of_RPR); + fprintf(fp, "max sql length: %"PRIu64"\n", g_args.max_sql_len); fprintf(fp, "database count: %d\n", g_Dbs.dbCount); for (int i = 0; i < g_Dbs.dbCount; i++) { @@ -1500,7 +1522,7 @@ static void printfInsertMetaToFile(FILE* fp) { } } - fprintf(fp, " super table count: %"PRId64"\n", g_Dbs.db[i].superTblCount); + fprintf(fp, " super table count: %"PRIu64"\n", g_Dbs.db[i].superTblCount); for (int j = 0; j < g_Dbs.db[i].superTblCount; j++) { fprintf(fp, " super table[%d]:\n", j); @@ -1522,7 +1544,7 @@ static void printfInsertMetaToFile(FILE* fp) { fprintf(fp, " childTblExists: %s\n", "error"); } - fprintf(fp, " childTblCount: %"PRId64"\n", + fprintf(fp, " childTblCount: %"PRIu64"\n", g_Dbs.db[i].superTbls[j].childTblCount); fprintf(fp, " childTblPrefix: %s\n", g_Dbs.db[i].superTbls[j].childTblPrefix); @@ -1530,12 +1552,12 @@ static void printfInsertMetaToFile(FILE* fp) { g_Dbs.db[i].superTbls[j].dataSource); fprintf(fp, " insertMode: %s\n", g_Dbs.db[i].superTbls[j].insertMode); - fprintf(fp, " insertRows: %"PRId64"\n", + fprintf(fp, " insertRows: %"PRIu64"\n", g_Dbs.db[i].superTbls[j].insertRows); - fprintf(fp, " interlace rows: %"PRId64"\n", + fprintf(fp, " interlace rows: %"PRIu64"\n", g_Dbs.db[i].superTbls[j].interlaceRows); if (g_Dbs.db[i].superTbls[j].interlaceRows > 0) { - fprintf(fp, " stable insert interval: %"PRId64"\n", + fprintf(fp, " stable insert interval: %"PRIu64"\n", g_Dbs.db[i].superTbls[j].insertInterval); } /* @@ -1545,11 +1567,11 @@ static void printfInsertMetaToFile(FILE* fp) { fprintf(fp, " multiThreadWriteOneTbl: yes\n"); } */ - fprintf(fp, " interlaceRows: %"PRId64"\n", + fprintf(fp, " interlaceRows: %"PRIu64"\n", g_Dbs.db[i].superTbls[j].interlaceRows); fprintf(fp, " disorderRange: %d\n", g_Dbs.db[i].superTbls[j].disorderRange); fprintf(fp, " disorderRatio: %d\n", g_Dbs.db[i].superTbls[j].disorderRatio); - fprintf(fp, " maxSqlLen: %"PRId64"\n", + fprintf(fp, " maxSqlLen: %"PRIu64"\n", g_Dbs.db[i].superTbls[j].maxSqlLen); fprintf(fp, " timeStampStep: %"PRId64"\n", @@ -1609,64 +1631,68 @@ static void printfQueryMeta() { printf("database name: \033[33m%s\033[0m\n", g_queryInfo.dbName); printf("\n"); - printf("specified table query info: \n"); - printf("query interval: \033[33m%"PRId64" ms\033[0m\n", - g_queryInfo.specifiedQueryInfo.queryInterval); - printf("top query times:\033[33m%"PRId64"\033[0m\n", g_args.query_times); - printf("concurrent: \033[33m%"PRId64"\033[0m\n", - g_queryInfo.specifiedQueryInfo.concurrent); - printf("sqlCount: \033[33m%"PRId64"\033[0m\n", + + if ((SUBSCRIBE_TEST == g_args.test_mode) || (QUERY_TEST == g_args.test_mode)) { + printf("specified table query info: \n"); + printf("sqlCount: \033[33m%"PRIu64"\033[0m\n", g_queryInfo.specifiedQueryInfo.sqlCount); - printf("specified tbl query times:\n"); - printf(" \033[33m%"PRId64"\033[0m\n", + if (g_queryInfo.specifiedQueryInfo.sqlCount > 0) { + printf("specified tbl query times:\n"); + printf(" \033[33m%"PRIu64"\033[0m\n", g_queryInfo.specifiedQueryInfo.queryTimes); - - if (SUBSCRIBE_TEST == g_args.test_mode) { - printf("mod: \033[33m%d\033[0m\n", - g_queryInfo.specifiedQueryInfo.mode); - printf("interval: \033[33m%"PRId64"\033[0m\n", + printf("query interval: \033[33m%"PRIu64" ms\033[0m\n", + g_queryInfo.specifiedQueryInfo.queryInterval); + printf("top query times:\033[33m%"PRIu64"\033[0m\n", g_args.query_times); + printf("concurrent: \033[33m%"PRIu64"\033[0m\n", + g_queryInfo.specifiedQueryInfo.concurrent); + printf("mod: \033[33m%s\033[0m\n", + (g_queryInfo.specifiedQueryInfo.mode)?"async":"sync"); + printf("interval: \033[33m%"PRIu64"\033[0m\n", g_queryInfo.specifiedQueryInfo.subscribeInterval); - printf("restart: \033[33m%d\033[0m\n", + printf("restart: \033[33m%d\033[0m\n", g_queryInfo.specifiedQueryInfo.subscribeRestart); - printf("keepProgress: \033[33m%d\033[0m\n", + printf("keepProgress: \033[33m%d\033[0m\n", g_queryInfo.specifiedQueryInfo.subscribeKeepProgress); - } - for (int64_t i = 0; i < g_queryInfo.specifiedQueryInfo.sqlCount; i++) { - printf(" sql[%"PRId64"]: \033[33m%s\033[0m\n", - i, g_queryInfo.specifiedQueryInfo.sql[i]); - } - printf("\n"); - printf("super table query info:\n"); - printf("query interval: \033[33m%"PRId64"\033[0m\n", - g_queryInfo.superQueryInfo.queryInterval); - printf("threadCnt: \033[33m%d\033[0m\n", - g_queryInfo.superQueryInfo.threadCnt); - printf("childTblCount: \033[33m%"PRId64"\033[0m\n", - g_queryInfo.superQueryInfo.childTblCount); - printf("stable name: \033[33m%s\033[0m\n", - g_queryInfo.superQueryInfo.sTblName); - printf("stb query times:\033[33m%"PRId64"\033[0m\n", - g_queryInfo.superQueryInfo.queryTimes); - - if (SUBSCRIBE_TEST == g_args.test_mode) { - printf("mod: \033[33m%d\033[0m\n", - g_queryInfo.superQueryInfo.mode); - printf("interval: \033[33m%"PRId64"\033[0m\n", + for (uint64_t i = 0; i < g_queryInfo.specifiedQueryInfo.sqlCount; i++) { + printf(" sql[%"PRIu64"]: \033[33m%s\033[0m\n", + i, g_queryInfo.specifiedQueryInfo.sql[i]); + } + printf("\n"); + } + + printf("super table query info:\n"); + printf("sqlCount: \033[33m%"PRIu64"\033[0m\n", + g_queryInfo.superQueryInfo.sqlCount); + + if (g_queryInfo.superQueryInfo.sqlCount > 0) { + printf("query interval: \033[33m%"PRIu64"\033[0m\n", + g_queryInfo.superQueryInfo.queryInterval); + printf("threadCnt: \033[33m%d\033[0m\n", + g_queryInfo.superQueryInfo.threadCnt); + printf("childTblCount: \033[33m%"PRIu64"\033[0m\n", + g_queryInfo.superQueryInfo.childTblCount); + printf("stable name: \033[33m%s\033[0m\n", + g_queryInfo.superQueryInfo.sTblName); + printf("stb query times:\033[33m%"PRIu64"\033[0m\n", + g_queryInfo.superQueryInfo.queryTimes); + + printf("mod: \033[33m%s\033[0m\n", + (g_queryInfo.superQueryInfo.mode)?"async":"sync"); + printf("interval: \033[33m%"PRIu64"\033[0m\n", g_queryInfo.superQueryInfo.subscribeInterval); - printf("restart: \033[33m%d\033[0m\n", + printf("restart: \033[33m%d\033[0m\n", g_queryInfo.superQueryInfo.subscribeRestart); - printf("keepProgress: \033[33m%d\033[0m\n", + printf("keepProgress: \033[33m%d\033[0m\n", g_queryInfo.superQueryInfo.subscribeKeepProgress); - } - printf("sqlCount: \033[33m%"PRId64"\033[0m\n", - g_queryInfo.superQueryInfo.sqlCount); - for (int i = 0; i < g_queryInfo.superQueryInfo.sqlCount; i++) { - printf(" sql[%d]: \033[33m%s\033[0m\n", - i, g_queryInfo.superQueryInfo.sql[i]); + for (int i = 0; i < g_queryInfo.superQueryInfo.sqlCount; i++) { + printf(" sql[%d]: \033[33m%s\033[0m\n", + i, g_queryInfo.superQueryInfo.sql[i]); + } + printf("\n"); + } } - printf("\n"); SHOW_PARSE_RESULT_END(); } @@ -1955,14 +1981,12 @@ static void printfQuerySystemInfo(TAOS * taos) { free(dbInfos); } -static int postProceSql(char* host, uint16_t port, char* sqlstr) +static int postProceSql(char *host, struct sockaddr_in *pServAddr, uint16_t port, char* sqlstr) { char *req_fmt = "POST %s HTTP/1.1\r\nHost: %s:%d\r\nAccept: */*\r\nAuthorization: Basic %s\r\nContent-Length: %d\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\n%s"; char *url = "/rest/sql"; - struct hostent *server; - struct sockaddr_in serv_addr; int bytes, sent, received, req_str_len, resp_len; char *request_buf; char response_buf[RESP_BUF_LEN]; @@ -2011,27 +2035,7 @@ static int postProceSql(char* host, uint16_t port, char* sqlstr) ERROR_EXIT("ERROR opening socket"); } - server = gethostbyname(host); - if (server == NULL) { - free(request_buf); - ERROR_EXIT("ERROR, no such host"); - } - - debugPrint("h_name: %s\nh_addretype: %s\nh_length: %d\n", - server->h_name, - (server->h_addrtype == AF_INET)?"ipv4":"ipv6", - server->h_length); - - memset(&serv_addr, 0, sizeof(serv_addr)); - serv_addr.sin_family = AF_INET; - serv_addr.sin_port = htons(rest_port); -#ifdef WINDOWS - serv_addr.sin_addr.s_addr = inet_addr(host); -#else - memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length); -#endif - - int retConn = connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)); + int retConn = connect(sockfd, (struct sockaddr *)pServAddr, sizeof(struct sockaddr)); debugPrint("%s() LN%d connect() return %d\n", __func__, __LINE__, retConn); if (retConn < 0) { free(request_buf); @@ -2291,7 +2295,7 @@ static int calcRowLen(SSuperTable* superTbls) { static int getChildNameOfSuperTableWithLimitAndOffset(TAOS * taos, char* dbName, char* sTblName, char** childTblNameOfSuperTbl, - int64_t* childTblCountOfSuperTbl, int64_t limit, int64_t offset) { + uint64_t* childTblCountOfSuperTbl, int64_t limit, uint64_t offset) { char command[BUFFER_SIZE] = "\0"; char limitBuf[100] = "\0"; @@ -2302,7 +2306,7 @@ static int getChildNameOfSuperTableWithLimitAndOffset(TAOS * taos, char* childTblName = *childTblNameOfSuperTbl; if (offset >= 0) { - snprintf(limitBuf, 100, " limit %"PRId64" offset %"PRId64"", + snprintf(limitBuf, 100, " limit %"PRId64" offset %"PRIu64"", limit, offset); } @@ -2368,11 +2372,11 @@ static int getChildNameOfSuperTableWithLimitAndOffset(TAOS * taos, static int getAllChildNameOfSuperTable(TAOS * taos, char* dbName, char* sTblName, char** childTblNameOfSuperTbl, - int64_t* childTblCountOfSuperTbl) { + uint64_t* childTblCountOfSuperTbl) { return getChildNameOfSuperTableWithLimitAndOffset(taos, dbName, sTblName, childTblNameOfSuperTbl, childTblCountOfSuperTbl, - -1, -1); + -1, 0); } static int getSuperTableFromServer(TAOS * taos, char* dbName, @@ -2708,7 +2712,7 @@ static int createDatabasesAndStables() { printf("\ncreate database %s success!\n\n", g_Dbs.db[i].dbName); } - debugPrint("%s() LN%d supertbl count:%"PRId64"\n", + debugPrint("%s() LN%d supertbl count:%"PRIu64"\n", __func__, __LINE__, g_Dbs.db[i].superTblCount); int validStbCount = 0; @@ -2767,15 +2771,15 @@ static void* createTable(void *sarg) int len = 0; int batchNum = 0; - verbosePrint("%s() LN%d: Creating table from %"PRId64" to %"PRId64"\n", + verbosePrint("%s() LN%d: Creating table from %"PRIu64" to %"PRIu64"\n", __func__, __LINE__, pThreadInfo->start_table_from, pThreadInfo->end_table_to); - for (int64_t i = pThreadInfo->start_table_from; + for (uint64_t i = pThreadInfo->start_table_from; i <= pThreadInfo->end_table_to; i++) { if (0 == g_Dbs.use_metric) { snprintf(buffer, buff_len, - "create table if not exists %s.%s%"PRId64" %s;", + "create table if not exists %s.%s%"PRIu64" %s;", pThreadInfo->db_name, g_args.tb_prefix, i, pThreadInfo->cols); @@ -2806,7 +2810,7 @@ static void* createTable(void *sarg) } len += snprintf(buffer + len, buff_len - len, - "if not exists %s.%s%"PRId64" using %s.%s tags %s ", + "if not exists %s.%s%"PRIu64" using %s.%s tags %s ", pThreadInfo->db_name, superTblInfo->childTblPrefix, i, pThreadInfo->db_name, superTblInfo->sTblName, tagsValBuf); @@ -2830,7 +2834,7 @@ static void* createTable(void *sarg) int64_t currentPrintTime = taosGetTimestampMs(); if (currentPrintTime - lastPrintTime > 30*1000) { - printf("thread[%d] already create %"PRId64" - %"PRId64" tables\n", + printf("thread[%d] already create %"PRIu64" - %"PRIu64" tables\n", pThreadInfo->threadID, pThreadInfo->start_table_from, i); lastPrintTime = currentPrintTime; } @@ -2848,7 +2852,7 @@ static void* createTable(void *sarg) } static int startMultiThreadCreateChildTable( - char* cols, int threads, int64_t startFrom, int64_t ntables, + char* cols, int threads, uint64_t startFrom, uint64_t ntables, char* db_name, SSuperTable* superTblInfo) { pthread_t *pids = malloc(threads * sizeof(pthread_t)); @@ -2863,13 +2867,13 @@ static int startMultiThreadCreateChildTable( threads = 1; } - int64_t a = ntables / threads; + uint64_t a = ntables / threads; if (a < 1) { threads = ntables; a = 1; } - int64_t b = 0; + uint64_t b = 0; b = ntables % threads; for (int64_t i = 0; i < threads; i++) { @@ -2898,7 +2902,7 @@ static int startMultiThreadCreateChildTable( startFrom = t_info->end_table_to + 1; t_info->use_metric = true; t_info->cols = cols; - t_info->minDelay = INT16_MAX; + t_info->minDelay = UINT64_MAX; pthread_create(pids + i, NULL, createTable, t_info); } @@ -2964,7 +2968,7 @@ static void createChildTables() { snprintf(tblColsBuf + len, MAX_SQL_SIZE - len, ")"); - verbosePrint("%s() LN%d: dbName: %s num of tb: %"PRId64" schema: %s\n", + verbosePrint("%s() LN%d: dbName: %s num of tb: %"PRIu64" schema: %s\n", __func__, __LINE__, g_Dbs.db[i].dbName, g_args.num_of_tables, tblColsBuf); startMultiThreadCreateChildTable( @@ -3092,7 +3096,7 @@ static int readSampleFromCsvFileToMem( } if (readLen > superTblInfo->lenOfOneRow) { - printf("sample row len[%d] overflow define schema len[%"PRId64"], so discard this row\n", + printf("sample row len[%d] overflow define schema len[%"PRIu64"], so discard this row\n", (int32_t)readLen, superTblInfo->lenOfOneRow); continue; } @@ -3335,7 +3339,7 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { if (threads2 && threads2->type == cJSON_Number) { g_Dbs.threadCountByCreateTbl = threads2->valueint; } else if (!threads2) { - g_Dbs.threadCountByCreateTbl = g_args.num_of_threads; + g_Dbs.threadCountByCreateTbl = 1; } else { errorPrint("%s() LN%d, failed to read json, threads2 not found\n", __func__, __LINE__); @@ -3344,6 +3348,11 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { cJSON* gInsertInterval = cJSON_GetObjectItem(root, "insert_interval"); if (gInsertInterval && gInsertInterval->type == cJSON_Number) { + if (gInsertInterval->valueint <0) { + errorPrint("%s() LN%d, failed to read json, insert interval input mistake\n", + __func__, __LINE__); + goto PARSE_OVER; + } g_args.insert_interval = gInsertInterval->valueint; } else if (!gInsertInterval) { g_args.insert_interval = 0; @@ -3355,13 +3364,19 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { cJSON* interlaceRows = cJSON_GetObjectItem(root, "interlace_rows"); if (interlaceRows && interlaceRows->type == cJSON_Number) { + if (interlaceRows->valueint < 0) { + errorPrint("%s() LN%d, failed to read json, interlace_rows input mistake\n", + __func__, __LINE__); + goto PARSE_OVER; + + } g_args.interlace_rows = interlaceRows->valueint; // rows per table need be less than insert batch if (g_args.interlace_rows > g_args.num_of_RPR) { - printf("NOTICE: interlace rows value %"PRId64" > num_of_records_per_req %"PRId64"\n\n", + printf("NOTICE: interlace rows value %"PRIu64" > num_of_records_per_req %"PRIu64"\n\n", g_args.interlace_rows, g_args.num_of_RPR); - printf(" interlace rows value will be set to num_of_records_per_req %"PRId64"\n\n", + printf(" interlace rows value will be set to num_of_records_per_req %"PRIu64"\n\n", g_args.num_of_RPR); printf(" press Enter key to continue or Ctrl-C to stop."); (void)getchar(); @@ -3377,9 +3392,14 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { cJSON* maxSqlLen = cJSON_GetObjectItem(root, "max_sql_len"); if (maxSqlLen && maxSqlLen->type == cJSON_Number) { + if (maxSqlLen->valueint < 0) { + errorPrint("%s() LN%d, failed to read json, max_sql_len input mistake\n", + __func__, __LINE__); + goto PARSE_OVER; + } g_args.max_sql_len = maxSqlLen->valueint; } else if (!maxSqlLen) { - g_args.max_sql_len = 1024000; + g_args.max_sql_len = (1024*1024); } else { errorPrint("%s() LN%d, failed to read json, max_sql_len input mistake\n", __func__, __LINE__); @@ -3388,9 +3408,14 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { cJSON* numRecPerReq = cJSON_GetObjectItem(root, "num_of_records_per_req"); if (numRecPerReq && numRecPerReq->type == cJSON_Number) { + if (numRecPerReq->valueint <= 0) { + errorPrint("%s() LN%d, failed to read json, num_of_records_per_req input mistake\n", + __func__, __LINE__); + goto PARSE_OVER; + } g_args.num_of_RPR = numRecPerReq->valueint; } else if (!numRecPerReq) { - g_args.num_of_RPR = INT64_MAX; + g_args.num_of_RPR = UINT64_MAX; } else { errorPrint("%s() LN%d, failed to read json, num_of_records_per_req not found\n", __func__, __LINE__); @@ -3550,7 +3575,7 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { if (minRows && minRows->type == cJSON_Number) { g_Dbs.db[i].dbCfg.minRows = minRows->valueint; } else if (!minRows) { - g_Dbs.db[i].dbCfg.minRows = -1; + g_Dbs.db[i].dbCfg.minRows = 0; // 0 means default } else { printf("ERROR: failed to read json, minRows not found\n"); goto PARSE_OVER; @@ -3560,7 +3585,7 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { if (maxRows && maxRows->type == cJSON_Number) { g_Dbs.db[i].dbCfg.maxRows = maxRows->valueint; } else if (!maxRows) { - g_Dbs.db[i].dbCfg.maxRows = -1; + g_Dbs.db[i].dbCfg.maxRows = 0; // 0 means default } else { printf("ERROR: failed to read json, maxRows not found\n"); goto PARSE_OVER; @@ -3705,7 +3730,7 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { cJSON* count = cJSON_GetObjectItem(stbInfo, "childtable_count"); if (!count || count->type != cJSON_Number || 0 >= count->valueint) { - errorPrint("%s() LN%d, failed to read json, childtable_count not found\n", + errorPrint("%s() LN%d, failed to read json, childtable_count input mistake\n", __func__, __LINE__); goto PARSE_OVER; } @@ -3724,7 +3749,7 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { goto PARSE_OVER; } - cJSON *insertMode = cJSON_GetObjectItem(stbInfo, "insert_mode"); // taosc , restful + cJSON *insertMode = cJSON_GetObjectItem(stbInfo, "insert_mode"); // taosc , rest if (insertMode && insertMode->type == cJSON_String && insertMode->valuestring != NULL) { tstrncpy(g_Dbs.db[i].superTbls[j].insertMode, @@ -3859,12 +3884,17 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { */ cJSON* interlaceRows = cJSON_GetObjectItem(stbInfo, "interlace_rows"); if (interlaceRows && interlaceRows->type == cJSON_Number) { + if (interlaceRows->valueint < 0) { + errorPrint("%s() LN%d, failed to read json, interlace rows input mistake\n", + __func__, __LINE__); + goto PARSE_OVER; + } g_Dbs.db[i].superTbls[j].interlaceRows = interlaceRows->valueint; // rows per table need be less than insert batch if (g_Dbs.db[i].superTbls[j].interlaceRows > g_args.num_of_RPR) { - printf("NOTICE: db[%d].superTbl[%d]'s interlace rows value %"PRId64" > num_of_records_per_req %"PRId64"\n\n", + printf("NOTICE: db[%d].superTbl[%d]'s interlace rows value %"PRIu64" > num_of_records_per_req %"PRIu64"\n\n", i, j, g_Dbs.db[i].superTbls[j].interlaceRows, g_args.num_of_RPR); - printf(" interlace rows value will be set to num_of_records_per_req %"PRId64"\n\n", + printf(" interlace rows value will be set to num_of_records_per_req %"PRIu64"\n\n", g_args.num_of_RPR); printf(" press Enter key to continue or Ctrl-C to stop."); (void)getchar(); @@ -3907,6 +3937,11 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { cJSON* insertRows = cJSON_GetObjectItem(stbInfo, "insert_rows"); if (insertRows && insertRows->type == cJSON_Number) { + if (insertRows->valueint < 0) { + errorPrint("%s() LN%d, failed to read json, insert_rows input mistake\n", + __func__, __LINE__); + goto PARSE_OVER; + } g_Dbs.db[i].superTbls[j].insertRows = insertRows->valueint; } else if (!insertRows) { g_Dbs.db[i].superTbls[j].insertRows = 0x7FFFFFFFFFFFFFFF; @@ -3919,8 +3954,13 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { cJSON* insertInterval = cJSON_GetObjectItem(stbInfo, "insert_interval"); if (insertInterval && insertInterval->type == cJSON_Number) { g_Dbs.db[i].superTbls[j].insertInterval = insertInterval->valueint; + if (insertInterval->valueint < 0) { + errorPrint("%s() LN%d, failed to read json, insert_interval input mistake\n", + __func__, __LINE__); + goto PARSE_OVER; + } } else if (!insertInterval) { - verbosePrint("%s() LN%d: stable insert interval be overrided by global %"PRId64".\n", + verbosePrint("%s() LN%d: stable insert interval be overrided by global %"PRIu64".\n", __func__, __LINE__, g_args.insert_interval); g_Dbs.db[i].superTbls[j].insertInterval = g_args.insert_interval; } else { @@ -4001,6 +4041,11 @@ static bool getMetaFromQueryJsonFile(cJSON* root) { cJSON* gQueryTimes = cJSON_GetObjectItem(root, "query_times"); if (gQueryTimes && gQueryTimes->type == cJSON_Number) { + if (gQueryTimes->valueint <= 0) { + errorPrint("%s() LN%d, failed to read json, query_times: %"PRId64", need be a valid (>0) number\n", + __func__, __LINE__, gQueryTimes->valueint); + goto PARSE_OVER; + } g_args.query_times = gQueryTimes->valueint; } else if (!gQueryTimes) { g_args.query_times = 1; @@ -4028,10 +4073,10 @@ static bool getMetaFromQueryJsonFile(cJSON* root) { goto PARSE_OVER; } - // super_table_query + // specified_table_query cJSON *specifiedQuery = cJSON_GetObjectItem(root, "specified_table_query"); if (!specifiedQuery) { - g_queryInfo.specifiedQueryInfo.concurrent = 0; + g_queryInfo.specifiedQueryInfo.concurrent = 1; g_queryInfo.specifiedQueryInfo.sqlCount = 0; } else if (specifiedQuery->type != cJSON_Object) { printf("ERROR: failed to read json, super_table_query not found\n"); @@ -4047,6 +4092,12 @@ static bool getMetaFromQueryJsonFile(cJSON* root) { cJSON* specifiedQueryTimes = cJSON_GetObjectItem(specifiedQuery, "query_times"); if (specifiedQueryTimes && specifiedQueryTimes->type == cJSON_Number) { + if (specifiedQueryTimes->valueint <= 0) { + errorPrint("%s() LN%d, failed to read json, query_times: %"PRId64", need be a valid (>0) number\n", + __func__, __LINE__, specifiedQueryTimes->valueint); + goto PARSE_OVER; + + } g_queryInfo.specifiedQueryInfo.queryTimes = specifiedQueryTimes->valueint; } else if (!specifiedQueryTimes) { g_queryInfo.specifiedQueryInfo.queryTimes = g_args.query_times; @@ -4058,13 +4109,14 @@ static bool getMetaFromQueryJsonFile(cJSON* root) { cJSON* concurrent = cJSON_GetObjectItem(specifiedQuery, "concurrent"); if (concurrent && concurrent->type == cJSON_Number) { - g_queryInfo.specifiedQueryInfo.concurrent = concurrent->valueint; - if (g_queryInfo.specifiedQueryInfo.concurrent <= 0) { - errorPrint("%s() LN%d, query sqlCount %"PRId64" or concurrent %"PRId64" is not correct.\n", - __func__, __LINE__, g_queryInfo.specifiedQueryInfo.sqlCount, + if (concurrent->valueint <= 0) { + errorPrint("%s() LN%d, query sqlCount %"PRIu64" or concurrent %"PRIu64" is not correct.\n", + __func__, __LINE__, + g_queryInfo.specifiedQueryInfo.sqlCount, g_queryInfo.specifiedQueryInfo.concurrent); goto PARSE_OVER; } + g_queryInfo.specifiedQueryInfo.concurrent = concurrent->valueint; } else if (!concurrent) { g_queryInfo.specifiedQueryInfo.concurrent = 1; } @@ -4165,10 +4217,10 @@ static bool getMetaFromQueryJsonFile(cJSON* root) { } } - // sub_table_query + // super_table_query cJSON *superQuery = cJSON_GetObjectItem(root, "super_table_query"); if (!superQuery) { - g_queryInfo.superQueryInfo.threadCnt = 0; + g_queryInfo.superQueryInfo.threadCnt = 1; g_queryInfo.superQueryInfo.sqlCount = 0; } else if (superQuery->type != cJSON_Object) { printf("ERROR: failed to read json, sub_table_query not found\n"); @@ -4184,6 +4236,11 @@ static bool getMetaFromQueryJsonFile(cJSON* root) { cJSON* superQueryTimes = cJSON_GetObjectItem(superQuery, "query_times"); if (superQueryTimes && superQueryTimes->type == cJSON_Number) { + if (superQueryTimes->valueint <= 0) { + errorPrint("%s() LN%d, failed to read json, query_times: %"PRId64", need be a valid (>0) number\n", + __func__, __LINE__, superQueryTimes->valueint); + goto PARSE_OVER; + } g_queryInfo.superQueryInfo.queryTimes = superQueryTimes->valueint; } else if (!superQueryTimes) { g_queryInfo.superQueryInfo.queryTimes = g_args.query_times; @@ -4195,6 +4252,12 @@ static bool getMetaFromQueryJsonFile(cJSON* root) { cJSON* threads = cJSON_GetObjectItem(superQuery, "threads"); if (threads && threads->type == cJSON_Number) { + if (threads->valueint <= 0) { + errorPrint("%s() LN%d, failed to read json, threads input mistake\n", + __func__, __LINE__); + goto PARSE_OVER; + + } g_queryInfo.superQueryInfo.threadCnt = threads->valueint; } else if (!threads) { g_queryInfo.superQueryInfo.threadCnt = 1; @@ -4234,10 +4297,15 @@ static bool getMetaFromQueryJsonFile(cJSON* root) { g_queryInfo.superQueryInfo.mode = SYNC_QUERY_MODE; } - cJSON* subinterval = cJSON_GetObjectItem(superQuery, "interval"); - if (subinterval && subinterval->type == cJSON_Number) { - g_queryInfo.superQueryInfo.subscribeInterval = subinterval->valueint; - } else if (!subinterval) { + cJSON* superInterval = cJSON_GetObjectItem(superQuery, "interval"); + if (superInterval && superInterval->type == cJSON_Number) { + if (superInterval->valueint < 0) { + errorPrint("%s() LN%d, failed to read json, interval input mistake\n", + __func__, __LINE__); + goto PARSE_OVER; + } + g_queryInfo.superQueryInfo.subscribeInterval = superInterval->valueint; + } else if (!superInterval) { //printf("failed to read json, subscribe interval no found\n"); //goto PARSE_OVER; g_queryInfo.superQueryInfo.subscribeInterval = 10000; @@ -4457,11 +4525,11 @@ static int64_t generateRowData(char* recBuf, int64_t timestamp, SSuperTable* stb char *pstr = recBuf; int64_t maxLen = MAX_DATA_SIZE; - dataLen += snprintf(pstr + dataLen, maxLen - dataLen, "(%" PRId64 ", ", timestamp); + dataLen += snprintf(pstr + dataLen, maxLen - dataLen, "(%" PRId64 ",", timestamp); for (int i = 0; i < stbInfo->columnCount; i++) { - if ((0 == strncasecmp(stbInfo->columns[i].dataType, "binary", 6)) - || (0 == strncasecmp(stbInfo->columns[i].dataType, "nchar", 5))) { + if ((0 == strncasecmp(stbInfo->columns[i].dataType, "BINARY", strlen("BINARY"))) + || (0 == strncasecmp(stbInfo->columns[i].dataType, "NCHAR", strlen("NCHAR")))) { if (stbInfo->columns[i].dataLen > TSDB_MAX_BINARY_LEN) { errorPrint( "binary or nchar length overflow, max size:%u\n", (uint32_t)TSDB_MAX_BINARY_LEN); @@ -4474,47 +4542,47 @@ static int64_t generateRowData(char* recBuf, int64_t timestamp, SSuperTable* stb return -1; } rand_string(buf, stbInfo->columns[i].dataLen); - dataLen += snprintf(pstr + dataLen, maxLen - dataLen, "\'%s\', ", buf); + dataLen += snprintf(pstr + dataLen, maxLen - dataLen, "\'%s\',", buf); tmfree(buf); } else if (0 == strncasecmp(stbInfo->columns[i].dataType, - "int", 3)) { + "INT", 3)) { dataLen += snprintf(pstr + dataLen, maxLen - dataLen, - "%d, ", rand_int()); + "%d,", rand_int()); } else if (0 == strncasecmp(stbInfo->columns[i].dataType, - "bigint", 6)) { + "BIGINT", 6)) { dataLen += snprintf(pstr + dataLen, maxLen - dataLen, - "%"PRId64", ", rand_bigint()); + "%"PRId64",", rand_bigint()); } else if (0 == strncasecmp(stbInfo->columns[i].dataType, - "float", 5)) { + "FLOAT", 5)) { dataLen += snprintf(pstr + dataLen, maxLen - dataLen, - "%f, ", rand_float()); + "%f,", rand_float()); } else if (0 == strncasecmp(stbInfo->columns[i].dataType, - "double", 6)) { + "DOUBLE", 6)) { dataLen += snprintf(pstr + dataLen, maxLen - dataLen, - "%f, ", rand_double()); + "%f,", rand_double()); } else if (0 == strncasecmp(stbInfo->columns[i].dataType, - "smallint", 8)) { + "SMALLINT", 8)) { dataLen += snprintf(pstr + dataLen, maxLen - dataLen, - "%d, ", rand_smallint()); + "%d,", rand_smallint()); } else if (0 == strncasecmp(stbInfo->columns[i].dataType, - "tinyint", strlen("tinyint"))) { + "TINYINT", strlen("TINYINT"))) { dataLen += snprintf(pstr + dataLen, maxLen - dataLen, - "%d, ", rand_tinyint()); + "%d,", rand_tinyint()); } else if (0 == strncasecmp(stbInfo->columns[i].dataType, - "bool", strlen("bool"))) { + "BOOL", strlen("BOOL"))) { dataLen += snprintf(pstr + dataLen, maxLen - dataLen, - "%d, ", rand_bool()); + "%d,", rand_bool()); } else if (0 == strncasecmp(stbInfo->columns[i].dataType, - "timestamp", strlen("timestamp"))) { + "TIMESTAMP", strlen("TIMESTAMP"))) { dataLen += snprintf(pstr + dataLen, maxLen - dataLen, - "%"PRId64", ", rand_bigint()); + "%"PRId64",", rand_bigint()); } else { errorPrint( "No support data type: %s\n", stbInfo->columns[i].dataType); return -1; } } - dataLen -= 2; + dataLen -= 1; dataLen += snprintf(pstr + dataLen, maxLen - dataLen, ")"); verbosePrint("%s() LN%d, recBuf:\n\t%s\n", __func__, __LINE__, recBuf); @@ -4541,31 +4609,31 @@ static int64_t generateData(char *recBuf, char **data_type, } for (int i = 0; i < c; i++) { - if (strcasecmp(data_type[i % c], "tinyint") == 0) { - pstr += sprintf(pstr, ", %d", rand_tinyint() ); - } else if (strcasecmp(data_type[i % c], "smallint") == 0) { - pstr += sprintf(pstr, ", %d", rand_smallint()); - } else if (strcasecmp(data_type[i % c], "int") == 0) { - pstr += sprintf(pstr, ", %d", rand_int()); - } else if (strcasecmp(data_type[i % c], "bigint") == 0) { - pstr += sprintf(pstr, ", %" PRId64, rand_bigint()); - } else if (strcasecmp(data_type[i % c], "float") == 0) { - pstr += sprintf(pstr, ", %10.4f", rand_float()); - } else if (strcasecmp(data_type[i % c], "double") == 0) { + if (strcasecmp(data_type[i % c], "TINYINT") == 0) { + pstr += sprintf(pstr, ",%d", rand_tinyint() ); + } else if (strcasecmp(data_type[i % c], "SMALLINT") == 0) { + pstr += sprintf(pstr, ",%d", rand_smallint()); + } else if (strcasecmp(data_type[i % c], "INT") == 0) { + pstr += sprintf(pstr, ",%d", rand_int()); + } else if (strcasecmp(data_type[i % c], "BIGINT") == 0) { + pstr += sprintf(pstr, ",%" PRId64, rand_bigint()); + } else if (strcasecmp(data_type[i % c], "FLOAT") == 0) { + pstr += sprintf(pstr, ",%10.4f", rand_float()); + } else if (strcasecmp(data_type[i % c], "DOUBLE") == 0) { double t = rand_double(); - pstr += sprintf(pstr, ", %20.8f", t); - } else if (strcasecmp(data_type[i % c], "bool") == 0) { + pstr += sprintf(pstr, ",%20.8f", t); + } else if (strcasecmp(data_type[i % c], "BOOL") == 0) { bool b = taosRandom() & 1; - pstr += sprintf(pstr, ", %s", b ? "true" : "false"); - } else if (strcasecmp(data_type[i % c], "binary") == 0) { + pstr += sprintf(pstr, ",%s", b ? "true" : "false"); + } else if (strcasecmp(data_type[i % c], "BINARY") == 0) { char *s = malloc(lenOfBinary); rand_string(s, lenOfBinary); - pstr += sprintf(pstr, ", \"%s\"", s); + pstr += sprintf(pstr, ",\"%s\"", s); free(s); - } else if (strcasecmp(data_type[i % c], "nchar") == 0) { + } else if (strcasecmp(data_type[i % c], "NCHAR") == 0) { char *s = malloc(lenOfBinary); rand_string(s, lenOfBinary); - pstr += sprintf(pstr, ", \"%s\"", s); + pstr += sprintf(pstr, ",\"%s\"", s); free(s); } @@ -4588,7 +4656,7 @@ static int prepareSampleDataForSTable(SSuperTable *superTblInfo) { sampleDataBuf = calloc( superTblInfo->lenOfOneRow * MAX_SAMPLES_ONCE_FROM_FILE, 1); if (sampleDataBuf == NULL) { - errorPrint("%s() LN%d, Failed to calloc %"PRId64" Bytes, reason:%s\n", + errorPrint("%s() LN%d, Failed to calloc %"PRIu64" Bytes, reason:%s\n", __func__, __LINE__, superTblInfo->lenOfOneRow * MAX_SAMPLES_ONCE_FROM_FILE, strerror(errno)); @@ -4609,7 +4677,7 @@ static int prepareSampleDataForSTable(SSuperTable *superTblInfo) { return 0; } -static int64_t execInsert(threadInfo *pThreadInfo, char *buffer, int k) +static int64_t execInsert(threadInfo *pThreadInfo, char *buffer, uint64_t k) { int affectedRows; SSuperTable* superTblInfo = pThreadInfo->superTblInfo; @@ -4619,14 +4687,18 @@ static int64_t execInsert(threadInfo *pThreadInfo, char *buffer, int k) if (superTblInfo) { if (0 == strncasecmp(superTblInfo->insertMode, "taosc", strlen("taosc"))) { affectedRows = queryDbExec(pThreadInfo->taos, buffer, INSERT_TYPE, false); - } else { - if (0 != postProceSql(g_Dbs.host, g_Dbs.port, buffer)) { + } else if (0 == strncasecmp(superTblInfo->insertMode, "rest", strlen("rest"))) { + if (0 != postProceSql(g_Dbs.host, &g_Dbs.serv_addr, g_Dbs.port, buffer)) { affectedRows = -1; printf("========restful return fail, threadID[%d]\n", pThreadInfo->threadID); } else { affectedRows = k; } + } else { + errorPrint("%s() LN%d: unknown insert mode: %s\n", + __func__, __LINE__, superTblInfo->insertMode); + affectedRows = 0; } } else { affectedRows = queryDbExec(pThreadInfo->taos, buffer, INSERT_TYPE, false); @@ -4635,18 +4707,17 @@ static int64_t execInsert(threadInfo *pThreadInfo, char *buffer, int k) return affectedRows; } -static void getTableName(char *pTblName, threadInfo* pThreadInfo, int64_t tableSeq) +static void getTableName(char *pTblName, threadInfo* pThreadInfo, uint64_t tableSeq) { SSuperTable* superTblInfo = pThreadInfo->superTblInfo; if (superTblInfo) { - if ((superTblInfo->childTblOffset >= 0) - && (superTblInfo->childTblLimit > 0)) { + if (superTblInfo->childTblLimit > 0) { snprintf(pTblName, TSDB_TABLE_NAME_LEN, "%s", superTblInfo->childTblName + (tableSeq - superTblInfo->childTblOffset) * TSDB_TABLE_NAME_LEN); } else { - verbosePrint("[%d] %s() LN%d: from=%"PRId64" count=%"PRId64" seq=%"PRId64"\n", + verbosePrint("[%d] %s() LN%d: from=%"PRIu64" count=%"PRIu64" seq=%"PRIu64"\n", pThreadInfo->threadID, __func__, __LINE__, pThreadInfo->start_table_from, pThreadInfo->ntables, tableSeq); @@ -4654,31 +4725,31 @@ static void getTableName(char *pTblName, threadInfo* pThreadInfo, int64_t tableS superTblInfo->childTblName + tableSeq * TSDB_TABLE_NAME_LEN); } } else { - snprintf(pTblName, TSDB_TABLE_NAME_LEN, "%s%"PRId64"", + snprintf(pTblName, TSDB_TABLE_NAME_LEN, "%s%"PRIu64"", g_args.tb_prefix, tableSeq); } } static int64_t generateDataTail( SSuperTable* superTblInfo, - int64_t batch, char* buffer, int64_t remainderBufLen, int64_t insertRows, + uint64_t batch, char* buffer, int64_t remainderBufLen, int64_t insertRows, int64_t startFrom, int64_t startTime, int64_t *pSamplePos, int64_t *dataLen) { - int64_t len = 0; - int ncols_per_record = 1; // count first col ts + uint64_t len = 0; + uint32_t ncols_per_record = 1; // count first col ts char *pstr = buffer; if (superTblInfo == NULL) { - int datatypeSeq = 0; + uint32_t datatypeSeq = 0; while(g_args.datatype[datatypeSeq]) { datatypeSeq ++; ncols_per_record ++; } } - verbosePrint("%s() LN%d batch=%"PRId64"\n", __func__, __LINE__, batch); + verbosePrint("%s() LN%d batch=%"PRIu64"\n", __func__, __LINE__, batch); - int64_t k = 0; + uint64_t k = 0; for (k = 0; k < batch;) { char data[MAX_DATA_SIZE]; memset(data, 0, MAX_DATA_SIZE); @@ -4753,7 +4824,7 @@ static int64_t generateDataTail( remainderBufLen -= retLen; } - verbosePrint("%s() LN%d len=%"PRId64" k=%"PRId64" \nbuffer=%s\n", + verbosePrint("%s() LN%d len=%"PRIu64" k=%"PRIu64" \nbuffer=%s\n", __func__, __LINE__, len, k, buffer); startFrom ++; @@ -4835,12 +4906,12 @@ static int generateSQLHead(char *tableName, int32_t tableSeq, } static int64_t generateInterlaceDataBuffer( - char *tableName, int64_t batchPerTbl, int64_t i, int64_t batchPerTblTimes, - int64_t tableSeq, + char *tableName, uint64_t batchPerTbl, uint64_t i, uint64_t batchPerTblTimes, + uint64_t tableSeq, threadInfo *pThreadInfo, char *buffer, - int64_t insertRows, + uint64_t insertRows, int64_t startTime, - int64_t *pRemainderBufLen) + uint64_t *pRemainderBufLen) { assert(buffer); char *pstr = buffer; @@ -4853,7 +4924,7 @@ static int64_t generateInterlaceDataBuffer( return 0; } // generate data buffer - verbosePrint("[%d] %s() LN%d i=%"PRId64" buffer:\n%s\n", + verbosePrint("[%d] %s() LN%d i=%"PRIu64" buffer:\n%s\n", pThreadInfo->threadID, __func__, __LINE__, i, buffer); pstr += headLen; @@ -4861,7 +4932,7 @@ static int64_t generateInterlaceDataBuffer( int64_t dataLen = 0; - verbosePrint("[%d] %s() LN%d i=%"PRId64" batchPerTblTimes=%"PRId64" batchPerTbl = %"PRId64"\n", + verbosePrint("[%d] %s() LN%d i=%"PRIu64" batchPerTblTimes=%"PRIu64" batchPerTbl = %"PRIu64"\n", pThreadInfo->threadID, __func__, __LINE__, i, batchPerTblTimes, batchPerTbl); @@ -4883,7 +4954,7 @@ static int64_t generateInterlaceDataBuffer( pstr += dataLen; *pRemainderBufLen -= dataLen; } else { - debugPrint("%s() LN%d, generated data tail: %"PRId64", not equal batch per table: %"PRId64"\n", + debugPrint("%s() LN%d, generated data tail: %"PRIu64", not equal batch per table: %"PRIu64"\n", __func__, __LINE__, k, batchPerTbl); pstr -= headLen; pstr[0] = '\0'; @@ -4893,7 +4964,7 @@ static int64_t generateInterlaceDataBuffer( return k; } -static int generateProgressiveDataBuffer( +static int64_t generateProgressiveDataBuffer( char *tableName, int64_t tableSeq, threadInfo *pThreadInfo, char *buffer, @@ -4938,12 +5009,21 @@ static int generateProgressiveDataBuffer( return k; } +static void printStatPerThread(threadInfo *pThreadInfo) +{ + fprintf(stderr, "====thread[%d] completed total inserted rows: %"PRIu64 ", total affected rows: %"PRIu64". %.2f records/second====\n", + pThreadInfo->threadID, + pThreadInfo->totalInsertRows, + pThreadInfo->totalAffectedRows, + (double)(pThreadInfo->totalAffectedRows / (pThreadInfo->totalDelay/1000.0))); +} + static void* syncWriteInterlace(threadInfo *pThreadInfo) { debugPrint("[%d] %s() LN%d: ### interlace write\n", pThreadInfo->threadID, __func__, __LINE__); - int64_t insertRows; - int64_t interlaceRows; + uint64_t insertRows; + uint64_t interlaceRows; SSuperTable* superTblInfo = pThreadInfo->superTblInfo; @@ -4978,10 +5058,10 @@ static void* syncWriteInterlace(threadInfo *pThreadInfo) { // TODO: prompt tbl count multple interlace rows and batch // - int64_t maxSqlLen = superTblInfo?superTblInfo->maxSqlLen:g_args.max_sql_len; + uint64_t maxSqlLen = superTblInfo?superTblInfo->maxSqlLen:g_args.max_sql_len; char* buffer = calloc(maxSqlLen, 1); if (NULL == buffer) { - errorPrint( "%s() LN%d, Failed to alloc %"PRId64" Bytes, reason:%s\n", + errorPrint( "%s() LN%d, Failed to alloc %"PRIu64" Bytes, reason:%s\n", __func__, __LINE__, maxSqlLen, strerror(errno)); return NULL; } @@ -4993,18 +5073,18 @@ static void* syncWriteInterlace(threadInfo *pThreadInfo) { int64_t nTimeStampStep = superTblInfo?superTblInfo->timeStampStep:DEFAULT_TIMESTAMP_STEP; - int insert_interval = + uint64_t insert_interval = superTblInfo?superTblInfo->insertInterval:g_args.insert_interval; - int64_t st = 0; - int64_t et = 0xffffffff; + uint64_t st = 0; + uint64_t et = UINT64_MAX; - int64_t lastPrintTime = taosGetTimestampMs(); - int64_t startTs = taosGetTimestampMs(); - int64_t endTs; + uint64_t lastPrintTime = taosGetTimestampMs(); + uint64_t startTs = taosGetTimestampMs(); + uint64_t endTs; - int64_t tableSeq = pThreadInfo->start_table_from; + uint64_t tableSeq = pThreadInfo->start_table_from; - debugPrint("[%d] %s() LN%d: start_table_from=%"PRId64" ntables=%"PRId64" insertRows=%"PRId64"\n", + debugPrint("[%d] %s() LN%d: start_table_from=%"PRIu64" ntables=%"PRIu64" insertRows=%"PRIu64"\n", pThreadInfo->threadID, __func__, __LINE__, pThreadInfo->start_table_from, pThreadInfo->ntables, insertRows); @@ -5012,9 +5092,9 @@ static void* syncWriteInterlace(threadInfo *pThreadInfo) { assert(pThreadInfo->ntables > 0); - int64_t batchPerTbl = interlaceRows; + uint64_t batchPerTbl = interlaceRows; + uint64_t batchPerTblTimes; - int64_t batchPerTblTimes; if ((interlaceRows > 0) && (pThreadInfo->ntables > 1)) { batchPerTblTimes = g_args.num_of_RPR / interlaceRows; @@ -5022,9 +5102,9 @@ static void* syncWriteInterlace(threadInfo *pThreadInfo) { batchPerTblTimes = 1; } - int64_t generatedRecPerTbl = 0; + uint64_t generatedRecPerTbl = 0; bool flagSleep = true; - int64_t sleepTimeTotal = 0; + uint64_t sleepTimeTotal = 0; char *strInsertInto = "insert into "; int nInsertBufLen = strlen(strInsertInto); @@ -5036,7 +5116,7 @@ static void* syncWriteInterlace(threadInfo *pThreadInfo) { } // generate data memset(buffer, 0, maxSqlLen); - int64_t remainderBufLen = maxSqlLen; + uint64_t remainderBufLen = maxSqlLen; char *pstr = buffer; @@ -5044,9 +5124,9 @@ static void* syncWriteInterlace(threadInfo *pThreadInfo) { pstr += len; remainderBufLen -= len; - int64_t recOfBatch = 0; + uint64_t recOfBatch = 0; - for (int64_t i = 0; i < batchPerTblTimes; i ++) { + for (uint64_t i = 0; i < batchPerTblTimes; i ++) { getTableName(tableName, pThreadInfo, tableSeq); if (0 == strlen(tableName)) { errorPrint("[%d] %s() LN%d, getTableName return null\n", @@ -5055,7 +5135,7 @@ static void* syncWriteInterlace(threadInfo *pThreadInfo) { return NULL; } - int64_t oldRemainderLen = remainderBufLen; + uint64_t oldRemainderLen = remainderBufLen; int64_t generated = generateInterlaceDataBuffer( tableName, batchPerTbl, i, batchPerTblTimes, tableSeq, @@ -5064,10 +5144,12 @@ static void* syncWriteInterlace(threadInfo *pThreadInfo) { startTime, &remainderBufLen); + debugPrint("[%d] %s() LN%d, generated records is %"PRId64"\n", + pThreadInfo->threadID, __func__, __LINE__, generated); if (generated < 0) { - debugPrint("[%d] %s() LN%d, generated data is %"PRId64"\n", + errorPrint("[%d] %s() LN%d, generated records is %"PRId64"\n", pThreadInfo->threadID, __func__, __LINE__, generated); - goto free_and_statistics_interlace; + goto free_of_interlace; } else if (generated == 0) { break; } @@ -5111,7 +5193,7 @@ static void* syncWriteInterlace(threadInfo *pThreadInfo) { break; } - verbosePrint("[%d] %s() LN%d recOfBatch=%"PRId64" totalInsertRows=%"PRId64"\n", + verbosePrint("[%d] %s() LN%d recOfBatch=%"PRIu64" totalInsertRows=%"PRIu64"\n", pThreadInfo->threadID, __func__, __LINE__, recOfBatch, pThreadInfo->totalInsertRows); verbosePrint("[%d] %s() LN%d, buffer=%s\n", @@ -5119,33 +5201,40 @@ static void* syncWriteInterlace(threadInfo *pThreadInfo) { startTs = taosGetTimestampMs(); + if (recOfBatch == 0) { + errorPrint("[%d] %s() LN%d try inserting records of batch is %"PRIu64"\n", + pThreadInfo->threadID, __func__, __LINE__, + recOfBatch); + errorPrint("%s\n", "\tPlease check if the batch or the buffer length is proper value!\n"); + goto free_of_interlace; + } int64_t affectedRows = execInsert(pThreadInfo, buffer, recOfBatch); endTs = taosGetTimestampMs(); - int64_t delay = endTs - startTs; - performancePrint("%s() LN%d, insert execution time is %"PRId64"ms\n", + uint64_t delay = endTs - startTs; + performancePrint("%s() LN%d, insert execution time is %"PRIu64"ms\n", __func__, __LINE__, delay); + verbosePrint("[%d] %s() LN%d affectedRows=%"PRId64"\n", + pThreadInfo->threadID, + __func__, __LINE__, affectedRows); if (delay > pThreadInfo->maxDelay) pThreadInfo->maxDelay = delay; if (delay < pThreadInfo->minDelay) pThreadInfo->minDelay = delay; pThreadInfo->cntDelay++; pThreadInfo->totalDelay += delay; - verbosePrint("[%d] %s() LN%d affectedRows=%"PRId64"\n", - pThreadInfo->threadID, - __func__, __LINE__, affectedRows); - if ((affectedRows < 0) || (recOfBatch != affectedRows)) { - errorPrint("[%d] %s() LN%d execInsert insert %"PRId64", affected rows: %"PRId64"\n%s\n", + if (recOfBatch != affectedRows) { + errorPrint("[%d] %s() LN%d execInsert insert %"PRIu64", affected rows: %"PRId64"\n%s\n", pThreadInfo->threadID, __func__, __LINE__, recOfBatch, affectedRows, buffer); - goto free_and_statistics_interlace; + goto free_of_interlace; } pThreadInfo->totalAffectedRows += affectedRows; int64_t currentPrintTime = taosGetTimestampMs(); if (currentPrintTime - lastPrintTime > 30*1000) { - printf("thread[%d] has currently inserted rows: %"PRId64 ", affected rows: %"PRId64 "\n", + printf("thread[%d] has currently inserted rows: %"PRIu64 ", affected rows: %"PRIu64 "\n", pThreadInfo->threadID, pThreadInfo->totalInsertRows, pThreadInfo->totalAffectedRows); @@ -5165,13 +5254,9 @@ static void* syncWriteInterlace(threadInfo *pThreadInfo) { } } -free_and_statistics_interlace: +free_of_interlace: tmfree(buffer); - - printf("====thread[%d] completed total inserted rows: %"PRId64 ", total affected rows: %"PRId64 "====\n", - pThreadInfo->threadID, - pThreadInfo->totalInsertRows, - pThreadInfo->totalAffectedRows); + printStatPerThread(pThreadInfo); return NULL; } @@ -5187,19 +5272,19 @@ static void* syncWriteProgressive(threadInfo *pThreadInfo) { debugPrint("%s() LN%d: ### progressive write\n", __func__, __LINE__); SSuperTable* superTblInfo = pThreadInfo->superTblInfo; - int maxSqlLen = superTblInfo?superTblInfo->maxSqlLen:g_args.max_sql_len; + uint64_t maxSqlLen = superTblInfo?superTblInfo->maxSqlLen:g_args.max_sql_len; char* buffer = calloc(maxSqlLen, 1); if (NULL == buffer) { - errorPrint( "Failed to alloc %d Bytes, reason:%s\n", + errorPrint( "Failed to alloc %"PRIu64" Bytes, reason:%s\n", maxSqlLen, strerror(errno)); return NULL; } - int64_t lastPrintTime = taosGetTimestampMs(); - int64_t startTs = taosGetTimestampMs(); - int64_t endTs; + uint64_t lastPrintTime = taosGetTimestampMs(); + uint64_t startTs = taosGetTimestampMs(); + uint64_t endTs; int64_t timeStampStep = superTblInfo?superTblInfo->timeStampStep:DEFAULT_TIMESTAMP_STEP; @@ -5214,15 +5299,15 @@ static void* syncWriteProgressive(threadInfo *pThreadInfo) { pThreadInfo->samplePos = 0; - for (int64_t tableSeq = + for (uint64_t tableSeq = pThreadInfo->start_table_from; tableSeq <= pThreadInfo->end_table_to; tableSeq ++) { int64_t start_time = pThreadInfo->start_time; - int64_t insertRows = (superTblInfo)?superTblInfo->insertRows:g_args.num_of_DPT; + uint64_t insertRows = (superTblInfo)?superTblInfo->insertRows:g_args.num_of_DPT; verbosePrint("%s() LN%d insertRows=%"PRId64"\n", __func__, __LINE__, insertRows); - for (int64_t i = 0; i < insertRows;) { + for (uint64_t i = 0; i < insertRows;) { /* if (insert_interval) { st = taosGetTimestampMs(); @@ -5244,7 +5329,7 @@ static void* syncWriteProgressive(threadInfo *pThreadInfo) { pstr += len; remainderBufLen -= len; - int generated = generateProgressiveDataBuffer( + int64_t generated = generateProgressiveDataBuffer( tableName, tableSeq, pThreadInfo, pstr, insertRows, i, start_time, &(pThreadInfo->samplePos), @@ -5252,7 +5337,7 @@ static void* syncWriteProgressive(threadInfo *pThreadInfo) { if (generated > 0) i += generated; else - goto free_and_statistics_2; + goto free_of_progressive; start_time += generated * timeStampStep; pThreadInfo->totalInsertRows += generated; @@ -5262,17 +5347,23 @@ static void* syncWriteProgressive(threadInfo *pThreadInfo) { int64_t affectedRows = execInsert(pThreadInfo, buffer, generated); endTs = taosGetTimestampMs(); - int64_t delay = endTs - startTs; + uint64_t delay = endTs - startTs; performancePrint("%s() LN%d, insert execution time is %"PRId64"ms\n", __func__, __LINE__, delay); + verbosePrint("[%d] %s() LN%d affectedRows=%"PRId64"\n", + pThreadInfo->threadID, + __func__, __LINE__, affectedRows); if (delay > pThreadInfo->maxDelay) pThreadInfo->maxDelay = delay; if (delay < pThreadInfo->minDelay) pThreadInfo->minDelay = delay; pThreadInfo->cntDelay++; pThreadInfo->totalDelay += delay; - if (affectedRows < 0) - goto free_and_statistics_2; + if (affectedRows < 0) { + errorPrint("%s() LN%d, affected rows: %"PRId64"\n", + __func__, __LINE__, affectedRows); + goto free_of_progressive; + } pThreadInfo->totalAffectedRows += affectedRows; @@ -5311,13 +5402,9 @@ static void* syncWriteProgressive(threadInfo *pThreadInfo) { } } // tableSeq -free_and_statistics_2: +free_of_progressive: tmfree(buffer); - - printf("====thread[%d] completed total inserted rows: %"PRId64 ", total affected rows: %"PRId64 "====\n", - pThreadInfo->threadID, - pThreadInfo->totalInsertRows, - pThreadInfo->totalAffectedRows); + printStatPerThread(pThreadInfo); return NULL; } @@ -5346,6 +5433,7 @@ static void* syncWrite(void *sarg) { // progressive mode return syncWriteProgressive(pThreadInfo); } + } static void callBack(void *param, TAOS_RES *res, int code) { @@ -5425,6 +5513,32 @@ static void *asyncWrite(void *sarg) { return NULL; } +static int convertHostToServAddr(char *host, uint16_t port, struct sockaddr_in *serv_addr) +{ + uint16_t rest_port = port + TSDB_PORT_HTTP; + struct hostent *server = gethostbyname(host); + if ((server == NULL) || (server->h_addr == NULL)) { + errorPrint("%s", "ERROR, no such host"); + return -1; + } + + debugPrint("h_name: %s\nh_addr=%p\nh_addretype: %s\nh_length: %d\n", + server->h_name, + server->h_addr, + (server->h_addrtype == AF_INET)?"ipv4":"ipv6", + server->h_length); + + memset(serv_addr, 0, sizeof(struct sockaddr_in)); + serv_addr->sin_family = AF_INET; + serv_addr->sin_port = htons(rest_port); +#ifdef WINDOWS + serv_addr->sin_addr.s_addr = inet_addr(host); +#else + memcpy(&(serv_addr->sin_addr.s_addr), server->h_addr, server->h_length); +#endif + return 0; +} + static void startMultiThreadInsertData(int threads, char* db_name, char* precision,SSuperTable* superTblInfo) { @@ -5510,15 +5624,15 @@ static void startMultiThreadInsertData(int threads, char* db_name, int startFrom; if (superTblInfo) { - int limit, offset; + int64_t limit; + uint64_t offset; if ((NULL != g_args.sqlFile) && (superTblInfo->childTblExists == TBL_NO_EXISTS) && ((superTblInfo->childTblOffset != 0) || (superTblInfo->childTblLimit >= 0))) { printf("WARNING: offset and limit will not be used since the child tables not exists!\n"); } - if ((superTblInfo->childTblExists == TBL_ALREADY_EXISTS) - && (superTblInfo->childTblOffset >= 0)) { + if (superTblInfo->childTblExists == TBL_ALREADY_EXISTS) { if ((superTblInfo->childTblLimit < 0) || ((superTblInfo->childTblOffset + superTblInfo->childTblLimit) > (superTblInfo->childTblCount))) { @@ -5563,7 +5677,7 @@ static void startMultiThreadInsertData(int threads, char* db_name, exit(-1); } - int64_t childTblCount; + uint64_t childTblCount; getChildNameOfSuperTableWithLimitAndOffset( taos, db_name, superTblInfo->sTblName, @@ -5577,17 +5691,23 @@ static void startMultiThreadInsertData(int threads, char* db_name, taos_close(taos); - int a = ntables / threads; + uint64_t a = ntables / threads; if (a < 1) { threads = ntables; a = 1; } - int b = 0; + uint64_t b = 0; if (threads != 0) { b = ntables % threads; } + if ((superTblInfo) + && (0 == strncasecmp(superTblInfo->insertMode, "rest", strlen("rest")))) { + if (convertHostToServAddr(g_Dbs.host, g_Dbs.port, &(g_Dbs.serv_addr)) != 0) + exit(-1); + } + for (int i = 0; i < threads; i++) { threadInfo *t_info = infos + i; t_info->threadID = i; @@ -5596,7 +5716,7 @@ static void startMultiThreadInsertData(int threads, char* db_name, t_info->superTblInfo = superTblInfo; t_info->start_time = start_time; - t_info->minDelay = INT16_MAX; + t_info->minDelay = UINT64_MAX; if ((NULL == superTblInfo) || (0 == strncasecmp(superTblInfo->insertMode, "taosc", 5))) { @@ -5639,10 +5759,10 @@ static void startMultiThreadInsertData(int threads, char* db_name, pthread_join(pids[i], NULL); } - int64_t totalDelay = 0; - int64_t maxDelay = 0; - int64_t minDelay = INT16_MAX; - int64_t cntDelay = 1; + uint64_t totalDelay = 0; + uint64_t maxDelay = 0; + uint64_t minDelay = UINT64_MAX; + uint64_t cntDelay = 1; double avgDelay = 0; for (int i = 0; i < threads; i++) { @@ -5651,7 +5771,7 @@ static void startMultiThreadInsertData(int threads, char* db_name, tsem_destroy(&(t_info->lock_sem)); taos_close(t_info->taos); - debugPrint("%s() LN%d, [%d] totalInsert=%"PRId64" totalAffected=%"PRId64"\n", + debugPrint("%s() LN%d, [%d] totalInsert=%"PRIu64" totalAffected=%"PRIu64"\n", __func__, __LINE__, t_info->threadID, t_info->totalInsertRows, t_info->totalAffectedRows); @@ -5677,35 +5797,42 @@ static void startMultiThreadInsertData(int threads, char* db_name, int64_t t = end - start; if (superTblInfo) { - printf("Spent %.2f seconds to insert rows: %"PRId64", affected rows: %"PRId64" with %d thread(s) into %s.%s. %2.f records/second\n\n", + fprintf(stderr, "Spent %.2f seconds to insert rows: %"PRIu64", affected rows: %"PRIu64" with %d thread(s) into %s.%s. %.2f records/second\n\n", t / 1000.0, superTblInfo->totalInsertRows, superTblInfo->totalAffectedRows, threads, db_name, superTblInfo->sTblName, (double)superTblInfo->totalInsertRows / (t / 1000.0)); - fprintf(g_fpOfInsertResult, - "Spent %.2f seconds to insert rows: %"PRId64", affected rows: %"PRId64" with %d thread(s) into %s.%s. %2.f records/second\n\n", + + if (g_fpOfInsertResult) { + fprintf(g_fpOfInsertResult, + "Spent %.2f seconds to insert rows: %"PRIu64", affected rows: %"PRIu64" with %d thread(s) into %s.%s. %.2f records/second\n\n", t / 1000.0, superTblInfo->totalInsertRows, superTblInfo->totalAffectedRows, threads, db_name, superTblInfo->sTblName, (double)superTblInfo->totalInsertRows / (t / 1000.0)); + } } else { - printf("Spent %.2f seconds to insert rows: %"PRId64", affected rows: %"PRId64" with %d thread(s) into %s %2.f records/second\n\n", + fprintf(stderr, "Spent %.2f seconds to insert rows: %"PRIu64", affected rows: %"PRIu64" with %d thread(s) into %s %.2f records/second\n\n", t / 1000.0, g_args.totalInsertRows, g_args.totalAffectedRows, threads, db_name, (double)g_args.totalInsertRows / (t / 1000.0)); - fprintf(g_fpOfInsertResult, - "Spent %.2f seconds to insert rows: %"PRId64", affected rows: %"PRId64" with %d thread(s) into %s %2.f records/second\n\n", + if (g_fpOfInsertResult) { + fprintf(g_fpOfInsertResult, + "Spent %.2f seconds to insert rows: %"PRIu64", affected rows: %"PRIu64" with %d thread(s) into %s %.2f records/second\n\n", t * 1000.0, g_args.totalInsertRows, g_args.totalAffectedRows, threads, db_name, (double)g_args.totalInsertRows / (t / 1000.0)); + } } - printf("insert delay, avg: %10.2fms, max: %"PRId64"ms, min: %"PRId64"ms\n\n", + fprintf(stderr, "insert delay, avg: %10.2fms, max: %"PRIu64"ms, min: %"PRIu64"ms\n\n", avgDelay, maxDelay, minDelay); - fprintf(g_fpOfInsertResult, "insert delay, avg:%10.2fms, max: %"PRId64"ms, min: %"PRId64"ms\n\n", + if (g_fpOfInsertResult) { + fprintf(g_fpOfInsertResult, "insert delay, avg:%10.2fms, max: %"PRIu64"ms, min: %"PRIu64"ms\n\n", avgDelay, maxDelay, minDelay); + } //taos_close(taos); @@ -5745,11 +5872,11 @@ static void *readTable(void *sarg) { printf("%d records:\n", totalData); fprintf(fp, "| QFunctions | QRecords | QSpeed(R/s) | QLatency(ms) |\n"); - for (int j = 0; j < n; j++) { + for (uint64_t j = 0; j < n; j++) { double totalT = 0; - int count = 0; - for (int i = 0; i < num_of_tables; i++) { - sprintf(command, "select %s from %s%d where ts>= %" PRId64, + uint64_t count = 0; + for (uint64_t i = 0; i < num_of_tables; i++) { + sprintf(command, "select %s from %s%"PRIu64" where ts>= %" PRIu64, aggreFunc[j], tb_prefix, i, sTime); double t = taosGetTimestampMs(); @@ -5875,7 +6002,8 @@ static int insertTestProcess() { return -1; } - printfInsertMetaToFile(g_fpOfInsertResult); + if (g_fpOfInsertResult) + printfInsertMetaToFile(g_fpOfInsertResult); if (!g_args.answer_yes) { printf("Press enter key to continue\n\n"); @@ -5886,7 +6014,8 @@ static int insertTestProcess() { // create database and super tables if(createDatabasesAndStables() != 0) { - fclose(g_fpOfInsertResult); + if (g_fpOfInsertResult) + fclose(g_fpOfInsertResult); return -1; } @@ -5902,11 +6031,13 @@ static int insertTestProcess() { end = taosGetTimestampMs(); if (g_totalChildTables > 0) { - printf("Spent %.4f seconds to create %d tables with %d thread(s)\n\n", + fprintf(stderr, "Spent %.4f seconds to create %d tables with %d thread(s)\n\n", (end - start)/1000.0, g_totalChildTables, g_Dbs.threadCountByCreateTbl); - fprintf(g_fpOfInsertResult, + if (g_fpOfInsertResult) { + fprintf(g_fpOfInsertResult, "Spent %.4f seconds to create %d tables with %d thread(s)\n\n", (end - start)/1000.0, g_totalChildTables, g_Dbs.threadCountByCreateTbl); + } } taosMsleep(1000); @@ -5979,14 +6110,14 @@ static void *specifiedTableQuery(void *sarg) { return NULL; } - int64_t st = 0; - int64_t et = 0; + uint64_t st = 0; + uint64_t et = 0; - int queryTimes = g_queryInfo.specifiedQueryInfo.queryTimes; + uint64_t queryTimes = g_queryInfo.specifiedQueryInfo.queryTimes; - int totalQueried = 0; - int64_t lastPrintTime = taosGetTimestampMs(); - int64_t startTs = taosGetTimestampMs(); + uint64_t totalQueried = 0; + uint64_t lastPrintTime = taosGetTimestampMs(); + uint64_t startTs = taosGetTimestampMs(); while(queryTimes --) { if (g_queryInfo.specifiedQueryInfo.queryInterval && (et - st) < @@ -5996,7 +6127,7 @@ static void *specifiedTableQuery(void *sarg) { st = taosGetTimestampMs(); - if (0 == strncasecmp(g_queryInfo.queryMode, "taosc", 5)) { + if (0 == strncasecmp(g_queryInfo.queryMode, "taosc", strlen("taosc"))) { int64_t t1 = taosGetTimestampMs(); char tmpFile[MAX_FILE_NAME_LEN*2] = {0}; if (g_queryInfo.specifiedQueryInfo.result[pThreadInfo->querySeq][0] != 0) { @@ -6009,9 +6140,9 @@ static void *specifiedTableQuery(void *sarg) { int64_t t2 = taosGetTimestampMs(); printf("=[taosc] thread[%"PRId64"] complete one sql, Spent %10.3f s\n", taosGetSelfPthreadId(), (t2 - t1)/1000.0); - } else { + } else if (0 == strncasecmp(g_queryInfo.queryMode, "rest", strlen("rest"))) { int64_t t1 = taosGetTimestampMs(); - int retCode = postProceSql(g_queryInfo.host, + int retCode = postProceSql(g_queryInfo.host, &(g_queryInfo.serv_addr), g_queryInfo.port, g_queryInfo.specifiedQueryInfo.sql[pThreadInfo->querySeq]); if (0 != retCode) { @@ -6022,18 +6153,22 @@ static void *specifiedTableQuery(void *sarg) { printf("=[restful] thread[%"PRId64"] complete one sql, Spent %10.3f s\n", taosGetSelfPthreadId(), (t2 - t1)/1000.0); + } else { + errorPrint("%s() LN%d, unknown query mode: %s\n", + __func__, __LINE__, g_queryInfo.queryMode); + return NULL; } totalQueried ++; g_queryInfo.specifiedQueryInfo.totalQueried ++; et = taosGetTimestampMs(); - int64_t currentPrintTime = taosGetTimestampMs(); - int64_t endTs = taosGetTimestampMs(); + uint64_t currentPrintTime = taosGetTimestampMs(); + uint64_t endTs = taosGetTimestampMs(); if (currentPrintTime - lastPrintTime > 30*1000) { - debugPrint("%s() LN%d, endTs=%"PRId64"ms, startTs=%"PRId64"ms\n", + debugPrint("%s() LN%d, endTs=%"PRIu64"ms, startTs=%"PRIu64"ms\n", __func__, __LINE__, endTs, startTs); - printf("thread[%d] has currently completed queries: %d, QPS: %10.6f\n", + printf("thread[%d] has currently completed queries: %"PRIu64", QPS: %10.6f\n", pThreadInfo->threadID, totalQueried, (double)(totalQueried/((endTs-startTs)/1000.0))); @@ -6085,14 +6220,14 @@ static void *superTableQuery(void *sarg) { } } - int64_t st = 0; - int64_t et = (int64_t)g_queryInfo.superQueryInfo.queryInterval; + uint64_t st = 0; + uint64_t et = (int64_t)g_queryInfo.superQueryInfo.queryInterval; - int queryTimes = g_queryInfo.superQueryInfo.queryTimes; - int totalQueried = 0; - int64_t startTs = taosGetTimestampMs(); + uint64_t queryTimes = g_queryInfo.superQueryInfo.queryTimes; + uint64_t totalQueried = 0; + uint64_t startTs = taosGetTimestampMs(); - int64_t lastPrintTime = taosGetTimestampMs(); + uint64_t lastPrintTime = taosGetTimestampMs(); while(queryTimes --) { if (g_queryInfo.superQueryInfo.queryInterval && (et - st) < (int64_t)g_queryInfo.superQueryInfo.queryInterval) { @@ -6119,7 +6254,7 @@ static void *superTableQuery(void *sarg) { int64_t currentPrintTime = taosGetTimestampMs(); int64_t endTs = taosGetTimestampMs(); if (currentPrintTime - lastPrintTime > 30*1000) { - printf("thread[%d] has currently completed queries: %d, QPS: %10.3f\n", + printf("thread[%d] has currently completed queries: %"PRIu64", QPS: %10.3f\n", pThreadInfo->threadID, totalQueried, (double)(totalQueried/((endTs-startTs)/1000.0))); @@ -6128,7 +6263,7 @@ static void *superTableQuery(void *sarg) { } } et = taosGetTimestampMs(); - printf("####thread[%"PRId64"] complete all sqls to allocate all sub-tables[%"PRId64" - %"PRId64"] once queries duration:%.4fs\n\n", + printf("####thread[%"PRId64"] complete all sqls to allocate all sub-tables[%"PRIu64" - %"PRIu64"] once queries duration:%.4fs\n\n", taosGetSelfPthreadId(), pThreadInfo->start_table_from, pThreadInfo->end_table_to, @@ -6171,13 +6306,19 @@ static int queryTestProcess() { printfQuerySystemInfo(taos); + if (0 == strncasecmp(g_queryInfo.queryMode, "rest", strlen("rest"))) { + if (convertHostToServAddr( + g_queryInfo.host, g_queryInfo.port, &g_queryInfo.serv_addr) != 0) + exit(-1); + } + pthread_t *pids = NULL; threadInfo *infos = NULL; //==== create sub threads for query from specify table int nConcurrent = g_queryInfo.specifiedQueryInfo.concurrent; int nSqlCount = g_queryInfo.specifiedQueryInfo.sqlCount; - int64_t startTs = taosGetTimestampMs(); + uint64_t startTs = taosGetTimestampMs(); if ((nSqlCount > 0) && (nConcurrent > 0)) { @@ -6237,21 +6378,21 @@ static int queryTestProcess() { ERROR_EXIT("memory allocation failed for create threads\n"); } - int ntables = g_queryInfo.superQueryInfo.childTblCount; + uint64_t ntables = g_queryInfo.superQueryInfo.childTblCount; int threads = g_queryInfo.superQueryInfo.threadCnt; - int a = ntables / threads; + uint64_t a = ntables / threads; if (a < 1) { threads = ntables; a = 1; } - int b = 0; + uint64_t b = 0; if (threads != 0) { b = ntables % threads; } - int startFrom = 0; + uint64_t startFrom = 0; for (int i = 0; i < threads; i++) { threadInfo *t_info = infosOfSub + i; t_info->threadID = i; @@ -6288,12 +6429,12 @@ static int queryTestProcess() { tmfree((char*)infosOfSub); // taos_close(taos);// TODO: workaround to use separate taos connection; - int64_t endTs = taosGetTimestampMs(); + uint64_t endTs = taosGetTimestampMs(); - int totalQueried = g_queryInfo.specifiedQueryInfo.totalQueried + + uint64_t totalQueried = g_queryInfo.specifiedQueryInfo.totalQueried + g_queryInfo.superQueryInfo.totalQueried; - printf("==== completed total queries: %d, the QPS of all threads: %10.3f====\n", + fprintf(stderr, "==== completed total queries: %"PRIu64", the QPS of all threads: %10.3f====\n", totalQueried, (double)(totalQueried/((endTs-startTs)/1000.0))); return 0; @@ -6307,13 +6448,14 @@ static void subscribe_callback(TAOS_SUB* tsub, TAOS_RES *res, void* param, int c } getResult(res, (char*)param); - taos_free_result(res); + // tao_unscribe() will free result. } -static TAOS_SUB* subscribeImpl(TAOS *taos, char *sql, char* topic, char* resultFileName) { +static TAOS_SUB* subscribeImpl( + TAOS *taos, char *sql, char* topic, char* resultFileName) { TAOS_SUB* tsub = NULL; - if (g_queryInfo.specifiedQueryInfo.mode) { + if (ASYNC_QUERY_MODE == g_queryInfo.specifiedQueryInfo.mode) { tsub = taos_subscribe(taos, g_queryInfo.specifiedQueryInfo.subscribeRestart, topic, sql, subscribe_callback, (void*)resultFileName, @@ -6337,6 +6479,9 @@ static void *superSubscribe(void *sarg) { char subSqlstr[1024]; TAOS_SUB* tsub[MAX_QUERY_SQL_COUNT] = {0}; + if (g_queryInfo.superQueryInfo.sqlCount == 0) + return NULL; + if (pThreadInfo->taos == NULL) { TAOS * taos = NULL; taos = taos_connect(g_queryInfo.host, @@ -6388,14 +6533,14 @@ static void *superSubscribe(void *sarg) { } } //et = taosGetTimestampMs(); - //printf("========thread[%"PRId64"] complete all sqls to super table once queries duration:%.4fs\n", taosGetSelfPthreadId(), (double)(et - st)/1000.0); + //printf("========thread[%"PRIu64"] complete all sqls to super table once queries duration:%.4fs\n", taosGetSelfPthreadId(), (double)(et - st)/1000.0); } while(0); // start loop to consume result TAOS_RES* res = NULL; while(1) { for (int i = 0; i < g_queryInfo.superQueryInfo.sqlCount; i++) { - if (1 == g_queryInfo.superQueryInfo.mode) { + if (ASYNC_QUERY_MODE == g_queryInfo.superQueryInfo.mode) { continue; } @@ -6425,6 +6570,9 @@ static void *specifiedSubscribe(void *sarg) { threadInfo *pThreadInfo = (threadInfo *)sarg; TAOS_SUB* tsub[MAX_QUERY_SQL_COUNT] = {0}; + if (g_queryInfo.specifiedQueryInfo.sqlCount == 0) + return NULL; + if (pThreadInfo->taos == NULL) { TAOS * taos = NULL; taos = taos_connect(g_queryInfo.host, @@ -6454,7 +6602,7 @@ static void *specifiedSubscribe(void *sarg) { do { //if (g_queryInfo.specifiedQueryInfo.queryInterval && (et - st) < g_queryInfo.specifiedQueryInfo.queryInterval) { // taosMsleep(g_queryInfo.specifiedQueryInfo.queryInterval- (et - st)); // ms - // //printf("========sleep duration:%"PRId64 "========inserted rows:%d, table range:%d - %d\n", (1000 - (et - st)), i, pThreadInfo->start_table_from, pThreadInfo->end_table_to); + // //printf("========sleep duration:%"PRIu64 "========inserted rows:%d, table range:%d - %d\n", (1000 - (et - st)), i, pThreadInfo->start_table_from, pThreadInfo->end_table_to); //} //st = taosGetTimestampMs(); @@ -6462,7 +6610,7 @@ static void *specifiedSubscribe(void *sarg) { for (int i = 0; i < g_queryInfo.specifiedQueryInfo.sqlCount; i++) { sprintf(topic, "taosdemo-subscribe-%d", i); char tmpFile[MAX_FILE_NAME_LEN*2] = {0}; - if (g_queryInfo.superQueryInfo.result[i][0] != 0) { + if (g_queryInfo.specifiedQueryInfo.result[i][0] != 0) { sprintf(tmpFile, "%s-%d", g_queryInfo.specifiedQueryInfo.result[i], pThreadInfo->threadID); } @@ -6474,14 +6622,14 @@ static void *specifiedSubscribe(void *sarg) { } } //et = taosGetTimestampMs(); - //printf("========thread[%"PRId64"] complete all sqls to super table once queries duration:%.4fs\n", taosGetSelfPthreadId(), (double)(et - st)/1000.0); + //printf("========thread[%"PRIu64"] complete all sqls to super table once queries duration:%.4fs\n", taosGetSelfPthreadId(), (double)(et - st)/1000.0); } while(0); // start loop to consume result TAOS_RES* res = NULL; while(1) { for (int i = 0; i < g_queryInfo.specifiedQueryInfo.sqlCount; i++) { - if (SYNC_QUERY_MODE == g_queryInfo.specifiedQueryInfo.mode) { + if (ASYNC_QUERY_MODE == g_queryInfo.specifiedQueryInfo.mode) { continue; } @@ -6544,8 +6692,9 @@ static int subscribeTestProcess() { //==== create sub threads for query from super table if ((g_queryInfo.specifiedQueryInfo.sqlCount <= 0) || (g_queryInfo.specifiedQueryInfo.concurrent <= 0)) { - errorPrint("%s() LN%d, query sqlCount %"PRId64" or concurrent %"PRId64" is not correct.\n", - __func__, __LINE__, g_queryInfo.specifiedQueryInfo.sqlCount, + errorPrint("%s() LN%d, query sqlCount %"PRIu64" or concurrent %"PRIu64" is not correct.\n", + __func__, __LINE__, + g_queryInfo.specifiedQueryInfo.sqlCount, g_queryInfo.specifiedQueryInfo.concurrent); exit(-1); } @@ -6580,21 +6729,21 @@ static int subscribeTestProcess() { exit(-1); } - int ntables = g_queryInfo.superQueryInfo.childTblCount; + uint64_t ntables = g_queryInfo.superQueryInfo.childTblCount; int threads = g_queryInfo.superQueryInfo.threadCnt; - int a = ntables / threads; + uint64_t a = ntables / threads; if (a < 1) { threads = ntables; a = 1; } - int b = 0; + uint64_t b = 0; if (threads != 0) { b = ntables % threads; } - int startFrom = 0; + uint64_t startFrom = 0; for (int i = 0; i < threads; i++) { threadInfo *t_info = infosOfSub + i; t_info->threadID = i; diff --git a/src/kit/taosdump/taosdump.c b/src/kit/taosdump/taosdump.c index 96a1cd16f8f724efbee8780a72bcfadea4121be1..f80ac069a02e3df028f3356e2d13d58c219108e9 100644 --- a/src/kit/taosdump/taosdump.c +++ b/src/kit/taosdump/taosdump.c @@ -72,7 +72,8 @@ enum _show_db_index { TSDB_SHOW_DB_WALLEVEL_INDEX, TSDB_SHOW_DB_FSYNC_INDEX, TSDB_SHOW_DB_COMP_INDEX, - TSDB_SHOW_DB_PRECISION_INDEX, + TSDB_SHOW_DB_CACHELAST_INDEX, + TSDB_SHOW_DB_PRECISION_INDEX, TSDB_SHOW_DB_UPDATE_INDEX, TSDB_SHOW_DB_STATUS_INDEX, TSDB_MAX_SHOW_DB @@ -83,10 +84,10 @@ enum _show_tables_index { TSDB_SHOW_TABLES_NAME_INDEX, TSDB_SHOW_TABLES_CREATED_TIME_INDEX, TSDB_SHOW_TABLES_COLUMNS_INDEX, - TSDB_SHOW_TABLES_METRIC_INDEX, - TSDB_SHOW_TABLES_UID_INDEX, + TSDB_SHOW_TABLES_METRIC_INDEX, + TSDB_SHOW_TABLES_UID_INDEX, TSDB_SHOW_TABLES_TID_INDEX, - TSDB_SHOW_TABLES_VGID_INDEX, + TSDB_SHOW_TABLES_VGID_INDEX, TSDB_MAX_SHOW_TABLES }; @@ -99,22 +100,24 @@ enum _describe_table_index { TSDB_MAX_DESCRIBE_METRIC }; +#define COL_NOTE_LEN 128 + typedef struct { char field[TSDB_COL_NAME_LEN + 1]; char type[16]; int length; - char note[128]; + char note[COL_NOTE_LEN]; } SColDes; typedef struct { - char name[TSDB_COL_NAME_LEN + 1]; + char name[TSDB_TABLE_NAME_LEN]; SColDes cols[]; } STableDef; extern char version[]; typedef struct { - char name[TSDB_DB_NAME_LEN + 1]; + char name[TSDB_DB_NAME_LEN]; char create_time[32]; int32_t ntables; int32_t vgroups; @@ -132,14 +135,15 @@ typedef struct { int8_t wallevel; int32_t fsync; int8_t comp; + int8_t cachelast; char precision[8]; // time resolution int8_t update; char status[16]; } SDbInfo; typedef struct { - char name[TSDB_TABLE_NAME_LEN + 1]; - char metric[TSDB_TABLE_NAME_LEN + 1]; + char name[TSDB_TABLE_NAME_LEN]; + char metric[TSDB_TABLE_NAME_LEN]; } STableRecord; typedef struct { @@ -151,7 +155,7 @@ typedef struct { pthread_t threadID; int32_t threadIndex; int32_t totalThreads; - char dbName[TSDB_TABLE_NAME_LEN + 1]; + char dbName[TSDB_DB_NAME_LEN]; void *taosCon; int64_t rowsOfDumpOut; int64_t tablesOfDumpOut; @@ -210,13 +214,13 @@ static struct argp_option options[] = { {"encode", 'e', "ENCODE", 0, "Input file encoding.", 1}, // dump unit options {"all-databases", 'A', 0, 0, "Dump all databases.", 2}, - {"databases", 'B', 0, 0, "Dump assigned databases", 2}, + {"databases", 'D', 0, 0, "Dump assigned databases", 2}, // dump format options {"schemaonly", 's', 0, 0, "Only dump schema.", 3}, - {"with-property", 'M', 0, 0, "Dump schema with properties.", 3}, + {"without-property", 'N', 0, 0, "Dump schema without properties.", 3}, {"start-time", 'S', "START_TIME", 0, "Start time to dump. Either Epoch or ISO8601/RFC3339 format is acceptable. Epoch precision millisecond. ISO8601 format example: 2017-10-01T18:00:00.000+0800 or 2017-10-0100:00:00.000+0800 or '2017-10-01 00:00:00.000+0800'", 3}, {"end-time", 'E', "END_TIME", 0, "End time to dump. Either Epoch or ISO8601/RFC3339 format is acceptable. Epoch precision millisecond. ISO8601 format example: 2017-10-01T18:00:00.000+0800 or 2017-10-0100:00:00.000+0800 or '2017-10-01 00:00:00.000+0800'", 3}, - {"data-batch", 'N', "DATA_BATCH", 0, "Number of data point per insert statement. Default is 1.", 3}, + {"data-batch", 'B', "DATA_BATCH", 0, "Number of data point per insert statement. Default is 1.", 3}, {"max-sql-len", 'L', "SQL_LEN", 0, "Max length of one sql. Default is 65480.", 3}, {"table-batch", 't', "TABLE_BATCH", 0, "Number of table dumpout into one output file. Default is 1.", 3}, {"thread_num", 'T', "THREAD_NUM", 0, "Number of thread for dump in file. Default is 5.", 3}, @@ -337,15 +341,15 @@ static error_t parse_opt(int key, char *arg, struct argp_state *state) { case 'A': arguments->all_databases = true; break; - case 'B': + case 'D': arguments->databases = true; break; // dump format option case 's': arguments->schemaonly = true; break; - case 'M': - arguments->with_property = true; + case 'N': + arguments->with_property = false; break; case 'S': // parse time here. @@ -354,23 +358,23 @@ static error_t parse_opt(int key, char *arg, struct argp_state *state) { case 'E': arguments->end_time = atol(arg); break; - case 'N': + case 'B': arguments->data_batch = atoi(arg); if (arguments->data_batch >= INT16_MAX) { arguments->data_batch = INT16_MAX - 1; - } + } break; - case 'L': + case 'L': { int32_t len = atoi(arg); if (len > TSDB_MAX_ALLOWED_SQL_LEN) { len = TSDB_MAX_ALLOWED_SQL_LEN; } else if (len < TSDB_MAX_SQL_LEN) { len = TSDB_MAX_SQL_LEN; - } + } arguments->max_sql_len = len; break; - } + } case 't': arguments->table_batch = atoi(arg); break; @@ -398,27 +402,27 @@ static resultStatistics g_resultStatistics = {0}; static FILE *g_fpOfResult = NULL; static int g_numOfCores = 1; -int taosDumpOut(struct arguments *arguments); -int taosDumpIn(struct arguments *arguments); -void taosDumpCreateDbClause(SDbInfo *dbInfo, bool isDumpProperty, FILE *fp); -int taosDumpDb(SDbInfo *dbInfo, struct arguments *arguments, FILE *fp, TAOS *taosCon); -int32_t taosDumpStable(char *table, FILE *fp, TAOS* taosCon, char* dbName); -void taosDumpCreateTableClause(STableDef *tableDes, int numOfCols, FILE *fp, char* dbName); -void taosDumpCreateMTableClause(STableDef *tableDes, char *metric, int numOfCols, FILE *fp, char* dbName); -int32_t taosDumpTable(char *table, char *metric, struct arguments *arguments, FILE *fp, TAOS* taosCon, char* dbName); -int taosDumpTableData(FILE *fp, char *tbname, struct arguments *arguments, TAOS* taosCon, char* dbName); -int taosCheckParam(struct arguments *arguments); -void taosFreeDbInfos(); +static int taosDumpOut(struct arguments *arguments); +static int taosDumpIn(struct arguments *arguments); +static void taosDumpCreateDbClause(SDbInfo *dbInfo, bool isDumpProperty, FILE *fp); +static int taosDumpDb(SDbInfo *dbInfo, struct arguments *arguments, FILE *fp, TAOS *taosCon); +static int32_t taosDumpStable(char *table, FILE *fp, TAOS* taosCon, char* dbName); +static void taosDumpCreateTableClause(STableDef *tableDes, int numOfCols, FILE *fp, char* dbName); +static void taosDumpCreateMTableClause(STableDef *tableDes, char *metric, int numOfCols, FILE *fp, char* dbName); +static int32_t taosDumpTable(char *table, char *metric, struct arguments *arguments, FILE *fp, TAOS* taosCon, char* dbName); +static int taosDumpTableData(FILE *fp, char *tbname, struct arguments *arguments, TAOS* taosCon, char* dbName); +static int taosCheckParam(struct arguments *arguments); +static void taosFreeDbInfos(); static void taosStartDumpOutWorkThreads(void* taosCon, struct arguments* args, int32_t numOfThread, char *dbName); struct arguments g_args = { // connection option - NULL, - "root", + NULL, + "root", #ifdef _TD_POWER_ - "powerdb", + "powerdb", #else - "taosdata", + "taosdata", #endif 0, "", @@ -432,8 +436,8 @@ struct arguments g_args = { false, false, // dump format option - false, - false, + false, // schemeonly + true, // with_property 0, INT64_MAX, 1, @@ -523,7 +527,7 @@ int main(int argc, char *argv[]) { /* Parse our arguments; every option seen by parse_opt will be reflected in arguments. */ - if (argc > 1) + if (argc > 2) parse_args(argc, argv, &g_args); argp_parse(&argp, argc, argv, 0, 0, &g_args); @@ -675,10 +679,10 @@ int taosGetTableRecordInfo(char *table, STableRecordInfo *pTableRecordInfo, TAOS } sprintf(tempCommand, "show tables like %s", table); - - result = taos_query(taosCon, tempCommand); + + result = taos_query(taosCon, tempCommand); int32_t code = taos_errno(result); - + if (code != 0) { fprintf(stderr, "failed to run command %s\n", tempCommand); free(tempCommand); @@ -705,12 +709,12 @@ int taosGetTableRecordInfo(char *table, STableRecordInfo *pTableRecordInfo, TAOS free(tempCommand); return 0; } - + sprintf(tempCommand, "show stables like %s", table); - - result = taos_query(taosCon, tempCommand); + + result = taos_query(taosCon, tempCommand); code = taos_errno(result); - + if (code != 0) { fprintf(stderr, "failed to run command %s\n", tempCommand); free(tempCommand); @@ -748,7 +752,7 @@ int32_t taosSaveAllNormalTableToTempFile(TAOS *taosCon, char*meter, char* metric return -1; } } - + memset(&tableRecord, 0, sizeof(STableRecord)); tstrncpy(tableRecord.name, meter, TSDB_TABLE_NAME_LEN); tstrncpy(tableRecord.metric, metric, TSDB_TABLE_NAME_LEN); @@ -770,7 +774,7 @@ int32_t taosSaveTableOfMetricToTempFile(TAOS *taosCon, char* metric, struct argu } sprintf(tmpCommand, "select tbname from %s", metric); - + TAOS_RES *res = taos_query(taosCon, tmpCommand); int32_t code = taos_errno(res); if (code != 0) { @@ -792,20 +796,20 @@ int32_t taosSaveTableOfMetricToTempFile(TAOS *taosCon, char* metric, struct argu } TAOS_FIELD *fields = taos_fetch_fields(res); - + int32_t numOfTable = 0; - while ((row = taos_fetch_row(res)) != NULL) { + while ((row = taos_fetch_row(res)) != NULL) { memset(&tableRecord, 0, sizeof(STableRecord)); tstrncpy(tableRecord.name, (char *)row[0], fields[0].bytes); tstrncpy(tableRecord.metric, metric, TSDB_TABLE_NAME_LEN); - - taosWrite(fd, &tableRecord, sizeof(STableRecord)); + + taosWrite(fd, &tableRecord, sizeof(STableRecord)); numOfTable++; } taos_free_result(res); lseek(fd, 0, SEEK_SET); - + int maxThreads = arguments->thread_num; int tableOfPerFile ; if (numOfTable <= arguments->thread_num) { @@ -815,16 +819,16 @@ int32_t taosSaveTableOfMetricToTempFile(TAOS *taosCon, char* metric, struct argu tableOfPerFile = numOfTable / arguments->thread_num; if (0 != numOfTable % arguments->thread_num) { tableOfPerFile += 1; - } + } } char* tblBuf = (char*)calloc(1, tableOfPerFile * sizeof(STableRecord)); if (NULL == tblBuf){ - fprintf(stderr, "failed to calloc %" PRIzu "\n", tableOfPerFile * sizeof(STableRecord)); + fprintf(stderr, "failed to calloc %" PRIzu "\n", tableOfPerFile * sizeof(STableRecord)); close(fd); return -1; } - + int32_t numOfThread = *totalNumOfThread; int subFd = -1; for (; numOfThread < maxThreads; numOfThread++) { @@ -838,7 +842,7 @@ int32_t taosSaveTableOfMetricToTempFile(TAOS *taosCon, char* metric, struct argu (void)remove(tmpBuf); } sprintf(tmpBuf, ".select-tbname.tmp"); - (void)remove(tmpBuf); + (void)remove(tmpBuf); free(tblBuf); close(fd); return -1; @@ -856,11 +860,11 @@ int32_t taosSaveTableOfMetricToTempFile(TAOS *taosCon, char* metric, struct argu sprintf(tmpBuf, ".select-tbname.tmp"); (void)remove(tmpBuf); - + if (fd >= 0) { close(fd); fd = -1; - } + } *totalNumOfThread = numOfThread; @@ -884,7 +888,7 @@ int taosDumpOut(struct arguments *arguments) { } else { sprintf(tmpBuf, "dbs.sql"); } - + fp = fopen(tmpBuf, "w"); if (fp == NULL) { fprintf(stderr, "failed to open file %s\n", tmpBuf); @@ -916,9 +920,9 @@ int taosDumpOut(struct arguments *arguments) { taosDumpCharset(fp); sprintf(command, "show databases"); - result = taos_query(taos, command); + result = taos_query(taos, command); int32_t code = taos_errno(result); - + if (code != 0) { fprintf(stderr, "failed to run command: %s, reason: %s\n", command, taos_errstr(result)); goto _exit_failure; @@ -955,15 +959,17 @@ int taosDumpOut(struct arguments *arguments) { goto _exit_failure; } - strncpy(dbInfos[count]->name, (char *)row[TSDB_SHOW_DB_NAME_INDEX], fields[TSDB_SHOW_DB_NAME_INDEX].bytes); + strncpy(dbInfos[count]->name, (char *)row[TSDB_SHOW_DB_NAME_INDEX], + fields[TSDB_SHOW_DB_NAME_INDEX].bytes); if (arguments->with_property) { dbInfos[count]->ntables = *((int32_t *)row[TSDB_SHOW_DB_NTABLES_INDEX]); - dbInfos[count]->vgroups = *((int32_t *)row[TSDB_SHOW_DB_VGROUPS_INDEX]); + dbInfos[count]->vgroups = *((int32_t *)row[TSDB_SHOW_DB_VGROUPS_INDEX]); dbInfos[count]->replica = *((int16_t *)row[TSDB_SHOW_DB_REPLICA_INDEX]); dbInfos[count]->quorum = *((int16_t *)row[TSDB_SHOW_DB_QUORUM_INDEX]); - dbInfos[count]->days = *((int16_t *)row[TSDB_SHOW_DB_DAYS_INDEX]); + dbInfos[count]->days = *((int16_t *)row[TSDB_SHOW_DB_DAYS_INDEX]); - strncpy(dbInfos[count]->keeplist, (char *)row[TSDB_SHOW_DB_KEEP_INDEX], fields[TSDB_SHOW_DB_KEEP_INDEX].bytes); + strncpy(dbInfos[count]->keeplist, (char *)row[TSDB_SHOW_DB_KEEP_INDEX], + fields[TSDB_SHOW_DB_KEEP_INDEX].bytes); //dbInfos[count]->daysToKeep = *((int16_t *)row[TSDB_SHOW_DB_KEEP_INDEX]); //dbInfos[count]->daysToKeep1; //dbInfos[count]->daysToKeep2; @@ -974,8 +980,10 @@ int taosDumpOut(struct arguments *arguments) { dbInfos[count]->wallevel = *((int8_t *)row[TSDB_SHOW_DB_WALLEVEL_INDEX]); dbInfos[count]->fsync = *((int32_t *)row[TSDB_SHOW_DB_FSYNC_INDEX]); dbInfos[count]->comp = (int8_t)(*((int8_t *)row[TSDB_SHOW_DB_COMP_INDEX])); + dbInfos[count]->cachelast = (int8_t)(*((int8_t *)row[TSDB_SHOW_DB_CACHELAST_INDEX])); - strncpy(dbInfos[count]->precision, (char *)row[TSDB_SHOW_DB_PRECISION_INDEX], fields[TSDB_SHOW_DB_PRECISION_INDEX].bytes); + strncpy(dbInfos[count]->precision, (char *)row[TSDB_SHOW_DB_PRECISION_INDEX], + fields[TSDB_SHOW_DB_PRECISION_INDEX].bytes); //dbInfos[count]->precision = *((int8_t *)row[TSDB_SHOW_DB_PRECISION_INDEX]); dbInfos[count]->update = *((int8_t *)row[TSDB_SHOW_DB_UPDATE_INDEX]); } @@ -1007,8 +1015,8 @@ int taosDumpOut(struct arguments *arguments) { g_resultStatistics.totalDatabasesOfDumpOut++; sprintf(command, "use %s", dbInfos[0]->name); - - result = taos_query(taos, command); + + result = taos_query(taos, command); int32_t code = taos_errno(result); if (code != 0) { fprintf(stderr, "invalid database %s\n", dbInfos[0]->name); @@ -1038,7 +1046,7 @@ int taosDumpOut(struct arguments *arguments) { int ret = taosDumpStable(tableRecordInfo.tableRecord.metric, fp, taos, dbInfos[0]->name); if (0 == ret) { superTblCnt++; - } + } } retCode = taosSaveAllNormalTableToTempFile(taos, tableRecordInfo.tableRecord.name, tableRecordInfo.tableRecord.metric, &normalTblFd); } @@ -1050,7 +1058,7 @@ int taosDumpOut(struct arguments *arguments) { goto _clean_tmp_file; } } - + // TODO: save dump super table into result_output.txt fprintf(g_fpOfResult, "# super table counter: %d\n", superTblCnt); g_resultStatistics.totalSuperTblsOfDumpOut += superTblCnt; @@ -1076,7 +1084,7 @@ int taosDumpOut(struct arguments *arguments) { taos_close(taos); taos_free_result(result); tfree(command); - taosFreeDbInfos(); + taosFreeDbInfos(); fprintf(stderr, "dump out rows: %" PRId64 "\n", totalDumpOutRows); return 0; @@ -1090,15 +1098,17 @@ _exit_failure: return -1; } -int taosGetTableDes(char* dbName, char *table, STableDef *tableDes, TAOS* taosCon, bool isSuperTable) { +int taosGetTableDes( + char* dbName, char *table, + STableDef *tableDes, TAOS* taosCon, bool isSuperTable) { TAOS_ROW row = NULL; TAOS_RES* res = NULL; int count = 0; char sqlstr[COMMAND_SIZE]; sprintf(sqlstr, "describe %s.%s;", dbName, table); - - res = taos_query(taosCon, sqlstr); + + res = taos_query(taosCon, sqlstr); int32_t code = taos_errno(res); if (code != 0) { fprintf(stderr, "failed to run command <%s>, reason:%s\n", sqlstr, taos_errstr(res)); @@ -1108,7 +1118,7 @@ int taosGetTableDes(char* dbName, char *table, STableDef *tableDes, TAOS* taosCo TAOS_FIELD *fields = taos_fetch_fields(res); - tstrncpy(tableDes->name, table, TSDB_COL_NAME_LEN); + tstrncpy(tableDes->name, table, TSDB_TABLE_NAME_LEN); while ((row = taos_fetch_row(res)) != NULL) { strncpy(tableDes->cols[count].field, (char *)row[TSDB_DESCRIBE_METRIC_FIELD_INDEX], @@ -1128,23 +1138,23 @@ int taosGetTableDes(char* dbName, char *table, STableDef *tableDes, TAOS* taosCo if (isSuperTable) { return count; } - + // if chidl-table have tag, using select tagName from table to get tagValue for (int i = 0 ; i < count; i++) { if (strcmp(tableDes->cols[i].note, "TAG") != 0) continue; sprintf(sqlstr, "select %s from %s.%s", tableDes->cols[i].field, dbName, table); - - res = taos_query(taosCon, sqlstr); + + res = taos_query(taosCon, sqlstr); code = taos_errno(res); if (code != 0) { fprintf(stderr, "failed to run command <%s>, reason:%s\n", sqlstr, taos_errstr(res)); taos_free_result(res); return -1; } - - fields = taos_fetch_fields(res); + + fields = taos_fetch_fields(res); row = taos_fetch_row(res); if (NULL == row) { @@ -1159,7 +1169,7 @@ int taosGetTableDes(char* dbName, char *table, STableDef *tableDes, TAOS* taosCo res = NULL; continue; } - + int32_t* length = taos_fetch_lengths(res); //int32_t* length = taos_fetch_lengths(tmpResult); @@ -1188,16 +1198,16 @@ int taosGetTableDes(char* dbName, char *table, STableDef *tableDes, TAOS* taosCo case TSDB_DATA_TYPE_BINARY: { memset(tableDes->cols[i].note, 0, sizeof(tableDes->cols[i].note)); tableDes->cols[i].note[0] = '\''; - char tbuf[COMMAND_SIZE]; - converStringToReadable((char *)row[0], length[0], tbuf, COMMAND_SIZE); + char tbuf[COL_NOTE_LEN]; + converStringToReadable((char *)row[0], length[0], tbuf, COL_NOTE_LEN); char* pstr = stpcpy(&(tableDes->cols[i].note[1]), tbuf); *(pstr++) = '\''; break; } case TSDB_DATA_TYPE_NCHAR: { memset(tableDes->cols[i].note, 0, sizeof(tableDes->cols[i].note)); - char tbuf[COMMAND_SIZE]; - convertNCharToReadable((char *)row[0], length[0], tbuf, COMMAND_SIZE); + char tbuf[COL_NOTE_LEN-2]; // need reserve 2 bytes for ' ' + convertNCharToReadable((char *)row[0], length[0], tbuf, COL_NOTE_LEN); sprintf(tableDes->cols[i].note, "\'%s\'", tbuf); break; } @@ -1219,15 +1229,17 @@ int taosGetTableDes(char* dbName, char *table, STableDef *tableDes, TAOS* taosCo default: break; } - + taos_free_result(res); - res = NULL; + res = NULL; } return count; } -int32_t taosDumpTable(char *table, char *metric, struct arguments *arguments, FILE *fp, TAOS* taosCon, char* dbName) { +int32_t taosDumpTable( + char *table, char *metric, struct arguments *arguments, + FILE *fp, TAOS* taosCon, char* dbName) { int count = 0; STableDef *tableDes = (STableDef *)calloc(1, sizeof(STableDef) + sizeof(SColDes) * TSDB_MAX_COLUMNS); @@ -1280,9 +1292,10 @@ void taosDumpCreateDbClause(SDbInfo *dbInfo, bool isDumpProperty, FILE *fp) { pstr += sprintf(pstr, "CREATE DATABASE IF NOT EXISTS %s ", dbInfo->name); if (isDumpProperty) { pstr += sprintf(pstr, - "TABLES %d VGROUPS %d REPLICA %d QUORUM %d DAYS %d KEEP %s CACHE %d BLOCKS %d MINROWS %d MAXROWS %d WALLEVEL %d FYNC %d COMP %d PRECISION '%s' UPDATE %d", - dbInfo->ntables, dbInfo->vgroups, dbInfo->replica, dbInfo->quorum, dbInfo->days, dbInfo->keeplist, dbInfo->cache, - dbInfo->blocks, dbInfo->minrows, dbInfo->maxrows, dbInfo->wallevel, dbInfo->fsync, dbInfo->comp, dbInfo->precision, dbInfo->update); + "REPLICA %d QUORUM %d DAYS %d KEEP %s CACHE %d BLOCKS %d MINROWS %d MAXROWS %d FSYNC %d CACHELAST %d COMP %d PRECISION '%s' UPDATE %d", + dbInfo->replica, dbInfo->quorum, dbInfo->days, dbInfo->keeplist, dbInfo->cache, + dbInfo->blocks, dbInfo->minrows, dbInfo->maxrows, dbInfo->fsync, dbInfo->cachelast, + dbInfo->comp, dbInfo->precision, dbInfo->update); } pstr += sprintf(pstr, ";"); @@ -1293,8 +1306,8 @@ void* taosDumpOutWorkThreadFp(void *arg) { SThreadParaObj *pThread = (SThreadParaObj*)arg; STableRecord tableRecord; - int fd; - + int fd; + char tmpBuf[TSDB_FILENAME_LEN*4] = {0}; sprintf(tmpBuf, ".tables.tmp.%d", pThread->threadIndex); fd = open(tmpBuf, O_RDWR | O_CREAT, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH); @@ -1305,13 +1318,13 @@ void* taosDumpOutWorkThreadFp(void *arg) FILE *fp = NULL; memset(tmpBuf, 0, TSDB_FILENAME_LEN + 128); - + if (g_args.outpath[0] != 0) { sprintf(tmpBuf, "%s/%s.tables.%d.sql", g_args.outpath, pThread->dbName, pThread->threadIndex); } else { sprintf(tmpBuf, "%s.tables.%d.sql", pThread->dbName, pThread->threadIndex); } - + fp = fopen(tmpBuf, "w"); if (fp == NULL) { fprintf(stderr, "failed to open file %s\n", tmpBuf); @@ -1321,13 +1334,13 @@ void* taosDumpOutWorkThreadFp(void *arg) memset(tmpBuf, 0, TSDB_FILENAME_LEN); sprintf(tmpBuf, "use %s", pThread->dbName); - - TAOS_RES* tmpResult = taos_query(pThread->taosCon, tmpBuf); + + TAOS_RES* tmpResult = taos_query(pThread->taosCon, tmpBuf); int32_t code = taos_errno(tmpResult); if (code != 0) { fprintf(stderr, "invalid database %s\n", pThread->dbName); taos_free_result(tmpResult); - fclose(fp); + fclose(fp); close(fd); return NULL; } @@ -1340,14 +1353,17 @@ void* taosDumpOutWorkThreadFp(void *arg) ssize_t readLen = read(fd, &tableRecord, sizeof(STableRecord)); if (readLen <= 0) break; - int ret = taosDumpTable(tableRecord.name, tableRecord.metric, &g_args, fp, pThread->taosCon, pThread->dbName); + int ret = taosDumpTable( + tableRecord.name, tableRecord.metric, &g_args, + fp, pThread->taosCon, pThread->dbName); if (ret >= 0) { // TODO: sum table count and table rows by self pThread->tablesOfDumpOut++; pThread->rowsOfDumpOut += ret; - + if (pThread->rowsOfDumpOut >= lastRowsPrint) { - printf(" %"PRId64 " rows already be dumpout from database %s\n", pThread->rowsOfDumpOut, pThread->dbName); + printf(" %"PRId64 " rows already be dumpout from database %s\n", + pThread->rowsOfDumpOut, pThread->dbName); lastRowsPrint += 5000000; } @@ -1355,15 +1371,18 @@ void* taosDumpOutWorkThreadFp(void *arg) if (tablesInOneFile >= g_args.table_batch) { fclose(fp); tablesInOneFile = 0; - - memset(tmpBuf, 0, TSDB_FILENAME_LEN + 128); + + memset(tmpBuf, 0, TSDB_FILENAME_LEN + 128); if (g_args.outpath[0] != 0) { - sprintf(tmpBuf, "%s/%s.tables.%d-%d.sql", g_args.outpath, pThread->dbName, pThread->threadIndex, fileNameIndex); + sprintf(tmpBuf, "%s/%s.tables.%d-%d.sql", + g_args.outpath, pThread->dbName, + pThread->threadIndex, fileNameIndex); } else { - sprintf(tmpBuf, "%s.tables.%d-%d.sql", pThread->dbName, pThread->threadIndex, fileNameIndex); + sprintf(tmpBuf, "%s.tables.%d-%d.sql", + pThread->dbName, pThread->threadIndex, fileNameIndex); } fileNameIndex++; - + fp = fopen(tmpBuf, "w"); if (fp == NULL) { fprintf(stderr, "failed to open file %s\n", tmpBuf); @@ -1377,7 +1396,7 @@ void* taosDumpOutWorkThreadFp(void *arg) taos_free_result(tmpResult); close(fd); - fclose(fp); + fclose(fp); return NULL; } @@ -1385,15 +1404,16 @@ void* taosDumpOutWorkThreadFp(void *arg) static void taosStartDumpOutWorkThreads(void* taosCon, struct arguments* args, int32_t numOfThread, char *dbName) { pthread_attr_t thattr; - SThreadParaObj *threadObj = (SThreadParaObj *)calloc(numOfThread, sizeof(SThreadParaObj)); + SThreadParaObj *threadObj = + (SThreadParaObj *)calloc(numOfThread, sizeof(SThreadParaObj)); for (int t = 0; t < numOfThread; ++t) { SThreadParaObj *pThread = threadObj + t; pThread->rowsOfDumpOut = 0; pThread->tablesOfDumpOut = 0; pThread->threadIndex = t; pThread->totalThreads = numOfThread; - tstrncpy(pThread->dbName, dbName, TSDB_TABLE_NAME_LEN); - pThread->taosCon = taosCon; + tstrncpy(pThread->dbName, dbName, TSDB_DB_NAME_LEN); + pThread->taosCon = taosCon; pthread_attr_init(&thattr); pthread_attr_setdetachstate(&thattr, PTHREAD_CREATE_JOINABLE); @@ -1408,7 +1428,7 @@ static void taosStartDumpOutWorkThreads(void* taosCon, struct arguments* args, i pthread_join(threadObj[t].threadID, NULL); } - // TODO: sum all thread dump table count and rows of per table, then save into result_output.txt + // TODO: sum all thread dump table count and rows of per table, then save into result_output.txt int64_t totalRowsOfDumpOut = 0; int64_t totalChildTblsOfDumpOut = 0; for (int32_t t = 0; t < numOfThread; ++t) { @@ -1449,7 +1469,7 @@ int32_t taosDumpStable(char *table, FILE *fp, TAOS* taosCon, char* dbName) { } -int32_t taosDumpCreateSuperTableClause(TAOS* taosCon, char* dbName, FILE *fp) +int32_t taosDumpCreateSuperTableClause(TAOS* taosCon, char* dbName, FILE *fp) { TAOS_ROW row; int fd = -1; @@ -1457,8 +1477,8 @@ int32_t taosDumpCreateSuperTableClause(TAOS* taosCon, char* dbName, FILE *fp) char sqlstr[TSDB_MAX_SQL_LEN] = {0}; sprintf(sqlstr, "show %s.stables", dbName); - - TAOS_RES* res = taos_query(taosCon, sqlstr); + + TAOS_RES* res = taos_query(taosCon, sqlstr); int32_t code = taos_errno(res); if (code != 0) { fprintf(stderr, "failed to run command <%s>, reason: %s\n", sqlstr, taos_errstr(res)); @@ -1478,13 +1498,14 @@ int32_t taosDumpCreateSuperTableClause(TAOS* taosCon, char* dbName, FILE *fp) (void)remove(".stables.tmp"); exit(-1); } - - while ((row = taos_fetch_row(res)) != NULL) { + + while ((row = taos_fetch_row(res)) != NULL) { memset(&tableRecord, 0, sizeof(STableRecord)); - strncpy(tableRecord.name, (char *)row[TSDB_SHOW_TABLES_NAME_INDEX], fields[TSDB_SHOW_TABLES_NAME_INDEX].bytes); + strncpy(tableRecord.name, (char *)row[TSDB_SHOW_TABLES_NAME_INDEX], + fields[TSDB_SHOW_TABLES_NAME_INDEX].bytes); taosWrite(fd, &tableRecord, sizeof(STableRecord)); - } - + } + taos_free_result(res); (void)lseek(fd, 0, SEEK_SET); @@ -1492,7 +1513,7 @@ int32_t taosDumpCreateSuperTableClause(TAOS* taosCon, char* dbName, FILE *fp) while (1) { ssize_t readLen = read(fd, &tableRecord, sizeof(STableRecord)); if (readLen <= 0) break; - + int ret = taosDumpStable(tableRecord.name, fp, taosCon, dbName); if (0 == ret) { superTblCnt++; @@ -1505,8 +1526,8 @@ int32_t taosDumpCreateSuperTableClause(TAOS* taosCon, char* dbName, FILE *fp) close(fd); (void)remove(".stables.tmp"); - - return 0; + + return 0; } @@ -1516,19 +1537,19 @@ int taosDumpDb(SDbInfo *dbInfo, struct arguments *arguments, FILE *fp, TAOS *tao STableRecord tableRecord; taosDumpCreateDbClause(dbInfo, arguments->with_property, fp); - + fprintf(g_fpOfResult, "\n#### database: %s\n", dbInfo->name); g_resultStatistics.totalDatabasesOfDumpOut++; char sqlstr[TSDB_MAX_SQL_LEN] = {0}; fprintf(fp, "USE %s;\n\n", dbInfo->name); - + (void)taosDumpCreateSuperTableClause(taosCon, dbInfo->name, fp); sprintf(sqlstr, "show %s.tables", dbInfo->name); - - TAOS_RES* res = taos_query(taosCon, sqlstr); + + TAOS_RES* res = taos_query(taosCon, sqlstr); int code = taos_errno(res); if (code != 0) { fprintf(stderr, "failed to run command <%s>, reason:%s\n", sqlstr, taos_errstr(res)); @@ -1547,15 +1568,17 @@ int taosDumpDb(SDbInfo *dbInfo, struct arguments *arguments, FILE *fp, TAOS *tao } TAOS_FIELD *fields = taos_fetch_fields(res); - + int32_t numOfTable = 0; - while ((row = taos_fetch_row(res)) != NULL) { + while ((row = taos_fetch_row(res)) != NULL) { memset(&tableRecord, 0, sizeof(STableRecord)); - tstrncpy(tableRecord.name, (char *)row[TSDB_SHOW_TABLES_NAME_INDEX], fields[TSDB_SHOW_TABLES_NAME_INDEX].bytes); - tstrncpy(tableRecord.metric, (char *)row[TSDB_SHOW_TABLES_METRIC_INDEX], fields[TSDB_SHOW_TABLES_METRIC_INDEX].bytes); - + tstrncpy(tableRecord.name, (char *)row[TSDB_SHOW_TABLES_NAME_INDEX], + fields[TSDB_SHOW_TABLES_NAME_INDEX].bytes); + tstrncpy(tableRecord.metric, (char *)row[TSDB_SHOW_TABLES_METRIC_INDEX], + fields[TSDB_SHOW_TABLES_METRIC_INDEX].bytes); + taosWrite(fd, &tableRecord, sizeof(STableRecord)); - + numOfTable++; } taos_free_result(res); @@ -1570,7 +1593,7 @@ int taosDumpDb(SDbInfo *dbInfo, struct arguments *arguments, FILE *fp, TAOS *tao tableOfPerFile = numOfTable / g_args.thread_num; if (0 != numOfTable % g_args.thread_num) { tableOfPerFile += 1; - } + } } char* tblBuf = (char*)calloc(1, tableOfPerFile * sizeof(STableRecord)); @@ -1579,7 +1602,7 @@ int taosDumpDb(SDbInfo *dbInfo, struct arguments *arguments, FILE *fp, TAOS *tao close(fd); return -1; } - + int32_t numOfThread = 0; int subFd = -1; for (numOfThread = 0; numOfThread < maxThreads; numOfThread++) { @@ -1616,7 +1639,7 @@ int taosDumpDb(SDbInfo *dbInfo, struct arguments *arguments, FILE *fp, TAOS *tao close(fd); fd = -1; } - + taos_free_result(res); // start multi threads to dumpout @@ -1624,7 +1647,7 @@ int taosDumpDb(SDbInfo *dbInfo, struct arguments *arguments, FILE *fp, TAOS *tao for (int loopCnt = 0; loopCnt < numOfThread; loopCnt++) { sprintf(tmpBuf, ".tables.tmp.%d", loopCnt); (void)remove(tmpBuf); - } + } free(tblBuf); return 0; @@ -1637,15 +1660,18 @@ void taosDumpCreateTableClause(STableDef *tableDes, int numOfCols, FILE *fp, cha char* pstr = sqlstr; - pstr += sprintf(sqlstr, "CREATE TABLE IF NOT EXISTS %s.%s", dbName, tableDes->name); + pstr += sprintf(sqlstr, "CREATE TABLE IF NOT EXISTS %s.%s", + dbName, tableDes->name); for (; counter < numOfCols; counter++) { if (tableDes->cols[counter].note[0] != '\0') break; if (counter == 0) { - pstr += sprintf(pstr, " (%s %s", tableDes->cols[counter].field, tableDes->cols[counter].type); + pstr += sprintf(pstr, " (%s %s", + tableDes->cols[counter].field, tableDes->cols[counter].type); } else { - pstr += sprintf(pstr, ", %s %s", tableDes->cols[counter].field, tableDes->cols[counter].type); + pstr += sprintf(pstr, ", %s %s", + tableDes->cols[counter].field, tableDes->cols[counter].type); } if (strcasecmp(tableDes->cols[counter].type, "binary") == 0 || @@ -1658,9 +1684,11 @@ void taosDumpCreateTableClause(STableDef *tableDes, int numOfCols, FILE *fp, cha for (; counter < numOfCols; counter++) { if (counter == count_temp) { - pstr += sprintf(pstr, ") TAGS (%s %s", tableDes->cols[counter].field, tableDes->cols[counter].type); + pstr += sprintf(pstr, ") TAGS (%s %s", + tableDes->cols[counter].field, tableDes->cols[counter].type); } else { - pstr += sprintf(pstr, ", %s %s", tableDes->cols[counter].field, tableDes->cols[counter].type); + pstr += sprintf(pstr, ", %s %s", + tableDes->cols[counter].field, tableDes->cols[counter].type); } if (strcasecmp(tableDes->cols[counter].type, "binary") == 0 || @@ -1687,7 +1715,8 @@ void taosDumpCreateMTableClause(STableDef *tableDes, char *metric, int numOfCols char *pstr = NULL; pstr = tmpBuf; - pstr += sprintf(tmpBuf, "CREATE TABLE IF NOT EXISTS %s.%s USING %s.%s TAGS (", dbName, tableDes->name, dbName, metric); + pstr += sprintf(tmpBuf, "CREATE TABLE IF NOT EXISTS %s.%s USING %s.%s TAGS (", + dbName, tableDes->name, dbName, metric); for (; counter < numOfCols; counter++) { if (tableDes->cols[counter].note[0] != '\0') break; @@ -1735,7 +1764,7 @@ int taosDumpTableData(FILE *fp, char *tbname, struct arguments *arguments, TAOS* char *pstr = NULL; TAOS_ROW row = NULL; int numFields = 0; - + if (arguments->schemaonly) { return 0; } @@ -1750,11 +1779,11 @@ int taosDumpTableData(FILE *fp, char *tbname, struct arguments *arguments, TAOS* pstr = tmpBuffer; char sqlstr[1024] = {0}; - sprintf(sqlstr, - "select * from %s.%s where _c0 >= %" PRId64 " and _c0 <= %" PRId64 " order by _c0 asc;", + sprintf(sqlstr, + "select * from %s.%s where _c0 >= %" PRId64 " and _c0 <= %" PRId64 " order by _c0 asc;", dbName, tbname, arguments->start_time, arguments->end_time); - - TAOS_RES* tmpResult = taos_query(taosCon, sqlstr); + + TAOS_RES* tmpResult = taos_query(taosCon, sqlstr); int32_t code = taos_errno(tmpResult); if (code != 0) { fprintf(stderr, "failed to run command %s, reason: %s\n", sqlstr, taos_errstr(tmpResult)); @@ -1774,7 +1803,7 @@ int taosDumpTableData(FILE *fp, char *tbname, struct arguments *arguments, TAOS* while ((row = taos_fetch_row(tmpResult)) != NULL) { pstr = tmpBuffer; curr_sqlstr_len = 0; - + int32_t* length = taos_fetch_lengths(tmpResult); // act len if (count == 0) { @@ -1829,7 +1858,7 @@ int taosDumpTableData(FILE *fp, char *tbname, struct arguments *arguments, TAOS* converStringToReadable((char *)row[col], length[col], tbuf, COMMAND_SIZE); //pstr = stpcpy(pstr, tbuf); //*(pstr++) = '\''; - pstr += sprintf(pstr + curr_sqlstr_len, "\'%s\'", tbuf); + pstr += sprintf(pstr + curr_sqlstr_len, "\'%s\'", tbuf); break; } case TSDB_DATA_TYPE_NCHAR: { @@ -1857,10 +1886,10 @@ int taosDumpTableData(FILE *fp, char *tbname, struct arguments *arguments, TAOS* curr_sqlstr_len += sprintf(pstr + curr_sqlstr_len, ") "); - totalRows++; + totalRows++; count++; fprintf(fp, "%s", tmpBuffer); - + if (totalRows >= lastRowsPrint) { printf(" %"PRId64 " rows already be dumpout from %s.%s\n", totalRows, dbName, tbname); lastRowsPrint += 5000000; @@ -2206,7 +2235,7 @@ static FILE* taosOpenDumpInFile(char *fptr) { } char *fname = full_path.we_wordv[0]; - + FILE *f = fopen(fname, "r"); if (f == NULL) { fprintf(stderr, "ERROR: failed to open file %s\n", fname); @@ -2240,7 +2269,7 @@ int taosDumpInOneFile(TAOS * taos, FILE* fp, char* fcharset, char* encode, c line[--read_len] = '\0'; //if (read_len == 0 || isCommentLine(line)) { // line starts with # - if (read_len == 0 ) { + if (read_len == 0 ) { continue; } @@ -2259,8 +2288,8 @@ int taosDumpInOneFile(TAOS * taos, FILE* fp, char* fcharset, char* encode, c } memset(cmd, 0, TSDB_MAX_ALLOWED_SQL_LEN); - cmd_len = 0; - + cmd_len = 0; + if (lineNo >= lastRowsPrint) { printf(" %d lines already be executed from file %s\n", lineNo, fileName); lastRowsPrint += 5000000; @@ -2300,7 +2329,7 @@ static void taosStartDumpInWorkThreads(void* taosCon, struct arguments *args) if (totalThreads > tsSqlFileNum) { totalThreads = tsSqlFileNum; } - + SThreadParaObj *threadObj = (SThreadParaObj *)calloc(totalThreads, sizeof(SThreadParaObj)); for (int32_t t = 0; t < totalThreads; ++t) { pThread = threadObj + t; @@ -2330,7 +2359,7 @@ static void taosStartDumpInWorkThreads(void* taosCon, struct arguments *args) int taosDumpIn(struct arguments *arguments) { assert(arguments->isDumpIn); - + TAOS *taos = NULL; FILE *fp = NULL; @@ -2345,22 +2374,22 @@ int taosDumpIn(struct arguments *arguments) { int32_t tsSqlFileNumOfTbls = tsSqlFileNum; if (tsDbSqlFile[0] != 0) { tsSqlFileNumOfTbls--; - + fp = taosOpenDumpInFile(tsDbSqlFile); if (NULL == fp) { fprintf(stderr, "failed to open input file %s\n", tsDbSqlFile); return -1; } fprintf(stderr, "Success Open input file: %s\n", tsDbSqlFile); - + taosLoadFileCharset(fp, tsfCharset); - + taosDumpInOneFile(taos, fp, tsfCharset, arguments->encode, tsDbSqlFile); } if (0 != tsSqlFileNumOfTbls) { taosStartDumpInWorkThreads(taos, arguments); - } + } taos_close(taos); taosFreeSQLFiles(); diff --git a/src/mnode/inc/mnodeDef.h b/src/mnode/inc/mnodeDef.h index ed1de1b87a475cf5a2264abb4b8787c0841d1b63..e052f34a33b2a74dcd858721694225859f1581b8 100644 --- a/src/mnode/inc/mnodeDef.h +++ b/src/mnode/inc/mnodeDef.h @@ -249,7 +249,7 @@ typedef struct SAcctObj { } SAcctObj; typedef struct { - char db[TSDB_DB_NAME_LEN]; + char db[TSDB_ACCT_ID_LEN + TSDB_DB_NAME_LEN]; int8_t type; int16_t numOfColumns; int32_t index; diff --git a/src/mnode/src/mnodeShow.c b/src/mnode/src/mnodeShow.c index 03772f2724c87c74da2f3ab7128705d90c5bb1ad..c0fa6368f302387a4cec841215761063be7415d8 100644 --- a/src/mnode/src/mnodeShow.c +++ b/src/mnode/src/mnodeShow.c @@ -129,7 +129,7 @@ static int32_t mnodeProcessShowMsg(SMnodeMsg *pMsg) { SShowObj *pShow = calloc(1, showObjSize); pShow->type = pShowMsg->type; pShow->payloadLen = htons(pShowMsg->payloadLen); - tstrncpy(pShow->db, pShowMsg->db, TSDB_DB_NAME_LEN); + tstrncpy(pShow->db, pShowMsg->db, TSDB_ACCT_ID_LEN + TSDB_DB_NAME_LEN); memcpy(pShow->payload, pShowMsg->payload, pShow->payloadLen); pShow = mnodePutShowObj(pShow); diff --git a/src/plugins/http/inc/httpInt.h b/src/plugins/http/inc/httpInt.h index 634468f3ccfd041300e0b99c728a8fb6a9b8fbae..0a5822b90893861eb12aea756bf877bc81730413 100644 --- a/src/plugins/http/inc/httpInt.h +++ b/src/plugins/http/inc/httpInt.h @@ -171,7 +171,7 @@ typedef struct HttpThread { EpollFd pollFd; int32_t numOfContexts; int32_t threadId; - char label[HTTP_LABEL_SIZE]; + char label[HTTP_LABEL_SIZE << 1]; bool (*processData)(HttpContext *pContext); } HttpThread; diff --git a/src/rpc/src/rpcMain.c b/src/rpc/src/rpcMain.c index db3c72c2fc8a1a1c326c37974bfde0741f93004b..2ec508f050ea7cf916f8b1c1e6ff37d18fb96523 100644 --- a/src/rpc/src/rpcMain.c +++ b/src/rpc/src/rpcMain.c @@ -295,7 +295,7 @@ void *rpcOpen(const SRpcInit *pInit) { return NULL; } } else { - pRpc->pCache = rpcOpenConnCache(pRpc->sessions, rpcCloseConn, pRpc->tmrCtrl, pRpc->idleTime * 30); + pRpc->pCache = rpcOpenConnCache(pRpc->sessions, rpcCloseConn, pRpc->tmrCtrl, pRpc->idleTime * 20); if ( pRpc->pCache == NULL ) { tError("%s failed to init connection cache", pRpc->label); rpcClose(pRpc); diff --git a/src/util/src/terror.c b/src/util/src/terror.c index 586a886f47ab4ea71d30689f88c2a386a24a0fde..fc24b28dc3cb694f45be7246193711f74ac729c2 100644 --- a/src/util/src/terror.c +++ b/src/util/src/terror.c @@ -230,6 +230,7 @@ TAOS_DEFINE_ERROR(TSDB_CODE_VND_IS_BALANCING, "Database is balancing TAOS_DEFINE_ERROR(TSDB_CODE_VND_NOT_SYNCED, "Database suspended") TAOS_DEFINE_ERROR(TSDB_CODE_VND_NO_WRITE_AUTH, "Database write operation denied") TAOS_DEFINE_ERROR(TSDB_CODE_VND_IS_SYNCING, "Database is syncing") +TAOS_DEFINE_ERROR(TSDB_CODE_VND_INVALID_TSDB_STATE, "Invalid tsdb state") // tsdb TAOS_DEFINE_ERROR(TSDB_CODE_TDB_INVALID_TABLE_ID, "Invalid table ID") @@ -253,6 +254,7 @@ TAOS_DEFINE_ERROR(TSDB_CODE_TDB_TABLE_RECONFIGURE, "Need to reconfigure t TAOS_DEFINE_ERROR(TSDB_CODE_TDB_IVD_CREATE_TABLE_INFO, "Invalid information to create table") TAOS_DEFINE_ERROR(TSDB_CODE_TDB_NO_AVAIL_DISK, "No available disk") TAOS_DEFINE_ERROR(TSDB_CODE_TDB_MESSED_MSG, "TSDB messed message") +TAOS_DEFINE_ERROR(TSDB_CODE_TDB_IVLD_TAG_VAL, "TSDB invalid tag value") // query TAOS_DEFINE_ERROR(TSDB_CODE_QRY_INVALID_QHANDLE, "Invalid handle") diff --git a/src/util/src/tnettest.c b/src/util/src/tnettest.c index 131063b0de8b456ebd74011f74f95d199695b75b..318a2d48609a129bcf6094455ff2a7cc8f7c0467 100644 --- a/src/util/src/tnettest.c +++ b/src/util/src/tnettest.c @@ -539,7 +539,7 @@ static void taosNetTestServer(char *host, int32_t startPort, int32_t pkgLen) { } void taosNetTest(char *role, char *host, int32_t port, int32_t pkgLen) { -// tscEmbedded = 1; + tscEmbedded = 1; if (host == NULL) host = tsLocalFqdn; if (port == 0) port = tsServerPort; if (pkgLen <= 10) pkgLen = 1000; @@ -550,6 +550,7 @@ void taosNetTest(char *role, char *host, int32_t port, int32_t pkgLen) { } else if (0 == strcmp("server", role)) { taosNetTestServer(host, port, pkgLen); } else if (0 == strcmp("rpc", role)) { + tscEmbedded = 0; taosNetTestRpc(host, port, pkgLen); } else if (0 == strcmp("sync", role)) { taosNetCheckSync(host, port); @@ -559,5 +560,5 @@ void taosNetTest(char *role, char *host, int32_t port, int32_t pkgLen) { taosNetTestStartup(host, port); } -// tscEmbedded = 0; + tscEmbedded = 0; } diff --git a/src/vnode/src/vnodeMain.c b/src/vnode/src/vnodeMain.c index ee8ed9e0fa3507363f04841060011de85422efec..8ec66316e33a09825248a3628e990c854a7e554b 100644 --- a/src/vnode/src/vnodeMain.c +++ b/src/vnode/src/vnodeMain.c @@ -310,11 +310,11 @@ int32_t vnodeOpen(int32_t vgId) { vnodeCleanUp(pVnode); return terrno; } else if (tsdbGetState(pVnode->tsdb) != TSDB_STATE_OK) { - vError("vgId:%d, failed to open tsdb, replica:%d reason:%s", pVnode->vgId, pVnode->syncCfg.replica, - tstrerror(terrno)); + vError("vgId:%d, failed to open tsdb(state: %d), replica:%d reason:%s", pVnode->vgId, + tsdbGetState(pVnode->tsdb), pVnode->syncCfg.replica, tstrerror(terrno)); if (pVnode->syncCfg.replica <= 1) { vnodeCleanUp(pVnode); - return terrno; + return TSDB_CODE_VND_INVALID_TSDB_STATE; } else { pVnode->fversion = 0; pVnode->version = 0; diff --git a/src/vnode/src/vnodeSync.c b/src/vnode/src/vnodeSync.c index aa4cf0fc15bd9db749888699baf90a97bfbeb39f..05af34a34f0bed6fd72d24946c9a50e7232e5352 100644 --- a/src/vnode/src/vnodeSync.c +++ b/src/vnode/src/vnodeSync.c @@ -119,7 +119,6 @@ void vnodeConfirmForard(int32_t vgId, void *wparam, int32_t code) { void *pVnode = vnodeAcquire(vgId); if (pVnode == NULL) { vError("vgId:%d, vnode not found while confirm forward", vgId); - return; } dnodeSendRpcVWriteRsp(pVnode, wparam, code); @@ -162,4 +161,4 @@ int32_t vnodeGetVersion(int32_t vgId, uint64_t *fver, uint64_t *wver) { void vnodeConfirmForward(void *vparam, uint64_t version, int32_t code, bool force) { SVnodeObj *pVnode = vparam; syncConfirmForward(pVnode->sync, version, code, force); -} \ No newline at end of file +} diff --git a/src/vnode/src/vnodeWrite.c b/src/vnode/src/vnodeWrite.c index def9cf3b32121206f270fdbe9c131ddad668a7e5..36516d81df50a1903bb0d6c332b4eacf35f248c1 100644 --- a/src/vnode/src/vnodeWrite.c +++ b/src/vnode/src/vnodeWrite.c @@ -317,12 +317,13 @@ int32_t vnodeWriteToWQueue(void *vparam, void *wparam, int32_t qtype, void *rpar void vnodeFreeFromWQueue(void *vparam, SVWriteMsg *pWrite) { SVnodeObj *pVnode = vparam; + if (pVnode) { + int32_t queued = atomic_sub_fetch_32(&pVnode->queuedWMsg, 1); + int64_t queuedSize = atomic_sub_fetch_64(&pVnode->queuedWMsgSize, pWrite->pHead.len); - int32_t queued = atomic_sub_fetch_32(&pVnode->queuedWMsg, 1); - int64_t queuedSize = atomic_sub_fetch_64(&pVnode->queuedWMsgSize, pWrite->pHead.len); - - vTrace("vgId:%d, msg:%p, app:%p, free from vwqueue, queued:%d size:%" PRId64, pVnode->vgId, pWrite, - pWrite->rpcMsg.ahandle, queued, queuedSize); + vTrace("vgId:%d, msg:%p, app:%p, free from vwqueue, queued:%d size:%" PRId64, pVnode->vgId, pWrite, + pWrite->rpcMsg.ahandle, queued, queuedSize); + } taosFreeQitem(pWrite); vnodeRelease(pVnode); @@ -371,8 +372,8 @@ static int32_t vnodePerformFlowCtrl(SVWriteMsg *pWrite) { taosMsleep(ms); return 0; } else { - void *unUsed = NULL; - taosTmrReset(vnodeFlowCtrlMsgToWQueue, 100, pWrite, tsDnodeTmr, &unUsed); + void *unUsedTimerId = NULL; + taosTmrReset(vnodeFlowCtrlMsgToWQueue, 100, pWrite, tsDnodeTmr, &unUsedTimerId); vTrace("vgId:%d, msg:%p, app:%p, perform flowctrl, retry:%d", pVnode->vgId, pWrite, pWrite->rpcMsg.ahandle, pWrite->processedCount); diff --git a/tests/Jenkinsfile b/tests/Jenkinsfile index 178a0446c387118b167ee98e0fb39d6466697e92..64a71ef8f9bac63563cc96463daf283b6b8ece29 100644 --- a/tests/Jenkinsfile +++ b/tests/Jenkinsfile @@ -21,6 +21,7 @@ def pre_test(){ cmake .. > /dev/null make > /dev/null make install > /dev/null + pip3 install ${WKC}/src/connector/python/linux/python3/ ''' return 1 } diff --git a/tests/pytest/client/version.py b/tests/pytest/client/version.py index 93b302f619d2ab6da2a3a24950ae70999e968425..7cbeeb60df54e8d89fdcc7815a2b2757793dfaec 100644 --- a/tests/pytest/client/version.py +++ b/tests/pytest/client/version.py @@ -28,20 +28,22 @@ class TDTestCase: sql = "select server_version()" ret = tdSql.query(sql) version = tdSql.getData(0, 0)[0:3] - expectedVersion = "2.0" - if(version == expectedVersion): - tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" % (sql, 0, 0, version, expectedVersion)) + expectedVersion_dev = "2.0" + expectedVersion_master = "2.1" + if(version == expectedVersion_dev or version == expectedVersion_master): + tdLog.info("sql:%s, row:%d col:%d data:%s == expect" % (sql, 0, 0, version)) else: - tdLog.exit("sql:%s, row:%d col:%d data:%s != expect:%s" % (sql, 0, 0, version, expectedVersion)) + tdLog.exit("sql:%s, row:%d col:%d data:%s != expect:%s or %s " % (sql, 0, 0, version, expectedVersion_dev, expectedVersion_master)) sql = "select client_version()" ret = tdSql.query(sql) version = tdSql.getData(0, 0)[0:3] - expectedVersion = "2.0" - if(version == expectedVersion): - tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" % (sql, 0, 0, version, expectedVersion)) + expectedVersion_dev = "2.0" + expectedVersion_master = "2.1" + if(version == expectedVersion_dev or version == expectedVersion_master): + tdLog.info("sql:%s, row:%d col:%d data:%s == expect" % (sql, 0, 0, version)) else: - tdLog.exit("sql:%s, row:%d col:%d data:%s != expect:%s" % (sql, 0, 0, version, expectedVersion)) + tdLog.exit("sql:%s, row:%d col:%d data:%s != expect:%s or %s " % (sql, 0, 0, version, expectedVersion_dev, expectedVersion_master)) def stop(self): diff --git a/tests/pytest/cluster/clusterEnvSetup/basic.py b/tests/pytest/cluster/clusterEnvSetup/basic.py deleted file mode 100644 index dc7e07fd5cea3473270afa6cb2ddbfba6c2402e4..0000000000000000000000000000000000000000 --- a/tests/pytest/cluster/clusterEnvSetup/basic.py +++ /dev/null @@ -1,119 +0,0 @@ -################################################################### -# Copyright (c) 2016 by TAOS Technologies, Inc. -# All rights reserved. -# -# This file is proprietary and confidential to TAOS Technologies. -# No part of this file may be reproduced, stored, transmitted, -# disclosed or used in any form or by any means other than as -# expressly provided by the written permission from Jianhui Tao -# -################################################################### - -# -*- coding: utf-8 -*- - -import os -import taos -import random -import argparse - -class BuildDockerCluser: - - def __init__(self, hostName, user, password, configDir, numOfNodes, clusterVersion, dockerDir, removeFlag): - self.hostName = hostName - self.user = user - self.password = password - self.configDir = configDir - self.numOfNodes = numOfNodes - self.clusterVersion = clusterVersion - self.dockerDir = dockerDir - self.removeFlag = removeFlag - - def getConnection(self): - self.conn = taos.connect( - host = self.hostName, - user = self.user, - password = self.password, - config = self.configDir) - - def createDondes(self): - self.cursor = self.conn.cursor() - for i in range(2, self.numOfNodes + 1): - self.cursor.execute("create dnode tdnode%d" % i) - - def startArbitrator(self): - print("start arbitrator") - os.system("docker exec -d $(docker ps|grep tdnode1|awk '{print $1}') tarbitrator") - - def run(self): - if self.numOfNodes < 2 or self.numOfNodes > 10: - print("the number of nodes must be between 2 and 10") - exit(0) - print("remove Flag value %s" % self.removeFlag) - if self.removeFlag == False: - os.system("./cleanClusterEnv.sh -d %s" % self.dockerDir) - os.system("./buildClusterEnv.sh -n %d -v %s -d %s" % (self.numOfNodes, self.clusterVersion, self.dockerDir)) - self.getConnection() - self.createDondes() - self.startArbitrator() - -parser = argparse.ArgumentParser() -parser.add_argument( - '-H', - '--host', - action='store', - default='tdnode1', - type=str, - help='host name to be connected (default: tdnode1)') -parser.add_argument( - '-u', - '--user', - action='store', - default='root', - type=str, - help='user (default: root)') -parser.add_argument( - '-p', - '--password', - action='store', - default='taosdata', - type=str, - help='password (default: taosdata)') -parser.add_argument( - '-c', - '--config-dir', - action='store', - default='/etc/taos', - type=str, - help='configuration directory (default: /etc/taos)') -parser.add_argument( - '-n', - '--num-of-nodes', - action='store', - default=2, - type=int, - help='number of nodes in the cluster (default: 2, min: 2, max: 5)') -parser.add_argument( - '-v', - '--version', - action='store', - default='2.0.18.1', - type=str, - help='the version of the cluster to be build, Default is 2.0.17.1') -parser.add_argument( - '-d', - '--docker-dir', - action='store', - default='/data', - type=str, - help='the data dir for docker, default is /data') -parser.add_argument( - '--flag', - action='store_true', - help='remove docker containers flag, default: True') - -args = parser.parse_args() -cluster = BuildDockerCluser(args.host, args.user, args.password, args.config_dir, args.num_of_nodes, args.version, args.docker_dir, args.flag) -cluster.run() - -# usage 1: python3 basic.py -n 2 --flag (flag is True) -# usage 2: python3 basic.py -n 2 (flag should be False when it is not specified) \ No newline at end of file diff --git a/tests/pytest/cluster/clusterEnvSetup/cleanClusterEnv.sh b/tests/pytest/cluster/clusterEnvSetup/cleanClusterEnv.sh deleted file mode 100755 index 675cae5fef850947c2c53899ef1863dc00b55422..0000000000000000000000000000000000000000 --- a/tests/pytest/cluster/clusterEnvSetup/cleanClusterEnv.sh +++ /dev/null @@ -1,39 +0,0 @@ -#!/bin/bash -echo "Executing cleanClusterEnv.sh" -CURR_DIR=`pwd` - -if [ $# != 2 ]; then - echo "argument list need input : " - echo " -d docker dir" - exit 1 -fi - -DOCKER_DIR= -while getopts "d:" arg -do - case $arg in - d) - DOCKER_DIR=$OPTARG - ;; - ?) - echo "unkonwn argument" - ;; - esac -done - -function removeDockerContainers { - cd $DOCKER_DIR - docker-compose down --remove-orphans -} - -function cleanEnv { - echo "Clean up docker environment" - for i in {1..10} - do - rm -rf $DOCKER_DIR/node$i/data/* - rm -rf $DOCKER_DIR/node$i/log/* - done -} - -removeDockerContainers -cleanEnv \ No newline at end of file diff --git a/tests/pytest/cluster/clusterEnvSetup/node4.yml b/tests/pytest/cluster/clusterEnvSetup/node4.yml deleted file mode 100644 index f542c22c4537dd6dc2c529dff39ba93c5c0ec3a4..0000000000000000000000000000000000000000 --- a/tests/pytest/cluster/clusterEnvSetup/node4.yml +++ /dev/null @@ -1,62 +0,0 @@ -version: '3.7' - -services: - td2.0-node4: - build: - context: . - args: - - PACKAGE=${PACKAGE} - - TARBITRATORPKG=${TARBITRATORPKG} - - EXTRACTDIR=${DIR} - - EXTRACTDIR2=${DIR2} - - DATADIR=${DATADIR} - image: 'tdengine:${VERSION}' - container_name: 'tdnode4' - cap_add: - - ALL - stdin_open: true - tty: true - environment: - TZ: "Asia/Shanghai" - command: > - sh -c "ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && - echo $TZ > /etc/timezone && - mkdir /coredump && - echo 'kernel.core_pattern=/coredump/core_%e_%p' >> /etc/sysctl.conf && - sysctl -p && - exec my-main-application" - extra_hosts: - - "tdnode2:172.27.0.8" - - "tdnode3:172.27.0.9" - - "tdnode4:172.27.0.10" - - "tdnode5:172.27.0.11" - - "tdnode6:172.27.0.12" - - "tdnode7:172.27.0.13" - - "tdnode8:172.27.0.14" - - "tdnode9:172.27.0.15" - - "tdnode10:172.27.0.16" - volumes: - # bind data directory - - type: bind - source: ${DATADIR}/node4/data - target: /var/lib/taos - # bind log directory - - type: bind - source: ${DATADIR}/node4/log - target: /var/log/taos - # bind configuration - - type: bind - source: ${DATADIR}/node4/cfg - target: /etc/taos - # bind core dump path - - type: bind - source: ${DATADIR}/node4/core - target: /coredump - - type: bind - source: ${DATADIR} - target: /root - hostname: tdnode4 - networks: - taos_update_net: - ipv4_address: 172.27.0.10 - command: taosd \ No newline at end of file diff --git a/tests/pytest/cluster/clusterEnvSetup/node5.yml b/tests/pytest/cluster/clusterEnvSetup/node5.yml deleted file mode 100644 index dd5941ac769273031c98bca3248adcf633240088..0000000000000000000000000000000000000000 --- a/tests/pytest/cluster/clusterEnvSetup/node5.yml +++ /dev/null @@ -1,62 +0,0 @@ -version: '3.7' - -services: - td2.0-node5: - build: - context: . - args: - - PACKAGE=${PACKAGE} - - TARBITRATORPKG=${TARBITRATORPKG} - - EXTRACTDIR=${DIR} - - EXTRACTDIR2=${DIR2} - - DATADIR=${DATADIR} - image: 'tdengine:${VERSION}' - container_name: 'tdnode5' - cap_add: - - ALL - stdin_open: true - tty: true - environment: - TZ: "Asia/Shanghai" - command: > - sh -c "ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && - echo $TZ > /etc/timezone && - mkdir /coredump && - echo 'kernel.core_pattern=/coredump/core_%e_%p' >> /etc/sysctl.conf && - sysctl -p && - exec my-main-application" - extra_hosts: - - "tdnode2:172.27.0.8" - - "tdnode3:172.27.0.9" - - "tdnode4:172.27.0.10" - - "tdnode5:172.27.0.11" - - "tdnode6:172.27.0.12" - - "tdnode7:172.27.0.13" - - "tdnode8:172.27.0.14" - - "tdnode9:172.27.0.15" - - "tdnode10:172.27.0.16" - volumes: - # bind data directory - - type: bind - source: ${DATADIR}/node5/data - target: /var/lib/taos - # bind log directory - - type: bind - source: ${DATADIR}/node5/log - target: /var/log/taos - # bind configuration - - type: bind - source: ${DATADIR}/node5/cfg - target: /etc/taos - # bind core dump path - - type: bind - source: ${DATADIR}/node5/core - target: /coredump - - type: bind - source: ${DATADIR} - target: /root - hostname: tdnode5 - networks: - taos_update_net: - ipv4_address: 172.27.0.11 - command: taosd \ No newline at end of file diff --git a/tests/pytest/crash_gen/valgrind_taos.supp b/tests/pytest/crash_gen/valgrind_taos.supp index 5eb5403395f4956bd2c6332e58566ccfe4ccc56a..a00b2d830c2e4a3261fcb6fc9a1769b2b583799f 100644 --- a/tests/pytest/crash_gen/valgrind_taos.supp +++ b/tests/pytest/crash_gen/valgrind_taos.supp @@ -17332,3 +17332,168 @@ fun:PyVectorcall_Call fun:_PyEval_EvalFrameDefault } +{ + + Memcheck:Leak + match-leak-kinds: definite + fun:malloc + fun:lib_build_and_cache_attr + fun:lib_getattr + fun:_PyEval_EvalFrameDefault + fun:_PyFunction_Vectorcall + fun:_PyEval_EvalFrameDefault + fun:_PyEval_EvalCodeWithName + fun:PyEval_EvalCode + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + fun:PyVectorcall_Call + fun:_PyEval_EvalFrameDefault +} +{ + + Memcheck:Leak + match-leak-kinds: definite + fun:malloc + fun:lib_build_and_cache_attr + fun:lib_getattr + obj:/usr/bin/python3.8 + fun:_PyEval_EvalFrameDefault + fun:_PyFunction_Vectorcall + fun:_PyEval_EvalFrameDefault + obj:/usr/bin/python3.8 + fun:_PyEval_EvalFrameDefault + fun:PyEval_EvalCode + obj:/usr/bin/python3.8 + fun:_PyEval_EvalFrameDefault + fun:_PyEval_EvalCodeWithName +} +{ + + Memcheck:Leak + match-leak-kinds: definite + fun:malloc + fun:_my_Py_InitModule + fun:lib_getattr + fun:b_init_cffi_1_0_external_module + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + fun:PyObject_CallMethod + fun:_cffi_init + fun:PyInit__bcrypt + fun:_PyImport_LoadDynamicModuleWithSpec + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + fun:PyVectorcall_Call + fun:_PyEval_EvalFrameDefault +} +{ + + Memcheck:Leak + match-leak-kinds: definite + fun:malloc + fun:_PyObject_GC_New + fun:lib_getattr + fun:ffi_internal_new + fun:b_init_cffi_1_0_external_module + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + fun:PyObject_CallMethod + fun:_cffi_init + fun:PyInit__bcrypt + fun:_PyImport_LoadDynamicModuleWithSpec + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + fun:PyVectorcall_Call +} +{ + + Memcheck:Leak + match-leak-kinds: definite + fun:malloc + fun:lib_build_cpython_func.isra.87 + fun:lib_build_and_cache_attr + fun:lib_getattr + obj:/usr/bin/python3.8 + fun:_PyEval_EvalFrameDefault + fun:_PyFunction_Vectorcall + fun:_PyEval_EvalFrameDefault + obj:/usr/bin/python3.8 + fun:_PyEval_EvalFrameDefault + obj:/usr/bin/python3.8 + fun:_PyEval_EvalFrameDefault +} +{ + + Memcheck:Leak + match-leak-kinds: definite + fun:malloc + fun:lib_build_and_cache_attr + fun:lib_getattr + obj:/usr/bin/python3.8 + fun:_PyEval_EvalFrameDefault + fun:_PyFunction_Vectorcall + fun:_PyEval_EvalFrameDefault + obj:/usr/bin/python3.8 + fun:_PyEval_EvalFrameDefault + obj:/usr/bin/python3.8 + fun:_PyEval_EvalFrameDefault + fun:_PyEval_EvalCodeWithName +} +{ + + Memcheck:Leak + match-leak-kinds: definite + fun:malloc + fun:_my_Py_InitModule + fun:b_init_cffi_1_0_external_module + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + fun:PyObject_CallMethod + fun:_cffi_init + fun:PyInit__bcrypt + fun:_PyImport_LoadDynamicModuleWithSpec + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + fun:PyVectorcall_Call + fun:_PyEval_EvalFrameDefault +} +{ + + Memcheck:Leak + match-leak-kinds: definite + fun:malloc + fun:_my_Py_InitModule + fun:b_init_cffi_1_0_external_module + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + fun:PyObject_CallMethod + fun:PyInit__openssl + fun:_PyImport_LoadDynamicModuleWithSpec + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + fun:PyVectorcall_Call + fun:_PyEval_EvalFrameDefault +} +{ + + Memcheck:Leak + match-leak-kinds: definite + fun:malloc + fun:_PyObject_GC_New + fun:ffi_internal_new + fun:b_init_cffi_1_0_external_module + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + fun:PyObject_CallMethod + fun:_cffi_init + fun:PyInit__bcrypt + fun:_PyImport_LoadDynamicModuleWithSpec + obj:/usr/bin/python3.8 + obj:/usr/bin/python3.8 + fun:PyVectorcall_Call +} \ No newline at end of file diff --git a/tests/pytest/cluster/clusterEnvSetup/Dockerfile b/tests/pytest/dockerCluster/Dockerfile similarity index 100% rename from tests/pytest/cluster/clusterEnvSetup/Dockerfile rename to tests/pytest/dockerCluster/Dockerfile diff --git a/tests/pytest/dockerCluster/OneMnodeMultipleVnodesTest.py b/tests/pytest/dockerCluster/OneMnodeMultipleVnodesTest.py new file mode 100644 index 0000000000000000000000000000000000000000..ee663f89b0a6dd776c80033f177f63ec843eaa1e --- /dev/null +++ b/tests/pytest/dockerCluster/OneMnodeMultipleVnodesTest.py @@ -0,0 +1,39 @@ +################################################################### +# Copyright (c) 2016 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +from basic import * +from util.sql import tdSql + + + +class TDTestCase: + + def init(self): + # tdLog.debug("start to execute %s" % __file__) + + self.numOfNodes = 5 + self.dockerDir = "/data" + cluster.init(self.numOfNodes, self.dockerDir) + cluster.prepardBuild() + for i in range(self.numOfNodes): + if i == 0: + cluster.cfg("role", "1", i + 1) + else: + cluster.cfg("role", "2", i + 1) + cluster.run() + +td = TDTestCase() +td.init() + + + diff --git a/tests/pytest/dockerCluster/__init__.py b/tests/pytest/dockerCluster/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/pytest/dockerCluster/basic.py b/tests/pytest/dockerCluster/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..50914b0be9428ab77f479c9a18a099ecbd0a2d51 --- /dev/null +++ b/tests/pytest/dockerCluster/basic.py @@ -0,0 +1,152 @@ +################################################################### +# Copyright (c) 2016 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +import os +import taos + +class BuildDockerCluser: + + def init(self, numOfNodes, dockerDir): + self.numOfNodes = numOfNodes + self.dockerDir = dockerDir + + self.hostName = "tdnode1" + self.user = "root" + self.password = "taosdata" + self.configDir = "/etc/taos" + self.dirs = ["data", "cfg", "log", "core"] + self.cfgDict = { + "numOfLogLines":"100000000", + "mnodeEqualVnodeNum":"0", + "walLevel":"1", + "numOfThreadsPerCore":"2.0", + "monitor":"0", + "vnodeBak":"1", + "dDebugFlag":"135", + "mDebugFlag":"135", + "sdbDebugFlag":"135", + "rpcDebugFlag":"135", + "tmrDebugFlag":"131", + "cDebugFlag":"135", + "httpDebugFlag":"135", + "monitorDebugFlag":"135", + "udebugFlag":"135", + "jnidebugFlag":"135", + "qdebugFlag":"135", + "maxSQLLength":"1048576" + } + + # execute command, and return the output + # ref: https://blog.csdn.net/wowocpp/article/details/80775650 + def execCmdAndGetOutput(self, cmd): + r = os.popen(cmd) + text = r.read() + r.close() + return text + + def execCmd(self, cmd): + if os.system(cmd) != 0: + quit() + + def getTaosdVersion(self): + cmd = "taosd -V |grep version|awk '{print $3}'" + taosdVersion = self.execCmdAndGetOutput(cmd) + cmd = "find %s -name '*server*.tar.gz' | awk -F- '{print $(NF-2)}'|sort|awk 'END {print}'" % self.dockerDir + packageVersion = self.execCmdAndGetOutput(cmd) + + if (taosdVersion is None or taosdVersion.isspace()) and (packageVersion is None or packageVersion.isspace()): + print("Please install taosd or have a install package ready") + quit() + else: + self.version = taosdVersion if taosdVersion >= packageVersion else packageVersion + return self.version.strip() + + def getConnection(self): + self.conn = taos.connect( + host = self.hostName, + user = self.user, + password = self.password, + config = self.configDir) + + def removeFile(self, rootDir, index, dir): + cmd = "rm -rf %s/node%d/%s/*" % (rootDir, index, dir) + self.execCmd(cmd) + + def clearEnv(self): + cmd = "cd %s && docker-compose down --remove-orphans" % self.dockerDir + self.execCmd(cmd) + for i in range(1, self.numOfNodes + 1): + self.removeFile(self.dockerDir, i, self.dirs[0]) + self.removeFile(self.dockerDir, i, self.dirs[1]) + self.removeFile(self.dockerDir, i, self.dirs[2]) + + def createDir(self, rootDir, index, dir): + cmd = "mkdir -p %s/node%d/%s" % (rootDir, index, dir) + self.execCmd(cmd) + + def createDirs(self): + for i in range(1, self.numOfNodes + 1): + for j in range(len(self.dirs)): + self.createDir(self.dockerDir, i, self.dirs[j]) + + def addExtraCfg(self, option, value): + self.cfgDict.update({option: value}) + + def cfg(self, option, value, nodeIndex): + cfgPath = "%s/node%d/cfg/taos.cfg" % (self.dockerDir, nodeIndex) + cmd = "echo '%s %s' >> %s" % (option, value, cfgPath) + self.execCmd(cmd) + + def updateLocalhosts(self): + cmd = "grep '172.27.0.7 *tdnode1' /etc/hosts" + result = self.execCmdAndGetOutput(cmd) + if result and not result.isspace(): + cmd = "echo '172.27.0.7 tdnode1' >> /etc/hosts" + self.execCmd(cmd) + + def deploy(self): + self.clearEnv() + self.createDirs() + for i in range(1, self.numOfNodes + 1): + self.cfg("firstEp", "tdnode1:6030", i) + + for key, value in self.cfgDict.items(): + self.cfg(key, value, i) + + def createDondes(self): + self.cursor = self.conn.cursor() + for i in range(2, self.numOfNodes + 1): + self.cursor.execute("create dnode tdnode%d" % i) + + def startArbitrator(self): + for i in range(1, self.numOfNodes + 1): + self.cfg("arbitrator", "tdnode1:6042", i) + cmd = "docker exec -d $(docker ps|grep tdnode1|awk '{print $1}') tarbitrator" + self.execCmd(cmd) + + def prepardBuild(self): + if self.numOfNodes < 2 or self.numOfNodes > 10: + print("the number of nodes must be between 2 and 10") + exit(0) + self.clearEnv() + self.createDirs() + self.updateLocalhosts() + self.deploy() + + def run(self): + cmd = "./buildClusterEnv.sh -n %d -v %s -d %s" % (self.numOfNodes, self.getTaosdVersion(), self.dockerDir) + self.execCmd(cmd) + self.getConnection() + self.createDondes() + +cluster = BuildDockerCluser() \ No newline at end of file diff --git a/tests/pytest/cluster/clusterEnvSetup/buildClusterEnv.sh b/tests/pytest/dockerCluster/buildClusterEnv.sh similarity index 69% rename from tests/pytest/cluster/clusterEnvSetup/buildClusterEnv.sh rename to tests/pytest/dockerCluster/buildClusterEnv.sh index 60c81cd82b916a290c190c44f7b96f53154c4731..7bd92cad72c4180d5405364ebe2fbd81a8a20386 100755 --- a/tests/pytest/cluster/clusterEnvSetup/buildClusterEnv.sh +++ b/tests/pytest/dockerCluster/buildClusterEnv.sh @@ -32,43 +32,14 @@ do esac done -function addTaoscfg { - for((i=1;i<=$NUM_OF_NODES;i++)) - do - touch $DOCKER_DIR/node$i/cfg/taos.cfg - echo 'firstEp tdnode1:6030' > $DOCKER_DIR/node$i/cfg/taos.cfg - echo 'fqdn tdnode'$i >> $DOCKER_DIR/node$i/cfg/taos.cfg - echo 'arbitrator tdnode1:6042' >> $DOCKER_DIR/node$i/cfg/taos.cfg - done -} - -function createDIR { - for((i=1;i<=$NUM_OF_NODES;i++)) - do - mkdir -p $DOCKER_DIR/node$i/data - mkdir -p $DOCKER_DIR/node$i/log - mkdir -p $DOCKER_DIR/node$i/cfg - mkdir -p $DOCKER_DIR/node$i/core - done -} - -function cleanEnv { - echo "Clean up docker environment" - for((i=1;i<=$NUM_OF_NODES;i++)) - do - rm -rf $DOCKER_DIR/node$i/data/* - rm -rf $DOCKER_DIR/node$i/log/* - done -} - function prepareBuild { - if [ -d $CURR_DIR/../../../../release ]; then + if [ -d $CURR_DIR/../../../release ]; then echo release exists - rm -rf $CURR_DIR/../../../../release/* + rm -rf $CURR_DIR/../../../release/* fi - cd $CURR_DIR/../../../../packaging + cd $CURR_DIR/../../../packaging if [[ "$CURR_DIR" == *"$IN_TDINTERNAL"* ]]; then if [ ! -e $DOCKER_DIR/TDengine-enterprise-server-$VERSION-Linux-x64.tar.gz ] || [ ! -e $DOCKER_DIR/TDengine-enterprise-arbitrator-$VERSION-Linux-x64.tar.gz ]; then @@ -76,17 +47,17 @@ function prepareBuild { echo "generating TDeninge enterprise packages" ./release.sh -v cluster -n $VERSION >> /dev/null 2>&1 - if [ ! -e $CURR_DIR/../../../../release/TDengine-enterprise-server-$VERSION-Linux-x64.tar.gz ]; then + if [ ! -e $CURR_DIR/../../../release/TDengine-enterprise-server-$VERSION-Linux-x64.tar.gz ]; then echo "no TDengine install package found" exit 1 fi - if [ ! -e $CURR_DIR/../../../../release/TDengine-enterprise-arbitrator-$VERSION-Linux-x64.tar.gz ]; then + if [ ! -e $CURR_DIR/../../../release/TDengine-enterprise-arbitrator-$VERSION-Linux-x64.tar.gz ]; then echo "no arbitrator install package found" exit 1 fi - cd $CURR_DIR/../../../../release + cd $CURR_DIR/../../../release mv TDengine-enterprise-server-$VERSION-Linux-x64.tar.gz $DOCKER_DIR mv TDengine-enterprise-arbitrator-$VERSION-Linux-x64.tar.gz $DOCKER_DIR fi @@ -96,17 +67,17 @@ function prepareBuild { echo "generating TDeninge community packages" ./release.sh -v edge -n $VERSION >> /dev/null 2>&1 - if [ ! -e $CURR_DIR/../../../../release/TDengine-server-$VERSION-Linux-x64.tar.gz ]; then + if [ ! -e $CURR_DIR/../../../release/TDengine-server-$VERSION-Linux-x64.tar.gz ]; then echo "no TDengine install package found" exit 1 fi - if [ ! -e $CURR_DIR/../../../../release/TDengine-arbitrator-$VERSION-Linux-x64.tar.gz ]; then + if [ ! -e $CURR_DIR/../../../release/TDengine-arbitrator-$VERSION-Linux-x64.tar.gz ]; then echo "no arbitrator install package found" exit 1 fi - cd $CURR_DIR/../../../../release + cd $CURR_DIR/../../../release mv TDengine-server-$VERSION-Linux-x64.tar.gz $DOCKER_DIR mv TDengine-arbitrator-$VERSION-Linux-x64.tar.gz $DOCKER_DIR fi @@ -147,13 +118,10 @@ function clusterUp { done docker_run=$docker_run" up -d" fi - echo $docker_run |sh + echo $docker_run |sh echo "docker compose finish" } -createDIR -cleanEnv -addTaoscfg prepareBuild clusterUp \ No newline at end of file diff --git a/tests/pytest/cluster/clusterEnvSetup/docker-compose.yml b/tests/pytest/dockerCluster/docker-compose.yml similarity index 94% rename from tests/pytest/cluster/clusterEnvSetup/docker-compose.yml rename to tests/pytest/dockerCluster/docker-compose.yml index d241062a2dd50fa82f934d9e915cddeb74505248..7855f3013687406f407cfb9a5aec27e0da78a5f5 100644 --- a/tests/pytest/cluster/clusterEnvSetup/docker-compose.yml +++ b/tests/pytest/dockerCluster/docker-compose.yml @@ -53,7 +53,7 @@ services: source: ${DATADIR}/node1/core target: /coredump - type: bind - source: /data + source: ${DATADIR} target: /root hostname: tdnode1 networks: @@ -90,6 +90,11 @@ services: - "tdnode3:172.27.0.9" - "tdnode4:172.27.0.10" - "tdnode5:172.27.0.11" + - "tdnode6:172.27.0.12" + - "tdnode7:172.27.0.13" + - "tdnode8:172.27.0.14" + - "tdnode9:172.27.0.15" + - "tdnode10:172.27.0.16" volumes: # bind data directory - type: bind diff --git a/tests/pytest/cluster/clusterEnvSetup/insert.json b/tests/pytest/dockerCluster/insert.json similarity index 100% rename from tests/pytest/cluster/clusterEnvSetup/insert.json rename to tests/pytest/dockerCluster/insert.json diff --git a/tests/pytest/cluster/clusterEnvSetup/node3.yml b/tests/pytest/dockerCluster/node3.yml similarity index 97% rename from tests/pytest/cluster/clusterEnvSetup/node3.yml rename to tests/pytest/dockerCluster/node3.yml index 18f1b37c1c029f50cc6e66e662ec2a42bc475c5e..86e37c2f308cdc240178cd3e660f4e31bef55b6e 100644 --- a/tests/pytest/cluster/clusterEnvSetup/node3.yml +++ b/tests/pytest/dockerCluster/node3.yml @@ -26,6 +26,7 @@ services: sysctl -p && exec my-main-application" extra_hosts: + - "tdnode1:172.27.0.7" - "tdnode2:172.27.0.8" - "tdnode3:172.27.0.9" - "tdnode4:172.27.0.10" diff --git a/tests/pytest/cluster/clusterEnvSetup/taosdemoWrapper.py b/tests/pytest/dockerCluster/taosdemoWrapper.py similarity index 100% rename from tests/pytest/cluster/clusterEnvSetup/taosdemoWrapper.py rename to tests/pytest/dockerCluster/taosdemoWrapper.py diff --git a/tests/pytest/fulltest.sh b/tests/pytest/fulltest.sh index 3a6e0d5ba2e1a2504619cf060dbc7afa901d5218..b5aae6fcefba1a3cfb74f3f19be7c2f2855fb566 100755 --- a/tests/pytest/fulltest.sh +++ b/tests/pytest/fulltest.sh @@ -23,6 +23,7 @@ python3 ./test.py -f insert/insertIntoTwoTables.py python3 ./test.py -f insert/before_1970.py python3 bug2265.py python3 ./test.py -f insert/bug3654.py +python3 ./test.py -f insert/insertDynamicColBeforeVal.py #table python3 ./test.py -f table/alter_wal0.py @@ -151,8 +152,7 @@ python3 test.py -f tools/taosdemoTestTblAlt.py python3 test.py -f tools/taosdemoTestSampleData.py python3 test.py -f tools/taosdemoTestInterlace.py python3 test.py -f tools/taosdemoTestQuery.py -python3 test.py -f tools/taosdemoAllTest/taosdemoTestInsertWithJson.py -python3 test.py -f tools/taosdemoAllTest/taosdemoTestQueryWithJson.py + # update @@ -226,6 +226,7 @@ python3 ./test.py -f query/querySecondtscolumnTowherenow.py python3 ./test.py -f query/queryFilterTswithDateUnit.py python3 ./test.py -f query/queryTscomputWithNow.py python3 ./test.py -f query/computeErrorinWhere.py +python3 ./test.py -f query/queryTsisNull.py @@ -328,4 +329,7 @@ python3 ./test.py -f alter/alter_debugFlag.py python3 ./test.py -f query/queryBetweenAnd.py python3 ./test.py -f tag_lite/alter_tag.py +python3 test.py -f tools/taosdemoAllTest/taosdemoTestInsertWithJson.py +python3 test.py -f tools/taosdemoAllTest/taosdemoTestQueryWithJson.py + #======================p4-end=============== diff --git a/tests/pytest/insert/insertDynamicColBeforeVal.py b/tests/pytest/insert/insertDynamicColBeforeVal.py new file mode 100644 index 0000000000000000000000000000000000000000..4b596049d16a194b37b2e48e9c7dc521a20b3282 --- /dev/null +++ b/tests/pytest/insert/insertDynamicColBeforeVal.py @@ -0,0 +1,136 @@ +################################################################### +# Copyright (c) 2016 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +import sys +from util.log import * +from util.cases import * +from util.sql import * +from util.dnodes import * + + +class TDTestCase: + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + + def run(self): + tdSql.prepare() + tdSql.execute("drop database if exists db") + tdSql.execute("create database if not exists db keep 3650") + tdSql.execute("use db") + + tdLog.printNoPrefix("==========step1:create table") + tdSql.execute( + "create table stb1 (ts timestamp, c11 int, c12 float ) TAGS(t11 int, t12 int )" + ) + + tdLog.printNoPrefix("==========step2:insert data with new syntax") + tdSql.execute( + "insert into t1 using stb1(t11, t12) tags(11, 12) (ts, c11, c12) values (now, 10, 20)" + ) + + # case for tag-value + tdSql.execute( + "insert into t2 using stb1(t11) tags(21) (ts, c11, c12) values (now-1m, 11, 21)" + ) + tdSql.execute( + "insert into t3 using stb1 tags(31, 32) (ts, c11, c12) values (now-2m, 12, 22)" + ) + tdSql.error( + "insert into t4 using stb1(t11, t12) (ts, c11, c12) values (now-3m, 13, 23)" + ) + tdSql.error( + "insert into t5 using stb1(t11, t12) tags() (ts, c11, c12) values (now-4m, 14, 24)" + ) + tdSql.error( + "insert into t6 using stb1(t11, t12) tags(41) (ts, c11, c12) values (now-5m, 15, 25)" + ) + tdSql.error( + "insert into t7 using stb1(t12) tags(51, 52) (ts, c11, c12) values (now-6m, 16, 26)" + ) + tdSql.execute( + "insert into t8 using stb1(t11, t12) tags('61', 62) (ts, c11, c12) values (now-7m, 17, 27)" + ) + + + # case for col-value + tdSql.execute( + "insert into t9 using stb1(t11, t12) tags(71, 72) values (now-8m, 18, 28)" + ) + tdSql.error( + "insert into t10 using stb1(t11, t12) tags(81, 82) (ts, c11, c12) values ()" + ) + tdSql.error( + "insert into t11 using stb1(t11, t12) tags(91, 92) (ts, c11, c12) " + ) + tdSql.error( + "insert into t12 using stb1(t11, t12) tags(101, 102) values (now-9m, 19)" + ) + tdSql.error( + "insert into t13 using stb1(t11, t12) tags(111, 112) (ts, c11) values (now-10m, 110, 210)" + ) + tdSql.error( + "insert into t14 using stb1(t11, t12) tags(121, 122) (ts, c11, c12) values (now-11m, 111)" + ) + tdSql.execute( + "insert into t15 using stb1(t11, t12) tags(131, 132) (ts, c11, c12) values (now-12m, NULL , 212)" + ) + tdSql.execute( + "insert into t16 using stb1(t11, t12) tags(141, 142) (ts, c11, c12) values (now-13m, 'NULL', 213)" + ) + tdSql.error( + "insert into t17 using stb1(t11, t12) tags(151, 152) (ts, c11, c12) values (now-14m, Nan, 214)" + ) + tdSql.error( + "insert into t18 using stb1(t11, t12) tags(161, 162) (ts, c11, c12) values (now-15m, 'NaN', 215)" + ) + tdSql.execute( + "insert into t19 using stb1(t11, t12) tags(171, 172) (ts, c11) values (now-16m, 216)" + ) + tdSql.error( + "insert into t20 using stb1(t11, t12) tags(181, 182) (c11, c12) values (117, 217)" + ) + + # multi-col_value + tdSql.execute( + "insert into t21 using stb1(t11, t12) tags(191, 192) (ts, c11, c12) values (now-17m, 118, 218)(now-18m, 119, 219)" + ) + tdSql.execute( + "insert into t22 using stb1(t11, t12) tags(201, 202) values (now-19m, 120, 220)(now-19m, 121, 221)" + ) + tdSql.error( + "insert into t23 using stb1(t11, t12) tags(211, 212) values (now-20m, 122, 222) (ts, c11, c12) values (now-21m, 123, 223)" + ) + tdSql.error( + "insert into t24 using stb1(t11, t12) tags(221, 222) (ts, c11, c12) values (now-22m, 124, 224) (ts, c11, c12) values (now-23m, 125, 225)" + ) + tdSql.execute( + "insert into t25 (ts, c11, c12) using stb1(t11, t12) tags(231, 232) values (now-24m, 126, 226)(now-25m, 127, 227)" + ) + tdSql.error( + "insert into t26 (ts, c11, c12) values (now-24m, 128, 228)(now-25m, 129, 229) using stb1(t11, t12) tags(241, 242) " + ) + tdSql.error( + "insert into t27 (ts, c11, c12) values (now-24m, 130, 230) using stb1(t11, t12) tags(251, 252) " + ) + + tdSql.query("show tables") + tdSql.checkRows(21) + + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) \ No newline at end of file diff --git a/tests/pytest/query/queryTsisNull.py b/tests/pytest/query/queryTsisNull.py new file mode 100644 index 0000000000000000000000000000000000000000..df783f2fb86ab600ac579093a391d88cfd9370c5 --- /dev/null +++ b/tests/pytest/query/queryTsisNull.py @@ -0,0 +1,53 @@ +################################################################### +# Copyright (c) 2016 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +import sys +from util.log import * +from util.cases import * +from util.sql import * +from util.dnodes import * + + +class TDTestCase: + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + + def run(self): + tdSql.prepare() + tdSql.execute("drop database if exists db") + tdSql.execute("create database if not exists db keep 3650") + tdSql.execute("use db") + + tdLog.printNoPrefix("==========step1:create table and insert data") + tdSql.execute( + "create table stb1 (ts timestamp, c1 timestamp , c2 int) TAGS(t1 int )" + ) + + tdLog.printNoPrefix("==========step2:query data where timestamp data is null") + tdSql.execute( + "insert into t1 using stb1(t1) tags(1) (ts, c1, c2) values (now-1m, null, 1)" + ) + tdSql.execute( + "insert into t1 using stb1(t1) tags(1) (ts, c2) values (now-2m, 2)" + ) + tdSql.query("select * from t1 where c1 is NULL") + tdSql.checkRows(2) + + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/query/unionAllTest.py b/tests/pytest/query/unionAllTest.py index 1b69c8ac4d015a2ad8db72947022b7bd27e92756..3064e2f63e871e5c90d03d19bf125447714dd6cb 100644 --- a/tests/pytest/query/unionAllTest.py +++ b/tests/pytest/query/unionAllTest.py @@ -56,6 +56,34 @@ class TDTestCase: tdSql.query(sql) tdSql.checkRows(6) + tdSql.execute("create table stb(ts timestamp, options binary(7), city binary(10)) tags(type int)") + tdSql.execute("insert into tb1 using stb tags(1) values(%d, 'option1', 'beijing')" % self.ts) + tdSql.execute("insert into tb2 using stb tags(2) values(%d, 'option2', 'shanghai')" % self.ts) + + tdSql.query("select options from stb where type = 1 limit 1 union all select options from stb where type = 2 limit 1") + tdSql.checkData(0, 0, "option1") + tdSql.checkData(1, 0, "option2") + + tdSql.query("select 'dc' as options from stb where type = 1 limit 1 union all select 'ad' as options from stb where type = 2 limit 1") + tdSql.checkData(0, 0, "dc") + tdSql.checkData(1, 0, "ad") + + tdSql.query("select 'dc' as options from stb where type = 1 limit 1 union all select 'adc' as options from stb where type = 2 limit 1") + tdSql.checkData(0, 0, "dc") + tdSql.checkData(1, 0, "adc") + + tdSql.error("select 'dc' as options from stb where type = 1 limit 1 union all select 'ad' as city from stb where type = 2 limit 1") + + # for defect https://jira.taosdata.com:18080/browse/TD-4017 + tdSql.execute("alter table stb add column col int") + tdSql.execute("insert into tb1 values(%d, 'option1', 'beijing', 10)" % (self.ts + 1000)) + + tdSql.query("select 'dc' as options from stb where col > 10 limit 1") + tdSql.checkRows(0) + + tdSql.query("select 'dcs' as options from stb where col > 200 limit 1 union all select 'aaa' as options from stb limit 10") + tdSql.checkData(0, 0, 'aaa') + def stop(self): tdSql.close() tdLog.success("%s successfully executed" % __file__) diff --git a/tests/pytest/smoketest.sh b/tests/pytest/smoketest.sh index 7c14b673e5fac1f5d3b19dd583acc8462e5abab3..0eb850749fbb62f3d4149f6051dfd2851ed55a88 100755 --- a/tests/pytest/smoketest.sh +++ b/tests/pytest/smoketest.sh @@ -2,36 +2,36 @@ ulimit -c unlimited # insert -python3 ./test.py $1 -f insert/basic.py -python3 ./test.py $1 -s && sleep 1 -python3 ./test.py $1 -f insert/bigint.py -python3 ./test.py $1 -s && sleep 1 -python3 ./test.py $1 -f insert/nchar.py -python3 ./test.py $1 -s && sleep 1 -python3 ./test.py $1 -f insert/multi.py -python3 ./test.py $1 -s && sleep 1 +python3.8 ./test.py $1 -f insert/basic.py +python3.8 ./test.py $1 -s && sleep 1 +python3.8 ./test.py $1 -f insert/bigint.py +python3.8 ./test.py $1 -s && sleep 1 +python3.8 ./test.py $1 -f insert/nchar.py +python3.8 ./test.py $1 -s && sleep 1 +python3.8 ./test.py $1 -f insert/multi.py +python3.8 ./test.py $1 -s && sleep 1 # table -python3 ./test.py $1 -f table/column_name.py -python3 ./test.py $1 -s && sleep 1 -python3 ./test.py $1 -f table/column_num.py -python3 ./test.py $1 -s && sleep 1 -python3 ./test.py $1 -f table/db_table.py -python3 ./test.py $1 -s && sleep 1 +python3.8 ./test.py $1 -f table/column_name.py +python3.8 ./test.py $1 -s && sleep 1 +python3.8 ./test.py $1 -f table/column_num.py +python3.8 ./test.py $1 -s && sleep 1 +python3.8 ./test.py $1 -f table/db_table.py +python3.8 ./test.py $1 -s && sleep 1 # import -python3 ./test.py $1 -f import_merge/importDataLastSub.py -python3 ./test.py $1 -s && sleep 1 +python3.8 ./test.py $1 -f import_merge/importDataLastSub.py +python3.8 ./test.py $1 -s && sleep 1 #tag -python3 ./test.py $1 -f tag_lite/filter.py -python3 ./test.py $1 -s && sleep 1 +python3.8 ./test.py $1 -f tag_lite/filter.py +python3.8 ./test.py $1 -s && sleep 1 #query -python3 ./test.py $1 -f query/filter.py -python3 ./test.py $1 -s && sleep 1 +python3.8 ./test.py $1 -f query/filter.py +python3.8 ./test.py $1 -s && sleep 1 # client -python3 ./test.py $1 -f client/client.py -python3 ./test.py $1 -s && sleep 1 +python3.8 ./test.py $1 -f client/client.py +python3.8 ./test.py $1 -s && sleep 1 diff --git a/tests/pytest/stream/showStreamExecTimeisNull.py b/tests/pytest/stream/showStreamExecTimeisNull.py index 39b025901856c1de6c21a1889d97a4b599c53de4..8a2a09cec6f345d62fc821ba58f60f72d563249f 100644 --- a/tests/pytest/stream/showStreamExecTimeisNull.py +++ b/tests/pytest/stream/showStreamExecTimeisNull.py @@ -67,14 +67,15 @@ class TDTestCase: self.queryRows = len(self.queryResult) self.queryCols = len(tdSql.cursor.description) # tdLog.info("sql: %s, try to retrieve %d rows,get %d rows" % (sql, expectRows, self.queryRows)) - if self.queryRows >= timeout: + if self.queryRows >= 1: + tdSql.query(sql) + tdSql.checkData(0, 5, None) return (self.queryRows, i) time.sleep(1) except Exception as e: - tdLog.info(f"sql: {sql} except raise {exception}, actually raise {repr(e)} ") - else: - tdLog.exit(f"sql: {sql} except raise {exception}, actually not") - + tdLog.exit(f"sql: {sql} except raise {exception}, actually raise {repr(e)} ") + # else: + # tdLog.exit(f"sql: {sql} except raise {exception}, actually not") def run(self): tdSql.execute("drop database if exists dbcq") diff --git a/tests/pytest/tools/taosdemoAllTest/insert-1s1tnt1r.json b/tests/pytest/tools/taosdemoAllTest/insert-1s1tnt1r.json index 8e40ad812d0ad0a9e243fc2e371a9be35fa0f7f2..c67582fb56288c978a4d86d7e862ee29f95f820c 100644 --- a/tests/pytest/tools/taosdemoAllTest/insert-1s1tnt1r.json +++ b/tests/pytest/tools/taosdemoAllTest/insert-1s1tnt1r.json @@ -55,8 +55,8 @@ "sample_format": "csv", "sample_file": "./sample.csv", "tags_file": "", - "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":10}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], - "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] + "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":1}, {"type": "BINARY", "len": 16, "count":1}, {"type": "BINARY", "len": 32, "count":1}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":1}] }, { "name": "stb1", @@ -81,8 +81,8 @@ "sample_format": "csv", "sample_file": "./sample.csv", "tags_file": "", - "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":4}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], - "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] + "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":1}, {"type": "BINARY", "len": 16, "count":1}, {"type": "BINARY", "len": 32, "count":1}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":1}] }] }] } diff --git a/tests/pytest/tools/taosdemoAllTest/insert-1s1tntmr.json b/tests/pytest/tools/taosdemoAllTest/insert-1s1tntmr.json index e741fd5c056c329a0a785b050dc2e94dd2dfd9ca..e3db5476b8d4cdb7cc8ea125fa0557b133b1c0b8 100644 --- a/tests/pytest/tools/taosdemoAllTest/insert-1s1tntmr.json +++ b/tests/pytest/tools/taosdemoAllTest/insert-1s1tntmr.json @@ -55,8 +55,8 @@ "sample_format": "csv", "sample_file": "./sample.csv", "tags_file": "", - "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":10}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], - "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] + "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":1}, {"type": "BINARY", "len": 16, "count":1}, {"type": "BINARY", "len": 32, "count":1}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":1}] }, { "name": "stb1", @@ -81,8 +81,8 @@ "sample_format": "csv", "sample_file": "./sample.csv", "tags_file": "", - "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":10}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], - "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] + "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":1}, {"type": "BINARY", "len": 16, "count":1}, {"type": "BINARY", "len": 32, "count":1}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":1}] }] }] } diff --git a/tests/pytest/tools/taosdemoAllTest/insert-disorder.json b/tests/pytest/tools/taosdemoAllTest/insert-disorder.json index fddaa4b4b99d441fb81fcd350ad2d6a4279f9c4e..f2dca662fddc5991a9dcdb8371dc0e4086868190 100644 --- a/tests/pytest/tools/taosdemoAllTest/insert-disorder.json +++ b/tests/pytest/tools/taosdemoAllTest/insert-disorder.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "": 4, + "thread_count_create_tbl": 4, "result_file":"./insert_res.txt", "confirm_parameter_prompt": "no", "insert_interval": 0, diff --git a/tests/pytest/tools/taosdemoAllTest/insert-illegal-columns-count-0.json b/tests/pytest/tools/taosdemoAllTest/insert-illegal.json similarity index 89% rename from tests/pytest/tools/taosdemoAllTest/insert-illegal-columns-count-0.json rename to tests/pytest/tools/taosdemoAllTest/insert-illegal.json index f6a103f001f312514b3c17df481f6c0daa35c410..614402236ac2e1efa48d2647966f0c1cc425f475 100644 --- a/tests/pytest/tools/taosdemoAllTest/insert-illegal-columns-count-0.json +++ b/tests/pytest/tools/taosdemoAllTest/insert-illegal.json @@ -11,8 +11,8 @@ "confirm_parameter_prompt": "no", "insert_interval": 0, "interlace_rows": 10, - "num_of_records_per_req": 100, - "max_sql_len": 10240000000, + "num_of_records_per_req": "-asdf", + "max_sql_len": 1024000, "databases": [{ "dbinfo": { "name": "db", @@ -41,12 +41,12 @@ "batch_create_tbl_num": 10, "data_source": "rand", "insert_mode": "taosc", - "insert_rows": 1000, + "insert_rows": 10000, "childtable_limit": 0, "childtable_offset":0, "multi_thread_write_one_tbl": "no", "interlace_rows": 0, - "insert_interval":0, + "insert_interval":-4, "max_sql_len": 1024000, "disorder_ratio": 0, "disorder_range": 1000, @@ -55,8 +55,8 @@ "sample_format": "csv", "sample_file": "./sample.csv", "tags_file": "", - "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":0}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], - "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":7}] + "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":10}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] }, { "name": "stb1", @@ -64,10 +64,10 @@ "childtable_count": 20, "childtable_prefix": "stb01_", "auto_create_table": "no", - "batch_create_tbl_num": 12, + "batch_create_tbl_num": "asdf", "data_source": "rand", "insert_mode": "taosc", - "insert_rows": 2000, + "insert_rows": 20000, "childtable_limit": 0, "childtable_offset":0, "multi_thread_write_one_tbl": "no", diff --git a/tests/pytest/tools/taosdemoAllTest/insert-interval-speed.json b/tests/pytest/tools/taosdemoAllTest/insert-interval-speed.json index c7c5150a060ff76221025def1d7c31194c52dfed..38975a75a7f1041ffec91d597c9fb28d8a95c7ce 100644 --- a/tests/pytest/tools/taosdemoAllTest/insert-interval-speed.json +++ b/tests/pytest/tools/taosdemoAllTest/insert-interval-speed.json @@ -55,7 +55,7 @@ "sample_format": "csv", "sample_file": "./sample.csv", "tags_file": "", - "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":10}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], + "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":1}, {"type": "BINARY", "len": 16, "count":1}, {"type": "BINARY", "len": 32, "count":6}], "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] }, { @@ -81,8 +81,8 @@ "sample_format": "csv", "sample_file": "./sample.csv", "tags_file": "", - "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":9}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], - "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] + "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":1}, {"type": "BINARY", "len": 16, "count":1}, {"type": "BINARY", "len": 32, "count":1}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":1}] }] }] } diff --git a/tests/pytest/tools/taosdemoAllTest/insert-newdb.json b/tests/pytest/tools/taosdemoAllTest/insert-newdb.json index 72e380a66cb3cfd2b3bade57f000bbebbf29baf4..1a19ea00acb50a0140f55bde51ffe53429a099f0 100644 --- a/tests/pytest/tools/taosdemoAllTest/insert-newdb.json +++ b/tests/pytest/tools/taosdemoAllTest/insert-newdb.json @@ -55,7 +55,7 @@ "sample_format": "csv", "sample_file": "./sample.csv", "tags_file": "", - "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":6}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], + "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":1}, {"type": "BINARY", "len": 16, "count":1}, {"type": "BINARY", "len": 32, "count":1}], "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] }, { diff --git a/tests/pytest/tools/taosdemoAllTest/insertBinaryLenLarge16374AllcolLar16384.json b/tests/pytest/tools/taosdemoAllTest/insertBinaryLenLarge16374AllcolLar16384.json new file mode 100644 index 0000000000000000000000000000000000000000..55be0198916e3737d185deaa231885fbfa607c66 --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/insertBinaryLenLarge16374AllcolLar16384.json @@ -0,0 +1,140 @@ +{ + "filetype": "insert", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "thread_count": 4, + "thread_count_create_tbl": 4, + "result_file": "./insert_res.txt", + "confirm_parameter_prompt": "no", + "insert_interval": 0, + "interlace_rows": 10, + "num_of_records_per_req": 10240000000, + "max_sql_len": 10240000000, + "databases": [{ + "dbinfo": { + "name": "db", + "drop": "yes", + "replica": 1, + "days": 10, + "cache": 50, + "blocks": 8, + "precision": "ms", + "keep": 365, + "minRows": 100, + "maxRows": 4096, + "comp":2, + "walLevel":1, + "cachelast":0, + "quorum":1, + "fsync":3000, + "update": 0 + }, + "super_tables": [{ + "name": "stb0", + "child_table_exists":"no", + "childtable_count": 1, + "childtable_prefix": "stb00_", + "auto_create_table": "no", + "batch_create_tbl_num": 10, + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 1, + "childtable_limit": 0, + "childtable_offset":0, + "multi_thread_write_one_tbl": "no", + "interlace_rows": 0, + "insert_interval":0, + "max_sql_len": 1024000, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 1, + "start_timestamp": "2020-10-01 00:00:00.000", + "sample_format": "csv", + "sample_file": "./sample.csv", + "tags_file": "", + "columns": [{"type": "BINARY", "len": 16374, "count":1}], + "tags": [{"type": "TINYINT", "count":12}, {"type": "BINARY", "len": 16, "count":2}] + }, + { + "name": "stb1", + "child_table_exists":"no", + "childtable_count": 1, + "childtable_prefix": "stb01_", + "auto_create_table": "no", + "batch_create_tbl_num": 12, + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 1, + "childtable_limit": 0, + "childtable_offset":0, + "multi_thread_write_one_tbl": "no", + "interlace_rows": 1000000, + "insert_interval":0, + "max_sql_len": 1024000, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 1, + "start_timestamp": "2020-10-01 00:00:00.000", + "sample_format": "csv", + "sample_file": "./sample.csv", + "tags_file": "", + "columns": [{"type": "BINARY", "len": 16370, "count":1},{"type": "INT"}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] + }, + { + "name": "stb2", + "child_table_exists":"no", + "childtable_count": 1, + "childtable_prefix": "stb01_", + "auto_create_table": "no", + "batch_create_tbl_num": 12, + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 1, + "childtable_limit": 0, + "childtable_offset":0, + "multi_thread_write_one_tbl": "no", + "interlace_rows": 1000000, + "insert_interval":0, + "max_sql_len": 1024000, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 1, + "start_timestamp": "2020-10-01 00:00:00.000", + "sample_format": "csv", + "sample_file": "./sample.csv", + "tags_file": "", + "columns": [{"type": "BINARY", "len": 16375, "count":1},{"type": "INT"}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] + }, + { + "name": "stb3", + "child_table_exists":"no", + "childtable_count": 1, + "childtable_prefix": "stb01_", + "auto_create_table": "no", + "batch_create_tbl_num": 12, + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 1, + "childtable_limit": 0, + "childtable_offset":0, + "multi_thread_write_one_tbl": "no", + "interlace_rows": 1000000, + "insert_interval":0, + "max_sql_len": 1024000, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 1, + "start_timestamp": "2020-10-01 00:00:00.000", + "sample_format": "csv", + "sample_file": "./sample.csv", + "tags_file": "", + "columns": [{"type": "BINARY", "len": 16371, "count":1},{"type": "INT"}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] + }] + }] +} diff --git a/tests/pytest/tools/taosdemoAllTest/insert-illegal-columns.json b/tests/pytest/tools/taosdemoAllTest/insertChildTab0.json similarity index 82% rename from tests/pytest/tools/taosdemoAllTest/insert-illegal-columns.json rename to tests/pytest/tools/taosdemoAllTest/insertChildTab0.json index 53735dc41342cde1cc9cb0a3376be07629464531..1634e1cf065c1979d6e62c97daa56ba2bb3fe1e9 100644 --- a/tests/pytest/tools/taosdemoAllTest/insert-illegal-columns.json +++ b/tests/pytest/tools/taosdemoAllTest/insertChildTab0.json @@ -11,7 +11,7 @@ "confirm_parameter_prompt": "no", "insert_interval": 0, "interlace_rows": 10, - "num_of_records_per_req": 100, + "num_of_records_per_req": 10, "max_sql_len": 10240000000, "databases": [{ "dbinfo": { @@ -35,13 +35,13 @@ "super_tables": [{ "name": "stb0", "child_table_exists":"no", - "childtable_count": 10, + "childtable_count": 0, "childtable_prefix": "stb00_", "auto_create_table": "no", "batch_create_tbl_num": 10, "data_source": "rand", "insert_mode": "taosc", - "insert_rows": 1000, + "insert_rows": 1, "childtable_limit": 0, "childtable_offset":0, "multi_thread_write_one_tbl": "no", @@ -55,19 +55,19 @@ "sample_format": "csv", "sample_file": "./sample.csv", "tags_file": "", - "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":1005}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], - "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":7}] + "columns": [{"type": "BINARY", "len": 1, "count":1}], + "tags": [{"type": "TINYINT", "count":1}, {"type": "BINARY", "len": 16, "count":2}] }, { "name": "stb1", "child_table_exists":"no", - "childtable_count": 20, + "childtable_count": 10, "childtable_prefix": "stb01_", "auto_create_table": "no", "batch_create_tbl_num": 12, "data_source": "rand", "insert_mode": "taosc", - "insert_rows": 2000, + "insert_rows": 2, "childtable_limit": 0, "childtable_offset":0, "multi_thread_write_one_tbl": "no", @@ -81,7 +81,7 @@ "sample_format": "csv", "sample_file": "./sample.csv", "tags_file": "", - "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":10}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], + "columns": [{"type": "BINARY", "len": 1, "count":1}], "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] }] }] diff --git a/tests/pytest/tools/taosdemoAllTest/insert-illegal-columns-lmax.json b/tests/pytest/tools/taosdemoAllTest/insertChildTabLess0.json similarity index 81% rename from tests/pytest/tools/taosdemoAllTest/insert-illegal-columns-lmax.json rename to tests/pytest/tools/taosdemoAllTest/insertChildTabLess0.json index 17050278c8825fb4af9bbf8ed6edcc063a746007..f4e3ec8e9fad638910e644f624d6b4408163c340 100644 --- a/tests/pytest/tools/taosdemoAllTest/insert-illegal-columns-lmax.json +++ b/tests/pytest/tools/taosdemoAllTest/insertChildTabLess0.json @@ -11,7 +11,7 @@ "confirm_parameter_prompt": "no", "insert_interval": 0, "interlace_rows": 10, - "num_of_records_per_req": 100, + "num_of_records_per_req": 10, "max_sql_len": 10240000000, "databases": [{ "dbinfo": { @@ -35,13 +35,13 @@ "super_tables": [{ "name": "stb0", "child_table_exists":"no", - "childtable_count": 10, + "childtable_count": -1, "childtable_prefix": "stb00_", "auto_create_table": "no", "batch_create_tbl_num": 10, "data_source": "rand", "insert_mode": "taosc", - "insert_rows": 1000, + "insert_rows": 1, "childtable_limit": 0, "childtable_offset":0, "multi_thread_write_one_tbl": "no", @@ -55,19 +55,19 @@ "sample_format": "csv", "sample_file": "./sample.csv", "tags_file": "", - "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":1024}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], - "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":7}] + "columns": [{"type": "BINARY", "len": 1, "count":1}], + "tags": [{"type": "TINYINT", "count":1}, {"type": "BINARY", "len": 16, "count":2}] }, { "name": "stb1", "child_table_exists":"no", - "childtable_count": 20, + "childtable_count": 10, "childtable_prefix": "stb01_", "auto_create_table": "no", "batch_create_tbl_num": 12, "data_source": "rand", "insert_mode": "taosc", - "insert_rows": 2000, + "insert_rows": 2, "childtable_limit": 0, "childtable_offset":0, "multi_thread_write_one_tbl": "no", @@ -81,8 +81,8 @@ "sample_format": "csv", "sample_file": "./sample.csv", "tags_file": "", - "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":1004}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], - "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":7}] + "columns": [{"type": "BINARY", "len": 1, "count":1}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] }] }] } diff --git a/tests/pytest/tools/taosdemoAllTest/insertColumnsAndTagNum1024.json b/tests/pytest/tools/taosdemoAllTest/insertColumnsAndTagNum1024.json new file mode 100644 index 0000000000000000000000000000000000000000..42f6ef2f2fe90f7eac23778542475f152794a509 --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/insertColumnsAndTagNum1024.json @@ -0,0 +1,62 @@ +{ + "filetype": "insert", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "thread_count": 4, + "thread_count_create_tbl": 4, + "result_file": "./insert_res.txt", + "confirm_parameter_prompt": "no", + "insert_interval": 0, + "interlace_rows": 0, + "num_of_records_per_req": 1000, + "max_sql_len": 10240000000, + "databases": [{ + "dbinfo": { + "name": "db", + "drop": "yes", + "replica": 1, + "days": 10, + "cache": 50, + "blocks": 8, + "precision": "ms", + "keep": 365, + "minRows": 100, + "maxRows": 4096, + "comp":2, + "walLevel":1, + "cachelast":0, + "quorum":1, + "fsync":3000, + "update": 0 + }, + "super_tables": [{ + "name": "stb0", + "child_table_exists":"no", + "childtable_count": 10, + "childtable_prefix": "stb00_", + "auto_create_table": "no", + "batch_create_tbl_num": 10, + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 1000, + "childtable_limit": 0, + "childtable_offset":0, + "multi_thread_write_one_tbl": "no", + "interlace_rows": 0, + "insert_interval":0, + "max_sql_len": 1024000, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 1, + "start_timestamp": "2020-10-01 00:00:00.000", + "sample_format": "csv", + "sample_file": "./sample.csv", + "tags_file": "", + "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":1004}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":7}] + }] + }] +} diff --git a/tests/pytest/tools/taosdemoAllTest/insertColumnsAndTagNumLarge1024.json b/tests/pytest/tools/taosdemoAllTest/insertColumnsAndTagNumLarge1024.json new file mode 100644 index 0000000000000000000000000000000000000000..42461b2f6fba85093a6a45883608b49277669568 --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/insertColumnsAndTagNumLarge1024.json @@ -0,0 +1,62 @@ +{ + "filetype": "insert", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "thread_count": 4, + "thread_count_create_tbl": 4, + "result_file": "./insert_res.txt", + "confirm_parameter_prompt": "no", + "insert_interval": 0, + "interlace_rows": 10000, + "num_of_records_per_req": 10000, + "max_sql_len": 10240000000, + "databases": [{ + "dbinfo": { + "name": "db", + "drop": "yes", + "replica": 1, + "days": 10, + "cache": 50, + "blocks": 8, + "precision": "ms", + "keep": 365, + "minRows": 100, + "maxRows": 4096, + "comp":2, + "walLevel":1, + "cachelast":0, + "quorum":1, + "fsync":3000, + "update": 0 + }, + "super_tables": [{ + "name": "stb0", + "child_table_exists":"no", + "childtable_count": 10, + "childtable_prefix": "stb00_", + "auto_create_table": "no", + "batch_create_tbl_num": 10, + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 1000, + "childtable_limit": 0, + "childtable_offset":0, + "multi_thread_write_one_tbl": "no", + "interlace_rows": 0, + "insert_interval":0, + "max_sql_len": 1024000, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 1, + "start_timestamp": "2020-10-01 00:00:00.000", + "sample_format": "csv", + "sample_file": "./sample.csv", + "tags_file": "", + "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":1005}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":7}] + }] + }] +} diff --git a/tests/pytest/tools/taosdemoAllTest/insertColumnsNum0.json b/tests/pytest/tools/taosdemoAllTest/insertColumnsNum0.json new file mode 100644 index 0000000000000000000000000000000000000000..fd75f3b43ffa1e5f4c9cb7964ad218d15e0324fc --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/insertColumnsNum0.json @@ -0,0 +1,62 @@ +{ + "filetype": "insert", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "thread_count": 4, + "thread_count_create_tbl": 4, + "result_file": "./insert_res.txt", + "confirm_parameter_prompt": "no", + "insert_interval": 0, + "interlace_rows": 10, + "num_of_records_per_req": 100, + "max_sql_len": 10240000000, + "databases": [{ + "dbinfo": { + "name": "db", + "drop": "yes", + "replica": 1, + "days": 10, + "cache": 50, + "blocks": 8, + "precision": "ms", + "keep": 365, + "minRows": 100, + "maxRows": 4096, + "comp":2, + "walLevel":1, + "cachelast":0, + "quorum":1, + "fsync":3000, + "update": 0 + }, + "super_tables": [{ + "name": "stb0", + "child_table_exists":"no", + "childtable_count": 10, + "childtable_prefix": "stb00_", + "auto_create_table": "no", + "batch_create_tbl_num": 10, + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 1000, + "childtable_limit": 0, + "childtable_offset":0, + "multi_thread_write_one_tbl": "no", + "interlace_rows": 0, + "insert_interval":0, + "max_sql_len": 1024000, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 1, + "start_timestamp": "2020-10-01 00:00:00.000", + "sample_format": "csv", + "sample_file": "./sample.csv", + "tags_file": "", + "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":0}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":7}] + }] + }] +} diff --git a/tests/pytest/tools/taosdemoAllTest/insert-illegal-tags-count129.json b/tests/pytest/tools/taosdemoAllTest/insertNumOfrecordPerReq0.json similarity index 77% rename from tests/pytest/tools/taosdemoAllTest/insert-illegal-tags-count129.json rename to tests/pytest/tools/taosdemoAllTest/insertNumOfrecordPerReq0.json index 115c42b502951007aafa1b9c72de45bfcbb3f9fc..813eb9af0428d8455bda3c1a17ffdd61337cc617 100644 --- a/tests/pytest/tools/taosdemoAllTest/insert-illegal-tags-count129.json +++ b/tests/pytest/tools/taosdemoAllTest/insertNumOfrecordPerReq0.json @@ -11,11 +11,11 @@ "confirm_parameter_prompt": "no", "insert_interval": 0, "interlace_rows": 10, - "num_of_records_per_req": 100, + "num_of_records_per_req": 0, "max_sql_len": 10240000000, "databases": [{ "dbinfo": { - "name": "db1", + "name": "db", "drop": "yes", "replica": 1, "days": 10, @@ -35,13 +35,13 @@ "super_tables": [{ "name": "stb0", "child_table_exists":"no", - "childtable_count": 10, + "childtable_count": 1, "childtable_prefix": "stb00_", "auto_create_table": "no", "batch_create_tbl_num": 10, "data_source": "rand", "insert_mode": "taosc", - "insert_rows": 1000, + "insert_rows": 1, "childtable_limit": 0, "childtable_offset":0, "multi_thread_write_one_tbl": "no", @@ -55,19 +55,19 @@ "sample_format": "csv", "sample_file": "./sample.csv", "tags_file": "", - "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":1}, {"type": "BIGINT", "count":1}, {"type": "float", "count":1}, {"type": "double", "count":1}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], - "tags": [{"type": "TINYINT", "count":127}, {"type": "BINARY", "len": 16, "count":2}] + "columns": [{"type": "BINARY", "len": 1, "count":1}], + "tags": [{"type": "TINYINT", "count":1}, {"type": "BINARY", "len": 16, "count":2}] }, { "name": "stb1", "child_table_exists":"no", - "childtable_count": 20, + "childtable_count": 2, "childtable_prefix": "stb01_", "auto_create_table": "no", "batch_create_tbl_num": 12, "data_source": "rand", "insert_mode": "taosc", - "insert_rows": 2000, + "insert_rows": 2, "childtable_limit": 0, "childtable_offset":0, "multi_thread_write_one_tbl": "no", @@ -81,7 +81,7 @@ "sample_format": "csv", "sample_file": "./sample.csv", "tags_file": "", - "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":10}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], + "columns": [{"type": "BINARY", "len": 1, "count":1}], "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] }] }] diff --git a/tests/pytest/tools/taosdemoAllTest/insertNumOfrecordPerReqless0.json b/tests/pytest/tools/taosdemoAllTest/insertNumOfrecordPerReqless0.json new file mode 100644 index 0000000000000000000000000000000000000000..554115f3974b24746165e42e7309d9b4d3dd4a50 --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/insertNumOfrecordPerReqless0.json @@ -0,0 +1,88 @@ +{ + "filetype": "insert", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "thread_count": 4, + "thread_count_create_tbl": 4, + "result_file": "./insert_res.txt", + "confirm_parameter_prompt": "no", + "insert_interval": 0, + "interlace_rows": 10, + "num_of_records_per_req": -1, + "max_sql_len": 10240000000, + "databases": [{ + "dbinfo": { + "name": "db", + "drop": "yes", + "replica": 1, + "days": 10, + "cache": 50, + "blocks": 8, + "precision": "ms", + "keep": 365, + "minRows": 100, + "maxRows": 4096, + "comp":2, + "walLevel":1, + "cachelast":0, + "quorum":1, + "fsync":3000, + "update": 0 + }, + "super_tables": [{ + "name": "stb0", + "child_table_exists":"no", + "childtable_count": 1, + "childtable_prefix": "stb00_", + "auto_create_table": "no", + "batch_create_tbl_num": 10, + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 1, + "childtable_limit": 0, + "childtable_offset":0, + "multi_thread_write_one_tbl": "no", + "interlace_rows": 0, + "insert_interval":0, + "max_sql_len": 1024000, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 1, + "start_timestamp": "2020-10-01 00:00:00.000", + "sample_format": "csv", + "sample_file": "./sample.csv", + "tags_file": "", + "columns": [{"type": "BINARY", "len": 1, "count":1}], + "tags": [{"type": "TINYINT", "count":1}, {"type": "BINARY", "len": 16, "count":2}] + }, + { + "name": "stb1", + "child_table_exists":"no", + "childtable_count": 2, + "childtable_prefix": "stb01_", + "auto_create_table": "no", + "batch_create_tbl_num": 12, + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 2, + "childtable_limit": 0, + "childtable_offset":0, + "multi_thread_write_one_tbl": "no", + "interlace_rows": 0, + "insert_interval":0, + "max_sql_len": 1024000, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 1, + "start_timestamp": "2020-10-01 00:00:00.000", + "sample_format": "csv", + "sample_file": "./sample.csv", + "tags_file": "", + "columns": [{"type": "BINARY", "len": 1, "count":1}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] + }] + }] +} diff --git a/tests/pytest/tools/taosdemoAllTest/insertSigcolumnsNum1024.json b/tests/pytest/tools/taosdemoAllTest/insertSigcolumnsNum1024.json new file mode 100644 index 0000000000000000000000000000000000000000..7c12a62764ecd129342d916092cf732fe202151f --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/insertSigcolumnsNum1024.json @@ -0,0 +1,62 @@ +{ + "filetype": "insert", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "thread_count": 4, + "thread_count_create_tbl": 4, + "result_file": "./insert_res.txt", + "confirm_parameter_prompt": "no", + "insert_interval": 0, + "interlace_rows": 10, + "num_of_records_per_req": 100, + "max_sql_len": 10240000000, + "databases": [{ + "dbinfo": { + "name": "db", + "drop": "yes", + "replica": 1, + "days": 10, + "cache": 50, + "blocks": 8, + "precision": "ms", + "keep": 365, + "minRows": 100, + "maxRows": 4096, + "comp":2, + "walLevel":1, + "cachelast":0, + "quorum":1, + "fsync":3000, + "update": 0 + }, + "super_tables": [{ + "name": "stb0", + "child_table_exists":"no", + "childtable_count": 10, + "childtable_prefix": "stb00_", + "auto_create_table": "no", + "batch_create_tbl_num": 10, + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 1000, + "childtable_limit": 0, + "childtable_offset":0, + "multi_thread_write_one_tbl": "no", + "interlace_rows": 0, + "insert_interval":0, + "max_sql_len": 1024000, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 1, + "start_timestamp": "2020-10-01 00:00:00.000", + "sample_format": "csv", + "sample_file": "./sample.csv", + "tags_file": "", + "columns": [{"type": "DOUBLE", "count":1024}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":7}] + }] + }] +} diff --git a/tests/pytest/tools/taosdemoAllTest/insertTagsNumLarge128.json b/tests/pytest/tools/taosdemoAllTest/insertTagsNumLarge128.json new file mode 100644 index 0000000000000000000000000000000000000000..5cf8114472e00d5ebc90b5dc762f22f9698f7d76 --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/insertTagsNumLarge128.json @@ -0,0 +1,62 @@ +{ + "filetype": "insert", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "thread_count": 4, + "thread_count_create_tbl": 4, + "result_file": "./insert_res.txt", + "confirm_parameter_prompt": "no", + "insert_interval": 0, + "interlace_rows": 10, + "num_of_records_per_req": 100, + "max_sql_len": 10240000000, + "databases": [{ + "dbinfo": { + "name": "db1", + "drop": "yes", + "replica": 1, + "days": 10, + "cache": 50, + "blocks": 8, + "precision": "ms", + "keep": 365, + "minRows": 100, + "maxRows": 4096, + "comp":2, + "walLevel":1, + "cachelast":0, + "quorum":1, + "fsync":3000, + "update": 0 + }, + "super_tables": [{ + "name": "stb0", + "child_table_exists":"no", + "childtable_count": 10, + "childtable_prefix": "stb00_", + "auto_create_table": "no", + "batch_create_tbl_num": 10, + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 1000, + "childtable_limit": 0, + "childtable_offset":0, + "multi_thread_write_one_tbl": "no", + "interlace_rows": 0, + "insert_interval":0, + "max_sql_len": 1024000, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 1, + "start_timestamp": "2020-10-01 00:00:00.000", + "sample_format": "csv", + "sample_file": "./sample.csv", + "tags_file": "", + "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":1}, {"type": "BIGINT", "count":1}, {"type": "float", "count":1}, {"type": "double", "count":1}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], + "tags": [{"type": "TINYINT", "count":127}, {"type": "BINARY", "len": 16, "count":2}] + }] + }] +} diff --git a/tests/pytest/tools/taosdemoAllTest/insertTimestepMulRowsLargeint16.json b/tests/pytest/tools/taosdemoAllTest/insertTimestepMulRowsLargeint16.json new file mode 100644 index 0000000000000000000000000000000000000000..b563dcc94b3c69256f4b2a754e9244cef7874944 --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/insertTimestepMulRowsLargeint16.json @@ -0,0 +1,65 @@ +{ + "filetype": "insert", + "cfgdir": "/etc/taos", + "host": "localhost", + "port": 6030, + "user": "root", + "password": "taosdata", + "thread_count": 4, + "thread_count_create_tbl": 4, + "result_file": "./insert_res.txt", + "confirm_parameter_prompt": "no", + "insert_interval": 0, + "databases": [ + { + "dbinfo": { + "name": "blf", + "drop": "yes" + }, + "super_tables": [ + { + "name": "p_0_topics", + "child_table_exists": "no", + "childtable_count": 10, + "childtable_prefix": "p_0_topics_", + "auto_create_table": "no", + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 525600, + "multi_thread_write_one_tbl": "no", + "interlace_rows": 1000, + "max_sql_len": 1048576, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 60000, + "start_timestamp": "2019-10-01 00:00:00.000", + "sample_format": "csv", + "sample_file": "./sample.csv", + "tags_file": "", + "columns": [ + { + "type": "INT", + "count": 1 + }, + { + "type": "FLOAT", + "count": 1 + }, + { + "type": "BINARY", + "len": 12, + "count": 1 + } + ], + "tags": [ + { + "type": "BINARY", + "len": 12, + "count": 10 + } + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/tests/pytest/tools/taosdemoAllTest/query-interrupt.json b/tests/pytest/tools/taosdemoAllTest/query-interrupt.json new file mode 100644 index 0000000000000000000000000000000000000000..643cbf09c83f7191620dee32787caa9f5754ad18 --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/query-interrupt.json @@ -0,0 +1,62 @@ +{ + "filetype": "insert", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "thread_count": 4, + "thread_count_create_tbl": 4, + "result_file": "./insert_res.txt", + "confirm_parameter_prompt": "no", + "insert_interval": 0, + "interlace_rows": 100, + "num_of_records_per_req": 1000, + "max_sql_len": 1024000, + "databases": [{ + "dbinfo": { + "name": "db", + "drop": "yes", + "replica": 1, + "days": 10, + "cache": 50, + "blocks": 8, + "precision": "ms", + "keep": 365, + "minRows": 100, + "maxRows": 4096, + "comp":2, + "walLevel":1, + "cachelast":0, + "quorum":1, + "fsync":3000, + "update": 0 + }, + "super_tables": [{ + "name": "stb0", + "child_table_exists":"no", + "childtable_count": 100, + "childtable_prefix": "stb00_", + "auto_create_table": "no", + "batch_create_tbl_num": 20, + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 150000, + "childtable_limit": -1, + "childtable_offset":0, + "multi_thread_write_one_tbl": "no", + "interlace_rows": 1000, + "insert_interval":0, + "max_sql_len": 1024000, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 1, + "start_timestamp": "2020-10-01 00:00:00.000", + "sample_format": "csv", + "sample_file": "./sample.csv", + "tags_file": "", + "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":10}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] + }] + }] +} diff --git a/tests/pytest/tools/taosdemoAllTest/query-interrupt.py b/tests/pytest/tools/taosdemoAllTest/query-interrupt.py new file mode 100644 index 0000000000000000000000000000000000000000..270bfd8b60f559c370eb921cf74fe4f7b82ae06e --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/query-interrupt.py @@ -0,0 +1,88 @@ +################################################################### +# Copyright (c) 2016 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +import sys +import os +import subprocess +import time +from util.log import * +from util.cases import * +from util.sql import * +from util.dnodes import * + + +class TDTestCase: + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + + def getBuildPath(self): + selfPath = os.path.dirname(os.path.realpath(__file__)) + + if ("community" in selfPath): + projPath = selfPath[:selfPath.find("community")] + else: + projPath = selfPath[:selfPath.find("tests")] + + for root, dirs, files in os.walk(projPath): + if ("taosd" in files): + rootRealPath = os.path.dirname(os.path.realpath(root)) + if ("packaging" not in rootRealPath): + buildPath = root[:len(root)-len("/build/bin")] + break + return buildPath + + def run(self): + tdSql.prepare() + buildPath = self.getBuildPath() + if (buildPath == ""): + tdLog.exit("taosd not found!") + else: + tdLog.info("taosd found in %s" % buildPath) + binPath = buildPath+ "/build/bin/" + + # # insert 1000w rows in stb0 + os.system("%staosdemo -f tools/taosdemoAllTest/query-interrupt.json -y " % binPath) + tdSql.execute("use db") + tdSql.query("select count (tbname) from stb0") + tdSql.checkData(0, 0,60) + tdSql.query("select count(*) from stb0") + tdSql.checkData(0, 0, 6000000) + os.system('%staosdemo -f tools/taosdemoAllTest/queryall.json -y & ' % binPath) + time.sleep(2) + query_pid = int(subprocess.getstatusoutput('ps aux|grep "taosdemoAllTest/queryall.json" |grep -v "grep"|awk \'{print $2}\'')[1]) + taosd_cpu_load_1 = float(subprocess.getstatusoutput('top -n 1 -b -p $(ps aux|grep "bin/taosd -c"|grep -v "grep" |awk \'{print $2}\')|awk \'END{print}\' |awk \'{print $9}\'')[1]) + if taosd_cpu_load_1 > 10.0 : + os.system("kill -9 %d" % query_pid) + time.sleep(5) + taosd_cpu_load_2 = float(subprocess.getstatusoutput('top -n 1 -b -p $(ps aux|grep "bin/taosd -c"|grep -v "grep" |awk \'{print $2}\')|awk \'END{print}\' |awk \'{print $9}\'')[1]) + if taosd_cpu_load_2 < 10.0 : + suc_kill = 60 + else: + suc_kill = 10 + print("taosd_cpu_load is higher than 10%") + else: + suc_kill = 20 + print("taosd_cpu_load is still less than 10%") + tdSql.query("select count (tbname) from stb0") + tdSql.checkData(0, 0, "%d" % suc_kill) + os.system("rm -rf querySystemInfo*") + os.system("rm -rf insert_res.txt") + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/tools/taosdemoAllTest/queryQps.json b/tests/pytest/tools/taosdemoAllTest/queryQps.json new file mode 100644 index 0000000000000000000000000000000000000000..67a1cf3eb39c045192b5d35f698e38506777cef2 --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/queryQps.json @@ -0,0 +1,37 @@ +{ + "filetype": "query", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "confirm_parameter_prompt": "no", + "databases": "db", + "query_times": 1, + "specified_table_query": { + "query_interval": 0, + "concurrent": 1, + "sqls": [ + { + "sql": "select last_row(*) from stb00_0", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_99 ", + "result": "./query_res1.txt" + + }] + }, + "super_table_query": { + "stblname": "stb1", + "query_interval":0, + "threads": 1, + "sqls": [ + { + "sql": "select last_row(ts) from xxxx", + "result": "./query_res2.txt" + } + ] + } + } + \ No newline at end of file diff --git a/tests/pytest/tools/taosdemoAllTest/querySpeciMutisql100.json b/tests/pytest/tools/taosdemoAllTest/querySpeciMutisql100.json new file mode 100644 index 0000000000000000000000000000000000000000..4aa1c0b4dd1c8522ebac4b032387c974331f1a5d --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/querySpeciMutisql100.json @@ -0,0 +1,429 @@ +{ + "filetype": "query", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "confirm_parameter_prompt": "no", + "databases": "db", + "query_times": 2, + "specified_table_query": { + "query_interval": 1, + "concurrent": 3, + "sqls": [ + { + "sql": "select last_row(*) from stb00_0", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_1", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_2", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_3", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_4", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_5", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_6", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_7", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_8", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_9", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_10 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_11 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_12 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_13 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_14 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_15 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_16 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_17 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_18 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_19 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_20 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_21 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_22 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_23 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_24 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_25 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_26 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_27 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_28 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_29 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_30 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_31 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_32 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_33 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_34 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_35 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_36 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_37 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_38 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_39 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_40 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_41 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_42 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_43 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_44 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_45 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_46 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_47 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_48 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_49 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_50 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_51 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_52 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_53 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_54 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_55 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_56 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_57 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_58 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_59 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_60", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_61", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_62", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_63", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_64", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_65", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_66", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_67", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_68", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_69", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_70 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_71 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_72 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_73 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_74 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_75 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_76 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_77 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_78 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_79 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_80 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_81 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_82 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_83 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_84 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_85 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_86 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_87 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_88 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_89 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_90 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_91 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_92 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_93 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_94 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_95 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_96 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_97 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_98 ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from stb00_99 ", + "result": "./query_res0.txt" + + }] + }, + "super_table_query": { + "stblname": "stb1", + "query_interval": 1, + "threads": 3, + "sqls": [ + { + "sql": "select last_row(ts) from xxxx", + "result": "./query_res2.txt" + } + ] + } +} + \ No newline at end of file diff --git a/tests/pytest/tools/taosdemoAllTest/querySuperMutisql100.json b/tests/pytest/tools/taosdemoAllTest/querySuperMutisql100.json new file mode 100644 index 0000000000000000000000000000000000000000..c85713c94c3dd6fe5ee55bcc36badcce474a746e --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/querySuperMutisql100.json @@ -0,0 +1,419 @@ +{ + "filetype": "query", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "confirm_parameter_prompt": "no", + "databases": "db", + "query_times": 3, + "super_table_query": { + "stblname": "stb0", + "query_interval": 10000, + "concurrent": 9, + "sqls": [ + { + "sql": "select last_row(*) from xxxx", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select last_row(*) from xxxx ", + "result": "./query_res0.txt" + }, + { + "sql": "select * from xxxx ", + "result": "./query_res0.txt" + + }] + } + } + \ No newline at end of file diff --git a/tests/pytest/tools/taosdemoAllTest/queryall.json b/tests/pytest/tools/taosdemoAllTest/queryall.json new file mode 100644 index 0000000000000000000000000000000000000000..bbc3b9717c6afa8d54d5f48726afe6d4f87be528 --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/queryall.json @@ -0,0 +1,14 @@ +{ + "filetype":"query", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "confirm_parameter_prompt": "no", + "databases": "db", + "specified_table_query": + {"query_interval":1, "concurrent":1, + "sqls": [{"sql": "select * from stb0", "result": ""}] + } +} \ No newline at end of file diff --git a/tests/pytest/tools/taosdemoAllTest/speciQueryInsertdata.json b/tests/pytest/tools/taosdemoAllTest/speciQueryInsertdata.json index ec9cb5a40da9a85928dcc7aea4abb6c96ab36976..79471be2044d3ea7c637b4b1e500cfcc8e6413a9 100644 --- a/tests/pytest/tools/taosdemoAllTest/speciQueryInsertdata.json +++ b/tests/pytest/tools/taosdemoAllTest/speciQueryInsertdata.json @@ -69,7 +69,7 @@ "insert_rows": 200, "childtable_limit": 0, "childtable_offset": 0, - "interlace_rows": 0, + "interlace_rows": 0 , "insert_interval": 0, "max_sql_len": 1024000, "disorder_ratio": 0, diff --git a/tests/pytest/tools/taosdemoAllTest/speciQueryRestful.json b/tests/pytest/tools/taosdemoAllTest/speciQueryRestful.json new file mode 100644 index 0000000000000000000000000000000000000000..98e9b7a4e8ba71ee05c4cf83100504809d0e9c1d --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/speciQueryRestful.json @@ -0,0 +1,38 @@ +{ + "filetype": "query", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "confirm_parameter_prompt": "no", + "databases": "db", + "query_times": 2, + "query_mode": "restful", + "specified_table_query": { + "query_interval": 1, + "concurrent": 3, + "sqls": [ + { + "sql": "select last_row(*) from db.stb0 ", + "result": "./query_res0.txt" + }, + { + "sql": "select count(*) from db.stb00_1", + "result": "./query_res1.txt" + } + ] + }, + "super_table_query": { + "stblname": "stb1", + "query_interval": 1, + "threads": 3, + "sqls": [ + { + "sql": "select last_row(ts) from xxxx", + "result": "./query_res2.txt" + } + ] + } + } + \ No newline at end of file diff --git a/tests/pytest/tools/taosdemoAllTest/speciQuery.json b/tests/pytest/tools/taosdemoAllTest/speciQueryTaosc.json similarity index 96% rename from tests/pytest/tools/taosdemoAllTest/speciQuery.json rename to tests/pytest/tools/taosdemoAllTest/speciQueryTaosc.json index 5e99e80108d434da5b0010394e2aca97d58ea7a7..fece4e71c584ce18b14f70a54dbc7e9abd6130a5 100644 --- a/tests/pytest/tools/taosdemoAllTest/speciQuery.json +++ b/tests/pytest/tools/taosdemoAllTest/speciQueryTaosc.json @@ -8,6 +8,7 @@ "confirm_parameter_prompt": "no", "databases": "db", "query_times": 2, + "query_mode": "taosc", "specified_table_query": { "query_interval": 1, "concurrent": 3, diff --git a/tests/pytest/tools/taosdemoAllTest/sub.json b/tests/pytest/tools/taosdemoAllTest/sub.json new file mode 100644 index 0000000000000000000000000000000000000000..fe3c892a76bcc30678f60127d28ce79bf8682c18 --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/sub.json @@ -0,0 +1,37 @@ +{ + "filetype":"subscribe", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "databases": "db", + "confirm_parameter_prompt": "no", + "specified_table_query": + { + "concurrent":1, + "mode":"sync", + "interval":0, + "restart":"yes", + "keepProgress":"yes", + "sqls": [ + { + "sql": "select * from stb00_0 ;", + "result": "./subscribe_res0.txt" + }] + }, + "super_table_query": + { + "stblname": "stb0", + "threads":1, + "mode":"sync", + "interval":10000, + "restart":"yes", + "keepProgress":"yes", + "sqls": [ + { + "sql": "select * from xxxx where ts > '2021-02-25 11:35:00.000' ;", + "result": "./subscribe_res1.txt" + }] + } + } \ No newline at end of file diff --git a/tests/pytest/tools/taosdemoAllTest/subInsertdata.json b/tests/pytest/tools/taosdemoAllTest/subInsertdata.json new file mode 100644 index 0000000000000000000000000000000000000000..7d14d0ad4b888fc099becb176e84af54bb769f50 --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/subInsertdata.json @@ -0,0 +1,61 @@ +{ + "filetype": "insert", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "thread_count": 4, + "thread_count_create_tbl": 4, + "result_file": "./insert_res.txt", + "confirm_parameter_prompt": "no", + "insert_interval": 0, + "interlace_rows": 0, + "num_of_records_per_req": 3000, + "max_sql_len": 1024000, + "databases": [{ + "dbinfo": { + "name": "db", + "drop": "yes", + "replica": 1, + "days": 10, + "cache": 16, + "blocks": 8, + "precision": "ms", + "keep": 365, + "minRows": 100, + "maxRows": 4096, + "comp":2, + "walLevel":1, + "cachelast":0, + "quorum":1, + "fsync":3000, + "update": 0 + }, + "super_tables": [{ + "name": "stb0", + "child_table_exists":"no", + "childtable_count": 1, + "childtable_prefix": "stb00_", + "auto_create_table": "no", + "batch_create_tbl_num": 10, + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 1, + "childtable_limit": 0, + "childtable_offset": 0, + "interlace_rows": 0, + "insert_interval": 0, + "max_sql_len": 1024000, + "disorder_ratio": 0, + "disorder_range": 0, + "timestamp_step": 1000, + "start_timestamp": "2021-02-25 10:00:00.000", + "sample_format": "csv", + "sample_file": "./sample.csv", + "tags_file": "", + "columns": [{"type": "BINARY", "len":50, "count":1}, {"type": "BINARY", "len": 16, "count":1}, {"type": "INT"}, {"type": "DOUBLE", "count":1}], + "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] + }] + }] +} \ No newline at end of file diff --git a/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJson.py b/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJson.py index 2dd50bf63906f8e74ad9fffc6518d40ac017939a..5ecc4d70b293e131ae5037c3e1bc556f9e933a19 100644 --- a/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJson.py +++ b/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJson.py @@ -153,19 +153,56 @@ class TDTestCase: tdSql.checkData(0, 0, 160) - # insert: let parament in json file is illegal ,i need know how to write exception. + # insert: let parament in json file is illegal, it'll expect error. tdSql.execute("drop database if exists db") - os.system("%staosdemo -f tools/taosdemoAllTest/insert-illegal-columns.json -y " % binPath) + os.system("%staosdemo -f tools/taosdemoAllTest/insertColumnsAndTagNumLarge1024.json -y " % binPath) tdSql.error("use db") - os.system("%staosdemo -f tools/taosdemoAllTest/insert-illegal-columns-lmax.json -y " % binPath) + tdSql.execute("drop database if exists db") + os.system("%staosdemo -f tools/taosdemoAllTest/insertSigcolumnsNum1024.json -y " % binPath) tdSql.error("select * from db.stb0") - os.system("%staosdemo -f tools/taosdemoAllTest/insert-illegal-columns-count-0.json -y " % binPath) - tdSql.execute("use db") + tdSql.execute("drop database if exists db") + os.system("%staosdemo -f tools/taosdemoAllTest/insertColumnsAndTagNum1024.json -y " % binPath) tdSql.query("select count(*) from db.stb0") - tdSql.checkData(0, 0, 10000) + tdSql.checkData(0, 0, 10000) tdSql.execute("drop database if exists db") - os.system("%staosdemo -f tools/taosdemoAllTest/insert-illegal-tags-count129.json -y " % binPath) + os.system("%staosdemo -f tools/taosdemoAllTest/insertColumnsNum0.json -y " % binPath) + tdSql.execute("use db") + tdSql.query("show stables like 'stb0%' ") + tdSql.checkData(0, 2, 11) + tdSql.execute("drop database if exists db") + os.system("%staosdemo -f tools/taosdemoAllTest/insertTagsNumLarge128.json -y " % binPath) tdSql.error("use db1") + tdSql.execute("drop database if exists db") + os.system("%staosdemo -f tools/taosdemoAllTest/insertBinaryLenLarge16374AllcolLar16384.json -y " % binPath) + tdSql.query("select count(*) from db.stb0") + tdSql.checkRows(1) + tdSql.query("select count(*) from db.stb1") + tdSql.checkRows(1) + tdSql.error("select * from db.stb3") + tdSql.error("select * from db.stb2") + tdSql.execute("drop database if exists db") + os.system("%staosdemo -f tools/taosdemoAllTest/insertNumOfrecordPerReq0.json -y " % binPath) + tdSql.error("select count(*) from db.stb0") + tdSql.execute("drop database if exists db") + os.system("%staosdemo -f tools/taosdemoAllTest/insertNumOfrecordPerReqless0.json -y " % binPath) + tdSql.error("use db") + tdSql.execute("drop database if exists db") + os.system("%staosdemo -f tools/taosdemoAllTest/insertChildTab0.json -y " % binPath) + tdSql.error("use db") + tdSql.execute("drop database if exists db") + os.system("%staosdemo -f tools/taosdemoAllTest/insertChildTabLess0.json -y " % binPath) + tdSql.error("use db") + tdSql.execute("drop database if exists blf") + os.system("%staosdemo -f tools/taosdemoAllTest/insertTimestepMulRowsLargeint16.json -y " % binPath) + tdSql.execute("use blf") + tdSql.query("select ts from blf.p_0_topics_7 limit 262800,1") + tdSql.checkData(0, 0, "2020-03-31 12:00:00.000") + tdSql.query("select first(ts) from blf.p_0_topics_2") + tdSql.checkData(0, 0, "2019-10-01 00:00:00") + tdSql.query("select last(ts) from blf.p_0_topics_6 ") + tdSql.checkData(0, 0, "2020-09-29 23:59:00") + + # insert: timestamp and step os.system("%staosdemo -f tools/taosdemoAllTest/insert-timestep.json -y " % binPath) diff --git a/tests/pytest/tools/taosdemoAllTest/taosdemoTestQueryWithJson.py b/tests/pytest/tools/taosdemoAllTest/taosdemoTestQueryWithJson.py index 00b387e398bfba06efaeeaf1072905210b9ae99e..643cad942c6586486640ba125d520b46c93e3465 100644 --- a/tests/pytest/tools/taosdemoAllTest/taosdemoTestQueryWithJson.py +++ b/tests/pytest/tools/taosdemoAllTest/taosdemoTestQueryWithJson.py @@ -49,10 +49,9 @@ class TDTestCase: tdLog.info("taosd found in %s" % buildPath) binPath = buildPath+ "/build/bin/" - # insert: drop and child_table_exists combination test - # insert: using parament "childtable_offset and childtable_limit" to control table'offset point and offset + # query: query specified table and query super table os.system("%staosdemo -f tools/taosdemoAllTest/speciQueryInsertdata.json" % binPath) - os.system("%staosdemo -f tools/taosdemoAllTest/speciQuery.json" % binPath) + os.system("%staosdemo -f tools/taosdemoAllTest/speciQueryTaosc.json" % binPath) os.system("cat query_res0.txt* |sort -u > all_query_res0.txt") os.system("cat query_res1.txt* |sort -u > all_query_res1.txt") os.system("cat query_res2.txt* |sort -u > all_query_res2.txt") @@ -75,9 +74,55 @@ class TDTestCase: timest = d2.strftime("%Y-%m-%d %H:%M:%S.%f") tdSql.query("select last_row(ts) from stb1") tdSql.checkData(0, 0, "%s" % timest) + + # # delete useless files + # os.system("rm -rf ./insert_res.txt") + # os.system("rm -rf tools/taosdemoAllTest/*.py.sql") + # os.system("rm -rf ./querySystemInfo*") + # os.system("rm -rf ./query_res*") + # os.system("rm -rf ./all_query*") + # os.system("rm -rf ./test_query_res0.txt") + + + # # use restful api to query + # os.system("%staosdemo -f tools/taosdemoAllTest/speciQueryInsertdata.json" % binPath) + # os.system("%staosdemo -f tools/taosdemoAllTest/speciQueryRestful.json" % binPath) + # os.system("cat query_res0.txt* |sort -u > all_query_res0.txt") + # os.system("cat query_res1.txt* |sort -u > all_query_res1.txt") + # # os.system("cat query_res2.txt* |sort -u > all_query_res2.txt") + # tdSql.execute("use db") + # tdSql.execute('create table result0 using stb0 tags(121,43,"beijing","beijing","beijing","beijing","beijing")') + # os.system("python3 tools/taosdemoAllTest/convertResFile.py") + # tdSql.execute("insert into result0 file './test_query_res0.txt'") + # tdSql.query("select ts from result0") + # tdSql.checkData(0, 0, "2020-11-01 00:00:00.099000") + # tdSql.query("select count(*) from result0") + # tdSql.checkData(0, 0, 1) + # with open('./all_query_res1.txt','r+') as f1: + # result1 = int(f1.readline()) + # tdSql.query("select count(*) from stb00_1") + # tdSql.checkData(0, 0, "%d" % result1) + + # with open('./all_query_res2.txt','r+') as f2: + # result2 = int(f2.readline()) + # d2 = datetime.fromtimestamp(result2/1000) + # timest = d2.strftime("%Y-%m-%d %H:%M:%S.%f") + # tdSql.query("select last_row(ts) from stb1") + # tdSql.checkData(0, 0, "%s" % timest) + + + + # query times less than or equal to 100 + os.system("%staosdemo -f tools/taosdemoAllTest/querySpeciMutisql100.json" % binPath) + os.system("%staosdemo -f tools/taosdemoAllTest/querySuperMutisql100.json" % binPath) + + # query result print QPS + os.system("%staosdemo -f tools/taosdemoAllTest/queryQps.json" % binPath) + + # delete useless files os.system("rm -rf ./insert_res.txt") - os.system("rm -rf tools/taosdemoAllTest/taosdemoTestQuerytWithJson.py.sql") + os.system("rm -rf tools/taosdemoAllTest/*.py.sql") os.system("rm -rf ./querySystemInfo*") os.system("rm -rf ./query_res*") os.system("rm -rf ./all_query*") diff --git a/tests/pytest/tools/taosdemoAllTest/taosdemoTestSubWithJson.py b/tests/pytest/tools/taosdemoAllTest/taosdemoTestSubWithJson.py new file mode 100644 index 0000000000000000000000000000000000000000..1275b6a8b5d9345147ad36351d4269f0968fff5d --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/taosdemoTestSubWithJson.py @@ -0,0 +1,99 @@ +################################################################### +# Copyright (c) 2016 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +import sys +import os +from util.log import * +from util.cases import * +from util.sql import * +from util.dnodes import * +import time +from datetime import datetime + +class TDTestCase: + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + + def getBuildPath(self): + selfPath = os.path.dirname(os.path.realpath(__file__)) + + if ("community" in selfPath): + projPath = selfPath[:selfPath.find("community")] + else: + projPath = selfPath[:selfPath.find("tests")] + + for root, dirs, files in os.walk(projPath): + if ("taosd" in files): + rootRealPath = os.path.dirname(os.path.realpath(root)) + if ("packaging" not in rootRealPath): + buildPath = root[:len(root)-len("/build/bin")] + break + return buildPath + + def run(self): + buildPath = self.getBuildPath() + if (buildPath == ""): + tdLog.exit("taosd not found!") + else: + tdLog.info("taosd found in %s" % buildPath) + binPath = buildPath+ "/build/bin/" + + # query: query specified table and query super table + # os.system("%staosdemo -f tools/taosdemoAllTest/subInsertdata.json" % binPath) + # os.system("%staosdemo -f tools/taosdemoAllTest/sub.json" % binPath) + # os.system("cat query_res0.txt* |sort -u > all_query_res0.txt") + # os.system("cat query_res1.txt* |sort -u > all_query_res1.txt") + # os.system("cat query_res2.txt* |sort -u > all_query_res2.txt") + # tdSql.execute("use db") + # tdSql.execute('create table result0 using stb0 tags(121,43,"beijing","beijing","beijing","beijing","beijing")') + # os.system("python3 tools/taosdemoAllTest/convertResFile.py") + # tdSql.execute("insert into result0 file './test_query_res0.txt'") + # tdSql.query("select ts from result0") + # tdSql.checkData(0, 0, "2020-11-01 00:00:00.099000") + # tdSql.query("select count(*) from result0") + # tdSql.checkData(0, 0, 1) + # with open('./all_query_res1.txt','r+') as f1: + # result1 = int(f1.readline()) + # tdSql.query("select count(*) from stb00_1") + # tdSql.checkData(0, 0, "%d" % result1) + + # with open('./all_query_res2.txt','r+') as f2: + # result2 = int(f2.readline()) + # d2 = datetime.fromtimestamp(result2/1000) + # timest = d2.strftime("%Y-%m-%d %H:%M:%S.%f") + # tdSql.query("select last_row(ts) from stb1") + # tdSql.checkData(0, 0, "%s" % timest) + + + # # query times less than or equal to 100 + # os.system("%staosdemo -f tools/taosdemoAllTest/QuerySpeciMutisql100.json" % binPath) + # os.system("%staosdemo -f tools/taosdemoAllTest/QuerySuperMutisql100.json" % binPath) + + + + + # delete useless files + # os.system("rm -rf ./insert_res.txt") + # os.system("rm -rf tools/taosdemoAllTest/*.py.sql") + # os.system("rm -rf ./querySystemInfo*") + # os.system("rm -rf ./query_res*") + # os.system("rm -rf ./all_query*") + # os.system("rm -rf ./test_query_res0.txt") + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/util/sql.py b/tests/pytest/util/sql.py index ba9cb4d53d2ee733f4b087d7c4067e816cf8d112..8f62c5932b71049e97375ef6c57ecb563d204844 100644 --- a/tests/pytest/util/sql.py +++ b/tests/pytest/util/sql.py @@ -136,6 +136,11 @@ class TDSql: def checkData(self, row, col, data): self.checkRowCol(row, col) if self.queryResult[row][col] != data: + if self.cursor.istype(col, "TIMESTAMP") and self.queryResult[row][col] == datetime.datetime.fromisoformat(data): + tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" % + (self.sql, row, col, self.queryResult[row][col], data)) + return + if str(self.queryResult[row][col]) == str(data): tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" % (self.sql, row, col, self.queryResult[row][col], data)) diff --git a/tests/script/general/parser/constCol.sim b/tests/script/general/parser/constCol.sim index 716d36e82bcc4d4505426b2c3784de03d2f77c30..66523517be92eb7bddcb248b54522143f27e09d5 100644 --- a/tests/script/general/parser/constCol.sim +++ b/tests/script/general/parser/constCol.sim @@ -358,6 +358,13 @@ if $data00 != 0.300000000 then return -1 endi +print =============================> td-3996 +sql select 'abc' as res from t1 where f1 < 0 +if $rows != 0 then + return -1 +endi + + print ======================udc with normal column group by sql_error select from t1 diff --git a/tests/script/general/parser/union.sim b/tests/script/general/parser/union.sim index d50daea6566af4dd11c51e195e5b5a7f31ee4ad1..0cd3cba84d5843a423440e55db2bb6f1df946e06 100644 --- a/tests/script/general/parser/union.sim +++ b/tests/script/general/parser/union.sim @@ -139,6 +139,34 @@ if $data10 != 1 then return -1 endi +sql select 'ab' as options from union_tb1 limit 1 union all select 'dd' as options from union_tb0 limit 1; +if $rows != 2 then + return -1 +endi + +if $data00 != @ab@ then + return -1 +endi + +if $data10 != @dd@ then + return -1 +endi + + +sql select 'ab' as options from union_tb1 limit 1 union all select '1234567' as options from union_tb0 limit 1; +if $rows != 2 then + return -1 +endi + +if $data00 != @ab@ then + return -1 +endi + +if $data10 != @1234567@ then + return -1 +endi + + # mixed order sql select ts, c1 from union_tb1 order by ts asc limit 10 union all select ts, c1 from union_tb0 order by ts desc limit 2 union all select ts, c1 from union_tb2 order by ts asc limit 10 if $rows != 22 then @@ -421,8 +449,18 @@ if $data10 != @union_db0@ then return -1 endi +sql select 'aaa' as option from union_tb1 where c1 < 0 limit 1 union all select 'bbb' as option from union_tb0 limit 1 +if $rows != 1 then + return -1 +endi + +if $data00 != @bbb@ then + return -1 +endi + + sql_error show tables union all show tables sql_error show stables union all show stables sql_error show databases union all show databases -system sh/exec.sh -n dnode1 -s stop -x SIGINT \ No newline at end of file +system sh/exec.sh -n dnode1 -s stop -x SIGINT