提交 7f76cef5 编写于 作者: S Shengliang Guan

merge from master into develop

...@@ -6,6 +6,8 @@ IF (TD_LINUX) ...@@ -6,6 +6,8 @@ IF (TD_LINUX)
ELSEIF (TD_WINDOWS) ELSEIF (TD_WINDOWS)
IF (TD_POWER) IF (TD_POWER)
SET(CMAKE_INSTALL_PREFIX C:/PowerDB) SET(CMAKE_INSTALL_PREFIX C:/PowerDB)
ELSEIF (TD_PRO)
SET(CMAKE_INSTALL_PREFIX C:/ProDB)
ELSE () ELSE ()
SET(CMAKE_INSTALL_PREFIX C:/TDengine) SET(CMAKE_INSTALL_PREFIX C:/TDengine)
ENDIF () ENDIF ()
...@@ -24,6 +26,8 @@ ELSEIF (TD_WINDOWS) ...@@ -24,6 +26,8 @@ ELSEIF (TD_WINDOWS)
IF (TD_POWER) IF (TD_POWER)
INSTALL(FILES ${EXECUTABLE_OUTPUT_PATH}/power.exe DESTINATION .) INSTALL(FILES ${EXECUTABLE_OUTPUT_PATH}/power.exe DESTINATION .)
ELSEIF (TD_PRO)
INSTALL(FILES ${EXECUTABLE_OUTPUT_PATH}/prodbc.exe DESTINATION .)
ELSE () ELSE ()
INSTALL(FILES ${EXECUTABLE_OUTPUT_PATH}/taos.exe DESTINATION .) INSTALL(FILES ${EXECUTABLE_OUTPUT_PATH}/taos.exe DESTINATION .)
INSTALL(FILES ${EXECUTABLE_OUTPUT_PATH}/taosdemo.exe DESTINATION .) INSTALL(FILES ${EXECUTABLE_OUTPUT_PATH}/taosdemo.exe DESTINATION .)
......
...@@ -4,7 +4,7 @@ PROJECT(TDengine) ...@@ -4,7 +4,7 @@ PROJECT(TDengine)
IF (DEFINED VERNUMBER) IF (DEFINED VERNUMBER)
SET(TD_VER_NUMBER ${VERNUMBER}) SET(TD_VER_NUMBER ${VERNUMBER})
ELSE () ELSE ()
SET(TD_VER_NUMBER "2.1.7.2") SET(TD_VER_NUMBER "2.2.0.5")
ENDIF () ENDIF ()
IF (DEFINED VERCOMPATIBLE) IF (DEFINED VERCOMPATIBLE)
......
文件模式从 100755 更改为 100644
name: tdengine name: tdengine
base: core18 base: core18
version: '2.1.7.2' version: '2.2.0.5'
icon: snap/gui/t-dengine.svg icon: snap/gui/t-dengine.svg
summary: an open-source big data platform designed and optimized for IoT. summary: an open-source big data platform designed and optimized for IoT.
description: | description: |
...@@ -72,7 +72,7 @@ parts: ...@@ -72,7 +72,7 @@ parts:
- usr/bin/taosd - usr/bin/taosd
- usr/bin/taos - usr/bin/taos
- usr/bin/taosdemo - usr/bin/taosdemo
- usr/lib/libtaos.so.2.1.7.2 - usr/lib/libtaos.so.2.2.0.5
- usr/lib/libtaos.so.1 - usr/lib/libtaos.so.1
- usr/lib/libtaos.so - usr/lib/libtaos.so
......
...@@ -58,6 +58,7 @@ typedef struct SRetrieveSupport { ...@@ -58,6 +58,7 @@ typedef struct SRetrieveSupport {
int32_t subqueryIndex; // index of current vnode in vnode list int32_t subqueryIndex; // index of current vnode in vnode list
struct SSqlObj *pParentSql; struct SSqlObj *pParentSql;
tFilePage * localBuffer; // temp buffer, there is a buffer for each vnode to tFilePage * localBuffer; // temp buffer, there is a buffer for each vnode to
uint32_t localBufferSize;
uint32_t numOfRetry; // record the number of retry times uint32_t numOfRetry; // record the number of retry times
} SRetrieveSupport; } SRetrieveSupport;
......
...@@ -52,7 +52,7 @@ int tsInsertInitialCheck(SSqlObj *pSql); ...@@ -52,7 +52,7 @@ int tsInsertInitialCheck(SSqlObj *pSql);
void doCleanupSubqueries(SSqlObj *pSql, int32_t numOfSubs); void doCleanupSubqueries(SSqlObj *pSql, int32_t numOfSubs);
void tscFreeRetrieveSup(SSqlObj *pSql); void tscFreeRetrieveSup(void **param);
......
...@@ -64,7 +64,7 @@ typedef struct STidTags { ...@@ -64,7 +64,7 @@ typedef struct STidTags {
#pragma pack(pop) #pragma pack(pop)
typedef struct SJoinSupporter { typedef struct SJoinSupporter {
SSqlObj* pObj; // parent SqlObj int64_t pObj; // parent SqlObj
int32_t subqueryIndex; // index of sub query int32_t subqueryIndex; // index of sub query
SInterval interval; SInterval interval;
SLimitVal limit; // limit info SLimitVal limit; // limit info
...@@ -386,6 +386,8 @@ void tscRemoveCachedTableMeta(STableMetaInfo* pTableMetaInfo, uint64_t id); ...@@ -386,6 +386,8 @@ void tscRemoveCachedTableMeta(STableMetaInfo* pTableMetaInfo, uint64_t id);
char* cloneCurrentDBName(SSqlObj* pSql); char* cloneCurrentDBName(SSqlObj* pSql);
char* cloneCurrentDBName(SSqlObj* pSql);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
......
...@@ -311,6 +311,7 @@ typedef struct { ...@@ -311,6 +311,7 @@ typedef struct {
char * data; char * data;
TAOS_ROW tsrow; TAOS_ROW tsrow;
TAOS_ROW urow; TAOS_ROW urow;
bool dataConverted;
int32_t* length; // length for each field for current row int32_t* length; // length for each field for current row
char ** buffer; // Buffer used to put multibytes encoded using unicode (wchar_t) char ** buffer; // Buffer used to put multibytes encoded using unicode (wchar_t)
SColumnIndex* pColumnIndex; SColumnIndex* pColumnIndex;
...@@ -364,6 +365,7 @@ typedef struct SSqlObj { ...@@ -364,6 +365,7 @@ typedef struct SSqlObj {
__async_cb_func_t fp; __async_cb_func_t fp;
__async_cb_func_t fetchFp; __async_cb_func_t fetchFp;
void *param; void *param;
_freeSqlSupporter freeParam;
int64_t stime; int64_t stime;
uint32_t queryId; uint32_t queryId;
void * pStream; void * pStream;
...@@ -381,6 +383,7 @@ typedef struct SSqlObj { ...@@ -381,6 +383,7 @@ typedef struct SSqlObj {
SSubqueryState subState; SSubqueryState subState;
struct SSqlObj **pSubs; struct SSqlObj **pSubs;
struct SSqlObj *rootObj;
int64_t metaRid; int64_t metaRid;
int64_t svgroupRid; int64_t svgroupRid;
...@@ -448,7 +451,7 @@ int32_t tscTansformFuncForSTableQuery(SQueryInfo *pQueryInfo); ...@@ -448,7 +451,7 @@ int32_t tscTansformFuncForSTableQuery(SQueryInfo *pQueryInfo);
void tscRestoreFuncForSTableQuery(SQueryInfo *pQueryInfo); void tscRestoreFuncForSTableQuery(SQueryInfo *pQueryInfo);
int32_t tscCreateResPointerInfo(SSqlRes *pRes, SQueryInfo *pQueryInfo); int32_t tscCreateResPointerInfo(SSqlRes *pRes, SQueryInfo *pQueryInfo);
void tscSetResRawPtr(SSqlRes* pRes, SQueryInfo* pQueryInfo); void tscSetResRawPtr(SSqlRes* pRes, SQueryInfo* pQueryInfo, bool converted);
void tscSetResRawPtrRv(SSqlRes* pRes, SQueryInfo* pQueryInfo, SSDataBlock* pBlock, bool convertNchar); void tscSetResRawPtrRv(SSqlRes* pRes, SQueryInfo* pQueryInfo, SSDataBlock* pBlock, bool convertNchar);
void handleDownstreamOperator(SSqlObj** pSqlList, int32_t numOfUpstream, SQueryInfo* px, SSqlObj* pParent); void handleDownstreamOperator(SSqlObj** pSqlList, int32_t numOfUpstream, SQueryInfo* px, SSqlObj* pParent);
......
...@@ -44,3 +44,10 @@ taos_unsubscribe ...@@ -44,3 +44,10 @@ taos_unsubscribe
taos_open_stream taos_open_stream
taos_close_stream taos_close_stream
taos_load_table_info taos_load_table_info
taos_data_type
taos_stmt_set_sub_tbname
taos_stmt_get_param
taos_stmt_bind_param_batch
taos_stmt_bind_single_param_batch
taos_is_null
taos_insert_lines
...@@ -44,6 +44,7 @@ void doAsyncQuery(STscObj* pObj, SSqlObj* pSql, __async_cb_func_t fp, void* para ...@@ -44,6 +44,7 @@ void doAsyncQuery(STscObj* pObj, SSqlObj* pSql, __async_cb_func_t fp, void* para
pSql->maxRetry = TSDB_MAX_REPLICA; pSql->maxRetry = TSDB_MAX_REPLICA;
pSql->fp = fp; pSql->fp = fp;
pSql->fetchFp = fp; pSql->fetchFp = fp;
pSql->rootObj = pSql;
registerSqlObj(pSql); registerSqlObj(pSql);
...@@ -176,6 +177,9 @@ static void tscProcessAsyncRetrieveImpl(void *param, TAOS_RES *tres, int numOfRo ...@@ -176,6 +177,9 @@ static void tscProcessAsyncRetrieveImpl(void *param, TAOS_RES *tres, int numOfRo
} else { } else {
pRes->code = numOfRows; pRes->code = numOfRows;
} }
if (pRes->code == TSDB_CODE_SUCCESS) {
pRes->code = TSDB_CODE_TSC_INVALID_QHANDLE;
}
tscAsyncResultOnError(pSql); tscAsyncResultOnError(pSql);
return; return;
......
...@@ -114,7 +114,7 @@ int tsParseTime(SStrToken *pToken, int64_t *time, char **next, char *error, int1 ...@@ -114,7 +114,7 @@ int tsParseTime(SStrToken *pToken, int64_t *time, char **next, char *error, int1
} }
for (int k = pToken->n; pToken->z[k] != '\0'; k++) { for (int k = pToken->n; pToken->z[k] != '\0'; k++) {
if (pToken->z[k] == ' ' || pToken->z[k] == '\t') continue; if (isspace(pToken->z[k])) continue;
if (pToken->z[k] == ',') { if (pToken->z[k] == ',') {
*next = pTokenEnd; *next = pTokenEnd;
*time = useconds; *time = useconds;
...@@ -1618,7 +1618,8 @@ int tsParseSql(SSqlObj *pSql, bool initial) { ...@@ -1618,7 +1618,8 @@ int tsParseSql(SSqlObj *pSql, bool initial) {
ret = tsParseInsertSql(pSql); ret = tsParseInsertSql(pSql);
if (pSql->parseRetry < 1 && (ret == TSDB_CODE_TSC_SQL_SYNTAX_ERROR || ret == TSDB_CODE_TSC_INVALID_OPERATION)) { if (pSql->parseRetry < 1 && (ret == TSDB_CODE_TSC_SQL_SYNTAX_ERROR || ret == TSDB_CODE_TSC_INVALID_OPERATION)) {
tscDebug("0x%"PRIx64 " parse insert sql statement failed, code:%s, clear meta cache and retry ", pSql->self, tstrerror(ret)); SInsertStatementParam* pInsertParam = &pCmd->insertParam;
tscDebug("0x%"PRIx64 " parse insert sql statement failed, code:%s, msg:%s, clear meta cache and retry ", pSql->self, pInsertParam->msg, tstrerror(ret));
tscResetSqlCmd(pCmd, true, pSql->self); tscResetSqlCmd(pCmd, true, pSql->self);
pSql->parseRetry++; pSql->parseRetry++;
...@@ -1786,6 +1787,7 @@ static void parseFileSendDataBlock(void *param, TAOS_RES *tres, int32_t numOfRow ...@@ -1786,6 +1787,7 @@ static void parseFileSendDataBlock(void *param, TAOS_RES *tres, int32_t numOfRow
pSql->res.numOfRows = 0; pSql->res.numOfRows = 0;
code = doPackSendDataBlock(pSql, pInsertParam, pTableMeta, count, pTableDataBlock); code = doPackSendDataBlock(pSql, pInsertParam, pTableMeta, count, pTableDataBlock);
if (code != TSDB_CODE_SUCCESS) { if (code != TSDB_CODE_SUCCESS) {
pParentSql->res.code = code;
goto _error; goto _error;
} }
......
...@@ -28,7 +28,50 @@ typedef struct { ...@@ -28,7 +28,50 @@ typedef struct {
uint8_t precision; uint8_t precision;
} SSmlSTableSchema; } SSmlSTableSchema;
<<<<<<< HEAD
//================================================================================================= //=================================================================================================
=======
typedef struct {
char* key;
uint8_t type;
int16_t length;
char* value;
uint32_t fieldSchemaIdx;
} TAOS_SML_KV;
typedef struct {
char* stableName;
char* childTableName;
TAOS_SML_KV* tags;
int32_t tagNum;
// first kv must be timestamp
TAOS_SML_KV* fields;
int32_t fieldNum;
uint32_t schemaIdx;
} TAOS_SML_DATA_POINT;
>>>>>>> origin/master
static uint64_t linesSmlHandleId = 0;
uint64_t genLinesSmlId() {
uint64_t id;
<<<<<<< HEAD
do {
id = atomic_add_fetch_64(&linesSmlHandleId, 1);
} while (id == 0);
return id;
}
=======
} SSmlLinesInfo;
//=================================================================================================
>>>>>>> origin/master
static uint64_t linesSmlHandleId = 0; static uint64_t linesSmlHandleId = 0;
...@@ -184,6 +227,40 @@ static int32_t getSmlMd5ChildTableName(TAOS_SML_DATA_POINT* point, char* tableNa ...@@ -184,6 +227,40 @@ static int32_t getSmlMd5ChildTableName(TAOS_SML_DATA_POINT* point, char* tableNa
return 0; return 0;
} }
static int32_t getSmlMd5ChildTableName(TAOS_SML_DATA_POINT* point, char* tableName, int* tableNameLen,
SSmlLinesInfo* info) {
tscDebug("SML:0x%"PRIx64" taos_sml_insert get child table name through md5", info->id);
qsort(point->tags, point->tagNum, sizeof(TAOS_SML_KV), compareSmlColKv);
SStringBuilder sb; memset(&sb, 0, sizeof(sb));
char sTableName[TSDB_TABLE_NAME_LEN] = {0};
strtolower(sTableName, point->stableName);
taosStringBuilderAppendString(&sb, sTableName);
for (int j = 0; j < point->tagNum; ++j) {
taosStringBuilderAppendChar(&sb, ',');
TAOS_SML_KV* tagKv = point->tags + j;
char tagName[TSDB_COL_NAME_LEN] = {0};
strtolower(tagName, tagKv->key);
taosStringBuilderAppendString(&sb, tagName);
taosStringBuilderAppendChar(&sb, '=');
taosStringBuilderAppend(&sb, tagKv->value, tagKv->length);
}
size_t len = 0;
char* keyJoined = taosStringBuilderGetResult(&sb, &len);
MD5_CTX context;
MD5Init(&context);
MD5Update(&context, (uint8_t *)keyJoined, (uint32_t)len);
MD5Final(&context);
*tableNameLen = snprintf(tableName, *tableNameLen,
"t_%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", context.digest[0],
context.digest[1], context.digest[2], context.digest[3], context.digest[4], context.digest[5], context.digest[6],
context.digest[7], context.digest[8], context.digest[9], context.digest[10], context.digest[11],
context.digest[12], context.digest[13], context.digest[14], context.digest[15]);
taosStringBuilderDestroy(&sb);
tscDebug("SML:0x%"PRIx64" child table name: %s", info->id, tableName);
return 0;
}
static int32_t buildDataPointSchemas(TAOS_SML_DATA_POINT* points, int numPoint, SArray* stableSchemas, SSmlLinesInfo* info) { static int32_t buildDataPointSchemas(TAOS_SML_DATA_POINT* points, int numPoint, SArray* stableSchemas, SSmlLinesInfo* info) {
int32_t code = 0; int32_t code = 0;
SHashObj* sname2shema = taosHashInit(32, SHashObj* sname2shema = taosHashInit(32,
...@@ -355,6 +432,10 @@ static int32_t applySchemaAction(TAOS* taos, SSchemaAction* action, SSmlLinesInf ...@@ -355,6 +432,10 @@ static int32_t applySchemaAction(TAOS* taos, SSchemaAction* action, SSmlLinesInf
tscError("SML:0x%" PRIx64 " apply schema action. reset query cache. error: %s", info->id, taos_errstr(res2)); tscError("SML:0x%" PRIx64 " apply schema action. reset query cache. error: %s", info->id, taos_errstr(res2));
} }
taos_free_result(res2); taos_free_result(res2);
<<<<<<< HEAD
=======
taosMsleep(500);
>>>>>>> origin/master
} }
break; break;
} }
...@@ -379,6 +460,10 @@ static int32_t applySchemaAction(TAOS* taos, SSchemaAction* action, SSmlLinesInf ...@@ -379,6 +460,10 @@ static int32_t applySchemaAction(TAOS* taos, SSchemaAction* action, SSmlLinesInf
tscError("SML:0x%" PRIx64 " apply schema action. reset query cache. error: %s", info->id, taos_errstr(res2)); tscError("SML:0x%" PRIx64 " apply schema action. reset query cache. error: %s", info->id, taos_errstr(res2));
} }
taos_free_result(res2); taos_free_result(res2);
<<<<<<< HEAD
=======
taosMsleep(500);
>>>>>>> origin/master
} }
break; break;
} }
...@@ -400,6 +485,10 @@ static int32_t applySchemaAction(TAOS* taos, SSchemaAction* action, SSmlLinesInf ...@@ -400,6 +485,10 @@ static int32_t applySchemaAction(TAOS* taos, SSchemaAction* action, SSmlLinesInf
tscError("SML:0x%" PRIx64 " apply schema action. reset query cache. error: %s", info->id, taos_errstr(res2)); tscError("SML:0x%" PRIx64 " apply schema action. reset query cache. error: %s", info->id, taos_errstr(res2));
} }
taos_free_result(res2); taos_free_result(res2);
<<<<<<< HEAD
=======
taosMsleep(500);
>>>>>>> origin/master
} }
break; break;
} }
...@@ -421,6 +510,10 @@ static int32_t applySchemaAction(TAOS* taos, SSchemaAction* action, SSmlLinesInf ...@@ -421,6 +510,10 @@ static int32_t applySchemaAction(TAOS* taos, SSchemaAction* action, SSmlLinesInf
tscError("SML:0x%" PRIx64 " apply schema action. reset query cache. error: %s", info->id, taos_errstr(res2)); tscError("SML:0x%" PRIx64 " apply schema action. reset query cache. error: %s", info->id, taos_errstr(res2));
} }
taos_free_result(res2); taos_free_result(res2);
<<<<<<< HEAD
=======
taosMsleep(500);
>>>>>>> origin/master
} }
break; break;
} }
...@@ -462,6 +555,10 @@ static int32_t applySchemaAction(TAOS* taos, SSchemaAction* action, SSmlLinesInf ...@@ -462,6 +555,10 @@ static int32_t applySchemaAction(TAOS* taos, SSchemaAction* action, SSmlLinesInf
tscError("SML:0x%" PRIx64 " apply schema action. reset query cache. error: %s", info->id, taos_errstr(res2)); tscError("SML:0x%" PRIx64 " apply schema action. reset query cache. error: %s", info->id, taos_errstr(res2));
} }
taos_free_result(res2); taos_free_result(res2);
<<<<<<< HEAD
=======
taosMsleep(500);
>>>>>>> origin/master
} }
break; break;
} }
...@@ -558,6 +655,7 @@ static int32_t retrieveTableMeta(TAOS* taos, char* tableName, STableMeta** pTabl ...@@ -558,6 +655,7 @@ static int32_t retrieveTableMeta(TAOS* taos, char* tableName, STableMeta** pTabl
registerSqlObj(pSql); registerSqlObj(pSql);
SStrToken tableToken = {.z = tableNameLowerCase, .n = (uint32_t)strlen(tableNameLowerCase), .type = TK_ID}; SStrToken tableToken = {.z = tableNameLowerCase, .n = (uint32_t)strlen(tableNameLowerCase), .type = TK_ID};
tGetToken(tableNameLowerCase, &tableToken.type); tGetToken(tableNameLowerCase, &tableToken.type);
<<<<<<< HEAD
bool dbIncluded = false; bool dbIncluded = false;
// Check if the table name available or not // Check if the table name available or not
...@@ -565,21 +663,40 @@ static int32_t retrieveTableMeta(TAOS* taos, char* tableName, STableMeta** pTabl ...@@ -565,21 +663,40 @@ static int32_t retrieveTableMeta(TAOS* taos, char* tableName, STableMeta** pTabl
code = TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH; code = TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
sprintf(pSql->cmd.payload, "table name is invalid"); sprintf(pSql->cmd.payload, "table name is invalid");
tscFreeRegisteredSqlObj(pSql); tscFreeRegisteredSqlObj(pSql);
=======
// Check if the table name available or not
if (tscValidateName(&tableToken) != TSDB_CODE_SUCCESS) {
code = TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
sprintf(pSql->cmd.payload, "table name is invalid");
taosReleaseRef(tscObjRef, pSql->self);
>>>>>>> origin/master
return code; return code;
} }
SName sname = {0}; SName sname = {0};
<<<<<<< HEAD
if ((code = tscSetTableFullName(&sname, &tableToken, pSql, dbIncluded)) != TSDB_CODE_SUCCESS) { if ((code = tscSetTableFullName(&sname, &tableToken, pSql, dbIncluded)) != TSDB_CODE_SUCCESS) {
tscFreeRegisteredSqlObj(pSql); tscFreeRegisteredSqlObj(pSql);
=======
if ((code = tscSetTableFullName(&sname, &tableToken, pSql)) != TSDB_CODE_SUCCESS) {
taosReleaseRef(tscObjRef, pSql->self);
>>>>>>> origin/master
return code; return code;
} }
char fullTableName[TSDB_TABLE_FNAME_LEN] = {0}; char fullTableName[TSDB_TABLE_FNAME_LEN] = {0};
memset(fullTableName, 0, tListLen(fullTableName)); memset(fullTableName, 0, tListLen(fullTableName));
tNameExtractFullName(&sname, fullTableName); tNameExtractFullName(&sname, fullTableName);
<<<<<<< HEAD
size_t size = 0; size_t size = 0;
taosHashGetCloneExt(UTIL_GET_TABLEMETA(pSql), fullTableName, strlen(fullTableName), NULL, (void**)&tableMeta, &size); taosHashGetCloneExt(UTIL_GET_TABLEMETA(pSql), fullTableName, strlen(fullTableName), NULL, (void**)&tableMeta, &size);
tscFreeRegisteredSqlObj(pSql); tscFreeRegisteredSqlObj(pSql);
=======
taosReleaseRef(tscObjRef, pSql->self);
size_t size = 0;
taosHashGetCloneExt(tscTableMetaMap, fullTableName, strlen(fullTableName), NULL, (void**)&tableMeta, &size);
>>>>>>> origin/master
} }
if (tableMeta != NULL) { if (tableMeta != NULL) {
...@@ -747,41 +864,15 @@ static int32_t creatChildTableIfNotExists(TAOS* taos, const char* cTableName, co ...@@ -747,41 +864,15 @@ static int32_t creatChildTableIfNotExists(TAOS* taos, const char* cTableName, co
return code; return code;
} }
static int32_t insertChildTableBatch(TAOS* taos, char* cTableName, SArray* colsSchema, SArray* rowsBind, SSmlLinesInfo* info) { static int32_t doInsertChildTableWithStmt(TAOS* taos, char* sql, char* cTableName, SArray* batchBind, SSmlLinesInfo* info) {
size_t numCols = taosArrayGetSize(colsSchema);
char* sql = malloc(tsMaxSQLStringLen+1);
if (sql == NULL) {
tscError("malloc sql memory error");
return TSDB_CODE_TSC_OUT_OF_MEMORY;
}
int32_t freeBytes = tsMaxSQLStringLen + 1 ;
sprintf(sql, "insert into ? (");
for (int i = 0; i < numCols; ++i) {
SSchema* colSchema = taosArrayGet(colsSchema, i);
snprintf(sql+strlen(sql), freeBytes-strlen(sql), "%s,", colSchema->name);
}
snprintf(sql + strlen(sql)-1, freeBytes-strlen(sql)+1, ") values (");
for (int i = 0; i < numCols; ++i) {
snprintf(sql+strlen(sql), freeBytes-strlen(sql), "?,");
}
snprintf(sql + strlen(sql)-1, freeBytes-strlen(sql)+1, ")");
sql[strlen(sql)] = '\0';
tscDebug("SML:0x%"PRIx64" insert rows into child table %s. num of rows: %zu", info->id, cTableName, taosArrayGetSize(rowsBind));
int32_t code = 0; int32_t code = 0;
TAOS_STMT* stmt = taos_stmt_init(taos); TAOS_STMT* stmt = taos_stmt_init(taos);
if (stmt == NULL) { if (stmt == NULL) {
tfree(sql);
return TSDB_CODE_TSC_OUT_OF_MEMORY; return TSDB_CODE_TSC_OUT_OF_MEMORY;
} }
code = taos_stmt_prepare(stmt, sql, (unsigned long)strlen(sql)); code = taos_stmt_prepare(stmt, sql, (unsigned long)strlen(sql));
tfree(sql);
if (code != 0) { if (code != 0) {
tscError("SML:0x%"PRIx64" taos_stmt_prepare return %d:%s", info->id, code, tstrerror(code)); tscError("SML:0x%"PRIx64" taos_stmt_prepare return %d:%s", info->id, code, tstrerror(code));
...@@ -799,9 +890,9 @@ static int32_t insertChildTableBatch(TAOS* taos, char* cTableName, SArray* cols ...@@ -799,9 +890,9 @@ static int32_t insertChildTableBatch(TAOS* taos, char* cTableName, SArray* cols
return code; return code;
} }
size_t rows = taosArrayGetSize(rowsBind); size_t rows = taosArrayGetSize(batchBind);
for (int32_t i = 0; i < rows; ++i) { for (int32_t i = 0; i < rows; ++i) {
TAOS_BIND* colsBinds = taosArrayGetP(rowsBind, i); TAOS_BIND* colsBinds = taosArrayGetP(batchBind, i);
code = taos_stmt_bind_param(stmt, colsBinds); code = taos_stmt_bind_param(stmt, colsBinds);
if (code != 0) { if (code != 0) {
tscError("SML:0x%"PRIx64" taos_stmt_bind_param return %d:%s", info->id, code, tstrerror(code)); tscError("SML:0x%"PRIx64" taos_stmt_bind_param return %d:%s", info->id, code, tstrerror(code));
...@@ -823,10 +914,17 @@ static int32_t insertChildTableBatch(TAOS* taos, char* cTableName, SArray* cols ...@@ -823,10 +914,17 @@ static int32_t insertChildTableBatch(TAOS* taos, char* cTableName, SArray* cols
tryAgain = false; tryAgain = false;
if ((code == TSDB_CODE_TDB_INVALID_TABLE_ID if ((code == TSDB_CODE_TDB_INVALID_TABLE_ID
<<<<<<< HEAD
|| code == TSDB_CODE_VND_INVALID_VGROUP_ID || code == TSDB_CODE_VND_INVALID_VGROUP_ID
|| code == TSDB_CODE_TDB_TABLE_RECONFIGURE || code == TSDB_CODE_TDB_TABLE_RECONFIGURE
|| code == TSDB_CODE_APP_NOT_READY || code == TSDB_CODE_APP_NOT_READY
|| code == TSDB_CODE_RPC_NETWORK_UNAVAIL) && try++ < TSDB_MAX_REPLICA) { || code == TSDB_CODE_RPC_NETWORK_UNAVAIL) && try++ < TSDB_MAX_REPLICA) {
=======
|| code == TSDB_CODE_VND_INVALID_VGROUP_ID
|| code == TSDB_CODE_TDB_TABLE_RECONFIGURE
|| code == TSDB_CODE_APP_NOT_READY
|| code == TSDB_CODE_RPC_NETWORK_UNAVAIL) && try++ < TSDB_MAX_REPLICA) {
>>>>>>> origin/master
tryAgain = true; tryAgain = true;
} }
...@@ -838,11 +936,16 @@ static int32_t insertChildTableBatch(TAOS* taos, char* cTableName, SArray* cols ...@@ -838,11 +936,16 @@ static int32_t insertChildTableBatch(TAOS* taos, char* cTableName, SArray* cols
} }
taos_free_result(res2); taos_free_result(res2);
if (tryAgain) { if (tryAgain) {
<<<<<<< HEAD
taosMsleep(50 * (2 << try)); taosMsleep(50 * (2 << try));
=======
taosMsleep(100 * (2 << try));
>>>>>>> origin/master
} }
} }
if (code == TSDB_CODE_APP_NOT_READY || code == TSDB_CODE_RPC_NETWORK_UNAVAIL) { if (code == TSDB_CODE_APP_NOT_READY || code == TSDB_CODE_RPC_NETWORK_UNAVAIL) {
if (tryAgain) { if (tryAgain) {
<<<<<<< HEAD
taosMsleep( 50 * (2 << try)); taosMsleep( 50 * (2 << try));
} }
} }
...@@ -850,6 +953,67 @@ static int32_t insertChildTableBatch(TAOS* taos, char* cTableName, SArray* cols ...@@ -850,6 +953,67 @@ static int32_t insertChildTableBatch(TAOS* taos, char* cTableName, SArray* cols
taos_stmt_close(stmt); taos_stmt_close(stmt);
=======
taosMsleep( 100 * (2 << try));
}
}
} while (tryAgain);
taos_stmt_close(stmt);
return code;
}
static int32_t insertChildTableBatch(TAOS* taos, char* cTableName, SArray* colsSchema, SArray* rowsBind, size_t rowSize, SSmlLinesInfo* info) {
size_t numCols = taosArrayGetSize(colsSchema);
char* sql = malloc(tsMaxSQLStringLen+1);
if (sql == NULL) {
tscError("malloc sql memory error");
return TSDB_CODE_TSC_OUT_OF_MEMORY;
}
int32_t freeBytes = tsMaxSQLStringLen + 1 ;
sprintf(sql, "insert into ? (");
for (int i = 0; i < numCols; ++i) {
SSchema* colSchema = taosArrayGet(colsSchema, i);
snprintf(sql+strlen(sql), freeBytes-strlen(sql), "%s,", colSchema->name);
}
snprintf(sql + strlen(sql)-1, freeBytes-strlen(sql)+1, ") values (");
for (int i = 0; i < numCols; ++i) {
snprintf(sql+strlen(sql), freeBytes-strlen(sql), "?,");
}
snprintf(sql + strlen(sql)-1, freeBytes-strlen(sql)+1, ")");
sql[strlen(sql)] = '\0';
size_t rows = taosArrayGetSize(rowsBind);
size_t maxBatchSize = TSDB_MAX_WAL_SIZE/rowSize * 4 / 5;
size_t batchSize = MIN(maxBatchSize, rows);
tscDebug("SML:0x%"PRIx64" insert rows into child table %s. num of rows: %zu, batch size: %zu",
info->id, cTableName, rows, batchSize);
SArray* batchBind = taosArrayInit(batchSize, POINTER_BYTES);
int32_t code = TSDB_CODE_SUCCESS;
for (int i = 0; i < rows;) {
int j = i;
for (; j < i + batchSize && j<rows; ++j) {
taosArrayPush(batchBind, taosArrayGet(rowsBind, j));
}
if (j > i) {
tscDebug("SML:0x%"PRIx64" insert child table batch from line %d to line %d.", info->id, i, j - 1);
code = doInsertChildTableWithStmt(taos, sql, cTableName, batchBind, info);
if (code != 0) {
taosArrayDestroy(batchBind);
tfree(sql);
return code;
}
taosArrayClear(batchBind);
}
i = j;
}
taosArrayDestroy(batchBind);
tfree(sql);
>>>>>>> origin/master
return code; return code;
} }
...@@ -857,10 +1021,14 @@ static int32_t arrangePointsByChildTableName(TAOS_SML_DATA_POINT* points, int nu ...@@ -857,10 +1021,14 @@ static int32_t arrangePointsByChildTableName(TAOS_SML_DATA_POINT* points, int nu
SHashObj* cname2points, SArray* stableSchemas, SSmlLinesInfo* info) { SHashObj* cname2points, SArray* stableSchemas, SSmlLinesInfo* info) {
for (int32_t i = 0; i < numPoints; ++i) { for (int32_t i = 0; i < numPoints; ++i) {
TAOS_SML_DATA_POINT * point = points + i; TAOS_SML_DATA_POINT * point = points + i;
<<<<<<< HEAD
uintptr_t valPointer = (uintptr_t)point; uintptr_t valPointer = (uintptr_t)point;
size_t* pSchemaIndex = taosHashGet(info->smlDataToSchema, &valPointer, sizeof(uintptr_t)); size_t* pSchemaIndex = taosHashGet(info->smlDataToSchema, &valPointer, sizeof(uintptr_t));
assert(pSchemaIndex != NULL); assert(pSchemaIndex != NULL);
SSmlSTableSchema* stableSchema = taosArrayGet(stableSchemas, *pSchemaIndex); SSmlSTableSchema* stableSchema = taosArrayGet(stableSchemas, *pSchemaIndex);
=======
SSmlSTableSchema* stableSchema = taosArrayGet(stableSchemas, point->schemaIdx);
>>>>>>> origin/master
for (int j = 0; j < point->tagNum; ++j) { for (int j = 0; j < point->tagNum; ++j) {
TAOS_SML_KV* kv = point->tags + j; TAOS_SML_KV* kv = point->tags + j;
...@@ -904,10 +1072,14 @@ static int32_t applyChildTableTags(TAOS* taos, char* cTableName, char* sTableNam ...@@ -904,10 +1072,14 @@ static int32_t applyChildTableTags(TAOS* taos, char* cTableName, char* sTableNam
TAOS_SML_DATA_POINT * pDataPoint = taosArrayGetP(cTablePoints, i); TAOS_SML_DATA_POINT * pDataPoint = taosArrayGetP(cTablePoints, i);
for (int j = 0; j < pDataPoint->tagNum; ++j) { for (int j = 0; j < pDataPoint->tagNum; ++j) {
TAOS_SML_KV* kv = pDataPoint->tags + j; TAOS_SML_KV* kv = pDataPoint->tags + j;
<<<<<<< HEAD
uintptr_t valPointer = (uintptr_t)kv; uintptr_t valPointer = (uintptr_t)kv;
size_t* pFieldSchemaIdx = taosHashGet(info->smlDataToSchema, &valPointer, sizeof(uintptr_t)); size_t* pFieldSchemaIdx = taosHashGet(info->smlDataToSchema, &valPointer, sizeof(uintptr_t));
assert(pFieldSchemaIdx != NULL); assert(pFieldSchemaIdx != NULL);
tagKVs[*pFieldSchemaIdx] = kv; tagKVs[*pFieldSchemaIdx] = kv;
=======
tagKVs[kv->fieldSchemaIdx] = kv;
>>>>>>> origin/master
} }
} }
...@@ -943,13 +1115,14 @@ static int32_t applyChildTableTags(TAOS* taos, char* cTableName, char* sTableNam ...@@ -943,13 +1115,14 @@ static int32_t applyChildTableTags(TAOS* taos, char* cTableName, char* sTableNam
} }
static int32_t applyChildTableFields(TAOS* taos, SSmlSTableSchema* sTableSchema, char* cTableName, static int32_t applyChildTableFields(TAOS* taos, SSmlSTableSchema* sTableSchema, char* cTableName,
SArray* cTablePoints, SSmlLinesInfo* info) { SArray* cTablePoints, size_t rowSize, SSmlLinesInfo* info) {
int32_t code = TSDB_CODE_SUCCESS; int32_t code = TSDB_CODE_SUCCESS;
size_t numCols = taosArrayGetSize(sTableSchema->fields); size_t numCols = taosArrayGetSize(sTableSchema->fields);
size_t rows = taosArrayGetSize(cTablePoints); size_t rows = taosArrayGetSize(cTablePoints);
SArray* rowsBind = taosArrayInit(rows, POINTER_BYTES); SArray* rowsBind = taosArrayInit(rows, POINTER_BYTES);
int isNullColBind = TSDB_TRUE;
for (int i = 0; i < rows; ++i) { for (int i = 0; i < rows; ++i) {
TAOS_SML_DATA_POINT* point = taosArrayGetP(cTablePoints, i); TAOS_SML_DATA_POINT* point = taosArrayGetP(cTablePoints, i);
...@@ -960,7 +1133,6 @@ static int32_t applyChildTableFields(TAOS* taos, SSmlSTableSchema* sTableSchema, ...@@ -960,7 +1133,6 @@ static int32_t applyChildTableFields(TAOS* taos, SSmlSTableSchema* sTableSchema,
return TSDB_CODE_TSC_OUT_OF_MEMORY; return TSDB_CODE_TSC_OUT_OF_MEMORY;
} }
int isNullColBind = TSDB_TRUE;
for (int j = 0; j < numCols; ++j) { for (int j = 0; j < numCols; ++j) {
TAOS_BIND* bind = colBinds + j; TAOS_BIND* bind = colBinds + j;
bind->is_null = &isNullColBind; bind->is_null = &isNullColBind;
...@@ -980,7 +1152,7 @@ static int32_t applyChildTableFields(TAOS* taos, SSmlSTableSchema* sTableSchema, ...@@ -980,7 +1152,7 @@ static int32_t applyChildTableFields(TAOS* taos, SSmlSTableSchema* sTableSchema,
taosArrayPush(rowsBind, &colBinds); taosArrayPush(rowsBind, &colBinds);
} }
code = insertChildTableBatch(taos, cTableName, sTableSchema->fields, rowsBind, info); code = insertChildTableBatch(taos, cTableName, sTableSchema->fields, rowsBind, rowSize, info);
if (code != 0) { if (code != 0) {
tscError("SML:0x%"PRIx64" insert into child table %s failed. error %s", info->id, cTableName, tstrerror(code)); tscError("SML:0x%"PRIx64" insert into child table %s failed. error %s", info->id, cTableName, tstrerror(code));
} }
...@@ -1020,8 +1192,15 @@ static int32_t applyDataPoints(TAOS* taos, TAOS_SML_DATA_POINT* points, int32_t ...@@ -1020,8 +1192,15 @@ static int32_t applyDataPoints(TAOS* taos, TAOS_SML_DATA_POINT* points, int32_t
goto cleanup; goto cleanup;
} }
tscDebug("SML:0x%"PRIx64" apply child table points. child table: %s", info->id, point->childTableName); size_t rowSize = 0;
code = applyChildTableFields(taos, sTableSchema, point->childTableName, cTablePoints, info); size_t numCols = taosArrayGetSize(sTableSchema->fields);
for (int i = 0; i < numCols; ++i) {
SSchema* colSchema = taosArrayGet(sTableSchema->fields, i);
rowSize += colSchema->bytes;
}
tscDebug("SML:0x%"PRIx64" apply child table points. child table: %s, row size: %zu", info->id, point->childTableName, rowSize);
code = applyChildTableFields(taos, sTableSchema, point->childTableName, cTablePoints, rowSize, info);
if (code != 0) { if (code != 0) {
tscError("SML:0x%"PRIx64" Apply child table fields failed. child table %s, error %s", info->id, point->childTableName, tstrerror(code)); tscError("SML:0x%"PRIx64" Apply child table fields failed. child table %s, error %s", info->id, point->childTableName, tstrerror(code));
goto cleanup; goto cleanup;
...@@ -1089,6 +1268,14 @@ int taos_sml_insert(TAOS* taos, TAOS_SML_DATA_POINT* points, int numPoint) { ...@@ -1089,6 +1268,14 @@ int taos_sml_insert(TAOS* taos, TAOS_SML_DATA_POINT* points, int numPoint) {
return code; return code;
} }
int tsc_sml_insert(TAOS* taos, TAOS_SML_DATA_POINT* points, int numPoint) {
SSmlLinesInfo* info = calloc(1, sizeof(SSmlLinesInfo));
info->id = genLinesSmlId();
int code = tscSmlInsert(taos, points, numPoint, info);
free(info);
return code;
}
//========================================================================= //=========================================================================
/* Field Escape charaters /* Field Escape charaters
......
...@@ -86,6 +86,10 @@ typedef struct STscStmt { ...@@ -86,6 +86,10 @@ typedef struct STscStmt {
return _code; \ return _code; \
} while (0) } while (0)
#define STMT_CHECK if (pStmt == NULL || pStmt->pSql == NULL || pStmt->taos == NULL) { \
STMT_RET(TSDB_CODE_TSC_DISCONNECTED); \
}
static int32_t invalidOperationMsg(char* dstBuffer, const char* errMsg) { static int32_t invalidOperationMsg(char* dstBuffer, const char* errMsg) {
return tscInvalidOperationMsg(dstBuffer, errMsg, NULL); return tscInvalidOperationMsg(dstBuffer, errMsg, NULL);
} }
...@@ -155,6 +159,22 @@ static int normalStmtBindParam(STscStmt* stmt, TAOS_BIND* bind) { ...@@ -155,6 +159,22 @@ static int normalStmtBindParam(STscStmt* stmt, TAOS_BIND* bind) {
var->i64 = *(int64_t*)tb->buffer; var->i64 = *(int64_t*)tb->buffer;
break; break;
case TSDB_DATA_TYPE_UTINYINT:
var->u64 = *(uint8_t*)tb->buffer;
break;
case TSDB_DATA_TYPE_USMALLINT:
var->u64 = *(uint16_t*)tb->buffer;
break;
case TSDB_DATA_TYPE_UINT:
var->u64 = *(uint32_t*)tb->buffer;
break;
case TSDB_DATA_TYPE_UBIGINT:
var->u64 = *(uint64_t*)tb->buffer;
break;
case TSDB_DATA_TYPE_FLOAT: case TSDB_DATA_TYPE_FLOAT:
var->dKey = GET_FLOAT_VAL(tb->buffer); var->dKey = GET_FLOAT_VAL(tb->buffer);
break; break;
...@@ -261,9 +281,17 @@ static char* normalStmtBuildSql(STscStmt* stmt) { ...@@ -261,9 +281,17 @@ static char* normalStmtBuildSql(STscStmt* stmt) {
case TSDB_DATA_TYPE_SMALLINT: case TSDB_DATA_TYPE_SMALLINT:
case TSDB_DATA_TYPE_INT: case TSDB_DATA_TYPE_INT:
case TSDB_DATA_TYPE_BIGINT: case TSDB_DATA_TYPE_BIGINT:
case TSDB_DATA_TYPE_TIMESTAMP:
taosStringBuilderAppendInteger(&sb, var->i64); taosStringBuilderAppendInteger(&sb, var->i64);
break; break;
case TSDB_DATA_TYPE_UTINYINT:
case TSDB_DATA_TYPE_USMALLINT:
case TSDB_DATA_TYPE_UINT:
case TSDB_DATA_TYPE_UBIGINT:
taosStringBuilderAppendUnsignedInteger(&sb, var->u64);
break;
case TSDB_DATA_TYPE_FLOAT: case TSDB_DATA_TYPE_FLOAT:
case TSDB_DATA_TYPE_DOUBLE: case TSDB_DATA_TYPE_DOUBLE:
taosStringBuilderAppendDouble(&sb, var->dKey); taosStringBuilderAppendDouble(&sb, var->dKey);
...@@ -1493,6 +1521,7 @@ TAOS_STMT* taos_stmt_init(TAOS* taos) { ...@@ -1493,6 +1521,7 @@ TAOS_STMT* taos_stmt_init(TAOS* taos) {
pSql->maxRetry = TSDB_MAX_REPLICA; pSql->maxRetry = TSDB_MAX_REPLICA;
pStmt->pSql = pSql; pStmt->pSql = pSql;
pStmt->last = STMT_INIT; pStmt->last = STMT_INIT;
registerSqlObj(pSql);
return pStmt; return pStmt;
} }
...@@ -1500,9 +1529,7 @@ TAOS_STMT* taos_stmt_init(TAOS* taos) { ...@@ -1500,9 +1529,7 @@ TAOS_STMT* taos_stmt_init(TAOS* taos) {
int taos_stmt_prepare(TAOS_STMT* stmt, const char* sql, unsigned long length) { int taos_stmt_prepare(TAOS_STMT* stmt, const char* sql, unsigned long length) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
if (stmt == NULL || pStmt->taos == NULL || pStmt->pSql == NULL) { STMT_CHECK
STMT_RET(TSDB_CODE_TSC_DISCONNECTED);
}
if (sql == NULL) { if (sql == NULL) {
tscError("sql is NULL"); tscError("sql is NULL");
...@@ -1579,9 +1606,7 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags ...@@ -1579,9 +1606,7 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
int32_t code = 0; int32_t code = 0;
if (stmt == NULL || pStmt->pSql == NULL || pStmt->taos == NULL) { STMT_CHECK
STMT_RET(TSDB_CODE_TSC_DISCONNECTED);
}
SSqlObj* pSql = pStmt->pSql; SSqlObj* pSql = pStmt->pSql;
SSqlCmd* pCmd = &pSql->cmd; SSqlCmd* pCmd = &pSql->cmd;
...@@ -1757,6 +1782,7 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags ...@@ -1757,6 +1782,7 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags
int taos_stmt_set_sub_tbname(TAOS_STMT* stmt, const char* name) { int taos_stmt_set_sub_tbname(TAOS_STMT* stmt, const char* name) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
STMT_CHECK
pStmt->mtb.subSet = true; pStmt->mtb.subSet = true;
return taos_stmt_set_tbname_tags(stmt, name, NULL); return taos_stmt_set_tbname_tags(stmt, name, NULL);
} }
...@@ -1765,6 +1791,7 @@ int taos_stmt_set_sub_tbname(TAOS_STMT* stmt, const char* name) { ...@@ -1765,6 +1791,7 @@ int taos_stmt_set_sub_tbname(TAOS_STMT* stmt, const char* name) {
int taos_stmt_set_tbname(TAOS_STMT* stmt, const char* name) { int taos_stmt_set_tbname(TAOS_STMT* stmt, const char* name) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
STMT_CHECK
pStmt->mtb.subSet = false; pStmt->mtb.subSet = false;
return taos_stmt_set_tbname_tags(stmt, name, NULL); return taos_stmt_set_tbname_tags(stmt, name, NULL);
} }
...@@ -1772,6 +1799,9 @@ int taos_stmt_set_tbname(TAOS_STMT* stmt, const char* name) { ...@@ -1772,6 +1799,9 @@ int taos_stmt_set_tbname(TAOS_STMT* stmt, const char* name) {
int taos_stmt_close(TAOS_STMT* stmt) { int taos_stmt_close(TAOS_STMT* stmt) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
if (pStmt == NULL || pStmt->taos == NULL) {
STMT_RET(TSDB_CODE_TSC_DISCONNECTED);
}
if (!pStmt->isInsert) { if (!pStmt->isInsert) {
SNormalStmt* normal = &pStmt->normal; SNormalStmt* normal = &pStmt->normal;
if (normal->params != NULL) { if (normal->params != NULL) {
...@@ -1793,8 +1823,9 @@ int taos_stmt_close(TAOS_STMT* stmt) { ...@@ -1793,8 +1823,9 @@ int taos_stmt_close(TAOS_STMT* stmt) {
pStmt->mtb.pTableBlockHashList = tscDestroyBlockHashTable(pStmt->pSql, pStmt->mtb.pTableBlockHashList, rmMeta); pStmt->mtb.pTableBlockHashList = tscDestroyBlockHashTable(pStmt->pSql, pStmt->mtb.pTableBlockHashList, rmMeta);
if (pStmt->pSql){ if (pStmt->pSql){
taosHashCleanup(pStmt->pSql->cmd.insertParam.pTableBlockHashList); taosHashCleanup(pStmt->pSql->cmd.insertParam.pTableBlockHashList);
pStmt->pSql->cmd.insertParam.pTableBlockHashList = NULL;
} }
pStmt->pSql->cmd.insertParam.pTableBlockHashList = NULL;
taosArrayDestroy(pStmt->mtb.tags); taosArrayDestroy(pStmt->mtb.tags);
tfree(pStmt->mtb.sqlstr); tfree(pStmt->mtb.sqlstr);
} }
...@@ -1807,9 +1838,7 @@ int taos_stmt_close(TAOS_STMT* stmt) { ...@@ -1807,9 +1838,7 @@ int taos_stmt_close(TAOS_STMT* stmt) {
int taos_stmt_bind_param(TAOS_STMT* stmt, TAOS_BIND* bind) { int taos_stmt_bind_param(TAOS_STMT* stmt, TAOS_BIND* bind) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
if (stmt == NULL || pStmt->pSql == NULL || pStmt->taos == NULL) { STMT_CHECK
STMT_RET(TSDB_CODE_TSC_DISCONNECTED);
}
if (pStmt->isInsert) { if (pStmt->isInsert) {
if (pStmt->multiTbInsert) { if (pStmt->multiTbInsert) {
...@@ -1838,9 +1867,7 @@ int taos_stmt_bind_param(TAOS_STMT* stmt, TAOS_BIND* bind) { ...@@ -1838,9 +1867,7 @@ int taos_stmt_bind_param(TAOS_STMT* stmt, TAOS_BIND* bind) {
int taos_stmt_bind_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind) { int taos_stmt_bind_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
if (stmt == NULL || pStmt->pSql == NULL || pStmt->taos == NULL) { STMT_CHECK
STMT_RET(TSDB_CODE_TSC_DISCONNECTED);
}
if (bind == NULL || bind->num <= 0 || bind->num > INT16_MAX) { if (bind == NULL || bind->num <= 0 || bind->num > INT16_MAX) {
tscError("0x%"PRIx64" invalid parameter", pStmt->pSql->self); tscError("0x%"PRIx64" invalid parameter", pStmt->pSql->self);
...@@ -1871,9 +1898,7 @@ int taos_stmt_bind_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind) { ...@@ -1871,9 +1898,7 @@ int taos_stmt_bind_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind) {
int taos_stmt_bind_single_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind, int colIdx) { int taos_stmt_bind_single_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind, int colIdx) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
if (stmt == NULL || pStmt->pSql == NULL || pStmt->taos == NULL) { STMT_CHECK
STMT_RET(TSDB_CODE_TSC_DISCONNECTED);
}
if (bind == NULL || bind->num <= 0 || bind->num > INT16_MAX || colIdx < 0) { if (bind == NULL || bind->num <= 0 || bind->num > INT16_MAX || colIdx < 0) {
tscError("0x%"PRIx64" invalid parameter", pStmt->pSql->self); tscError("0x%"PRIx64" invalid parameter", pStmt->pSql->self);
...@@ -1906,9 +1931,7 @@ int taos_stmt_bind_single_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind, in ...@@ -1906,9 +1931,7 @@ int taos_stmt_bind_single_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind, in
int taos_stmt_add_batch(TAOS_STMT* stmt) { int taos_stmt_add_batch(TAOS_STMT* stmt) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
if (stmt == NULL || pStmt->pSql == NULL || pStmt->taos == NULL) { STMT_CHECK
STMT_RET(TSDB_CODE_TSC_DISCONNECTED);
}
if (pStmt->isInsert) { if (pStmt->isInsert) {
if (pStmt->last != STMT_BIND && pStmt->last != STMT_BIND_COL) { if (pStmt->last != STMT_BIND && pStmt->last != STMT_BIND_COL) {
...@@ -1935,9 +1958,7 @@ int taos_stmt_reset(TAOS_STMT* stmt) { ...@@ -1935,9 +1958,7 @@ int taos_stmt_reset(TAOS_STMT* stmt) {
int taos_stmt_execute(TAOS_STMT* stmt) { int taos_stmt_execute(TAOS_STMT* stmt) {
int ret = 0; int ret = 0;
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
if (stmt == NULL || pStmt->pSql == NULL || pStmt->taos == NULL) { STMT_CHECK
STMT_RET(TSDB_CODE_TSC_DISCONNECTED);
}
if (pStmt->isInsert) { if (pStmt->isInsert) {
if (pStmt->last != STMT_ADD_BATCH) { if (pStmt->last != STMT_ADD_BATCH) {
...@@ -1958,11 +1979,7 @@ int taos_stmt_execute(TAOS_STMT* stmt) { ...@@ -1958,11 +1979,7 @@ int taos_stmt_execute(TAOS_STMT* stmt) {
if (sql == NULL) { if (sql == NULL) {
ret = TSDB_CODE_TSC_OUT_OF_MEMORY; ret = TSDB_CODE_TSC_OUT_OF_MEMORY;
} else { } else {
if (pStmt->pSql != NULL) { taosReleaseRef(tscObjRef, pStmt->pSql->self);
tscFreeSqlObj(pStmt->pSql);
pStmt->pSql = NULL;
}
pStmt->pSql = taos_query((TAOS*)pStmt->taos, sql); pStmt->pSql = taos_query((TAOS*)pStmt->taos, sql);
ret = taos_errno(pStmt->pSql); ret = taos_errno(pStmt->pSql);
free(sql); free(sql);
...@@ -1983,7 +2000,6 @@ TAOS_RES *taos_stmt_use_result(TAOS_STMT* stmt) { ...@@ -1983,7 +2000,6 @@ TAOS_RES *taos_stmt_use_result(TAOS_STMT* stmt) {
tscError("result has been used already."); tscError("result has been used already.");
return NULL; return NULL;
} }
TAOS_RES* result = pStmt->pSql; TAOS_RES* result = pStmt->pSql;
pStmt->pSql = NULL; pStmt->pSql = NULL;
return result; return result;
...@@ -1992,9 +2008,7 @@ TAOS_RES *taos_stmt_use_result(TAOS_STMT* stmt) { ...@@ -1992,9 +2008,7 @@ TAOS_RES *taos_stmt_use_result(TAOS_STMT* stmt) {
int taos_stmt_is_insert(TAOS_STMT *stmt, int *insert) { int taos_stmt_is_insert(TAOS_STMT *stmt, int *insert) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
if (stmt == NULL || pStmt->taos == NULL || pStmt->pSql == NULL) { STMT_CHECK
STMT_RET(TSDB_CODE_TSC_DISCONNECTED);
}
if (insert) *insert = pStmt->isInsert; if (insert) *insert = pStmt->isInsert;
...@@ -2004,9 +2018,7 @@ int taos_stmt_is_insert(TAOS_STMT *stmt, int *insert) { ...@@ -2004,9 +2018,7 @@ int taos_stmt_is_insert(TAOS_STMT *stmt, int *insert) {
int taos_stmt_num_params(TAOS_STMT *stmt, int *nums) { int taos_stmt_num_params(TAOS_STMT *stmt, int *nums) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
if (stmt == NULL || pStmt->taos == NULL || pStmt->pSql == NULL) { STMT_CHECK
STMT_RET(TSDB_CODE_TSC_DISCONNECTED);
}
if (pStmt->isInsert) { if (pStmt->isInsert) {
SSqlObj* pSql = pStmt->pSql; SSqlObj* pSql = pStmt->pSql;
...@@ -2023,9 +2035,7 @@ int taos_stmt_num_params(TAOS_STMT *stmt, int *nums) { ...@@ -2023,9 +2035,7 @@ int taos_stmt_num_params(TAOS_STMT *stmt, int *nums) {
int taos_stmt_get_param(TAOS_STMT *stmt, int idx, int *type, int *bytes) { int taos_stmt_get_param(TAOS_STMT *stmt, int idx, int *type, int *bytes) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
if (stmt == NULL || pStmt->taos == NULL || pStmt->pSql == NULL) { STMT_CHECK
STMT_RET(TSDB_CODE_TSC_DISCONNECTED);
}
if (pStmt->isInsert) { if (pStmt->isInsert) {
SSqlCmd* pCmd = &pStmt->pSql->cmd; SSqlCmd* pCmd = &pStmt->pSql->cmd;
......
...@@ -440,6 +440,7 @@ int32_t handleUserDefinedFunc(SSqlObj* pSql, struct SSqlInfo* pInfo) { ...@@ -440,6 +440,7 @@ int32_t handleUserDefinedFunc(SSqlObj* pSql, struct SSqlInfo* pInfo) {
const char *msg2 = "path is too long"; const char *msg2 = "path is too long";
const char *msg3 = "invalid outputtype"; const char *msg3 = "invalid outputtype";
const char *msg4 = "invalid script"; const char *msg4 = "invalid script";
const char *msg5 = "invalid dyn lib";
SSqlCmd *pCmd = &pSql->cmd; SSqlCmd *pCmd = &pSql->cmd;
switch (pInfo->type) { switch (pInfo->type) {
...@@ -475,10 +476,16 @@ int32_t handleUserDefinedFunc(SSqlObj* pSql, struct SSqlInfo* pInfo) { ...@@ -475,10 +476,16 @@ int32_t handleUserDefinedFunc(SSqlObj* pSql, struct SSqlInfo* pInfo) {
if (ret) { if (ret) {
return ret; return ret;
} }
//distinguish *.lua and *.so //validate *.lua or .so
int32_t pathLen = (int32_t)strlen(createInfo->path.z); int32_t pathLen = (int32_t)strlen(createInfo->path.z);
if ((pathLen > 3) && (0 == strncmp(createInfo->path.z + pathLen - 3, "lua", 3)) && !isValidScript(buf, len)) { if ((pathLen > 4) && (0 == strncmp(createInfo->path.z + pathLen - 4, ".lua", 4)) && !isValidScript(buf, len)) {
return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg4); return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg4);
} else if (pathLen > 3 && (0 == strncmp(createInfo->path.z + pathLen - 3, ".so", 3))) {
void *handle = taosLoadDll(createInfo->path.z);
taosCloseDll(handle);
if (handle == NULL) {
return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg5);
}
} }
//TODO CHECK CODE //TODO CHECK CODE
...@@ -2011,6 +2018,7 @@ int32_t validateSelectNodeList(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SArray* pS ...@@ -2011,6 +2018,7 @@ int32_t validateSelectNodeList(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SArray* pS
const char* msg7 = "not support distinct mixed with groupby"; const char* msg7 = "not support distinct mixed with groupby";
const char* msg8 = "not support distinct in nest query"; const char* msg8 = "not support distinct in nest query";
const char* msg9 = "_block_dist not support subquery, only support stable/table"; const char* msg9 = "_block_dist not support subquery, only support stable/table";
const char* msg10 = "not support group by in block func";
// too many result columns not support order by in query // too many result columns not support order by in query
if (taosArrayGetSize(pSelNodeList) > TSDB_MAX_COLUMNS) { if (taosArrayGetSize(pSelNodeList) > TSDB_MAX_COLUMNS) {
...@@ -2045,6 +2053,10 @@ int32_t validateSelectNodeList(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SArray* pS ...@@ -2045,6 +2053,10 @@ int32_t validateSelectNodeList(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SArray* pS
return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg9); return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg9);
} }
if (pItem->pNode->functionId == TSDB_FUNC_BLKINFO && pQueryInfo->groupbyExpr.numOfGroupCols > 0) {
return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg10);
}
SUdfInfo* pUdfInfo = NULL; SUdfInfo* pUdfInfo = NULL;
if (pItem->pNode->functionId < 0) { if (pItem->pNode->functionId < 0) {
pUdfInfo = isValidUdf(pQueryInfo->pUdfInfo, pItem->pNode->Expr.operand.z, pItem->pNode->Expr.operand.n); pUdfInfo = isValidUdf(pQueryInfo->pUdfInfo, pItem->pNode->Expr.operand.z, pItem->pNode->Expr.operand.n);
...@@ -2440,6 +2452,7 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col ...@@ -2440,6 +2452,7 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col
const char* msg10 = "derivative duration should be greater than 1 Second"; const char* msg10 = "derivative duration should be greater than 1 Second";
const char* msg11 = "third parameter in derivative should be 0 or 1"; const char* msg11 = "third parameter in derivative should be 0 or 1";
const char* msg12 = "parameter is out of range [1, 100]"; const char* msg12 = "parameter is out of range [1, 100]";
const char* msg13 = "parameter list required";
switch (functionId) { switch (functionId) {
case TSDB_FUNC_COUNT: { case TSDB_FUNC_COUNT: {
...@@ -2586,6 +2599,7 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col ...@@ -2586,6 +2599,7 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col
SColumnIndex indexTS = {.tableIndex = index.tableIndex, .columnIndex = 0}; SColumnIndex indexTS = {.tableIndex = index.tableIndex, .columnIndex = 0};
SExprInfo* pExpr = tscExprAppend(pQueryInfo, TSDB_FUNC_TS_DUMMY, &indexTS, TSDB_DATA_TYPE_TIMESTAMP, SExprInfo* pExpr = tscExprAppend(pQueryInfo, TSDB_FUNC_TS_DUMMY, &indexTS, TSDB_DATA_TYPE_TIMESTAMP,
TSDB_KEYSIZE, getNewResColId(pCmd), TSDB_KEYSIZE, false); TSDB_KEYSIZE, getNewResColId(pCmd), TSDB_KEYSIZE, false);
tstrncpy(pExpr->base.aliasName, aAggs[TSDB_FUNC_TS_DUMMY].name, sizeof(pExpr->base.aliasName));
SColumnList ids = createColumnList(1, 0, 0); SColumnList ids = createColumnList(1, 0, 0);
insertResultField(pQueryInfo, colIndex, &ids, TSDB_KEYSIZE, TSDB_DATA_TYPE_TIMESTAMP, aAggs[TSDB_FUNC_TS_DUMMY].name, pExpr); insertResultField(pQueryInfo, colIndex, &ids, TSDB_KEYSIZE, TSDB_DATA_TYPE_TIMESTAMP, aAggs[TSDB_FUNC_TS_DUMMY].name, pExpr);
...@@ -3027,6 +3041,10 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col ...@@ -3027,6 +3041,10 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col
return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg9); return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg9);
} }
if (pItem->pNode->Expr.paramList == NULL || taosArrayGetSize(pItem->pNode->Expr.paramList) <= 0) {
return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg13);
}
tSqlExprItem* pParamElem = taosArrayGet(pItem->pNode->Expr.paramList, 0);; tSqlExprItem* pParamElem = taosArrayGet(pItem->pNode->Expr.paramList, 0);;
if (pParamElem->pNode->tokenId != TK_ID) { if (pParamElem->pNode->tokenId != TK_ID) {
return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg2); return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg2);
...@@ -3489,6 +3507,27 @@ static bool groupbyTagsOrNull(SQueryInfo* pQueryInfo) { ...@@ -3489,6 +3507,27 @@ static bool groupbyTagsOrNull(SQueryInfo* pQueryInfo) {
return true; return true;
} }
bool groupbyTbname(SQueryInfo* pQueryInfo) {
if (pQueryInfo->groupbyExpr.columnInfo == NULL ||
taosArrayGetSize(pQueryInfo->groupbyExpr.columnInfo) == 0) {
return false;
}
size_t s = taosArrayGetSize(pQueryInfo->groupbyExpr.columnInfo);
for (int32_t i = 0; i < s; i++) {
SColIndex* colIndex = taosArrayGet(pQueryInfo->groupbyExpr.columnInfo, i);
if (colIndex->colIndex == TSDB_TBNAME_COLUMN_INDEX) {
return true;
}
}
return false;
}
static bool functionCompatibleCheck(SQueryInfo* pQueryInfo, bool joinQuery, bool twQuery) { static bool functionCompatibleCheck(SQueryInfo* pQueryInfo, bool joinQuery, bool twQuery) {
int32_t startIdx = 0; int32_t startIdx = 0;
int32_t aggUdf = 0; int32_t aggUdf = 0;
...@@ -3661,7 +3700,7 @@ int32_t validateGroupbyNode(SQueryInfo* pQueryInfo, SArray* pList, SSqlCmd* pCmd ...@@ -3661,7 +3700,7 @@ int32_t validateGroupbyNode(SQueryInfo* pQueryInfo, SArray* pList, SSqlCmd* pCmd
tscColumnListInsert(pTableMetaInfo->tagColList, index.columnIndex, pTableMeta->id.uid, pSchema); tscColumnListInsert(pTableMetaInfo->tagColList, index.columnIndex, pTableMeta->id.uid, pSchema);
} else { } else {
// check if the column type is valid, here only support the bool/tinyint/smallint/bigint group by // check if the column type is valid, here only support the bool/tinyint/smallint/bigint group by
if (pSchema->type == TSDB_DATA_TYPE_TIMESTAMP || pSchema->type == TSDB_DATA_TYPE_FLOAT || pSchema->type == TSDB_DATA_TYPE_DOUBLE) { if (pSchema->type == TSDB_DATA_TYPE_FLOAT || pSchema->type == TSDB_DATA_TYPE_DOUBLE) {
return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg5); return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg5);
} }
...@@ -7269,6 +7308,35 @@ int32_t doFunctionsCompatibleCheck(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, char* ...@@ -7269,6 +7308,35 @@ int32_t doFunctionsCompatibleCheck(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, char*
} }
} }
int32_t validateFunctionFromUpstream(SQueryInfo* pQueryInfo, char* msg) {
const char* msg1 = "TWA/Diff/Derivative/Irate are not allowed to apply to super table without group by tbname";
int32_t numOfExprs = (int32_t)tscNumOfExprs(pQueryInfo);
size_t upNum = taosArrayGetSize(pQueryInfo->pUpstream);
for (int32_t i = 0; i < numOfExprs; ++i) {
SExprInfo* pExpr = tscExprGet(pQueryInfo, i);
int32_t f = pExpr->base.functionId;
if (f == TSDB_FUNC_DERIVATIVE || f == TSDB_FUNC_TWA || f == TSDB_FUNC_IRATE || f == TSDB_FUNC_DIFF) {
for (int32_t j = 0; j < upNum; ++j) {
SQueryInfo* pUp = taosArrayGetP(pQueryInfo->pUpstream, j);
STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pUp, 0);
bool isSTable = UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo);
if ((!isSTable) || groupbyTbname(pUp)) {
return TSDB_CODE_SUCCESS;
}
}
return invalidOperationMsg(msg, msg1);
}
}
return TSDB_CODE_SUCCESS;
}
int32_t doLocalQueryProcess(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSqlNode) { int32_t doLocalQueryProcess(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSqlNode) {
const char* msg1 = "only one expression allowed"; const char* msg1 = "only one expression allowed";
const char* msg2 = "invalid expression in select clause"; const char* msg2 = "invalid expression in select clause";
...@@ -8020,7 +8088,7 @@ int32_t tscGetExprFilters(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SArray* pSelect ...@@ -8020,7 +8088,7 @@ int32_t tscGetExprFilters(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SArray* pSelect
size_t n = tscNumOfExprs(pQueryInfo); size_t n = tscNumOfExprs(pQueryInfo);
*pExpr = tscExprGet(pQueryInfo, (int32_t)n - 1); *pExpr = tscExprGet(pQueryInfo, (int32_t)n - 1);
SInternalField* pField = taosArrayGet(pQueryInfo->fieldsInfo.internalField, n - 1); SInternalField* pField = taosArrayGetLast(pQueryInfo->fieldsInfo.internalField);
pField->visible = false; pField->visible = false;
return TSDB_CODE_SUCCESS; return TSDB_CODE_SUCCESS;
...@@ -8274,6 +8342,10 @@ static int32_t getTableNameFromSubquery(SSqlNode* pSqlNode, SArray* tableNameLis ...@@ -8274,6 +8342,10 @@ static int32_t getTableNameFromSubquery(SSqlNode* pSqlNode, SArray* tableNameLis
int32_t num = (int32_t)taosArrayGetSize(sub->pSubquery); int32_t num = (int32_t)taosArrayGetSize(sub->pSubquery);
for (int32_t i = 0; i < num; ++i) { for (int32_t i = 0; i < num; ++i) {
SSqlNode* p = taosArrayGetP(sub->pSubquery, i); SSqlNode* p = taosArrayGetP(sub->pSubquery, i);
if (p->from == NULL) {
return TSDB_CODE_TSC_INVALID_OPERATION;
}
if (p->from->type == SQL_NODE_FROM_TABLELIST) { if (p->from->type == SQL_NODE_FROM_TABLELIST) {
int32_t code = getTableNameFromSqlNode(p, tableNameList, msgBuf, pSql); int32_t code = getTableNameFromSqlNode(p, tableNameList, msgBuf, pSql);
if (code != TSDB_CODE_SUCCESS) { if (code != TSDB_CODE_SUCCESS) {
...@@ -8635,6 +8707,7 @@ static int32_t doValidateSubquery(SSqlNode* pSqlNode, int32_t index, SSqlObj* pS ...@@ -8635,6 +8707,7 @@ static int32_t doValidateSubquery(SSqlNode* pSqlNode, int32_t index, SSqlObj* pS
pSub->udfCopy = true; pSub->udfCopy = true;
pSub->pDownstream = pQueryInfo; pSub->pDownstream = pQueryInfo;
taosArrayPush(pQueryInfo->pUpstream, &pSub);
int32_t code = validateSqlNode(pSql, p, pSub); int32_t code = validateSqlNode(pSql, p, pSub);
if (code != TSDB_CODE_SUCCESS) { if (code != TSDB_CODE_SUCCESS) {
return code; return code;
...@@ -8658,8 +8731,6 @@ static int32_t doValidateSubquery(SSqlNode* pSqlNode, int32_t index, SSqlObj* pS ...@@ -8658,8 +8731,6 @@ static int32_t doValidateSubquery(SSqlNode* pSqlNode, int32_t index, SSqlObj* pS
tstrncpy(pTableMetaInfo1->aliasName, subInfo->aliasName.z, subInfo->aliasName.n + 1); tstrncpy(pTableMetaInfo1->aliasName, subInfo->aliasName.z, subInfo->aliasName.n + 1);
} }
taosArrayPush(pQueryInfo->pUpstream, &pSub);
// NOTE: order mix up in subquery not support yet. // NOTE: order mix up in subquery not support yet.
pQueryInfo->order = pSub->order; pQueryInfo->order = pSub->order;
...@@ -8851,6 +8922,10 @@ int32_t validateSqlNode(SSqlObj* pSql, SSqlNode* pSqlNode, SQueryInfo* pQueryInf ...@@ -8851,6 +8922,10 @@ int32_t validateSqlNode(SSqlObj* pSql, SSqlNode* pSqlNode, SQueryInfo* pQueryInf
return code; return code;
} }
if ((code = validateFunctionFromUpstream(pQueryInfo, tscGetErrorMsgPayload(pCmd))) != TSDB_CODE_SUCCESS) {
return code;
}
// updateFunctionInterBuf(pQueryInfo, false); // updateFunctionInterBuf(pQueryInfo, false);
updateLastScanOrderIfNeeded(pQueryInfo); updateLastScanOrderIfNeeded(pQueryInfo);
......
...@@ -423,9 +423,10 @@ void tscProcessMsgFromServer(SRpcMsg *rpcMsg, SRpcEpSet *pEpSet) { ...@@ -423,9 +423,10 @@ void tscProcessMsgFromServer(SRpcMsg *rpcMsg, SRpcEpSet *pEpSet) {
// 1. super table subquery // 1. super table subquery
// 2. nest queries are all not updated the tablemeta and retry parse the sql after cleanup local tablemeta/vgroup id buffer // 2. nest queries are all not updated the tablemeta and retry parse the sql after cleanup local tablemeta/vgroup id buffer
if ((TSDB_QUERY_HAS_TYPE(pQueryInfo->type, (TSDB_QUERY_TYPE_STABLE_SUBQUERY | TSDB_QUERY_TYPE_SUBQUERY | if ((TSDB_QUERY_HAS_TYPE(pQueryInfo->type, (TSDB_QUERY_TYPE_STABLE_SUBQUERY | TSDB_QUERY_TYPE_SUBQUERY |
TSDB_QUERY_TYPE_TAG_FILTER_QUERY)) && TSDB_QUERY_TYPE_TAG_FILTER_QUERY)) &&
!TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_PROJECTION_QUERY)) || !TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_PROJECTION_QUERY)) ||
(TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_NEST_SUBQUERY)) || (TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_STABLE_SUBQUERY) && pQueryInfo->distinct)) { (TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_NEST_SUBQUERY)) || (TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_STABLE_SUBQUERY) && pQueryInfo->distinct)
|| (TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_JOIN_QUERY))) {
// do nothing in case of super table subquery // do nothing in case of super table subquery
} else { } else {
pSql->retry += 1; pSql->retry += 1;
...@@ -1765,7 +1766,7 @@ static int tscLocalResultCommonBuilder(SSqlObj *pSql, int32_t numOfRes) { ...@@ -1765,7 +1766,7 @@ static int tscLocalResultCommonBuilder(SSqlObj *pSql, int32_t numOfRes) {
return pRes->code; return pRes->code;
} }
tscSetResRawPtr(pRes, pQueryInfo); tscSetResRawPtr(pRes, pQueryInfo, pRes->dataConverted);
} else { } else {
tscResetForNextRetrieve(pRes); tscResetForNextRetrieve(pRes);
} }
...@@ -2229,6 +2230,7 @@ int tscProcessRetrieveFuncRsp(SSqlObj* pSql) { ...@@ -2229,6 +2230,7 @@ int tscProcessRetrieveFuncRsp(SSqlObj* pSql) {
parQueryInfo->pUdfInfo = pQueryInfo->pUdfInfo; // assigned to parent sql obj. parQueryInfo->pUdfInfo = pQueryInfo->pUdfInfo; // assigned to parent sql obj.
pQueryInfo->pUdfInfo = NULL; pQueryInfo->pUdfInfo = NULL;
taosReleaseRef(tscObjRef, parent->self);
return TSDB_CODE_SUCCESS; return TSDB_CODE_SUCCESS;
} }
...@@ -2743,7 +2745,7 @@ int tscProcessRetrieveRspFromNode(SSqlObj *pSql) { ...@@ -2743,7 +2745,7 @@ int tscProcessRetrieveRspFromNode(SSqlObj *pSql) {
(tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) && (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) &&
!TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_JOIN_QUERY) && !TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_JOIN_QUERY) &&
!TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_JOIN_SEC_STAGE))) { !TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_JOIN_SEC_STAGE))) {
tscSetResRawPtr(pRes, pQueryInfo); tscSetResRawPtr(pRes, pQueryInfo, pRes->dataConverted);
} }
if (pSql->pSubscription != NULL) { if (pSql->pSubscription != NULL) {
...@@ -2908,7 +2910,7 @@ int32_t getMultiTableMetaFromMnode(SSqlObj *pSql, SArray* pNameList, SArray* pVg ...@@ -2908,7 +2910,7 @@ int32_t getMultiTableMetaFromMnode(SSqlObj *pSql, SArray* pNameList, SArray* pVg
pNew->self, numOfTable, numOfVgroupList, numOfUdf, pNew->cmd.payloadLen); pNew->self, numOfTable, numOfVgroupList, numOfUdf, pNew->cmd.payloadLen);
pNew->fp = fp; pNew->fp = fp;
pNew->param = (void *)pSql->self; pNew->param = (void *)pSql->rootObj->self;
tscDebug("0x%"PRIx64" metaRid from 0x%" PRIx64 " to 0x%" PRIx64 , pSql->self, pSql->metaRid, pNew->self); tscDebug("0x%"PRIx64" metaRid from 0x%" PRIx64 " to 0x%" PRIx64 , pSql->self, pSql->metaRid, pNew->self);
...@@ -2928,6 +2930,7 @@ int32_t tscGetTableMetaImpl(SSqlObj* pSql, STableMetaInfo *pTableMetaInfo, bool ...@@ -2928,6 +2930,7 @@ int32_t tscGetTableMetaImpl(SSqlObj* pSql, STableMetaInfo *pTableMetaInfo, bool
tNameExtractFullName(&pTableMetaInfo->name, name); tNameExtractFullName(&pTableMetaInfo->name, name);
size_t len = strlen(name); size_t len = strlen(name);
// just make runtime happy // just make runtime happy
if (pTableMetaInfo->tableMetaCapacity != 0 && pTableMetaInfo->pTableMeta != NULL) { if (pTableMetaInfo->tableMetaCapacity != 0 && pTableMetaInfo->pTableMeta != NULL) {
memset(pTableMetaInfo->pTableMeta, 0, pTableMetaInfo->tableMetaCapacity); memset(pTableMetaInfo->pTableMeta, 0, pTableMetaInfo->tableMetaCapacity);
...@@ -2935,6 +2938,7 @@ int32_t tscGetTableMetaImpl(SSqlObj* pSql, STableMetaInfo *pTableMetaInfo, bool ...@@ -2935,6 +2938,7 @@ int32_t tscGetTableMetaImpl(SSqlObj* pSql, STableMetaInfo *pTableMetaInfo, bool
if (NULL == taosHashGetCloneExt(UTIL_GET_TABLEMETA(pSql), name, len, NULL, (void **)&(pTableMetaInfo->pTableMeta), &pTableMetaInfo->tableMetaCapacity)) { if (NULL == taosHashGetCloneExt(UTIL_GET_TABLEMETA(pSql), name, len, NULL, (void **)&(pTableMetaInfo->pTableMeta), &pTableMetaInfo->tableMetaCapacity)) {
tfree(pTableMetaInfo->pTableMeta); tfree(pTableMetaInfo->pTableMeta);
pTableMetaInfo->tableMetaCapacity = 0;
} }
STableMeta* pMeta = pTableMetaInfo->pTableMeta; STableMeta* pMeta = pTableMetaInfo->pTableMeta;
...@@ -3056,7 +3060,13 @@ int tscRenewTableMeta(SSqlObj *pSql, int32_t tableIndex) { ...@@ -3056,7 +3060,13 @@ int tscRenewTableMeta(SSqlObj *pSql, int32_t tableIndex) {
// remove stored tableMeta info in hash table // remove stored tableMeta info in hash table
tscResetSqlCmd(pCmd, true, pSql->self); tscResetSqlCmd(pCmd, true, pSql->self);
SArray* pNameList = taosArrayInit(1, POINTER_BYTES); SSqlCmd* pCmd2 = &pSql->rootObj->cmd;
pCmd2->pTableMetaMap = tscCleanupTableMetaMap(pCmd2->pTableMetaMap);
pCmd2->pTableMetaMap = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
pSql->rootObj->retryReason = pSql->retryReason;
SArray* pNameList = taosArrayInit(1, POINTER_BYTES);
SArray* vgroupList = taosArrayInit(1, POINTER_BYTES); SArray* vgroupList = taosArrayInit(1, POINTER_BYTES);
char* n = strdup(name); char* n = strdup(name);
......
...@@ -880,6 +880,7 @@ int taos_validate_sql(TAOS *taos, const char *sql) { ...@@ -880,6 +880,7 @@ int taos_validate_sql(TAOS *taos, const char *sql) {
pSql->pTscObj = taos; pSql->pTscObj = taos;
pSql->signature = pSql; pSql->signature = pSql;
pSql->rootObj = pSql;
SSqlCmd *pCmd = &pSql->cmd; SSqlCmd *pCmd = &pSql->cmd;
pCmd->resColumnId = TSDB_RES_COL_ID; pCmd->resColumnId = TSDB_RES_COL_ID;
...@@ -988,6 +989,7 @@ int taos_load_table_info(TAOS *taos, const char *tableNameList) { ...@@ -988,6 +989,7 @@ int taos_load_table_info(TAOS *taos, const char *tableNameList) {
pSql->pTscObj = taos; pSql->pTscObj = taos;
pSql->signature = pSql; pSql->signature = pSql;
pSql->rootObj = pSql;
int32_t code = (uint8_t) tscTransferTableNameList(pSql, str, length, plist); int32_t code = (uint8_t) tscTransferTableNameList(pSql, str, length, plist);
free(str); free(str);
......
...@@ -682,6 +682,7 @@ TAOS_STREAM *taos_open_stream_withname(TAOS *taos, const char* dstTable, const c ...@@ -682,6 +682,7 @@ TAOS_STREAM *taos_open_stream_withname(TAOS *taos, const char* dstTable, const c
pSql->signature = pSql; pSql->signature = pSql;
pSql->pTscObj = pObj; pSql->pTscObj = pObj;
pSql->rootObj = pSql;
SSqlCmd *pCmd = &pSql->cmd; SSqlCmd *pCmd = &pSql->cmd;
SSqlRes *pRes = &pSql->res; SSqlRes *pRes = &pSql->res;
......
...@@ -127,6 +127,7 @@ static SSub* tscCreateSubscription(STscObj* pObj, const char* topic, const char* ...@@ -127,6 +127,7 @@ static SSub* tscCreateSubscription(STscObj* pObj, const char* topic, const char*
pSql->signature = pSql; pSql->signature = pSql;
pSql->pTscObj = pObj; pSql->pTscObj = pObj;
pSql->pSubscription = pSub; pSql->pSubscription = pSub;
pSql->rootObj = pSql;
pSub->pSql = pSql; pSub->pSql = pSql;
SSqlCmd* pCmd = &pSql->cmd; SSqlCmd* pCmd = &pSql->cmd;
......
此差异已折叠。
...@@ -29,6 +29,7 @@ ...@@ -29,6 +29,7 @@
#include "tsclient.h" #include "tsclient.h"
#include "ttimer.h" #include "ttimer.h"
#include "ttokendef.h" #include "ttokendef.h"
#include "httpInt.h"
#ifdef HTTP_EMBEDDED #ifdef HTTP_EMBEDDED
#include "httpInt.h" #include "httpInt.h"
...@@ -64,6 +65,21 @@ int32_t converToStr(char *str, int type, void *buf, int32_t bufSize, int32_t *le ...@@ -64,6 +65,21 @@ int32_t converToStr(char *str, int type, void *buf, int32_t bufSize, int32_t *le
case TSDB_DATA_TYPE_TIMESTAMP: case TSDB_DATA_TYPE_TIMESTAMP:
n = sprintf(str, "%" PRId64, *(int64_t*)buf); n = sprintf(str, "%" PRId64, *(int64_t*)buf);
break; break;
case TSDB_DATA_TYPE_UTINYINT:
n = sprintf(str, "%d", *(uint8_t*)buf);
break;
case TSDB_DATA_TYPE_USMALLINT:
n = sprintf(str, "%d", *(uint16_t*)buf);
break;
case TSDB_DATA_TYPE_UINT:
n = sprintf(str, "%d", *(uint32_t*)buf);
break;
case TSDB_DATA_TYPE_UBIGINT:
n = sprintf(str, "%" PRId64, *(uint64_t*)buf);
break;
case TSDB_DATA_TYPE_FLOAT: case TSDB_DATA_TYPE_FLOAT:
n = sprintf(str, "%e", GET_FLOAT_VAL(buf)); n = sprintf(str, "%e", GET_FLOAT_VAL(buf));
...@@ -739,9 +755,13 @@ static void setResRawPtrImpl(SSqlRes* pRes, SInternalField* pInfo, int32_t i, bo ...@@ -739,9 +755,13 @@ static void setResRawPtrImpl(SSqlRes* pRes, SInternalField* pInfo, int32_t i, bo
memcpy(pRes->urow[i], pRes->buffer[i], pInfo->field.bytes * pRes->numOfRows); memcpy(pRes->urow[i], pRes->buffer[i], pInfo->field.bytes * pRes->numOfRows);
} }
if (convertNchar) {
pRes->dataConverted = true;
}
} }
void tscSetResRawPtr(SSqlRes* pRes, SQueryInfo* pQueryInfo) { void tscSetResRawPtr(SSqlRes* pRes, SQueryInfo* pQueryInfo, bool converted) {
assert(pRes->numOfCols > 0); assert(pRes->numOfCols > 0);
if (pRes->numOfRows == 0) { if (pRes->numOfRows == 0) {
return; return;
...@@ -754,7 +774,7 @@ void tscSetResRawPtr(SSqlRes* pRes, SQueryInfo* pQueryInfo) { ...@@ -754,7 +774,7 @@ void tscSetResRawPtr(SSqlRes* pRes, SQueryInfo* pQueryInfo) {
pRes->length[i] = pInfo->field.bytes; pRes->length[i] = pInfo->field.bytes;
offset += pInfo->field.bytes; offset += pInfo->field.bytes;
setResRawPtrImpl(pRes, pInfo, i, true); setResRawPtrImpl(pRes, pInfo, i, converted ? false : true);
} }
} }
...@@ -1554,6 +1574,8 @@ void tscFreeSqlObj(SSqlObj* pSql) { ...@@ -1554,6 +1574,8 @@ void tscFreeSqlObj(SSqlObj* pSql) {
return; return;
} }
int64_t sid = pSql->self;
tscDebug("0x%"PRIx64" start to free sqlObj", pSql->self); tscDebug("0x%"PRIx64" start to free sqlObj", pSql->self);
pSql->res.code = TSDB_CODE_TSC_QUERY_CANCELLED; pSql->res.code = TSDB_CODE_TSC_QUERY_CANCELLED;
...@@ -1585,6 +1607,8 @@ void tscFreeSqlObj(SSqlObj* pSql) { ...@@ -1585,6 +1607,8 @@ void tscFreeSqlObj(SSqlObj* pSql) {
tfree(pCmd->payload); tfree(pCmd->payload);
pCmd->allocSize = 0; pCmd->allocSize = 0;
tscDebug("0x%"PRIx64" addr:%p free completed", sid, pSql);
tsem_destroy(&pSql->rspSem); tsem_destroy(&pSql->rspSem);
memset(pSql, 0, sizeof(*pSql)); memset(pSql, 0, sizeof(*pSql));
free(pSql); free(pSql);
...@@ -3613,6 +3637,7 @@ void tscResetForNextRetrieve(SSqlRes* pRes) { ...@@ -3613,6 +3637,7 @@ void tscResetForNextRetrieve(SSqlRes* pRes) {
pRes->row = 0; pRes->row = 0;
pRes->numOfRows = 0; pRes->numOfRows = 0;
pRes->dataConverted = false;
} }
void tscInitResForMerge(SSqlRes* pRes) { void tscInitResForMerge(SSqlRes* pRes) {
...@@ -3642,6 +3667,7 @@ SSqlObj* createSimpleSubObj(SSqlObj* pSql, __async_cb_func_t fp, void* param, in ...@@ -3642,6 +3667,7 @@ SSqlObj* createSimpleSubObj(SSqlObj* pSql, __async_cb_func_t fp, void* param, in
pNew->pTscObj = pSql->pTscObj; pNew->pTscObj = pSql->pTscObj;
pNew->signature = pNew; pNew->signature = pNew;
pNew->rootObj = pSql->rootObj;
SSqlCmd* pCmd = &pNew->cmd; SSqlCmd* pCmd = &pNew->cmd;
pCmd->command = cmd; pCmd->command = cmd;
...@@ -3722,7 +3748,8 @@ SSqlObj* createSubqueryObj(SSqlObj* pSql, int16_t tableIndex, __async_cb_func_t ...@@ -3722,7 +3748,8 @@ SSqlObj* createSubqueryObj(SSqlObj* pSql, int16_t tableIndex, __async_cb_func_t
pNew->pTscObj = pSql->pTscObj; pNew->pTscObj = pSql->pTscObj;
pNew->signature = pNew; pNew->signature = pNew;
pNew->sqlstr = strdup(pSql->sqlstr); pNew->sqlstr = strdup(pSql->sqlstr);
pNew->rootObj = pSql->rootObj;
tsem_init(&pNew->rspSem, 0, 0); tsem_init(&pNew->rspSem, 0, 0);
SSqlCmd* pnCmd = &pNew->cmd; SSqlCmd* pnCmd = &pNew->cmd;
...@@ -3992,7 +4019,7 @@ static void tscSubqueryCompleteCallback(void* param, TAOS_RES* tres, int code) { ...@@ -3992,7 +4019,7 @@ static void tscSubqueryCompleteCallback(void* param, TAOS_RES* tres, int code) {
int32_t index = ps->subqueryIndex; int32_t index = ps->subqueryIndex;
bool ret = subAndCheckDone(pSql, pParentSql, index); bool ret = subAndCheckDone(pSql, pParentSql, index);
tscFreeRetrieveSup(pSql); tscFreeRetrieveSup(&pSql->param);
if (!ret) { if (!ret) {
tscDebug("0x%"PRIx64" sub:0x%"PRIx64" orderOfSub:%d completed, not all subquery finished", pParentSql->self, pSql->self, index); tscDebug("0x%"PRIx64" sub:0x%"PRIx64" orderOfSub:%d completed, not all subquery finished", pParentSql->self, pSql->self, index);
...@@ -4011,23 +4038,26 @@ static void tscSubqueryCompleteCallback(void* param, TAOS_RES* tres, int code) { ...@@ -4011,23 +4038,26 @@ static void tscSubqueryCompleteCallback(void* param, TAOS_RES* tres, int code) {
tscFreeSubobj(pParentSql); tscFreeSubobj(pParentSql);
tfree(pParentSql->pSubs); tfree(pParentSql->pSubs);
pParentSql->res.code = TSDB_CODE_SUCCESS; tscFreeSubobj(rootObj);
pParentSql->retry++; tfree(rootObj->pSubs);
rootObj->res.code = TSDB_CODE_SUCCESS;
rootObj->retry++;
tscDebug("0x%"PRIx64" retry parse sql and send query, prev error: %s, retry:%d", pParentSql->self, tscDebug("0x%"PRIx64" retry parse sql and send query, prev error: %s, retry:%d", rootObj->self,
tstrerror(code), pParentSql->retry); tstrerror(code), rootObj->retry);
tscResetSqlCmd(&pParentSql->cmd, true, pParentSql->self); tscResetSqlCmd(&rootObj->cmd, true);
code = tsParseSql(pParentSql, true); code = tsParseSql(rootObj, true);
if (code == TSDB_CODE_TSC_ACTION_IN_PROGRESS) { if (code == TSDB_CODE_TSC_ACTION_IN_PROGRESS) {
return; return;
} }
if (code != TSDB_CODE_SUCCESS) { if (code != TSDB_CODE_SUCCESS) {
pParentSql->res.code = code; rootObj->res.code = code;
tscAsyncResultOnError(pParentSql); tscAsyncResultOnError(rootObj);
return; return;
} }
...@@ -4036,6 +4066,16 @@ static void tscSubqueryCompleteCallback(void* param, TAOS_RES* tres, int code) { ...@@ -4036,6 +4066,16 @@ static void tscSubqueryCompleteCallback(void* param, TAOS_RES* tres, int code) {
return; return;
} }
if (pSql->cmd.command == TSDB_SQL_RETRIEVE_EMPTY_RESULT) {
SSqlObj* pParentSql = ps->pParentSql;
pParentSql->cmd.command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
(*pParentSql->fp)(pParentSql->param, pParentSql, 0);
return;
}
taos_fetch_rows_a(tres, tscSubqueryRetrieveCallback, param); taos_fetch_rows_a(tres, tscSubqueryRetrieveCallback, param);
} }
...@@ -4091,7 +4131,8 @@ void executeQuery(SSqlObj* pSql, SQueryInfo* pQueryInfo) { ...@@ -4091,7 +4131,8 @@ void executeQuery(SSqlObj* pSql, SQueryInfo* pQueryInfo) {
pNew->sqlstr = strdup(pSql->sqlstr); pNew->sqlstr = strdup(pSql->sqlstr);
pNew->fp = tscSubqueryCompleteCallback; pNew->fp = tscSubqueryCompleteCallback;
pNew->fetchFp = tscSubqueryCompleteCallback; pNew->fetchFp = tscSubqueryCompleteCallback;
pNew->maxRetry = pSql->maxRetry; pNew->maxRetry = pSql->maxRetry;
pNew->rootObj = pSql->rootObj;
pNew->cmd.resColumnId = TSDB_RES_COL_ID; pNew->cmd.resColumnId = TSDB_RES_COL_ID;
...@@ -5024,7 +5065,7 @@ int32_t tscCreateQueryFromQueryInfo(SQueryInfo* pQueryInfo, SQueryAttr* pQueryAt ...@@ -5024,7 +5065,7 @@ int32_t tscCreateQueryFromQueryInfo(SQueryInfo* pQueryInfo, SQueryAttr* pQueryAt
} }
if (pQueryAttr->fillType != TSDB_FILL_NONE) { if (pQueryAttr->fillType != TSDB_FILL_NONE) {
pQueryAttr->fillVal = calloc(pQueryAttr->numOfOutput, sizeof(int64_t)); pQueryAttr->fillVal = calloc(pQueryInfo->numOfFillVal, sizeof(int64_t));
memcpy(pQueryAttr->fillVal, pQueryInfo->fillVal, pQueryInfo->numOfFillVal * sizeof(int64_t)); memcpy(pQueryAttr->fillVal, pQueryInfo->fillVal, pQueryInfo->numOfFillVal * sizeof(int64_t));
} }
...@@ -5258,3 +5299,31 @@ char* cloneCurrentDBName(SSqlObj* pSql) { ...@@ -5258,3 +5299,31 @@ char* cloneCurrentDBName(SSqlObj* pSql) {
return p; return p;
} }
char* cloneCurrentDBName(SSqlObj* pSql) {
char *p = NULL;
HttpContext *pCtx = NULL;
pthread_mutex_lock(&pSql->pTscObj->mutex);
STscObj *pTscObj = pSql->pTscObj;
switch (pTscObj->from) {
case TAOS_REQ_FROM_HTTP:
pCtx = pSql->param;
if (pCtx && pCtx->db[0] != '\0') {
char db[TSDB_ACCT_ID_LEN + TSDB_DB_NAME_LEN] = {0};
int32_t len = sprintf(db, "%s%s%s", pTscObj->acctId, TS_PATH_DELIMITER, pCtx->db);
assert(len <= sizeof(db));
p = strdup(db);
}
break;
default:
break;
}
if (p == NULL) {
p = strdup(pSql->pTscObj->db);
}
pthread_mutex_unlock(&pSql->pTscObj->mutex);
return p;
}
...@@ -91,7 +91,7 @@ int8_t tsTscEnableRecordSql = 0; ...@@ -91,7 +91,7 @@ int8_t tsTscEnableRecordSql = 0;
// the maximum number of results for projection query on super table that are returned from // the maximum number of results for projection query on super table that are returned from
// one virtual node, to order according to timestamp // one virtual node, to order according to timestamp
int32_t tsMaxNumOfOrderedResults = 100000; int32_t tsMaxNumOfOrderedResults = 1000000;
// 10 ms for sliding time, the value will changed in case of time precision changed // 10 ms for sliding time, the value will changed in case of time precision changed
int32_t tsMinSlidingTime = 10; int32_t tsMinSlidingTime = 10;
...@@ -681,16 +681,6 @@ static void doInitGlobalConfig(void) { ...@@ -681,16 +681,6 @@ static void doInitGlobalConfig(void) {
cfg.unitType = TAOS_CFG_UTYPE_MS; cfg.unitType = TAOS_CFG_UTYPE_MS;
taosInitConfigOption(cfg); taosInitConfigOption(cfg);
cfg.option = "rpcForceTcp";
cfg.ptr = &tsRpcForceTcp;
cfg.valType = TAOS_CFG_VTYPE_INT32;
cfg.cfgType = TSDB_CFG_CTYPE_B_CONFIG | TSDB_CFG_CTYPE_B_CLIENT;
cfg.minValue = 0;
cfg.maxValue = 1;
cfg.ptrLength = 0;
cfg.unitType = TAOS_CFG_UTYPE_NONE;
taosInitConfigOption(cfg);
cfg.option = "rpcMaxTime"; cfg.option = "rpcMaxTime";
cfg.ptr = &tsRpcMaxTime; cfg.ptr = &tsRpcMaxTime;
cfg.valType = TAOS_CFG_VTYPE_INT32; cfg.valType = TAOS_CFG_VTYPE_INT32;
...@@ -701,6 +691,16 @@ static void doInitGlobalConfig(void) { ...@@ -701,6 +691,16 @@ static void doInitGlobalConfig(void) {
cfg.unitType = TAOS_CFG_UTYPE_SECOND; cfg.unitType = TAOS_CFG_UTYPE_SECOND;
taosInitConfigOption(cfg); taosInitConfigOption(cfg);
cfg.option = "rpcForceTcp";
cfg.ptr = &tsRpcForceTcp;
cfg.valType = TAOS_CFG_VTYPE_INT32;
cfg.cfgType = TSDB_CFG_CTYPE_B_CONFIG | TSDB_CFG_CTYPE_B_CLIENT;
cfg.minValue = 0;
cfg.maxValue = 1;
cfg.ptrLength = 0;
cfg.unitType = TAOS_CFG_UTYPE_NONE;
taosInitConfigOption(cfg);
cfg.option = "statusInterval"; cfg.option = "statusInterval";
cfg.ptr = &tsStatusInterval; cfg.ptr = &tsStatusInterval;
cfg.valType = TAOS_CFG_VTYPE_INT32; cfg.valType = TAOS_CFG_VTYPE_INT32;
...@@ -1056,8 +1056,8 @@ static void doInitGlobalConfig(void) { ...@@ -1056,8 +1056,8 @@ static void doInitGlobalConfig(void) {
cfg.ptr = &tsMaxNumOfOrderedResults; cfg.ptr = &tsMaxNumOfOrderedResults;
cfg.valType = TAOS_CFG_VTYPE_INT32; cfg.valType = TAOS_CFG_VTYPE_INT32;
cfg.cfgType = TSDB_CFG_CTYPE_B_CONFIG | TSDB_CFG_CTYPE_B_CLIENT | TSDB_CFG_CTYPE_B_SHOW; cfg.cfgType = TSDB_CFG_CTYPE_B_CONFIG | TSDB_CFG_CTYPE_B_CLIENT | TSDB_CFG_CTYPE_B_SHOW;
cfg.minValue = TSDB_MAX_SQL_LEN; cfg.minValue = 100000;
cfg.maxValue = TSDB_MAX_ALLOWED_SQL_LEN; cfg.maxValue = 100000000;
cfg.ptrLength = 0; cfg.ptrLength = 0;
cfg.unitType = TAOS_CFG_UTYPE_NONE; cfg.unitType = TAOS_CFG_UTYPE_NONE;
taosInitConfigOption(cfg); taosInitConfigOption(cfg);
...@@ -1256,10 +1256,10 @@ static void doInitGlobalConfig(void) { ...@@ -1256,10 +1256,10 @@ static void doInitGlobalConfig(void) {
cfg.unitType = TAOS_CFG_UTYPE_NONE; cfg.unitType = TAOS_CFG_UTYPE_NONE;
taosInitConfigOption(cfg); taosInitConfigOption(cfg);
cfg.option = "topicBianryLen"; cfg.option = "topicBinaryLen";
cfg.ptr = &tsTopicBianryLen; cfg.ptr = &tsTopicBianryLen;
cfg.valType = TAOS_CFG_VTYPE_INT32; cfg.valType = TAOS_CFG_VTYPE_INT32;
cfg.cfgType = TSDB_CFG_CTYPE_B_CONFIG; cfg.cfgType = TSDB_CFG_CTYPE_B_CONFIG | TSDB_CFG_CTYPE_B_SHOW;
cfg.minValue = 16; cfg.minValue = 16;
cfg.maxValue = 16000; cfg.maxValue = 16000;
cfg.ptrLength = 0; cfg.ptrLength = 0;
...@@ -1671,8 +1671,6 @@ static void doInitGlobalConfig(void) { ...@@ -1671,8 +1671,6 @@ static void doInitGlobalConfig(void) {
cfg.maxValue = MAX_FLOAT; cfg.maxValue = MAX_FLOAT;
cfg.ptrLength = 0; cfg.ptrLength = 0;
cfg.unitType = TAOS_CFG_UTYPE_NONE; cfg.unitType = TAOS_CFG_UTYPE_NONE;
taosInitConfigOption(cfg); taosInitConfigOption(cfg);
cfg.option = "dPrecision"; cfg.option = "dPrecision";
......
...@@ -178,6 +178,8 @@ def taos_connect(host=None, user="root", password="taosdata", db=None, port=0): ...@@ -178,6 +178,8 @@ def taos_connect(host=None, user="root", password="taosdata", db=None, port=0):
raise ConnectionError("connect to TDengine failed") raise ConnectionError("connect to TDengine failed")
return connection return connection
_libtaos.taos_connect_auth.restype = c_void_p
_libtaos.taos_connect_auth.argtypes = c_char_p, c_char_p, c_char_p, c_char_p, c_uint16
_libtaos.taos_connect_auth.restype = c_void_p _libtaos.taos_connect_auth.restype = c_void_p
_libtaos.taos_connect_auth.argtypes = c_char_p, c_char_p, c_char_p, c_char_p, c_uint16 _libtaos.taos_connect_auth.argtypes = c_char_p, c_char_p, c_char_p, c_char_p, c_uint16
...@@ -231,7 +233,6 @@ def taos_connect_auth(host=None, user="root", auth="", db=None, port=0): ...@@ -231,7 +233,6 @@ def taos_connect_auth(host=None, user="root", auth="", db=None, port=0):
raise ConnectionError("connect to TDengine failed") raise ConnectionError("connect to TDengine failed")
return connection return connection
_libtaos.taos_query.restype = c_void_p _libtaos.taos_query.restype = c_void_p
_libtaos.taos_query.argtypes = c_void_p, c_char_p _libtaos.taos_query.argtypes = c_void_p, c_char_p
...@@ -283,7 +284,6 @@ def taos_affected_rows(result): ...@@ -283,7 +284,6 @@ def taos_affected_rows(result):
"""The affected rows after runing query""" """The affected rows after runing query"""
return _libtaos.taos_affected_rows(result) return _libtaos.taos_affected_rows(result)
subscribe_callback_type = CFUNCTYPE(None, c_void_p, c_void_p, c_void_p, c_int) subscribe_callback_type = CFUNCTYPE(None, c_void_p, c_void_p, c_void_p, c_int)
_libtaos.taos_subscribe.restype = c_void_p _libtaos.taos_subscribe.restype = c_void_p
# _libtaos.taos_subscribe.argtypes = c_void_p, c_int, c_char_p, c_char_p, subscribe_callback_type, c_void_p, c_int # _libtaos.taos_subscribe.argtypes = c_void_p, c_int, c_char_p, c_char_p, subscribe_callback_type, c_void_p, c_int
...@@ -597,7 +597,6 @@ def taos_stmt_init(connection): ...@@ -597,7 +597,6 @@ def taos_stmt_init(connection):
""" """
return c_void_p(_libtaos.taos_stmt_init(connection)) return c_void_p(_libtaos.taos_stmt_init(connection))
_libtaos.taos_stmt_prepare.restype = c_int _libtaos.taos_stmt_prepare.restype = c_int
_libtaos.taos_stmt_prepare.argstype = (c_void_p, c_char_p, c_int) _libtaos.taos_stmt_prepare.argstype = (c_void_p, c_char_p, c_int)
...@@ -616,7 +615,6 @@ def taos_stmt_prepare(stmt, sql): ...@@ -616,7 +615,6 @@ def taos_stmt_prepare(stmt, sql):
_libtaos.taos_stmt_close.restype = c_int _libtaos.taos_stmt_close.restype = c_int
_libtaos.taos_stmt_close.argstype = (c_void_p,) _libtaos.taos_stmt_close.argstype = (c_void_p,)
def taos_stmt_close(stmt): def taos_stmt_close(stmt):
# type: (ctypes.c_void_p) -> None # type: (ctypes.c_void_p) -> None
"""Close a statement query """Close a statement query
...@@ -626,6 +624,11 @@ def taos_stmt_close(stmt): ...@@ -626,6 +624,11 @@ def taos_stmt_close(stmt):
if res != 0: if res != 0:
raise StatementError(msg=taos_stmt_errstr(stmt), errno=res) raise StatementError(msg=taos_stmt_errstr(stmt), errno=res)
try:
_libtaos.taos_stmt_errstr.restype = c_char_p
_libtaos.taos_stmt_errstr.argstype = (c_void_p,)
except AttributeError:
print("WARNING: libtaos(%s) does not support taos_stmt_errstr" % taos_get_client_info())
try: try:
_libtaos.taos_stmt_errstr.restype = c_char_p _libtaos.taos_stmt_errstr.restype = c_char_p
...@@ -667,7 +670,6 @@ except AttributeError: ...@@ -667,7 +670,6 @@ except AttributeError:
print("WARNING: libtaos(%s) does not support taos_stmt_set_tbname_tags" % taos_get_client_info()) print("WARNING: libtaos(%s) does not support taos_stmt_set_tbname_tags" % taos_get_client_info())
def taos_stmt_set_tbname_tags(stmt, name, tags): def taos_stmt_set_tbname_tags(stmt, name, tags):
# type: (c_void_p, str, c_void_p) -> None # type: (c_void_p, str, c_void_p) -> None
"""Set table name with tags bind params. """Set table name with tags bind params.
...@@ -678,7 +680,6 @@ def taos_stmt_set_tbname_tags(stmt, name, tags): ...@@ -678,7 +680,6 @@ def taos_stmt_set_tbname_tags(stmt, name, tags):
if res != 0: if res != 0:
raise StatementError(msg=taos_stmt_errstr(stmt), errno=res) raise StatementError(msg=taos_stmt_errstr(stmt), errno=res)
_libtaos.taos_stmt_is_insert.restype = c_int _libtaos.taos_stmt_is_insert.restype = c_int
_libtaos.taos_stmt_is_insert.argstype = (c_void_p, POINTER(c_int)) _libtaos.taos_stmt_is_insert.argstype = (c_void_p, POINTER(c_int))
...@@ -698,7 +699,6 @@ def taos_stmt_is_insert(stmt): ...@@ -698,7 +699,6 @@ def taos_stmt_is_insert(stmt):
_libtaos.taos_stmt_num_params.restype = c_int _libtaos.taos_stmt_num_params.restype = c_int
_libtaos.taos_stmt_num_params.argstype = (c_void_p, POINTER(c_int)) _libtaos.taos_stmt_num_params.argstype = (c_void_p, POINTER(c_int))
def taos_stmt_num_params(stmt): def taos_stmt_num_params(stmt):
# type: (ctypes.c_void_p) -> int # type: (ctypes.c_void_p) -> int
"""Params number of the current statement query. """Params number of the current statement query.
...@@ -710,7 +710,6 @@ def taos_stmt_num_params(stmt): ...@@ -710,7 +710,6 @@ def taos_stmt_num_params(stmt):
raise StatementError(msg=taos_stmt_errstr(stmt), errno=res) raise StatementError(msg=taos_stmt_errstr(stmt), errno=res)
return num_params.value return num_params.value
_libtaos.taos_stmt_bind_param.restype = c_int _libtaos.taos_stmt_bind_param.restype = c_int
_libtaos.taos_stmt_bind_param.argstype = (c_void_p, c_void_p) _libtaos.taos_stmt_bind_param.argstype = (c_void_p, c_void_p)
...@@ -809,15 +808,15 @@ def taos_stmt_use_result(stmt): ...@@ -809,15 +808,15 @@ def taos_stmt_use_result(stmt):
return result return result
try: try:
_libtaos.taos_schemaless_insert.restype = c_int _libtaos.taos_insert_lines.restype = c_int
_libtaos.taos_schemaless_insert.argstype = c_void_p, c_void_p, c_int _libtaos.taos_insert_lines.argstype = c_void_p, c_void_p, c_int
except AttributeError: except AttributeError:
print("WARNING: libtaos(%s) does not support schemaless_insert" % taos_get_client_info()) print("WARNING: libtaos(%s) does not support insert_lines" % taos_get_client_info())
def taos_schemaless_insert(connection, lines, protocol): def taos_insert_lines(connection, lines):
# type: (c_void_p, list[str] | tuple(str)) -> None # type: (c_void_p, list[str] | tuple(str)) -> None
num_of_lines = len(lines) num_of_lines = len(lines)
lines = (c_char_p(line.encode("utf-8")) for line in lines) lines = (c_char_p(line.encode("utf-8")) for line in lines)
......
...@@ -84,3 +84,19 @@ class SchemalessError(DatabaseError): ...@@ -84,3 +84,19 @@ class SchemalessError(DatabaseError):
"""taos_schemaless_insert errors.""" """taos_schemaless_insert errors."""
pass pass
class StatementError(DatabaseError):
"""Exception raised in STMT API."""
pass
class ResultError(DatabaseError):
"""Result related APIs."""
pass
class LinesError(DatabaseError):
"""taos_insert_lines errors."""
pass
\ No newline at end of file
...@@ -206,11 +206,6 @@ typedef struct { ...@@ -206,11 +206,6 @@ typedef struct {
uint16_t port; uint16_t port;
} SEpAddrMsg; } SEpAddrMsg;
typedef struct {
char* fqdn;
uint16_t port;
} SEpAddr1;
typedef struct { typedef struct {
int32_t numOfVnodes; int32_t numOfVnodes;
} SMsgDesc; } SMsgDesc;
...@@ -768,7 +763,7 @@ typedef struct { ...@@ -768,7 +763,7 @@ typedef struct {
int32_t vgId; int32_t vgId;
int8_t numOfEps; int8_t numOfEps;
SEpAddrMsg epAddr[TSDB_MAX_REPLICA]; SEpAddrMsg epAddr[TSDB_MAX_REPLICA];
} SVgroupMsg; } SVgroupMsg, SVgroupInfo;
typedef struct { typedef struct {
int32_t numOfVgroups; int32_t numOfVgroups;
......
...@@ -34,6 +34,8 @@ ELSEIF (TD_WINDOWS) ...@@ -34,6 +34,8 @@ ELSEIF (TD_WINDOWS)
IF (TD_POWER) IF (TD_POWER)
SET_TARGET_PROPERTIES(shell PROPERTIES OUTPUT_NAME power) SET_TARGET_PROPERTIES(shell PROPERTIES OUTPUT_NAME power)
ELSEIF (TD_PRO)
SET_TARGET_PROPERTIES(shell PROPERTIES OUTPUT_NAME prodbc)
ELSE () ELSE ()
SET_TARGET_PROPERTIES(shell PROPERTIES OUTPUT_NAME taos) SET_TARGET_PROPERTIES(shell PROPERTIES OUTPUT_NAME taos)
ENDIF () ENDIF ()
......
...@@ -111,6 +111,7 @@ static void *shellCheckThreadFp(void *arg) { ...@@ -111,6 +111,7 @@ static void *shellCheckThreadFp(void *arg) {
int32_t start = pThread->threadIndex * interval; int32_t start = pThread->threadIndex * interval;
int32_t end = (pThread->threadIndex + 1) * interval; int32_t end = (pThread->threadIndex + 1) * interval;
if (start >= tbNum) return NULL;
if (end > tbNum) end = tbNum + 1; if (end > tbNum) end = tbNum + 1;
char file[32] = {0}; char file[32] = {0};
...@@ -193,9 +194,11 @@ void shellCheck(TAOS *con, SShellArguments *_args) { ...@@ -193,9 +194,11 @@ void shellCheck(TAOS *con, SShellArguments *_args) {
return; return;
} }
fprintf(stdout, "total %d tables will be checked by %d threads\n", tbNum, _args->threadNum); if (tbNum > 0) {
shellRunCheckThreads(con, _args); fprintf(stdout, "total %d tables will be checked by %d threads\n", tbNum, _args->threadNum);
shellRunCheckThreads(con, _args);
}
int64_t end = taosGetTimestampMs(); int64_t end = taosGetTimestampMs();
fprintf(stdout, "total %d tables checked, failed:%d, time spent %.2f seconds\n", checkedNum, errorNum, fprintf(stdout, "total %d tables checked, failed:%d, time spent %.2f seconds\n", checkedNum, errorNum,
(end - start) / 1000.0); (end - start) / 1000.0);
......
...@@ -1044,56 +1044,4 @@ void source_file(TAOS *con, char *fptr) { ...@@ -1044,56 +1044,4 @@ void source_file(TAOS *con, char *fptr) {
void shellGetGrantInfo(void *con) { void shellGetGrantInfo(void *con) {
return; return;
#if 0
char sql[] = "show grants";
TAOS_RES* tres = taos_query(con, sql);
int code = taos_errno(tres);
if (code != TSDB_CODE_SUCCESS) {
if (code == TSDB_CODE_COM_OPS_NOT_SUPPORT) {
fprintf(stdout, "Server is Community Edition, version is %s\n\n", taos_get_server_info(con));
} else {
fprintf(stderr, "Failed to check Server Edition, Reason:%d:%s\n\n", taos_errno(con), taos_errstr(con));
}
return;
}
int num_fields = taos_field_count(tres);
if (num_fields == 0) {
fprintf(stderr, "\nInvalid grant information.\n");
exit(0);
} else {
if (tres == NULL) {
fprintf(stderr, "\nGrant information is null.\n");
exit(0);
}
TAOS_FIELD *fields = taos_fetch_fields(tres);
TAOS_ROW row = taos_fetch_row(tres);
if (row == NULL) {
fprintf(stderr, "\nFailed to get grant information from server. Abort.\n");
exit(0);
}
char serverVersion[32] = {0};
char expiretime[32] = {0};
char expired[32] = {0};
memcpy(serverVersion, row[0], fields[0].bytes);
memcpy(expiretime, row[1], fields[1].bytes);
memcpy(expired, row[2], fields[2].bytes);
if (strcmp(expiretime, "unlimited") == 0) {
fprintf(stdout, "Server is Enterprise %s Edition, version is %s and will never expire.\n", serverVersion, taos_get_server_info(con));
} else {
fprintf(stdout, "Server is Enterprise %s Edition, version is %s and will expire at %s.\n", serverVersion, taos_get_server_info(con), expiretime);
}
result = NULL;
taos_free_result(tres);
}
fprintf(stdout, "\n");
#endif
} }
...@@ -210,7 +210,7 @@ static void shellSourceFile(TAOS *con, char *fptr) { ...@@ -210,7 +210,7 @@ static void shellSourceFile(TAOS *con, char *fptr) {
/* free local resouce: allocated memory/metric-meta refcnt */ /* free local resouce: allocated memory/metric-meta refcnt */
taos_free_result(pSql); taos_free_result(pSql);
memset(cmd, 0, MAX_COMMAND_SIZE); memset(cmd, 0, tsMaxSQLStringLen);
cmd_len = 0; cmd_len = 0;
} }
......
...@@ -1159,7 +1159,6 @@ static int64_t dumpNormalTable( ...@@ -1159,7 +1159,6 @@ static int64_t dumpNormalTable(
// create child-table using super-table // create child-table using super-table
dumpCreateMTableClause(dbName, stable, tableDes, colCount, fp); dumpCreateMTableClause(dbName, stable, tableDes, colCount, fp);
} else { // dump table definition } else { // dump table definition
colCount = getTableDes(dbName, tbName, tableDes, false); colCount = getTableDes(dbName, tbName, tableDes, false);
......
...@@ -712,6 +712,15 @@ void leakTest(){ ...@@ -712,6 +712,15 @@ void leakTest(){
} }
#define DB_CNT 500 #define DB_CNT 500
void test_same_float(int algo, bool lossy){
float ori = 123.456789123;
float floats [DB_CNT];
for(int i=0; i< DB_CNT; i++){
floats[i] = ori;
}
DoFloat(floats, DB_CNT, algo, lossy);
}
void test_same_double(int algo){ void test_same_double(int algo){
double ori = 3.1415926; double ori = 3.1415926;
...@@ -721,7 +730,6 @@ void test_same_double(int algo){ ...@@ -721,7 +730,6 @@ void test_same_double(int algo){
} }
DoDouble(doubles, DB_CNT, algo); DoDouble(doubles, DB_CNT, algo);
} }
#ifdef TD_TSZ #ifdef TD_TSZ
...@@ -781,6 +789,10 @@ int main(int argc, char *argv[]) { ...@@ -781,6 +789,10 @@ int main(int argc, char *argv[]) {
return 0; return 0;
} }
if(strcmp(argv[1], "-samef") == 0) {
test_same_float(atoi(argv[2]), true);
return 0;
}
if(strcmp(argv[1], "-samed") == 0) { if(strcmp(argv[1], "-samed") == 0) {
test_same_double(atoi(argv[2])); test_same_double(atoi(argv[2]));
return 0; return 0;
......
...@@ -197,6 +197,7 @@ typedef struct SQLFunctionCtx { ...@@ -197,6 +197,7 @@ typedef struct SQLFunctionCtx {
SResultRowCellInfo *resultInfo; SResultRowCellInfo *resultInfo;
int16_t colId;
SExtTagsInfo tagInfo; SExtTagsInfo tagInfo;
SPoint1 start; SPoint1 start;
SPoint1 end; SPoint1 end;
......
...@@ -67,7 +67,7 @@ void tHistogramDestroy(SHistogramInfo** pHisto); ...@@ -67,7 +67,7 @@ void tHistogramDestroy(SHistogramInfo** pHisto);
void tHistogramPrint(SHistogramInfo* pHisto); void tHistogramPrint(SHistogramInfo* pHisto);
int32_t histoBinarySearch(SHistBin* pEntry, int32_t len, double val); int32_t histoBinarySearch(SHistBin* pEntry, int32_t len, double val, int32_t maxEntries);
SHeapEntry* tHeapCreate(int32_t numOfEntries); SHeapEntry* tHeapCreate(int32_t numOfEntries);
void tHeapSort(SHeapEntry* pEntry, int32_t len); void tHeapSort(SHeapEntry* pEntry, int32_t len);
......
...@@ -98,11 +98,11 @@ cmd ::= SHOW CREATE TABLE ids(X) cpxName(Y). { ...@@ -98,11 +98,11 @@ cmd ::= SHOW CREATE TABLE ids(X) cpxName(Y). {
cmd ::= SHOW CREATE STABLE ids(X) cpxName(Y). { cmd ::= SHOW CREATE STABLE ids(X) cpxName(Y). {
X.n += Y.n; X.n += Y.n;
setDCLSqlElems(pInfo, TSDB_SQL_SHOW_CREATE_STABLE, 1, &X); setDCLSqlElems(pInfo, TSDB_SQL_SHOW_CREATE_STABLE, 1, &X);
} }
cmd ::= SHOW CREATE DATABASE ids(X). { cmd ::= SHOW CREATE DATABASE ids(X). {
setDCLSqlElems(pInfo, TSDB_SQL_SHOW_CREATE_DATABASE, 1, &X); setDCLSqlElems(pInfo, TSDB_SQL_SHOW_CREATE_DATABASE, 1, &X);
} }
cmd ::= SHOW dbPrefix(X) TABLES. { cmd ::= SHOW dbPrefix(X) TABLES. {
setShowOptions(pInfo, TSDB_MGMT_TABLE_TABLE, &X, 0); setShowOptions(pInfo, TSDB_MGMT_TABLE_TABLE, &X, 0);
...@@ -278,7 +278,7 @@ wal(Y) ::= WAL INTEGER(X). { Y = X; } ...@@ -278,7 +278,7 @@ wal(Y) ::= WAL INTEGER(X). { Y = X; }
fsync(Y) ::= FSYNC INTEGER(X). { Y = X; } fsync(Y) ::= FSYNC INTEGER(X). { Y = X; }
comp(Y) ::= COMP INTEGER(X). { Y = X; } comp(Y) ::= COMP INTEGER(X). { Y = X; }
prec(Y) ::= PRECISION STRING(X). { Y = X; } prec(Y) ::= PRECISION STRING(X). { Y = X; }
update(Y) ::= UPDATE INTEGER(X). { Y = X; } update(Y) ::= UPDATE INTEGER(X). { Y = X; }
cachelast(Y) ::= CACHELAST INTEGER(X). { Y = X; } cachelast(Y) ::= CACHELAST INTEGER(X). { Y = X; }
partitions(Y) ::= PARTITIONS INTEGER(X). { Y = X; } partitions(Y) ::= PARTITIONS INTEGER(X). { Y = X; }
...@@ -327,7 +327,7 @@ alter_topic_optr(Y) ::= alter_db_optr(Z). { Y = Z; Y.dbTyp ...@@ -327,7 +327,7 @@ alter_topic_optr(Y) ::= alter_db_optr(Z). { Y = Z; Y.dbTyp
alter_topic_optr(Y) ::= alter_topic_optr(Z) partitions(X). { Y = Z; Y.partitions = strtol(X.z, NULL, 10); } alter_topic_optr(Y) ::= alter_topic_optr(Z) partitions(X). { Y = Z; Y.partitions = strtol(X.z, NULL, 10); }
%type typename {TAOS_FIELD} %type typename {TAOS_FIELD}
typename(A) ::= ids(X). { typename(A) ::= ids(X). {
X.type = 0; X.type = 0;
tSetColumnType (&A, &X); tSetColumnType (&A, &X);
} }
......
...@@ -3752,7 +3752,7 @@ static void interp_function_impl(SQLFunctionCtx *pCtx) { ...@@ -3752,7 +3752,7 @@ static void interp_function_impl(SQLFunctionCtx *pCtx) {
bool ascQuery = (pCtx->order == TSDB_ORDER_ASC); bool ascQuery = (pCtx->order == TSDB_ORDER_ASC);
if (pCtx->inputType == TSDB_DATA_TYPE_TIMESTAMP) { if (pCtx->colId == 0 && pCtx->inputType == TSDB_DATA_TYPE_TIMESTAMP) {
*(TSKEY *)pCtx->pOutput = pCtx->startTs; *(TSKEY *)pCtx->pOutput = pCtx->startTs;
} else if (type == TSDB_FILL_NULL) { } else if (type == TSDB_FILL_NULL) {
setNull(pCtx->pOutput, pCtx->outputType, pCtx->outputBytes); setNull(pCtx->pOutput, pCtx->outputType, pCtx->outputBytes);
...@@ -3789,6 +3789,10 @@ static void interp_function_impl(SQLFunctionCtx *pCtx) { ...@@ -3789,6 +3789,10 @@ static void interp_function_impl(SQLFunctionCtx *pCtx) {
} }
} }
} else { } else {
if (GET_RES_INFO(pCtx)->numOfRes > 0) {
return;
}
// no data generated yet // no data generated yet
if (pCtx->size < 1) { if (pCtx->size < 1) {
return; return;
...@@ -3818,11 +3822,15 @@ static void interp_function_impl(SQLFunctionCtx *pCtx) { ...@@ -3818,11 +3822,15 @@ static void interp_function_impl(SQLFunctionCtx *pCtx) {
if (pCtx->size > 1) { if (pCtx->size > 1) {
ekey = GET_TS_DATA(pCtx, 1); ekey = GET_TS_DATA(pCtx, 1);
if ((ascQuery && ekey < pCtx->startTs) || ((!ascQuery) && ekey > pCtx->startTs)) { if ((ascQuery && ekey < pCtx->startTs) || ((!ascQuery) && ekey > pCtx->startTs)) {
setNull(pCtx->pOutput, pCtx->inputType, pCtx->inputBytes);
SET_VAL(pCtx, 1, 1);
return; return;
} }
val = ((char*)pCtx->pInput) + pCtx->inputBytes; val = ((char*)pCtx->pInput) + pCtx->inputBytes;
} else { } else {
setNull(pCtx->pOutput, pCtx->inputType, pCtx->inputBytes);
SET_VAL(pCtx, 1, 1);
return; return;
} }
} else { } else {
...@@ -3867,7 +3875,7 @@ static void interp_function_impl(SQLFunctionCtx *pCtx) { ...@@ -3867,7 +3875,7 @@ static void interp_function_impl(SQLFunctionCtx *pCtx) {
SET_VAL(pCtx, 1, 1); SET_VAL(pCtx, 1, 1);
} }
static void interp_function(SQLFunctionCtx *pCtx) { static void interp_function(SQLFunctionCtx *pCtx) {
// at this point, the value is existed, return directly // at this point, the value is existed, return directly
if (pCtx->size > 0) { if (pCtx->size > 0) {
bool ascQuery = (pCtx->order == TSDB_ORDER_ASC); bool ascQuery = (pCtx->order == TSDB_ORDER_ASC);
...@@ -4112,11 +4120,23 @@ static void irate_function(SQLFunctionCtx *pCtx) { ...@@ -4112,11 +4120,23 @@ static void irate_function(SQLFunctionCtx *pCtx) {
double v = 0; double v = 0;
GET_TYPED_DATA(v, double, pCtx->inputType, pData); GET_TYPED_DATA(v, double, pCtx->inputType, pData);
if ((INT64_MIN == pRateInfo->lastKey) || primaryKey[i] > pRateInfo->lastKey) { if (INT64_MIN == pRateInfo->lastKey) {
pRateInfo->lastValue = v; pRateInfo->lastValue = v;
pRateInfo->lastKey = primaryKey[i]; pRateInfo->lastKey = primaryKey[i];
continue; continue;
} }
if (primaryKey[i] > pRateInfo->lastKey) {
if ((INT64_MIN == pRateInfo->firstKey) || pRateInfo->lastKey > pRateInfo->firstKey) {
pRateInfo->firstValue = pRateInfo->lastValue;
pRateInfo->firstKey = pRateInfo->lastKey;
}
pRateInfo->lastValue = v;
pRateInfo->lastKey = primaryKey[i];
continue;
}
if ((INT64_MIN == pRateInfo->firstKey) || primaryKey[i] > pRateInfo->firstKey) { if ((INT64_MIN == pRateInfo->firstKey) || primaryKey[i] > pRateInfo->firstKey) {
pRateInfo->firstValue = v; pRateInfo->firstValue = v;
......
...@@ -776,6 +776,16 @@ static void setResultRowInterpo(SResultRow* pResult, SResultTsInterpType type) { ...@@ -776,6 +776,16 @@ static void setResultRowInterpo(SResultRow* pResult, SResultTsInterpType type) {
} }
} }
static void unsetResultRowInterpo(SResultRow* pResult, SResultTsInterpType type) {
assert(pResult != NULL && (type == RESULT_ROW_START_INTERP || type == RESULT_ROW_END_INTERP));
if (type == RESULT_ROW_START_INTERP) {
pResult->startInterp = false;
} else {
pResult->endInterp = false;
}
}
static bool resultRowInterpolated(SResultRow* pResult, SResultTsInterpType type) { static bool resultRowInterpolated(SResultRow* pResult, SResultTsInterpType type) {
assert(pResult != NULL && (type == RESULT_ROW_START_INTERP || type == RESULT_ROW_END_INTERP)); assert(pResult != NULL && (type == RESULT_ROW_START_INTERP || type == RESULT_ROW_END_INTERP));
if (type == RESULT_ROW_START_INTERP) { if (type == RESULT_ROW_START_INTERP) {
...@@ -1239,6 +1249,7 @@ static void doSetInputDataBlock(SOperatorInfo* pOperator, SQLFunctionCtx* pCtx, ...@@ -1239,6 +1249,7 @@ static void doSetInputDataBlock(SOperatorInfo* pOperator, SQLFunctionCtx* pCtx,
// in case of the block distribution query, the inputBytes is not a constant value. // in case of the block distribution query, the inputBytes is not a constant value.
pCtx[i].pInput = p->pData; pCtx[i].pInput = p->pData;
pCtx[i].colId = p->info.colId;
assert(p->info.colId == pColIndex->colId && pCtx[i].inputType == p->info.type); assert(p->info.colId == pColIndex->colId && pCtx[i].inputType == p->info.type);
if (pCtx[i].functionId < 0) { if (pCtx[i].functionId < 0) {
...@@ -1387,6 +1398,11 @@ static bool setTimeWindowInterpolationStartTs(SOperatorInfo* pOperatorInfo, SQLF ...@@ -1387,6 +1398,11 @@ static bool setTimeWindowInterpolationStartTs(SOperatorInfo* pOperatorInfo, SQLF
bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr); bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
if (pos < 0 && !ascQuery) {
setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
return true;
}
TSKEY curTs = tsCols[pos]; TSKEY curTs = tsCols[pos];
TSKEY lastTs = *(TSKEY *) pRuntimeEnv->prevRow[0]; TSKEY lastTs = *(TSKEY *) pRuntimeEnv->prevRow[0];
...@@ -1622,6 +1638,7 @@ static void hashAllIntervalAgg(SOperatorInfo* pOperatorInfo, SResultRowInfo* pRe ...@@ -1622,6 +1638,7 @@ static void hashAllIntervalAgg(SOperatorInfo* pOperatorInfo, SResultRowInfo* pRe
} }
int32_t startPos = ascQuery? 0 : (pSDataBlock->info.rows - 1); int32_t startPos = ascQuery? 0 : (pSDataBlock->info.rows - 1);
int32_t ostartPos = 0;
TSKEY ts = getStartTsKey(pQueryAttr, &pSDataBlock->info.window, tsCols, pSDataBlock->info.rows); TSKEY ts = getStartTsKey(pQueryAttr, &pSDataBlock->info.window, tsCols, pSDataBlock->info.rows);
STimeWindow win = getCurrentActiveTimeWindow(pResultRowInfo, ts, pQueryAttr); STimeWindow win = getCurrentActiveTimeWindow(pResultRowInfo, ts, pQueryAttr);
...@@ -1630,7 +1647,7 @@ static void hashAllIntervalAgg(SOperatorInfo* pOperatorInfo, SResultRowInfo* pRe ...@@ -1630,7 +1647,7 @@ static void hashAllIntervalAgg(SOperatorInfo* pOperatorInfo, SResultRowInfo* pRe
SResultRow* pResult = NULL; SResultRow* pResult = NULL;
int32_t forwardStep = 0; int32_t forwardStep = 0;
int32_t ret = 0; int32_t ret = 0;
STimeWindow preWin = win; //STimeWindow preWin = win;
while (1) { while (1) {
// null data, failed to allocate more memory buffer // null data, failed to allocate more memory buffer
...@@ -1644,11 +1661,17 @@ static void hashAllIntervalAgg(SOperatorInfo* pOperatorInfo, SResultRowInfo* pRe ...@@ -1644,11 +1661,17 @@ static void hashAllIntervalAgg(SOperatorInfo* pOperatorInfo, SResultRowInfo* pRe
forwardStep = getNumOfRowsInTimeWindow(pRuntimeEnv, &pSDataBlock->info, tsCols, startPos, ekey, binarySearchForKey, true); forwardStep = getNumOfRowsInTimeWindow(pRuntimeEnv, &pSDataBlock->info, tsCols, startPos, ekey, binarySearchForKey, true);
// window start(end) key interpolation // window start(end) key interpolation
unsetResultRowInterpo(pResult, RESULT_ROW_START_INTERP);
ostartPos = startPos;
if (!ascQuery) {
startPos += forwardStep * step;
}
doWindowBorderInterpolation(pOperatorInfo, pSDataBlock, pInfo->pCtx, pResult, &win, startPos, forwardStep); doWindowBorderInterpolation(pOperatorInfo, pSDataBlock, pInfo->pCtx, pResult, &win, startPos, forwardStep);
doApplyFunctions(pRuntimeEnv, pInfo->pCtx, ascQuery ? &win : &preWin, startPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput); doApplyFunctions(pRuntimeEnv, pInfo->pCtx, &win, ostartPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput);
preWin = win;
int32_t prevEndPos = (forwardStep - 1) * step + startPos; int32_t prevEndPos = (!ascQuery) ? startPos - step : (forwardStep - 1) * step + startPos;
startPos = getNextQualifiedWindow(pQueryAttr, &win, &pSDataBlock->info, tsCols, binarySearchForKey, prevEndPos); startPos = getNextQualifiedWindow(pQueryAttr, &win, &pSDataBlock->info, tsCols, binarySearchForKey, prevEndPos);
if (startPos < 0) { if (startPos < 0) {
if ((ascQuery && win.skey <= pQueryAttr->window.ekey) || ((!ascQuery) && win.ekey >= pQueryAttr->window.ekey)) { if ((ascQuery && win.skey <= pQueryAttr->window.ekey) || ((!ascQuery) && win.ekey >= pQueryAttr->window.ekey)) {
...@@ -1658,11 +1681,16 @@ static void hashAllIntervalAgg(SOperatorInfo* pOperatorInfo, SResultRowInfo* pRe ...@@ -1658,11 +1681,16 @@ static void hashAllIntervalAgg(SOperatorInfo* pOperatorInfo, SResultRowInfo* pRe
longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY); longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
} }
startPos = pSDataBlock->info.rows - 1; if (ascQuery) {
startPos = pSDataBlock->info.rows - 1;
} else {
startPos = 0;
}
// window start(end) key interpolation forwardStep = 1;
doWindowBorderInterpolation(pOperatorInfo, pSDataBlock, pInfo->pCtx, pResult, &win, startPos, forwardStep); unsetResultRowInterpo(pResult, RESULT_ROW_START_INTERP);
doApplyFunctions(pRuntimeEnv, pInfo->pCtx, ascQuery ? &win : &preWin, startPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput); setNotInterpoWindowKey(pInfo->pCtx, pQueryAttr->numOfOutput, RESULT_ROW_START_INTERP);
doApplyFunctions(pRuntimeEnv, pInfo->pCtx, &win, startPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput);
} }
break; break;
...@@ -2129,6 +2157,7 @@ static int32_t setupQueryRuntimeEnv(SQueryRuntimeEnv *pRuntimeEnv, int32_t numOf ...@@ -2129,6 +2157,7 @@ static int32_t setupQueryRuntimeEnv(SQueryRuntimeEnv *pRuntimeEnv, int32_t numOf
pRuntimeEnv->pResultRowHashTable = taosHashInit(numOfTables, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK); pRuntimeEnv->pResultRowHashTable = taosHashInit(numOfTables, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
pRuntimeEnv->pResultRowListSet = taosHashInit(numOfTables * 10, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK); pRuntimeEnv->pResultRowListSet = taosHashInit(numOfTables * 10, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
pRuntimeEnv->pResultRowArrayList = taosArrayInit(numOfTables, sizeof(SResultRowCell));
pRuntimeEnv->keyBuf = malloc(pQueryAttr->maxTableColumnWidth + sizeof(int64_t) + POINTER_BYTES); pRuntimeEnv->keyBuf = malloc(pQueryAttr->maxTableColumnWidth + sizeof(int64_t) + POINTER_BYTES);
pRuntimeEnv->pool = initResultRowPool(getResultRowSize(pRuntimeEnv)); pRuntimeEnv->pool = initResultRowPool(getResultRowSize(pRuntimeEnv));
pRuntimeEnv->pResultRowArrayList = taosArrayInit(numOfTables, sizeof(SResultRowCell)); pRuntimeEnv->pResultRowArrayList = taosArrayInit(numOfTables, sizeof(SResultRowCell));
...@@ -2405,6 +2434,7 @@ static void teardownQueryRuntimeEnv(SQueryRuntimeEnv *pRuntimeEnv) { ...@@ -2405,6 +2434,7 @@ static void teardownQueryRuntimeEnv(SQueryRuntimeEnv *pRuntimeEnv) {
destroyOperatorInfo(pRuntimeEnv->proot); destroyOperatorInfo(pRuntimeEnv->proot);
pRuntimeEnv->pool = destroyResultRowPool(pRuntimeEnv->pool); pRuntimeEnv->pool = destroyResultRowPool(pRuntimeEnv->pool);
taosArrayDestroy(pRuntimeEnv->pResultRowArrayList);
taosArrayDestroyEx(pRuntimeEnv->prevResult, freeInterResult); taosArrayDestroyEx(pRuntimeEnv->prevResult, freeInterResult);
taosArrayDestroy(pRuntimeEnv->pResultRowArrayList); taosArrayDestroy(pRuntimeEnv->pResultRowArrayList);
pRuntimeEnv->prevResult = NULL; pRuntimeEnv->prevResult = NULL;
...@@ -3562,7 +3592,7 @@ void copyToSDataBlock(SQueryRuntimeEnv* pRuntimeEnv, int32_t threshold, SSDataBl ...@@ -3562,7 +3592,7 @@ void copyToSDataBlock(SQueryRuntimeEnv* pRuntimeEnv, int32_t threshold, SSDataBl
} }
} }
static void updateTableQueryInfoForReverseScan(STableQueryInfo *pTableQueryInfo) { static void updateTableQueryInfoForReverseScan(STableQueryInfo *pTableQueryInfo, int64_t qId) {
if (pTableQueryInfo == NULL) { if (pTableQueryInfo == NULL) {
return; return;
} }
...@@ -3573,6 +3603,9 @@ static void updateTableQueryInfoForReverseScan(STableQueryInfo *pTableQueryInfo) ...@@ -3573,6 +3603,9 @@ static void updateTableQueryInfoForReverseScan(STableQueryInfo *pTableQueryInfo)
SWITCH_ORDER(pTableQueryInfo->cur.order); SWITCH_ORDER(pTableQueryInfo->cur.order);
pTableQueryInfo->cur.vgroupIndex = -1; pTableQueryInfo->cur.vgroupIndex = -1;
qDebug("0x%"PRIx64" update query window for reverse scan, %"PRId64" - %"PRId64", lastKey:%"PRId64, qId, pTableQueryInfo->win.skey, pTableQueryInfo->win.ekey,
pTableQueryInfo->lastKey);
// set the index to be the end slot of result rows array // set the index to be the end slot of result rows array
SResultRowInfo* pResultRowInfo = &pTableQueryInfo->resInfo; SResultRowInfo* pResultRowInfo = &pTableQueryInfo->resInfo;
if (pResultRowInfo->size > 0) { if (pResultRowInfo->size > 0) {
...@@ -3593,7 +3626,7 @@ static void setupQueryRangeForReverseScan(SQueryRuntimeEnv* pRuntimeEnv) { ...@@ -3593,7 +3626,7 @@ static void setupQueryRangeForReverseScan(SQueryRuntimeEnv* pRuntimeEnv) {
size_t t = taosArrayGetSize(group); size_t t = taosArrayGetSize(group);
for (int32_t j = 0; j < t; ++j) { for (int32_t j = 0; j < t; ++j) {
STableQueryInfo *pCheckInfo = taosArrayGetP(group, j); STableQueryInfo *pCheckInfo = taosArrayGetP(group, j);
updateTableQueryInfoForReverseScan(pCheckInfo); updateTableQueryInfoForReverseScan(pCheckInfo, GET_QID(pRuntimeEnv));
// update the last key in tableKeyInfo list, the tableKeyInfo is used to build the tsdbQueryHandle and decide // update the last key in tableKeyInfo list, the tableKeyInfo is used to build the tsdbQueryHandle and decide
// the start check timestamp of tsdbQueryHandle // the start check timestamp of tsdbQueryHandle
...@@ -4142,7 +4175,7 @@ void setParamForStableStddevByColData(SQueryRuntimeEnv* pRuntimeEnv, SQLFunction ...@@ -4142,7 +4175,7 @@ void setParamForStableStddevByColData(SQueryRuntimeEnv* pRuntimeEnv, SQLFunction
* merged during merge stage. In this case, we need the pTableQueryInfo->lastResRows to decide if there * merged during merge stage. In this case, we need the pTableQueryInfo->lastResRows to decide if there
* is a previous result generated or not. * is a previous result generated or not.
*/ */
void setIntervalQueryRange(SQueryRuntimeEnv *pRuntimeEnv, TSKEY key) { void setIntervalQueryRange(SQueryRuntimeEnv *pRuntimeEnv, STimeWindow* winx, int32_t tid) {
SQueryAttr *pQueryAttr = pRuntimeEnv->pQueryAttr; SQueryAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current; STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
SResultRowInfo *pResultRowInfo = &pTableQueryInfo->resInfo; SResultRowInfo *pResultRowInfo = &pTableQueryInfo->resInfo;
...@@ -4151,9 +4184,14 @@ void setIntervalQueryRange(SQueryRuntimeEnv *pRuntimeEnv, TSKEY key) { ...@@ -4151,9 +4184,14 @@ void setIntervalQueryRange(SQueryRuntimeEnv *pRuntimeEnv, TSKEY key) {
return; return;
} }
TSKEY key = QUERY_IS_ASC_QUERY(pQueryAttr)? winx->skey:winx->ekey;
qDebug("0x%"PRIx64" update query window, tid:%d, %"PRId64" - %"PRId64", old:%"PRId64" - %"PRId64, GET_QID(pRuntimeEnv), tid, key, pTableQueryInfo->win.ekey,
pTableQueryInfo->win.skey, pTableQueryInfo->win.ekey);
pTableQueryInfo->win.skey = key; pTableQueryInfo->win.skey = key;
STimeWindow win = {.skey = key, .ekey = pQueryAttr->window.ekey}; STimeWindow win = {.skey = key, .ekey = pQueryAttr->window.ekey};
/** /**
* In handling the both ascending and descending order super table query, we need to find the first qualified * In handling the both ascending and descending order super table query, we need to find the first qualified
* timestamp of this table, and then set the first qualified start timestamp. * timestamp of this table, and then set the first qualified start timestamp.
...@@ -5399,7 +5437,7 @@ SArray* getResultGroupCheckColumns(SQueryAttr* pQuery) { ...@@ -5399,7 +5437,7 @@ SArray* getResultGroupCheckColumns(SQueryAttr* pQuery) {
// TSDB_FUNC_TAG_DUMMY function needs to be ignored // TSDB_FUNC_TAG_DUMMY function needs to be ignored
if (index->colId == pExpr->colInfo.colId && if (index->colId == pExpr->colInfo.colId &&
((TSDB_COL_IS_TAG(pExpr->colInfo.flag) && pExpr->functionId == TSDB_FUNC_TAG) || ((TSDB_COL_IS_TAG(pExpr->colInfo.flag) && ((pExpr->functionId == TSDB_FUNC_TAG) || (pExpr->functionId == TSDB_FUNC_TAGPRJ))) ||
(TSDB_COL_IS_NORMAL_COL(pExpr->colInfo.flag) && pExpr->functionId == TSDB_FUNC_PRJ))) { (TSDB_COL_IS_NORMAL_COL(pExpr->colInfo.flag) && pExpr->functionId == TSDB_FUNC_PRJ))) {
index->colIndex = j; index->colIndex = j;
index->colId = pExpr->resColId; index->colId = pExpr->resColId;
...@@ -5602,8 +5640,10 @@ static SSDataBlock* doSort(void* param, bool* newgroup) { ...@@ -5602,8 +5640,10 @@ static SSDataBlock* doSort(void* param, bool* newgroup) {
} }
__compar_fn_t comp = getKeyComparFunc(pSchema[pInfo->colIndex].type, pInfo->order); __compar_fn_t comp = getKeyComparFunc(pSchema[pInfo->colIndex].type, pInfo->order);
taoscQSort(pCols, pSchema, numOfCols, pInfo->pDataBlock->info.rows, pInfo->colIndex, comp); if (pInfo->pDataBlock->info.rows) {
taoscQSort(pCols, pSchema, numOfCols, pInfo->pDataBlock->info.rows, pInfo->colIndex, comp);
}
tfree(pCols); tfree(pCols);
tfree(pSchema); tfree(pSchema);
return (pInfo->pDataBlock->info.rows > 0)? pInfo->pDataBlock:NULL; return (pInfo->pDataBlock->info.rows > 0)? pInfo->pDataBlock:NULL;
...@@ -5822,7 +5862,7 @@ static SSDataBlock* doProjectOperation(void* param, bool* newgroup) { ...@@ -5822,7 +5862,7 @@ static SSDataBlock* doProjectOperation(void* param, bool* newgroup) {
publishOperatorProfEvent(pOperator->upstream[0], QUERY_PROF_AFTER_OPERATOR_EXEC); publishOperatorProfEvent(pOperator->upstream[0], QUERY_PROF_AFTER_OPERATOR_EXEC);
if (pBlock == NULL) { if (pBlock == NULL) {
assert(*newgroup == false); //assert(*newgroup == false);
*newgroup = prevVal; *newgroup = prevVal;
setQueryStatus(pRuntimeEnv, QUERY_COMPLETED); setQueryStatus(pRuntimeEnv, QUERY_COMPLETED);
...@@ -6112,7 +6152,7 @@ static SSDataBlock* doSTableIntervalAgg(void* param, bool* newgroup) { ...@@ -6112,7 +6152,7 @@ static SSDataBlock* doSTableIntervalAgg(void* param, bool* newgroup) {
setTagValue(pOperator, pTableQueryInfo->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput); setTagValue(pOperator, pTableQueryInfo->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
setInputDataBlock(pOperator, pIntervalInfo->pCtx, pBlock, pQueryAttr->order.order); setInputDataBlock(pOperator, pIntervalInfo->pCtx, pBlock, pQueryAttr->order.order);
setIntervalQueryRange(pRuntimeEnv, pBlock->info.window.skey); setIntervalQueryRange(pRuntimeEnv, &pBlock->info.window, pBlock->info.tid);
hashIntervalAgg(pOperator, &pTableQueryInfo->resInfo, pBlock, pTableQueryInfo->groupIndex); hashIntervalAgg(pOperator, &pTableQueryInfo->resInfo, pBlock, pTableQueryInfo->groupIndex);
} }
...@@ -6167,7 +6207,8 @@ static SSDataBlock* doAllSTableIntervalAgg(void* param, bool* newgroup) { ...@@ -6167,7 +6207,8 @@ static SSDataBlock* doAllSTableIntervalAgg(void* param, bool* newgroup) {
setTagValue(pOperator, pTableQueryInfo->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput); setTagValue(pOperator, pTableQueryInfo->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
setInputDataBlock(pOperator, pIntervalInfo->pCtx, pBlock, pQueryAttr->order.order); setInputDataBlock(pOperator, pIntervalInfo->pCtx, pBlock, pQueryAttr->order.order);
setIntervalQueryRange(pRuntimeEnv, pBlock->info.window.skey);
setIntervalQueryRange(pRuntimeEnv, &pBlock->info.window, pBlock->info.tid);
hashAllIntervalAgg(pOperator, &pTableQueryInfo->resInfo, pBlock, pTableQueryInfo->groupIndex); hashAllIntervalAgg(pOperator, &pTableQueryInfo->resInfo, pBlock, pTableQueryInfo->groupIndex);
} }
......
...@@ -239,6 +239,9 @@ static int32_t fillResultImpl(SFillInfo* pFillInfo, void** data, int32_t outputR ...@@ -239,6 +239,9 @@ static int32_t fillResultImpl(SFillInfo* pFillInfo, void** data, int32_t outputR
} else { } else {
setNull(output, pCol->col.type, pCol->col.bytes); setNull(output, pCol->col.type, pCol->col.bytes);
} }
if (!FILL_IS_ASC_FILL(pFillInfo)) {
memcpy(*prev + pCol->col.offset, output, pCol->col.bytes);
}
} else { } else {
assignVal(output, (char*)&pCol->fillVal.i, pCol->col.bytes, pCol->col.type); assignVal(output, (char*)&pCol->fillVal.i, pCol->col.bytes, pCol->col.type);
} }
......
...@@ -161,8 +161,8 @@ int32_t tHistogramAdd(SHistogramInfo** pHisto, double val) { ...@@ -161,8 +161,8 @@ int32_t tHistogramAdd(SHistogramInfo** pHisto, double val) {
} }
#if defined(USE_ARRAYLIST) #if defined(USE_ARRAYLIST)
int32_t idx = histoBinarySearch((*pHisto)->elems, (*pHisto)->numOfEntries, val); int32_t idx = histoBinarySearch((*pHisto)->elems, (*pHisto)->numOfEntries, val, (*pHisto)->maxEntries);
assert(idx >= 0 && idx <= (*pHisto)->maxEntries && (*pHisto)->elems != NULL); assert(idx >= 0 && idx < (*pHisto)->maxEntries && (*pHisto)->elems != NULL);
if ((*pHisto)->elems[idx].val == val && idx >= 0) { if ((*pHisto)->elems[idx].val == val && idx >= 0) {
(*pHisto)->elems[idx].num += 1; (*pHisto)->elems[idx].num += 1;
...@@ -359,7 +359,7 @@ int32_t tHistogramAdd(SHistogramInfo** pHisto, double val) { ...@@ -359,7 +359,7 @@ int32_t tHistogramAdd(SHistogramInfo** pHisto, double val) {
return 0; return 0;
} }
int32_t histoBinarySearch(SHistBin* pEntry, int32_t len, double val) { int32_t histoBinarySearch(SHistBin* pEntry, int32_t len, double val, int32_t maxEntries) {
int32_t end = len - 1; int32_t end = len - 1;
int32_t start = 0; int32_t start = 0;
...@@ -377,6 +377,7 @@ int32_t histoBinarySearch(SHistBin* pEntry, int32_t len, double val) { ...@@ -377,6 +377,7 @@ int32_t histoBinarySearch(SHistBin* pEntry, int32_t len, double val) {
} }
int32_t ret = start > end ? start : end; int32_t ret = start > end ? start : end;
if(ret >= maxEntries) ret = maxEntries - 1;
if (ret < 0) { if (ret < 0) {
return 0; return 0;
} else { } else {
...@@ -469,7 +470,7 @@ void tHistogramPrint(SHistogramInfo* pHisto) { ...@@ -469,7 +470,7 @@ void tHistogramPrint(SHistogramInfo* pHisto) {
*/ */
int64_t tHistogramSum(SHistogramInfo* pHisto, double v) { int64_t tHistogramSum(SHistogramInfo* pHisto, double v) {
#if defined(USE_ARRAYLIST) #if defined(USE_ARRAYLIST)
int32_t slotIdx = histoBinarySearch(pHisto->elems, pHisto->numOfEntries, v); int32_t slotIdx = histoBinarySearch(pHisto->elems, pHisto->numOfEntries, v, pHisto->maxEntries);
if (pHisto->elems[slotIdx].val != v) { if (pHisto->elems[slotIdx].val != v) {
slotIdx -= 1; slotIdx -= 1;
......
...@@ -67,10 +67,18 @@ static int32_t setBoundingBox(MinMaxEntry* range, int16_t type, double minval, d ...@@ -67,10 +67,18 @@ static int32_t setBoundingBox(MinMaxEntry* range, int16_t type, double minval, d
if (IS_SIGNED_NUMERIC_TYPE(type)) { if (IS_SIGNED_NUMERIC_TYPE(type)) {
range->i64MinVal = (int64_t) minval; range->i64MinVal = (int64_t) minval;
range->i64MaxVal = (int64_t) maxval; if (maxval > INT64_MAX || (int64_t)maxval == INT64_MIN) {
range->i64MaxVal = INT64_MAX;
} else {
range->i64MaxVal = (int64_t) maxval;
}
} else if (IS_UNSIGNED_NUMERIC_TYPE(type)){ } else if (IS_UNSIGNED_NUMERIC_TYPE(type)){
range->u64MinVal = (uint64_t) minval; range->u64MinVal = (uint64_t) minval;
range->u64MaxVal = (uint64_t) maxval; if ((uint64_t)maxval > UINT64_MAX) {
range->u64MaxVal = UINT64_MAX;
} else {
range->u64MaxVal = (uint64_t) maxval;
}
} else { } else {
range->dMinVal = minval; range->dMinVal = minval;
range->dMaxVal = maxval; range->dMaxVal = maxval;
...@@ -127,8 +135,8 @@ int32_t tBucketIntHash(tMemBucket *pBucket, const void *value) { ...@@ -127,8 +135,8 @@ int32_t tBucketIntHash(tMemBucket *pBucket, const void *value) {
index = (delta % pBucket->numOfSlots); index = (delta % pBucket->numOfSlots);
} else { } else {
double slotSpan = (double)span / pBucket->numOfSlots; double slotSpan = (double)span / pBucket->numOfSlots;
index = (int32_t)((v - pBucket->range.i64MinVal) / slotSpan); index = (int32_t)(((double)v - pBucket->range.i64MinVal) / slotSpan);
if (v == pBucket->range.i64MaxVal) { if (index == pBucket->numOfSlots) {
index -= 1; index -= 1;
} }
} }
......
...@@ -375,6 +375,16 @@ STSBlock* readDataFromDisk(STSBuf* pTSBuf, int32_t order, bool decomp) { ...@@ -375,6 +375,16 @@ STSBlock* readDataFromDisk(STSBuf* pTSBuf, int32_t order, bool decomp) {
sz = fread(pBlock->payload, (size_t)pBlock->compLen, 1, pTSBuf->f); sz = fread(pBlock->payload, (size_t)pBlock->compLen, 1, pTSBuf->f);
if (decomp) { if (decomp) {
if (pBlock->numOfElem * TSDB_KEYSIZE > pTSBuf->tsData.allocSize) {
pTSBuf->tsData.rawBuf = realloc(pTSBuf->tsData.rawBuf, pBlock->numOfElem * TSDB_KEYSIZE);
pTSBuf->tsData.allocSize = pBlock->numOfElem * TSDB_KEYSIZE;
}
if (pBlock->numOfElem * TSDB_KEYSIZE > pTSBuf->bufSize) {
pTSBuf->assistBuf = realloc(pTSBuf->assistBuf, pBlock->numOfElem * TSDB_KEYSIZE);
pTSBuf->bufSize = pBlock->numOfElem * TSDB_KEYSIZE;
}
pTSBuf->tsData.len = pTSBuf->tsData.len =
tsDecompressTimestamp(pBlock->payload, pBlock->compLen, pBlock->numOfElem, pTSBuf->tsData.rawBuf, tsDecompressTimestamp(pBlock->payload, pBlock->compLen, pBlock->numOfElem, pTSBuf->tsData.rawBuf,
pTSBuf->tsData.allocSize, TWO_STAGE_COMP, pTSBuf->assistBuf, pTSBuf->bufSize); pTSBuf->tsData.allocSize, TWO_STAGE_COMP, pTSBuf->assistBuf, pTSBuf->bufSize);
...@@ -471,7 +481,7 @@ void tsBufAppend(STSBuf* pTSBuf, int32_t id, tVariant* tag, const char* pData, i ...@@ -471,7 +481,7 @@ void tsBufAppend(STSBuf* pTSBuf, int32_t id, tVariant* tag, const char* pData, i
// the size of raw data exceeds the size of the default prepared buffer, so // the size of raw data exceeds the size of the default prepared buffer, so
// during getBufBlock, the output buffer needs to be large enough. // during getBufBlock, the output buffer needs to be large enough.
if (ptsData->len >= ptsData->threshold) { if (ptsData->len >= ptsData->threshold - TSDB_KEYSIZE) {
writeDataToDisk(pTSBuf); writeDataToDisk(pTSBuf);
shrinkBuffer(ptsData); shrinkBuffer(ptsData);
} }
...@@ -603,6 +613,10 @@ static void tsBufGetBlock(STSBuf* pTSBuf, int32_t groupIndex, int32_t blockIndex ...@@ -603,6 +613,10 @@ static void tsBufGetBlock(STSBuf* pTSBuf, int32_t groupIndex, int32_t blockIndex
expandBuffer(&pTSBuf->tsData, (int32_t)s); expandBuffer(&pTSBuf->tsData, (int32_t)s);
} }
if (s > pTSBuf->bufSize) {
pTSBuf->assistBuf = realloc(pTSBuf->assistBuf, s);
pTSBuf->bufSize = (int32_t)s;
}
pTSBuf->tsData.len = pTSBuf->tsData.len =
tsDecompressTimestamp(pBlock->payload, pBlock->compLen, pBlock->numOfElem, pTSBuf->tsData.rawBuf, tsDecompressTimestamp(pBlock->payload, pBlock->compLen, pBlock->numOfElem, pTSBuf->tsData.rawBuf,
pTSBuf->tsData.allocSize, TWO_STAGE_COMP, pTSBuf->assistBuf, pTSBuf->bufSize); pTSBuf->tsData.allocSize, TWO_STAGE_COMP, pTSBuf->assistBuf, pTSBuf->bufSize);
......
...@@ -418,46 +418,6 @@ static int64_t getNumOfResultWindowRes(SQueryRuntimeEnv* pRuntimeEnv, SResultRow ...@@ -418,46 +418,6 @@ static int64_t getNumOfResultWindowRes(SQueryRuntimeEnv* pRuntimeEnv, SResultRow
return 0; return 0;
} }
static int32_t tableResultComparFn(const void *pLeft, const void *pRight, void *param) {
int32_t left = *(int32_t *)pLeft;
int32_t right = *(int32_t *)pRight;
SCompSupporter * supporter = (SCompSupporter *)param;
int32_t leftPos = supporter->rowIndex[left];
int32_t rightPos = supporter->rowIndex[right];
/* left source is exhausted */
if (leftPos == -1) {
return 1;
}
/* right source is exhausted*/
if (rightPos == -1) {
return -1;
}
STableQueryInfo** pList = supporter->pTableQueryInfo;
SResultRow* pWindowRes1 = pList[left]->resInfo.pResult[leftPos];
// SResultRow * pWindowRes1 = getResultRow(&(pList[left]->resInfo), leftPos);
TSKEY leftTimestamp = pWindowRes1->win.skey;
// SResultRowInfo *pWindowResInfo2 = &(pList[right]->resInfo);
// SResultRow * pWindowRes2 = getResultRow(pWindowResInfo2, rightPos);
SResultRow* pWindowRes2 = pList[right]->resInfo.pResult[rightPos];
TSKEY rightTimestamp = pWindowRes2->win.skey;
if (leftTimestamp == rightTimestamp) {
return 0;
}
if (supporter->order == TSDB_ORDER_ASC) {
return (leftTimestamp > rightTimestamp)? 1:-1;
} else {
return (leftTimestamp < rightTimestamp)? 1:-1;
}
}
int32_t tsAscOrder(const void* p1, const void* p2) { int32_t tsAscOrder(const void* p1, const void* p2) {
SResultRowCell* pc1 = (SResultRowCell*) p1; SResultRowCell* pc1 = (SResultRowCell*) p1;
SResultRowCell* pc2 = (SResultRowCell*) p2; SResultRowCell* pc2 = (SResultRowCell*) p2;
...@@ -532,102 +492,38 @@ static UNUSED_FUNC int32_t mergeIntoGroupResultImpl(SQueryRuntimeEnv *pRuntimeEn ...@@ -532,102 +492,38 @@ static UNUSED_FUNC int32_t mergeIntoGroupResultImpl(SQueryRuntimeEnv *pRuntimeEn
int32_t* rowCellInfoOffset) { int32_t* rowCellInfoOffset) {
bool ascQuery = QUERY_IS_ASC_QUERY(pRuntimeEnv->pQueryAttr); bool ascQuery = QUERY_IS_ASC_QUERY(pRuntimeEnv->pQueryAttr);
int32_t code = TSDB_CODE_SUCCESS; taosArraySort(pRuntimeEnv->pResultRowArrayList, fn);
}
int32_t *posList = NULL; static int32_t mergeIntoGroupResultImplRv(SQueryRuntimeEnv *pRuntimeEnv, SGroupResInfo* pGroupResInfo, uint64_t groupId, int32_t* rowCellInfoOffset) {
SLoserTreeInfo *pTree = NULL; if (!pGroupResInfo->ordered) {
STableQueryInfo **pTableQueryInfoList = NULL; orderTheResultRows(pRuntimeEnv);
pGroupResInfo->ordered = true;
}
size_t size = taosArrayGetSize(pTableList);
if (pGroupResInfo->pRows == NULL) { if (pGroupResInfo->pRows == NULL) {
pGroupResInfo->pRows = taosArrayInit(100, POINTER_BYTES); pGroupResInfo->pRows = taosArrayInit(100, POINTER_BYTES);
} }
posList = calloc(size, sizeof(int32_t)); size_t len = taosArrayGetSize(pRuntimeEnv->pResultRowArrayList);
pTableQueryInfoList = malloc(POINTER_BYTES * size); for(; pGroupResInfo->position < len; ++pGroupResInfo->position) {
if (pTableQueryInfoList == NULL || posList == NULL || pGroupResInfo->pRows == NULL || pGroupResInfo->pRows == NULL) {
qError("QInfo:%"PRIu64" failed alloc memory", GET_QID(pRuntimeEnv));
code = TSDB_CODE_QRY_OUT_OF_MEMORY;
goto _end;
}
int32_t numOfTables = 0; SResultRowCell* pResultRowCell = taosArrayGet(pRuntimeEnv->pResultRowArrayList, pGroupResInfo->position);
for (int32_t i = 0; i < size; ++i) { if (pResultRowCell->groupId != groupId) {
STableQueryInfo *item = taosArrayGetP(pTableList, i); break;
if (item->resInfo.size > 0) {
pTableQueryInfoList[numOfTables++] = item;
} }
}
// there is no data in current group
// no need to merge results since only one table in each group
if (numOfTables == 0) {
goto _end;
}
SCompSupporter cs = {pTableQueryInfoList, posList, pRuntimeEnv->pQueryAttr->order.order};
int32_t ret = tLoserTreeCreate(&pTree, numOfTables, &cs, tableResultComparFn);
if (ret != TSDB_CODE_SUCCESS) {
code = TSDB_CODE_QRY_OUT_OF_MEMORY;
goto _end;
}
int64_t lastTimestamp = ascQuery? INT64_MIN:INT64_MAX; int64_t num = getNumOfResultWindowRes(pRuntimeEnv, pResultRowCell->pRow, rowCellInfoOffset);
int64_t startt = taosGetTimestampMs();
while (1) {
int32_t tableIndex = pTree->pNode[0].index;
SResultRowInfo *pWindowResInfo = &pTableQueryInfoList[tableIndex]->resInfo;
SResultRow *pWindowRes = getResultRow(pWindowResInfo, cs.rowIndex[tableIndex]);
int64_t num = getNumOfResultWindowRes(pRuntimeEnv, pWindowRes, rowCellInfoOffset);
if (num <= 0) { if (num <= 0) {
cs.rowIndex[tableIndex] += 1; continue;
if (cs.rowIndex[tableIndex] >= pWindowResInfo->size) {
cs.rowIndex[tableIndex] = -1;
if (--numOfTables == 0) { // all input sources are exhausted
break;
}
}
} else {
assert((pWindowRes->win.skey >= lastTimestamp && ascQuery) || (pWindowRes->win.skey <= lastTimestamp && !ascQuery));
if (pWindowRes->win.skey != lastTimestamp) {
taosArrayPush(pGroupResInfo->pRows, &pWindowRes);
pWindowRes->numOfRows = (uint32_t) num;
}
lastTimestamp = pWindowRes->win.skey;
// move to the next row of current entry
if ((++cs.rowIndex[tableIndex]) >= pWindowResInfo->size) {
cs.rowIndex[tableIndex] = -1;
// all input sources are exhausted
if ((--numOfTables) == 0) {
break;
}
}
} }
tLoserTreeAdjust(pTree, tableIndex + pTree->numOfEntries); taosArrayPush(pGroupResInfo->pRows, &pResultRowCell->pRow);
} pResultRowCell->pRow->numOfRows = (uint32_t) num;
int64_t endt = taosGetTimestampMs();
qDebug("QInfo:%"PRIx64" result merge completed for group:%d, elapsed time:%" PRId64 " ms", GET_QID(pRuntimeEnv),
pGroupResInfo->currentGroup, endt - startt);
_end: }
tfree(pTableQueryInfoList);
tfree(posList);
tfree(pTree);
return code; return TSDB_CODE_SUCCESS;
} }
int32_t mergeIntoGroupResult(SGroupResInfo* pGroupResInfo, SQueryRuntimeEnv* pRuntimeEnv, int32_t* offset) { int32_t mergeIntoGroupResult(SGroupResInfo* pGroupResInfo, SQueryRuntimeEnv* pRuntimeEnv, int32_t* offset) {
......
...@@ -98,19 +98,19 @@ TEST(testCase, histogram_binary_search) { ...@@ -98,19 +98,19 @@ TEST(testCase, histogram_binary_search) {
pHisto->elems[i].val = i; pHisto->elems[i].val = i;
} }
int32_t idx = histoBinarySearch(pHisto->elems, pHisto->numOfEntries, 1); int32_t idx = histoBinarySearch(pHisto->elems, pHisto->numOfEntries, 1, pHisto->maxEntries);
assert(idx == 1); assert(idx == 1);
idx = histoBinarySearch(pHisto->elems, pHisto->numOfEntries, 9); idx = histoBinarySearch(pHisto->elems, pHisto->numOfEntries, 9, pHisto->maxEntries);
assert(idx == 9); assert(idx == 9);
idx = histoBinarySearch(pHisto->elems, pHisto->numOfEntries, 20); idx = histoBinarySearch(pHisto->elems, pHisto->numOfEntries, 20, pHisto->maxEntries);
assert(idx == 10); assert(idx == 10);
idx = histoBinarySearch(pHisto->elems, pHisto->numOfEntries, -1); idx = histoBinarySearch(pHisto->elems, pHisto->numOfEntries, -1, pHisto->maxEntries);
assert(idx == 0); assert(idx == 0);
idx = histoBinarySearch(pHisto->elems, pHisto->numOfEntries, 3.9); idx = histoBinarySearch(pHisto->elems, pHisto->numOfEntries, 3.9, pHisto->maxEntries);
assert(idx == 4); assert(idx == 4);
free(pHisto); free(pHisto);
......
...@@ -399,7 +399,8 @@ void rpcSendRequest(void *shandle, const SRpcEpSet *pEpSet, SRpcMsg *pMsg, int64 ...@@ -399,7 +399,8 @@ void rpcSendRequest(void *shandle, const SRpcEpSet *pEpSet, SRpcMsg *pMsg, int64
pContext->oldInUse = pEpSet->inUse; pContext->oldInUse = pEpSet->inUse;
pContext->connType = RPC_CONN_UDPC; pContext->connType = RPC_CONN_UDPC;
if (contLen > tsRpcMaxUdpSize || tsRpcForceTcp ) pContext->connType = RPC_CONN_TCPC;
if (contLen > tsRpcMaxUdpSize || tsRpcForceTcp) pContext->connType = RPC_CONN_TCPC;
// connection type is application specific. // connection type is application specific.
// for TDengine, all the query, show commands shall have TCP connection // for TDengine, all the query, show commands shall have TCP connection
......
...@@ -74,7 +74,7 @@ void tsdbFreeMeta(STsdbMeta* pMeta); ...@@ -74,7 +74,7 @@ void tsdbFreeMeta(STsdbMeta* pMeta);
int tsdbOpenMeta(STsdbRepo* pRepo); int tsdbOpenMeta(STsdbRepo* pRepo);
int tsdbCloseMeta(STsdbRepo* pRepo); int tsdbCloseMeta(STsdbRepo* pRepo);
STable* tsdbGetTableByUid(STsdbMeta* pMeta, uint64_t uid); STable* tsdbGetTableByUid(STsdbMeta* pMeta, uint64_t uid);
STSchema* tsdbGetTableSchemaByVersion(STable* pTable, int16_t _version); STSchema* tsdbGetTableSchemaByVersion(STable* pTable, int16_t _version, int8_t rowType);
int tsdbWLockRepoMeta(STsdbRepo* pRepo); int tsdbWLockRepoMeta(STsdbRepo* pRepo);
int tsdbRLockRepoMeta(STsdbRepo* pRepo); int tsdbRLockRepoMeta(STsdbRepo* pRepo);
int tsdbUnlockRepoMeta(STsdbRepo* pRepo); int tsdbUnlockRepoMeta(STsdbRepo* pRepo);
...@@ -110,8 +110,12 @@ static FORCE_INLINE STSchema* tsdbGetTableSchemaImpl(STable* pTable, bool lock, ...@@ -110,8 +110,12 @@ static FORCE_INLINE STSchema* tsdbGetTableSchemaImpl(STable* pTable, bool lock,
} else { // get the schema with version } else { // get the schema with version
void* ptr = taosArraySearch(pDTable->schema, &_version, tsdbCompareSchemaVersion, TD_EQ); void* ptr = taosArraySearch(pDTable->schema, &_version, tsdbCompareSchemaVersion, TD_EQ);
if (ptr == NULL) { if (ptr == NULL) {
terrno = TSDB_CODE_TDB_IVD_TB_SCHEMA_VERSION; if (rowType == SMEM_ROW_KV) {
goto _exit; ptr = taosArrayGetLast(pDTable->schema);
} else {
terrno = TSDB_CODE_TDB_IVD_TB_SCHEMA_VERSION;
goto _exit;
}
} }
pTSchema = *(STSchema**)ptr; pTSchema = *(STSchema**)ptr;
} }
...@@ -130,7 +134,7 @@ _exit: ...@@ -130,7 +134,7 @@ _exit:
} }
static FORCE_INLINE STSchema* tsdbGetTableSchema(STable* pTable) { static FORCE_INLINE STSchema* tsdbGetTableSchema(STable* pTable) {
return tsdbGetTableSchemaImpl(pTable, false, false, -1); return tsdbGetTableSchemaImpl(pTable, false, false, -1, -1);
} }
static FORCE_INLINE STSchema *tsdbGetTableTagSchema(STable *pTable) { static FORCE_INLINE STSchema *tsdbGetTableTagSchema(STable *pTable) {
......
...@@ -1021,7 +1021,7 @@ static int tsdbCommitToTable(SCommitH *pCommith, int tid) { ...@@ -1021,7 +1021,7 @@ static int tsdbCommitToTable(SCommitH *pCommith, int tid) {
} }
static int tsdbSetCommitTable(SCommitH *pCommith, STable *pTable) { static int tsdbSetCommitTable(SCommitH *pCommith, STable *pTable) {
STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -1); STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -1, -1);
pCommith->pTable = pTable; pCommith->pTable = pTable;
...@@ -1438,7 +1438,8 @@ static void tsdbLoadAndMergeFromCache(SDataCols *pDataCols, int *iter, SCommitIt ...@@ -1438,7 +1438,8 @@ static void tsdbLoadAndMergeFromCache(SDataCols *pDataCols, int *iter, SCommitIt
(*iter)++; (*iter)++;
} else if (key1 > key2) { } else if (key1 > key2) {
if (pSchema == NULL || schemaVersion(pSchema) != memRowVersion(row)) { if (pSchema == NULL || schemaVersion(pSchema) != memRowVersion(row)) {
pSchema = tsdbGetTableSchemaImpl(pCommitIter->pTable, false, false, memRowVersion(row)); pSchema =
tsdbGetTableSchemaImpl(pCommitIter->pTable, false, false, memRowVersion(row), (int8_t)memRowType(row));
ASSERT(pSchema != NULL); ASSERT(pSchema != NULL);
} }
...@@ -1459,7 +1460,8 @@ static void tsdbLoadAndMergeFromCache(SDataCols *pDataCols, int *iter, SCommitIt ...@@ -1459,7 +1460,8 @@ static void tsdbLoadAndMergeFromCache(SDataCols *pDataCols, int *iter, SCommitIt
if (update != TD_ROW_DISCARD_UPDATE) { if (update != TD_ROW_DISCARD_UPDATE) {
//copy mem data //copy mem data
if (pSchema == NULL || schemaVersion(pSchema) != memRowVersion(row)) { if (pSchema == NULL || schemaVersion(pSchema) != memRowVersion(row)) {
pSchema = tsdbGetTableSchemaImpl(pCommitIter->pTable, false, false, memRowVersion(row)); pSchema =
tsdbGetTableSchemaImpl(pCommitIter->pTable, false, false, memRowVersion(row), (int8_t)memRowType(row));
ASSERT(pSchema != NULL); ASSERT(pSchema != NULL);
} }
......
...@@ -431,7 +431,7 @@ static int tsdbCompactMeta(STsdbRepo *pRepo) { ...@@ -431,7 +431,7 @@ static int tsdbCompactMeta(STsdbRepo *pRepo) {
if (pTh->pTable == NULL || pTh->pBlkIdx == NULL) continue; if (pTh->pTable == NULL || pTh->pBlkIdx == NULL) continue;
pSchema = tsdbGetTableSchemaImpl(pTh->pTable, true, true, -1); pSchema = tsdbGetTableSchemaImpl(pTh->pTable, true, true, -1, -1);
taosArrayClear(pComph->aSupBlk); taosArrayClear(pComph->aSupBlk);
if ((tdInitDataCols(pComph->pDataCols, pSchema) < 0) || (tdInitDataCols(pReadh->pDCols[0], pSchema) < 0) || if ((tdInitDataCols(pComph->pDataCols, pSchema) < 0) || (tdInitDataCols(pReadh->pDCols[0], pSchema) < 0) ||
(tdInitDataCols(pReadh->pDCols[1], pSchema) < 0)) { (tdInitDataCols(pReadh->pDCols[1], pSchema) < 0)) {
......
...@@ -624,7 +624,7 @@ static void tsdbStartStream(STsdbRepo *pRepo) { ...@@ -624,7 +624,7 @@ static void tsdbStartStream(STsdbRepo *pRepo) {
STable *pTable = pMeta->tables[i]; STable *pTable = pMeta->tables[i];
if (pTable && pTable->type == TSDB_STREAM_TABLE) { if (pTable && pTable->type == TSDB_STREAM_TABLE) {
pTable->cqhandle = (*pRepo->appH.cqCreateFunc)(pRepo->appH.cqH, TABLE_UID(pTable), TABLE_TID(pTable), TABLE_NAME(pTable)->data, pTable->sql, pTable->cqhandle = (*pRepo->appH.cqCreateFunc)(pRepo->appH.cqH, TABLE_UID(pTable), TABLE_TID(pTable), TABLE_NAME(pTable)->data, pTable->sql,
tsdbGetTableSchemaImpl(pTable, false, false, -1), 0); tsdbGetTableSchemaImpl(pTable, false, false, -1, -1), 0);
} }
} }
} }
......
...@@ -587,7 +587,7 @@ static int tsdbAdjustMemMaxTables(SMemTable *pMemTable, int maxTables) { ...@@ -587,7 +587,7 @@ static int tsdbAdjustMemMaxTables(SMemTable *pMemTable, int maxTables) {
static int tsdbAppendTableRowToCols(STable *pTable, SDataCols *pCols, STSchema **ppSchema, SMemRow row) { static int tsdbAppendTableRowToCols(STable *pTable, SDataCols *pCols, STSchema **ppSchema, SMemRow row) {
if (pCols) { if (pCols) {
if (*ppSchema == NULL || schemaVersion(*ppSchema) != memRowVersion(row)) { if (*ppSchema == NULL || schemaVersion(*ppSchema) != memRowVersion(row)) {
*ppSchema = tsdbGetTableSchemaImpl(pTable, false, false, memRowVersion(row)); *ppSchema = tsdbGetTableSchemaImpl(pTable, false, false, memRowVersion(row), (int8_t)memRowType(row));
if (*ppSchema == NULL) { if (*ppSchema == NULL) {
ASSERT(false); ASSERT(false);
return -1; return -1;
...@@ -735,7 +735,7 @@ static SMemRow tsdbInsertDupKeyMerge(SMemRow row1, SMemRow row2, STsdbRepo* pRep ...@@ -735,7 +735,7 @@ static SMemRow tsdbInsertDupKeyMerge(SMemRow row1, SMemRow row2, STsdbRepo* pRep
if(pSchema2 != NULL && schemaVersion(pSchema2) == dv1) { if(pSchema2 != NULL && schemaVersion(pSchema2) == dv1) {
*ppSchema1 = pSchema2; *ppSchema1 = pSchema2;
} else { } else {
*ppSchema1 = tsdbGetTableSchemaImpl(pTable, false, false, memRowVersion(row1)); *ppSchema1 = tsdbGetTableSchemaImpl(pTable, false, false, memRowVersion(row1), (int8_t)memRowType(row1));
} }
pSchema1 = *ppSchema1; pSchema1 = *ppSchema1;
} }
...@@ -744,7 +744,7 @@ static SMemRow tsdbInsertDupKeyMerge(SMemRow row1, SMemRow row2, STsdbRepo* pRep ...@@ -744,7 +744,7 @@ static SMemRow tsdbInsertDupKeyMerge(SMemRow row1, SMemRow row2, STsdbRepo* pRep
if(schemaVersion(pSchema1) == dv2) { if(schemaVersion(pSchema1) == dv2) {
pSchema2 = pSchema1; pSchema2 = pSchema1;
} else { } else {
*ppSchema2 = tsdbGetTableSchemaImpl(pTable, false, false, memRowVersion(row2)); *ppSchema2 = tsdbGetTableSchemaImpl(pTable, false, false, memRowVersion(row2), (int8_t)memRowType(row2));
pSchema2 = *ppSchema2; pSchema2 = *ppSchema2;
} }
} }
...@@ -852,7 +852,7 @@ static int tsdbInsertDataToTable(STsdbRepo* pRepo, SSubmitBlk* pBlock, int32_t * ...@@ -852,7 +852,7 @@ static int tsdbInsertDataToTable(STsdbRepo* pRepo, SSubmitBlk* pBlock, int32_t *
} }
} }
STSchema *pSchema = tsdbGetTableSchemaByVersion(pTable, pBlock->sversion); STSchema *pSchema = tsdbGetTableSchemaByVersion(pTable, pBlock->sversion, -1);
pRepo->stat.pointsWritten += points * schemaNCols(pSchema); pRepo->stat.pointsWritten += points * schemaNCols(pSchema);
pRepo->stat.totalStorage += points * schemaVLen(pSchema); pRepo->stat.totalStorage += points * schemaVLen(pSchema);
...@@ -899,7 +899,7 @@ static int tsdbGetSubmitMsgNext(SSubmitMsgIter *pIter, SSubmitBlk **pPBlock) { ...@@ -899,7 +899,7 @@ static int tsdbGetSubmitMsgNext(SSubmitMsgIter *pIter, SSubmitBlk **pPBlock) {
static int tsdbCheckTableSchema(STsdbRepo *pRepo, SSubmitBlk *pBlock, STable *pTable) { static int tsdbCheckTableSchema(STsdbRepo *pRepo, SSubmitBlk *pBlock, STable *pTable) {
ASSERT(pTable != NULL); ASSERT(pTable != NULL);
STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -1); STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -1, -1);
int sversion = schemaVersion(pSchema); int sversion = schemaVersion(pSchema);
if (pBlock->sversion == sversion) { if (pBlock->sversion == sversion) {
...@@ -956,7 +956,7 @@ static int tsdbCheckTableSchema(STsdbRepo *pRepo, SSubmitBlk *pBlock, STable *pT ...@@ -956,7 +956,7 @@ static int tsdbCheckTableSchema(STsdbRepo *pRepo, SSubmitBlk *pBlock, STable *pT
} }
} else { } else {
ASSERT(pBlock->sversion >= 0); ASSERT(pBlock->sversion >= 0);
if (tsdbGetTableSchemaImpl(pTable, false, false, pBlock->sversion) == NULL) { if (tsdbGetTableSchemaImpl(pTable, false, false, pBlock->sversion, -1) == NULL) {
tsdbError("vgId:%d invalid submit schema version %d to table %s tid %d from client", REPO_ID(pRepo), tsdbError("vgId:%d invalid submit schema version %d to table %s tid %d from client", REPO_ID(pRepo),
pBlock->sversion, TABLE_CHAR_NAME(pTable), TABLE_TID(pTable)); pBlock->sversion, TABLE_CHAR_NAME(pTable), TABLE_TID(pTable));
terrno = TSDB_CODE_TDB_IVD_TB_SCHEMA_VERSION; terrno = TSDB_CODE_TDB_IVD_TB_SCHEMA_VERSION;
...@@ -977,7 +977,7 @@ static void updateTableLatestColumn(STsdbRepo *pRepo, STable *pTable, SMemRow ro ...@@ -977,7 +977,7 @@ static void updateTableLatestColumn(STsdbRepo *pRepo, STable *pTable, SMemRow ro
return; return;
} }
pSchema = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row)); pSchema = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row), (int8_t)memRowType(row));
if (pSchema == NULL) { if (pSchema == NULL) {
return; return;
} }
......
...@@ -545,8 +545,8 @@ STable *tsdbGetTableByUid(STsdbMeta *pMeta, uint64_t uid) { ...@@ -545,8 +545,8 @@ STable *tsdbGetTableByUid(STsdbMeta *pMeta, uint64_t uid) {
return *(STable **)ptr; return *(STable **)ptr;
} }
STSchema *tsdbGetTableSchemaByVersion(STable *pTable, int16_t _version) { STSchema *tsdbGetTableSchemaByVersion(STable *pTable, int16_t _version, int8_t rowType) {
return tsdbGetTableSchemaImpl(pTable, true, false, _version); return tsdbGetTableSchemaImpl(pTable, true, false, _version, rowType);
} }
int tsdbWLockRepoMeta(STsdbRepo *pRepo) { int tsdbWLockRepoMeta(STsdbRepo *pRepo) {
...@@ -664,7 +664,7 @@ int tsdbInitColIdCacheWithSchema(STable* pTable, STSchema* pSchema) { ...@@ -664,7 +664,7 @@ int tsdbInitColIdCacheWithSchema(STable* pTable, STSchema* pSchema) {
} }
STSchema* tsdbGetTableLatestSchema(STable *pTable) { STSchema* tsdbGetTableLatestSchema(STable *pTable) {
return tsdbGetTableSchemaByVersion(pTable, -1); return tsdbGetTableSchemaByVersion(pTable, -1, -1);
} }
int tsdbUpdateLastColSchema(STable *pTable, STSchema *pNewSchema) { int tsdbUpdateLastColSchema(STable *pTable, STSchema *pNewSchema) {
...@@ -969,7 +969,7 @@ static int tsdbAddTableToMeta(STsdbRepo *pRepo, STable *pTable, bool addIdx, boo ...@@ -969,7 +969,7 @@ static int tsdbAddTableToMeta(STsdbRepo *pRepo, STable *pTable, bool addIdx, boo
} }
if (TABLE_TYPE(pTable) != TSDB_CHILD_TABLE) { if (TABLE_TYPE(pTable) != TSDB_CHILD_TABLE) {
STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -1); STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -1, -1);
if (schemaNCols(pSchema) > pMeta->maxCols) pMeta->maxCols = schemaNCols(pSchema); if (schemaNCols(pSchema) > pMeta->maxCols) pMeta->maxCols = schemaNCols(pSchema);
if (schemaTLen(pSchema) > pMeta->maxRowBytes) pMeta->maxRowBytes = schemaTLen(pSchema); if (schemaTLen(pSchema) > pMeta->maxRowBytes) pMeta->maxRowBytes = schemaTLen(pSchema);
} }
...@@ -977,7 +977,7 @@ static int tsdbAddTableToMeta(STsdbRepo *pRepo, STable *pTable, bool addIdx, boo ...@@ -977,7 +977,7 @@ static int tsdbAddTableToMeta(STsdbRepo *pRepo, STable *pTable, bool addIdx, boo
if (lock && tsdbUnlockRepoMeta(pRepo) < 0) return -1; if (lock && tsdbUnlockRepoMeta(pRepo) < 0) return -1;
if (TABLE_TYPE(pTable) == TSDB_STREAM_TABLE && addIdx) { if (TABLE_TYPE(pTable) == TSDB_STREAM_TABLE && addIdx) {
pTable->cqhandle = (*pRepo->appH.cqCreateFunc)(pRepo->appH.cqH, TABLE_UID(pTable), TABLE_TID(pTable), TABLE_NAME(pTable)->data, pTable->sql, pTable->cqhandle = (*pRepo->appH.cqCreateFunc)(pRepo->appH.cqH, TABLE_UID(pTable), TABLE_TID(pTable), TABLE_NAME(pTable)->data, pTable->sql,
tsdbGetTableSchemaImpl(pTable, false, false, -1), 1); tsdbGetTableSchemaImpl(pTable, false, false, -1, -1), 1);
} }
tsdbDebug("vgId:%d table %s tid %d uid %" PRIu64 " is added to meta", REPO_ID(pRepo), TABLE_CHAR_NAME(pTable), tsdbDebug("vgId:%d table %s tid %d uid %" PRIu64 " is added to meta", REPO_ID(pRepo), TABLE_CHAR_NAME(pTable),
...@@ -996,7 +996,7 @@ static void tsdbRemoveTableFromMeta(STsdbRepo *pRepo, STable *pTable, bool rmFro ...@@ -996,7 +996,7 @@ static void tsdbRemoveTableFromMeta(STsdbRepo *pRepo, STable *pTable, bool rmFro
SListNode *pNode = NULL; SListNode *pNode = NULL;
STable * tTable = NULL; STable * tTable = NULL;
STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -1); STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -1, -1);
int maxCols = schemaNCols(pSchema); int maxCols = schemaNCols(pSchema);
int maxRowBytes = schemaTLen(pSchema); int maxRowBytes = schemaTLen(pSchema);
...@@ -1030,7 +1030,7 @@ static void tsdbRemoveTableFromMeta(STsdbRepo *pRepo, STable *pTable, bool rmFro ...@@ -1030,7 +1030,7 @@ static void tsdbRemoveTableFromMeta(STsdbRepo *pRepo, STable *pTable, bool rmFro
for (int i = 0; i < pMeta->maxTables; i++) { for (int i = 0; i < pMeta->maxTables; i++) {
STable *_pTable = pMeta->tables[i]; STable *_pTable = pMeta->tables[i];
if (_pTable != NULL) { if (_pTable != NULL) {
pSchema = tsdbGetTableSchemaImpl(_pTable, false, false, -1); pSchema = tsdbGetTableSchemaImpl(_pTable, false, false, -1, -1);
maxCols = MAX(maxCols, schemaNCols(pSchema)); maxCols = MAX(maxCols, schemaNCols(pSchema));
maxRowBytes = MAX(maxRowBytes, schemaTLen(pSchema)); maxRowBytes = MAX(maxRowBytes, schemaTLen(pSchema));
} }
......
...@@ -655,55 +655,8 @@ SArray* tsdbGetQueriedTableList(TsdbQueryHandleT *pHandle) { ...@@ -655,55 +655,8 @@ SArray* tsdbGetQueriedTableList(TsdbQueryHandleT *pHandle) {
return res; return res;
} }
// leave only one table for each group
static STableGroupInfo* trimTableGroup(STimeWindow* window, STableGroupInfo* pGroupList) {
assert(pGroupList);
size_t numOfGroup = taosArrayGetSize(pGroupList->pGroupList);
STableGroupInfo* pNew = calloc(1, sizeof(STableGroupInfo));
pNew->pGroupList = taosArrayInit(numOfGroup, POINTER_BYTES);
for(int32_t i = 0; i < numOfGroup; ++i) {
SArray* oneGroup = taosArrayGetP(pGroupList->pGroupList, i);
size_t numOfTables = taosArrayGetSize(oneGroup);
SArray* px = taosArrayInit(4, sizeof(STableKeyInfo));
for (int32_t j = 0; j < numOfTables; ++j) {
STableKeyInfo* pInfo = (STableKeyInfo*)taosArrayGet(oneGroup, j);
if (window->skey <= pInfo->lastKey && ((STable*)pInfo->pTable)->lastKey != TSKEY_INITIAL_VAL) {
taosArrayPush(px, pInfo);
pNew->numOfTables += 1;
break;
}
}
// there are no data in this group
if (taosArrayGetSize(px) == 0) {
taosArrayDestroy(px);
} else {
taosArrayPush(pNew->pGroupList, &px);
}
}
return pNew;
}
TsdbQueryHandleT tsdbQueryRowsInExternalWindow(STsdbRepo *tsdb, STsdbQueryCond* pCond, STableGroupInfo *groupList, uint64_t qId, SMemRef* pRef) { TsdbQueryHandleT tsdbQueryRowsInExternalWindow(STsdbRepo *tsdb, STsdbQueryCond* pCond, STableGroupInfo *groupList, uint64_t qId, SMemRef* pRef) {
STableGroupInfo* pNew = trimTableGroup(&pCond->twindow, groupList); STsdbQueryHandle *pQueryHandle = (STsdbQueryHandle*) tsdbQueryTables(tsdb, pCond, groupList, qId, pRef);
if (pNew->numOfTables == 0) {
tsdbDebug("update query time range to invalidate time window");
assert(taosArrayGetSize(pNew->pGroupList) == 0);
bool asc = ASCENDING_TRAVERSE(pCond->order);
if (asc) {
pCond->twindow.ekey = pCond->twindow.skey - 1;
} else {
pCond->twindow.skey = pCond->twindow.ekey - 1;
}
}
STsdbQueryHandle *pQueryHandle = (STsdbQueryHandle*) tsdbQueryTables(tsdb, pCond, pNew, qId, pRef);
pQueryHandle->loadExternalRow = true; pQueryHandle->loadExternalRow = true;
pQueryHandle->currentLoadExternalRows = true; pQueryHandle->currentLoadExternalRows = true;
...@@ -859,13 +812,25 @@ static TSKEY extractFirstTraverseKey(STableCheckInfo* pCheckInfo, int32_t order, ...@@ -859,13 +812,25 @@ static TSKEY extractFirstTraverseKey(STableCheckInfo* pCheckInfo, int32_t order,
pCheckInfo->chosen = CHECKINFO_CHOSEN_BOTH; pCheckInfo->chosen = CHECKINFO_CHOSEN_BOTH;
} }
return r1; return r1;
} else if (r1 < r2 && ASCENDING_TRAVERSE(order)) { } else {
pCheckInfo->chosen = CHECKINFO_CHOSEN_MEM; if (ASCENDING_TRAVERSE(order)) {
return r1; if (r1 < r2) {
} pCheckInfo->chosen = CHECKINFO_CHOSEN_MEM;
else { return r1;
pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM; } else {
return r2; pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM;
return r2;
}
} else {
if (r1 < r2) {
pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM;
return r2;
} else {
pCheckInfo->chosen = CHECKINFO_CHOSEN_MEM;
return r1;
}
}
} }
} }
...@@ -930,7 +895,7 @@ static SMemRow getSMemRowInTableMem(STableCheckInfo* pCheckInfo, int32_t order, ...@@ -930,7 +895,7 @@ static SMemRow getSMemRowInTableMem(STableCheckInfo* pCheckInfo, int32_t order,
pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM; pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM;
return rimem; return rimem;
} else { } else {
pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM; pCheckInfo->chosen = CHECKINFO_CHOSEN_MEM;
return rmem; return rmem;
} }
} }
...@@ -1329,11 +1294,11 @@ static int32_t handleDataMergeIfNeeded(STsdbQueryHandle* pQueryHandle, SBlock* p ...@@ -1329,11 +1294,11 @@ static int32_t handleDataMergeIfNeeded(STsdbQueryHandle* pQueryHandle, SBlock* p
assert(cur->blockCompleted); assert(cur->blockCompleted);
if (cur->rows == binfo.rows) { if (cur->rows == binfo.rows) {
tsdbDebug("%p whole file block qualified, brange:%"PRId64"-%"PRId64", rows:%d, lastKey:%"PRId64", %"PRIx64, tsdbDebug("%p whole file block qualified, brange:%"PRId64"-%"PRId64", rows:%d, lastKey:%"PRId64", tid:%d, %"PRIx64,
pQueryHandle, cur->win.skey, cur->win.ekey, cur->rows, cur->lastKey, pQueryHandle->qId); pQueryHandle, cur->win.skey, cur->win.ekey, cur->rows, cur->lastKey, binfo.tid, pQueryHandle->qId);
} else { } else {
tsdbDebug("%p create data block from remain file block, brange:%"PRId64"-%"PRId64", rows:%d, total:%d, lastKey:%"PRId64", %"PRIx64, tsdbDebug("%p create data block from remain file block, brange:%"PRId64"-%"PRId64", rows:%d, total:%d, lastKey:%"PRId64", tid:%d, %"PRIx64,
pQueryHandle, cur->win.skey, cur->win.ekey, cur->rows, binfo.rows, cur->lastKey, pQueryHandle->qId); pQueryHandle, cur->win.skey, cur->win.ekey, cur->rows, binfo.rows, cur->lastKey, binfo.tid, pQueryHandle->qId);
} }
} }
...@@ -1572,7 +1537,7 @@ static void mergeTwoRowFromMem(STsdbQueryHandle* pQueryHandle, int32_t capacity, ...@@ -1572,7 +1537,7 @@ static void mergeTwoRowFromMem(STsdbQueryHandle* pQueryHandle, int32_t capacity,
int32_t numOfColsOfRow1 = 0; int32_t numOfColsOfRow1 = 0;
if (pSchema1 == NULL) { if (pSchema1 == NULL) {
pSchema1 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row1)); pSchema1 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row1), (int8_t)memRowType(row1));
} }
if(isRow1DataRow) { if(isRow1DataRow) {
numOfColsOfRow1 = schemaNCols(pSchema1); numOfColsOfRow1 = schemaNCols(pSchema1);
...@@ -1584,7 +1549,7 @@ static void mergeTwoRowFromMem(STsdbQueryHandle* pQueryHandle, int32_t capacity, ...@@ -1584,7 +1549,7 @@ static void mergeTwoRowFromMem(STsdbQueryHandle* pQueryHandle, int32_t capacity,
if(row2) { if(row2) {
isRow2DataRow = isDataRow(row2); isRow2DataRow = isDataRow(row2);
if (pSchema2 == NULL) { if (pSchema2 == NULL) {
pSchema2 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row2)); pSchema2 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row2), (int8_t)memRowType(row2));
} }
if(isRow2DataRow) { if(isRow2DataRow) {
numOfColsOfRow2 = schemaNCols(pSchema2); numOfColsOfRow2 = schemaNCols(pSchema2);
...@@ -1951,11 +1916,11 @@ static void doMergeTwoLevelData(STsdbQueryHandle* pQueryHandle, STableCheckInfo* ...@@ -1951,11 +1916,11 @@ static void doMergeTwoLevelData(STsdbQueryHandle* pQueryHandle, STableCheckInfo*
if ((key < tsArray[pos] && ASCENDING_TRAVERSE(pQueryHandle->order)) || if ((key < tsArray[pos] && ASCENDING_TRAVERSE(pQueryHandle->order)) ||
(key > tsArray[pos] && !ASCENDING_TRAVERSE(pQueryHandle->order))) { (key > tsArray[pos] && !ASCENDING_TRAVERSE(pQueryHandle->order))) {
if (rv1 != memRowVersion(row1)) { if (rv1 != memRowVersion(row1)) {
pSchema1 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row1)); pSchema1 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row1), (int8_t)memRowType(row1));
rv1 = memRowVersion(row1); rv1 = memRowVersion(row1);
} }
if(row2 && rv2 != memRowVersion(row2)) { if(row2 && rv2 != memRowVersion(row2)) {
pSchema2 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row2)); pSchema2 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row2), (int8_t)memRowType(row2));
rv2 = memRowVersion(row2); rv2 = memRowVersion(row2);
} }
...@@ -1976,11 +1941,11 @@ static void doMergeTwoLevelData(STsdbQueryHandle* pQueryHandle, STableCheckInfo* ...@@ -1976,11 +1941,11 @@ static void doMergeTwoLevelData(STsdbQueryHandle* pQueryHandle, STableCheckInfo*
doCopyRowsFromFileBlock(pQueryHandle, pQueryHandle->outputCapacity, numOfRows, pos, pos); doCopyRowsFromFileBlock(pQueryHandle, pQueryHandle->outputCapacity, numOfRows, pos, pos);
} }
if (rv1 != memRowVersion(row1)) { if (rv1 != memRowVersion(row1)) {
pSchema1 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row1)); pSchema1 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row1), (int8_t)memRowType(row1));
rv1 = memRowVersion(row1); rv1 = memRowVersion(row1);
} }
if(row2 && rv2 != memRowVersion(row2)) { if(row2 && rv2 != memRowVersion(row2)) {
pSchema2 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row2)); pSchema2 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row2), (int8_t)memRowType(row2));
rv2 = memRowVersion(row2); rv2 = memRowVersion(row2);
} }
...@@ -2644,7 +2609,7 @@ static int tsdbReadRowsFromCache(STableCheckInfo* pCheckInfo, TSKEY maxKey, int ...@@ -2644,7 +2609,7 @@ static int tsdbReadRowsFromCache(STableCheckInfo* pCheckInfo, TSKEY maxKey, int
win->ekey = key; win->ekey = key;
if (rv != memRowVersion(row)) { if (rv != memRowVersion(row)) {
pSchema = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row)); pSchema = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row), (int8_t)memRowType(row));
rv = memRowVersion(row); rv = memRowVersion(row);
} }
mergeTwoRowFromMem(pQueryHandle, maxRowsToRead, numOfRows, row, NULL, numOfCols, pTable, pSchema, NULL, true); mergeTwoRowFromMem(pQueryHandle, maxRowsToRead, numOfRows, row, NULL, numOfCols, pTable, pSchema, NULL, true);
......
...@@ -153,7 +153,7 @@ int tsdbLoadBlockIdx(SReadH *pReadh) { ...@@ -153,7 +153,7 @@ int tsdbLoadBlockIdx(SReadH *pReadh) {
} }
int tsdbSetReadTable(SReadH *pReadh, STable *pTable) { int tsdbSetReadTable(SReadH *pReadh, STable *pTable) {
STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -1); STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -1, -1);
pReadh->pTable = pTable; pReadh->pTable = pTable;
......
...@@ -36,7 +36,7 @@ typedef struct SHashNode { ...@@ -36,7 +36,7 @@ typedef struct SHashNode {
uint32_t dataLen; // length of data uint32_t dataLen; // length of data
uint32_t keyLen; // length of the key uint32_t keyLen; // length of the key
int8_t removed; // flag to indicate removed int8_t removed; // flag to indicate removed
int8_t count; // reference count int32_t count; // reference count
char data[]; char data[];
} SHashNode; } SHashNode;
......
...@@ -43,6 +43,7 @@ void taosStringBuilderAppendStringLen(SStringBuilder* sb, const char* str, size_ ...@@ -43,6 +43,7 @@ void taosStringBuilderAppendStringLen(SStringBuilder* sb, const char* str, size_
void taosStringBuilderAppendString(SStringBuilder* sb, const char* str); void taosStringBuilderAppendString(SStringBuilder* sb, const char* str);
void taosStringBuilderAppendNull(SStringBuilder* sb); void taosStringBuilderAppendNull(SStringBuilder* sb);
void taosStringBuilderAppendInteger(SStringBuilder* sb, int64_t v); void taosStringBuilderAppendInteger(SStringBuilder* sb, int64_t v);
void taosStringBuilderAppendUnsignedInteger(SStringBuilder* sb, uint64_t v);
void taosStringBuilderAppendDouble(SStringBuilder* sb, double v); void taosStringBuilderAppendDouble(SStringBuilder* sb, double v);
#ifdef __cplusplus #ifdef __cplusplus
......
...@@ -119,7 +119,7 @@ static SHashNode *doCreateHashNode(const void *key, size_t keyLen, const void *p ...@@ -119,7 +119,7 @@ static SHashNode *doCreateHashNode(const void *key, size_t keyLen, const void *p
static FORCE_INLINE SHashNode *doUpdateHashNode(SHashObj *pHashObj, SHashEntry* pe, SHashNode* prev, SHashNode *pNode, SHashNode *pNewNode) { static FORCE_INLINE SHashNode *doUpdateHashNode(SHashObj *pHashObj, SHashEntry* pe, SHashNode* prev, SHashNode *pNode, SHashNode *pNewNode) {
assert(pNode->keyLen == pNewNode->keyLen); assert(pNode->keyLen == pNewNode->keyLen);
pNode->count--; atomic_sub_fetch_32(&pNode->count, 1);
if (prev != NULL) { if (prev != NULL) {
prev->next = pNewNode; prev->next = pNewNode;
} else { } else {
...@@ -459,7 +459,7 @@ int32_t taosHashRemoveWithData(SHashObj *pHashObj, const void *key, size_t keyLe ...@@ -459,7 +459,7 @@ int32_t taosHashRemoveWithData(SHashObj *pHashObj, const void *key, size_t keyLe
if (pNode) { if (pNode) {
code = 0; // it is found code = 0; // it is found
pNode->count--; atomic_sub_fetch_32(&pNode->count, 1);
pNode->removed = 1; pNode->removed = 1;
if (pNode->count <= 0) { if (pNode->count <= 0) {
if (prevNode) { if (prevNode) {
...@@ -820,7 +820,7 @@ static void *taosHashReleaseNode(SHashObj *pHashObj, void *p, int *slot) { ...@@ -820,7 +820,7 @@ static void *taosHashReleaseNode(SHashObj *pHashObj, void *p, int *slot) {
pNode = pNode->next; pNode = pNode->next;
} }
pOld->count--; atomic_sub_fetch_32(&pOld->count, 1);
if (pOld->count <=0) { if (pOld->count <=0) {
if (prevNode) { if (prevNode) {
prevNode->next = pOld->next; prevNode->next = pOld->next;
...@@ -886,7 +886,7 @@ void *taosHashIterate(SHashObj *pHashObj, void *p) { ...@@ -886,7 +886,7 @@ void *taosHashIterate(SHashObj *pHashObj, void *p) {
if (pNode) { if (pNode) {
SHashEntry *pe = pHashObj->hashList[slot]; SHashEntry *pe = pHashObj->hashList[slot];
pNode->count++; atomic_add_fetch_32(&pNode->count, 1);
data = GET_HASH_NODE_DATA(pNode); data = GET_HASH_NODE_DATA(pNode);
if (pHashObj->type == HASH_ENTRY_LOCK) { if (pHashObj->type == HASH_ENTRY_LOCK) {
taosWUnLockLatch(&pe->latch); taosWUnLockLatch(&pe->latch);
......
...@@ -442,7 +442,7 @@ static int taosDecRefCount(int rsetId, int64_t rid, int remove) { ...@@ -442,7 +442,7 @@ static int taosDecRefCount(int rsetId, int64_t rid, int remove) {
} }
released = 1; released = 1;
} else { } else {
uTrace("rsetId:%d p:%p rid:%" PRId64 " is released", rsetId, pNode->p, rid); uTrace("rsetId:%d p:%p rid:%" PRId64 " is released, count:%d", rsetId, pNode->p, rid, pNode->count);
} }
} else { } else {
uTrace("rsetId:%d rid:%" PRId64 " is not there, failed to release/remove", rsetId, rid); uTrace("rsetId:%d rid:%" PRId64 " is not there, failed to release/remove", rsetId, rid);
......
...@@ -73,6 +73,12 @@ void taosStringBuilderAppendInteger(SStringBuilder* sb, int64_t v) { ...@@ -73,6 +73,12 @@ void taosStringBuilderAppendInteger(SStringBuilder* sb, int64_t v) {
taosStringBuilderAppendStringLen(sb, buf, MIN(len, sizeof(buf))); taosStringBuilderAppendStringLen(sb, buf, MIN(len, sizeof(buf)));
} }
void taosStringBuilderAppendUnsignedInteger(SStringBuilder* sb, uint64_t v) {
char buf[64];
size_t len = snprintf(buf, sizeof(buf), "%" PRId64, v);
taosStringBuilderAppendStringLen(sb, buf, MIN(len, sizeof(buf)));
}
void taosStringBuilderAppendDouble(SStringBuilder* sb, double v) { void taosStringBuilderAppendDouble(SStringBuilder* sb, double v) {
char buf[512]; char buf[512];
size_t len = snprintf(buf, sizeof(buf), "%.9lf", v); size_t len = snprintf(buf, sizeof(buf), "%.9lf", v);
......
...@@ -142,6 +142,7 @@ static SKeyword keywordTable[] = { ...@@ -142,6 +142,7 @@ static SKeyword keywordTable[] = {
{"FROM", TK_FROM}, {"FROM", TK_FROM},
{"VARIABLE", TK_VARIABLE}, {"VARIABLE", TK_VARIABLE},
{"INTERVAL", TK_INTERVAL}, {"INTERVAL", TK_INTERVAL},
{"EVERY", TK_EVERY},
{"SESSION", TK_SESSION}, {"SESSION", TK_SESSION},
{"STATE_WINDOW", TK_STATE_WINDOW}, {"STATE_WINDOW", TK_STATE_WINDOW},
{"FILL", TK_FILL}, {"FILL", TK_FILL},
...@@ -622,7 +623,7 @@ SStrToken tStrGetToken(char* str, int32_t* i, bool isPrevOptr) { ...@@ -622,7 +623,7 @@ SStrToken tStrGetToken(char* str, int32_t* i, bool isPrevOptr) {
int32_t numOfComma = 0; int32_t numOfComma = 0;
char t = str[*i]; char t = str[*i];
while (t == ' ' || t == '\n' || t == '\r' || t == '\t' || t == '\f' || t == ',') { while (isspace(t) || t == ',') {
if (t == ',' && (++numOfComma > 1)) { // comma only allowed once if (t == ',' && (++numOfComma > 1)) { // comma only allowed once
t0.n = 0; t0.n = 0;
return t0; return t0;
......
...@@ -289,6 +289,13 @@ static int32_t vnodeWriteToWQueueImp(SVWriteMsg *pWrite) { ...@@ -289,6 +289,13 @@ static int32_t vnodeWriteToWQueueImp(SVWriteMsg *pWrite) {
int64_t queuedSize = atomic_add_fetch_64(&pVnode->queuedWMsgSize, pWrite->walHead.len); int64_t queuedSize = atomic_add_fetch_64(&pVnode->queuedWMsgSize, pWrite->walHead.len);
if (queued > MAX_QUEUED_MSG_NUM || queuedSize > MAX_QUEUED_MSG_SIZE) { if (queued > MAX_QUEUED_MSG_NUM || queuedSize > MAX_QUEUED_MSG_SIZE) {
if (pWrite->qtype == TAOS_QTYPE_FWD) {
queued = atomic_sub_fetch_32(&pVnode->queuedWMsg, 1);
queuedSize = atomic_sub_fetch_64(&pVnode->queuedWMsgSize, pWrite->walHead.len);
return -1;
}
int32_t ms = (queued / MAX_QUEUED_MSG_NUM) * 10 + 3; int32_t ms = (queued / MAX_QUEUED_MSG_NUM) * 10 + 3;
if (ms > 100) ms = 100; if (ms > 100) ms = 100;
vDebug("vgId:%d, too many msg:%d in vwqueue, flow control %dms", pVnode->vgId, queued, ms); vDebug("vgId:%d, too many msg:%d in vwqueue, flow control %dms", pVnode->vgId, queued, ms);
......
此差异已折叠。
...@@ -20,9 +20,9 @@ ...@@ -20,9 +20,9 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include <sys/time.h> #include <sys/time.h>
#include <unistd.h> #include <unistd.h>
#include <string.h>
#include <taos.h> #include <taos.h>
...@@ -33,14 +33,14 @@ int tablesSelectProcessed = 0; ...@@ -33,14 +33,14 @@ int tablesSelectProcessed = 0;
int64_t st, et; int64_t st, et;
typedef struct { typedef struct {
int id; int id;
TAOS *taos; TAOS * taos;
char name[16]; char name[16];
time_t timeStamp; time_t timeStamp;
int value; int value;
int rowsInserted; int rowsInserted;
int rowsTried; int rowsTried;
int rowsRetrieved; int rowsRetrieved;
} STable; } STable;
void taos_insert_call_back(void *param, TAOS_RES *tres, int code); void taos_insert_call_back(void *param, TAOS_RES *tres, int code);
...@@ -48,7 +48,7 @@ void taos_select_call_back(void *param, TAOS_RES *tres, int code); ...@@ -48,7 +48,7 @@ void taos_select_call_back(void *param, TAOS_RES *tres, int code);
void taos_error(TAOS *taos); void taos_error(TAOS *taos);
static void queryDB(TAOS *taos, char *command) { static void queryDB(TAOS *taos, char *command) {
int i; int i;
TAOS_RES *pSql = NULL; TAOS_RES *pSql = NULL;
int32_t code = -1; int32_t code = -1;
...@@ -57,12 +57,12 @@ static void queryDB(TAOS *taos, char *command) { ...@@ -57,12 +57,12 @@ static void queryDB(TAOS *taos, char *command) {
taos_free_result(pSql); taos_free_result(pSql);
pSql = NULL; pSql = NULL;
} }
pSql = taos_query(taos, command); pSql = taos_query(taos, command);
code = taos_errno(pSql); code = taos_errno(pSql);
if (0 == code) { if (0 == code) {
break; break;
} }
} }
if (code != 0) { if (code != 0) {
...@@ -76,15 +76,14 @@ static void queryDB(TAOS *taos, char *command) { ...@@ -76,15 +76,14 @@ static void queryDB(TAOS *taos, char *command) {
taos_free_result(pSql); taos_free_result(pSql);
} }
int main(int argc, char *argv[]) int main(int argc, char *argv[]) {
{ TAOS * taos;
TAOS *taos; struct timeval systemTime;
struct timeval systemTime; int i;
int i; char sql[1024] = {0};
char sql[1024] = { 0 }; char prefix[20] = {0};
char prefix[20] = { 0 }; char db[128] = {0};
char db[128] = { 0 }; STable * tableList;
STable *tableList;
if (argc != 5) { if (argc != 5) {
printf("usage: %s server-ip dbname rowsPerTable numOfTables\n", argv[0]); printf("usage: %s server-ip dbname rowsPerTable numOfTables\n", argv[0]);
...@@ -101,8 +100,7 @@ int main(int argc, char *argv[]) ...@@ -101,8 +100,7 @@ int main(int argc, char *argv[])
memset(tableList, 0, size); memset(tableList, 0, size);
taos = taos_connect(argv[1], "root", "taosdata", NULL, 0); taos = taos_connect(argv[1], "root", "taosdata", NULL, 0);
if (taos == NULL) if (taos == NULL) taos_error(taos);
taos_error(taos);
printf("success to connect to server\n"); printf("success to connect to server\n");
...@@ -122,7 +120,7 @@ int main(int argc, char *argv[]) ...@@ -122,7 +120,7 @@ int main(int argc, char *argv[])
sprintf(tableList[i].name, "%s%d", prefix, i); sprintf(tableList[i].name, "%s%d", prefix, i);
sprintf(sql, "create table %s%d (ts timestamp, volume bigint)", prefix, i); sprintf(sql, "create table %s%d (ts timestamp, volume bigint)", prefix, i);
queryDB(taos, sql); queryDB(taos, sql);
} }
gettimeofday(&systemTime, NULL); gettimeofday(&systemTime, NULL);
for (i = 0; i < numOfTables; ++i) for (i = 0; i < numOfTables; ++i)
...@@ -138,7 +136,7 @@ int main(int argc, char *argv[]) ...@@ -138,7 +136,7 @@ int main(int argc, char *argv[])
tablesInsertProcessed = 0; tablesInsertProcessed = 0;
tablesSelectProcessed = 0; tablesSelectProcessed = 0;
for (i = 0; i<numOfTables; ++i) { for (i = 0; i < numOfTables; ++i) {
// insert records in asynchronous API // insert records in asynchronous API
sprintf(sql, "insert into %s values(%ld, 0)", tableList[i].name, 1546300800000 + i); sprintf(sql, "insert into %s values(%ld, 0)", tableList[i].name, 1546300800000 + i);
taos_query_a(taos, sql, taos_insert_call_back, (void *)(tableList + i)); taos_query_a(taos, sql, taos_insert_call_back, (void *)(tableList + i));
...@@ -147,12 +145,12 @@ int main(int argc, char *argv[]) ...@@ -147,12 +145,12 @@ int main(int argc, char *argv[])
printf("once insert finished, presse any key to query\n"); printf("once insert finished, presse any key to query\n");
getchar(); getchar();
while(1) { while (1) {
if (tablesInsertProcessed < numOfTables) { if (tablesInsertProcessed < numOfTables) {
printf("wait for process finished\n"); printf("wait for process finished\n");
sleep(1); sleep(1);
continue; continue;
} }
break; break;
} }
...@@ -161,9 +159,8 @@ int main(int argc, char *argv[]) ...@@ -161,9 +159,8 @@ int main(int argc, char *argv[])
gettimeofday(&systemTime, NULL); gettimeofday(&systemTime, NULL);
st = systemTime.tv_sec * 1000000 + systemTime.tv_usec; st = systemTime.tv_sec * 1000000 + systemTime.tv_usec;
for (i = 0; i < numOfTables; ++i) { for (i = 0; i < numOfTables; ++i) {
// select records in asynchronous API // select records in asynchronous API
sprintf(sql, "select * from %s", tableList[i].name); sprintf(sql, "select * from %s", tableList[i].name);
taos_query_a(taos, sql, taos_select_call_back, (void *)(tableList + i)); taos_query_a(taos, sql, taos_select_call_back, (void *)(tableList + i));
} }
...@@ -171,17 +168,17 @@ int main(int argc, char *argv[]) ...@@ -171,17 +168,17 @@ int main(int argc, char *argv[])
printf("\nonce finished, press any key to exit\n"); printf("\nonce finished, press any key to exit\n");
getchar(); getchar();
while(1) { while (1) {
if (tablesSelectProcessed < numOfTables) { if (tablesSelectProcessed < numOfTables) {
printf("wait for process finished\n"); printf("wait for process finished\n");
sleep(1); sleep(1);
continue; continue;
} }
break; break;
} }
for (i = 0; i<numOfTables; ++i) { for (i = 0; i < numOfTables; ++i) {
printf("%s inserted:%d retrieved:%d\n", tableList[i].name, tableList[i].rowsInserted, tableList[i].rowsRetrieved); printf("%s inserted:%d retrieved:%d\n", tableList[i].name, tableList[i].rowsInserted, tableList[i].rowsRetrieved);
} }
...@@ -193,60 +190,54 @@ int main(int argc, char *argv[]) ...@@ -193,60 +190,54 @@ int main(int argc, char *argv[])
return 0; return 0;
} }
void taos_error(TAOS *con) void taos_error(TAOS *con) {
{
fprintf(stderr, "TDengine error: %s\n", taos_errstr(con)); fprintf(stderr, "TDengine error: %s\n", taos_errstr(con));
taos_close(con); taos_close(con);
taos_cleanup(); taos_cleanup();
exit(1); exit(1);
} }
void taos_insert_call_back(void *param, TAOS_RES *tres, int code) void taos_insert_call_back(void *param, TAOS_RES *tres, int code) {
{ STable * pTable = (STable *)param;
STable *pTable = (STable *)param; struct timeval systemTime;
struct timeval systemTime; char sql[128];
char sql[128];
pTable->rowsTried++; pTable->rowsTried++;
if (code < 0) { if (code < 0) {
printf("%s insert failed, code:%d, rows:%d\n", pTable->name, code, pTable->rowsTried); printf("%s insert failed, code:%d, rows:%d\n", pTable->name, code, pTable->rowsTried);
} } else if (code == 0) {
else if (code == 0) {
printf("%s not inserted\n", pTable->name); printf("%s not inserted\n", pTable->name);
} } else {
else {
pTable->rowsInserted++; pTable->rowsInserted++;
} }
if (pTable->rowsTried < points) { if (pTable->rowsTried < points) {
// for this demo, insert another record // for this demo, insert another record
sprintf(sql, "insert into %s values(%ld, %d)", pTable->name, 1546300800000+pTable->rowsTried*1000, pTable->rowsTried); sprintf(sql, "insert into %s values(%ld, %d)", pTable->name, 1546300800000 + pTable->rowsTried * 1000,
pTable->rowsTried);
taos_query_a(pTable->taos, sql, taos_insert_call_back, (void *)pTable); taos_query_a(pTable->taos, sql, taos_insert_call_back, (void *)pTable);
} } else {
else {
printf("%d rows data are inserted into %s\n", points, pTable->name); printf("%d rows data are inserted into %s\n", points, pTable->name);
tablesInsertProcessed++; tablesInsertProcessed++;
if (tablesInsertProcessed >= numOfTables) { if (tablesInsertProcessed >= numOfTables) {
gettimeofday(&systemTime, NULL); gettimeofday(&systemTime, NULL);
et = systemTime.tv_sec * 1000000 + systemTime.tv_usec; et = systemTime.tv_sec * 1000000 + systemTime.tv_usec;
printf("%lld mseconds to insert %d data points\n", (et - st) / 1000, points*numOfTables); printf("%lld mseconds to insert %d data points\n", (et - st) / 1000, points * numOfTables);
} }
} }
taos_free_result(tres); taos_free_result(tres);
} }
void taos_retrieve_call_back(void *param, TAOS_RES *tres, int numOfRows) void taos_retrieve_call_back(void *param, TAOS_RES *tres, int numOfRows) {
{ STable * pTable = (STable *)param;
STable *pTable = (STable *)param;
struct timeval systemTime; struct timeval systemTime;
if (numOfRows > 0) { if (numOfRows > 0) {
for (int i = 0; i < numOfRows; ++i) {
for (int i = 0; i<numOfRows; ++i) {
// synchronous API to retrieve a row from batch of records // synchronous API to retrieve a row from batch of records
/*TAOS_ROW row = */(void)taos_fetch_row(tres); /*TAOS_ROW row = */ (void)taos_fetch_row(tres);
// process row // process row
} }
...@@ -255,12 +246,10 @@ void taos_retrieve_call_back(void *param, TAOS_RES *tres, int numOfRows) ...@@ -255,12 +246,10 @@ void taos_retrieve_call_back(void *param, TAOS_RES *tres, int numOfRows)
// retrieve next batch of rows // retrieve next batch of rows
taos_fetch_rows_a(tres, taos_retrieve_call_back, pTable); taos_fetch_rows_a(tres, taos_retrieve_call_back, pTable);
} } else {
else { if (numOfRows < 0) printf("%s retrieve failed, code:%d\n", pTable->name, numOfRows);
if (numOfRows < 0)
printf("%s retrieve failed, code:%d\n", pTable->name, numOfRows);
//taos_free_result(tres); // taos_free_result(tres);
printf("%d rows data retrieved from %s\n", pTable->rowsRetrieved, pTable->name); printf("%d rows data retrieved from %s\n", pTable->rowsRetrieved, pTable->name);
tablesSelectProcessed++; tablesSelectProcessed++;
...@@ -272,19 +261,15 @@ void taos_retrieve_call_back(void *param, TAOS_RES *tres, int numOfRows) ...@@ -272,19 +261,15 @@ void taos_retrieve_call_back(void *param, TAOS_RES *tres, int numOfRows)
taos_free_result(tres); taos_free_result(tres);
} }
} }
void taos_select_call_back(void *param, TAOS_RES *tres, int code) void taos_select_call_back(void *param, TAOS_RES *tres, int code) {
{
STable *pTable = (STable *)param; STable *pTable = (STable *)param;
if (code == 0 && tres) { if (code == 0 && tres) {
// asynchronous API to fetch a batch of records // asynchronous API to fetch a batch of records
taos_fetch_rows_a(tres, taos_retrieve_call_back, pTable); taos_fetch_rows_a(tres, taos_retrieve_call_back, pTable);
} } else {
else {
printf("%s select failed, code:%d\n", pTable->name, code); printf("%s select failed, code:%d\n", pTable->name, code);
taos_free_result(tres); taos_free_result(tres);
taos_cleanup(); taos_cleanup();
......
...@@ -16,14 +16,14 @@ ...@@ -16,14 +16,14 @@
// TAOS standard API example. The same syntax as MySQL, but only a subset // TAOS standard API example. The same syntax as MySQL, but only a subset
// to compile: gcc -o demo demo.c -ltaos // to compile: gcc -o demo demo.c -ltaos
#include <inttypes.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <inttypes.h>
#include <taos.h> // TAOS header file #include <taos.h> // TAOS header file
static void queryDB(TAOS *taos, char *command) { static void queryDB(TAOS *taos, char *command) {
int i; int i;
TAOS_RES *pSql = NULL; TAOS_RES *pSql = NULL;
int32_t code = -1; int32_t code = -1;
...@@ -32,12 +32,12 @@ static void queryDB(TAOS *taos, char *command) { ...@@ -32,12 +32,12 @@ static void queryDB(TAOS *taos, char *command) {
taos_free_result(pSql); taos_free_result(pSql);
pSql = NULL; pSql = NULL;
} }
pSql = taos_query(taos, command); pSql = taos_query(taos, command);
code = taos_errno(pSql); code = taos_errno(pSql);
if (0 == code) { if (0 == code) {
break; break;
} }
} }
if (code != 0) { if (code != 0) {
...@@ -53,7 +53,7 @@ static void queryDB(TAOS *taos, char *command) { ...@@ -53,7 +53,7 @@ static void queryDB(TAOS *taos, char *command) {
void Test(TAOS *taos, char *qstr, int i); void Test(TAOS *taos, char *qstr, int i);
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
char qstr[1024]; char qstr[1024];
// connect to server // connect to server
if (argc < 2) { if (argc < 2) {
...@@ -63,7 +63,7 @@ int main(int argc, char *argv[]) { ...@@ -63,7 +63,7 @@ int main(int argc, char *argv[]) {
TAOS *taos = taos_connect(argv[1], "root", "taosdata", NULL, 0); TAOS *taos = taos_connect(argv[1], "root", "taosdata", NULL, 0);
if (taos == NULL) { if (taos == NULL) {
printf("failed to connect to server, reason:%s\n", "null taos"/*taos_errstr(taos)*/); printf("failed to connect to server, reason:%s\n", "null taos" /*taos_errstr(taos)*/);
exit(1); exit(1);
} }
for (int i = 0; i < 100; i++) { for (int i = 0; i < 100; i++) {
...@@ -72,28 +72,30 @@ int main(int argc, char *argv[]) { ...@@ -72,28 +72,30 @@ int main(int argc, char *argv[]) {
taos_close(taos); taos_close(taos);
taos_cleanup(); taos_cleanup();
} }
void Test(TAOS *taos, char *qstr, int index) { void Test(TAOS *taos, char *qstr, int index) {
printf("==================test at %d\n================================", index); printf("==================test at %d\n================================", index);
queryDB(taos, "drop database if exists demo"); queryDB(taos, "drop database if exists demo");
queryDB(taos, "create database demo"); queryDB(taos, "create database demo");
TAOS_RES *result; TAOS_RES *result;
queryDB(taos, "use demo"); queryDB(taos, "use demo");
queryDB(taos, "create table m1 (ts timestamp, ti tinyint, si smallint, i int, bi bigint, f float, d double, b binary(10))"); queryDB(taos,
"create table m1 (ts timestamp, ti tinyint, si smallint, i int, bi bigint, f float, d double, b binary(10))");
printf("success to create table\n"); printf("success to create table\n");
int i = 0; int i = 0;
for (i = 0; i < 10; ++i) { for (i = 0; i < 10; ++i) {
sprintf(qstr, "insert into m1 values (%" PRId64 ", %d, %d, %d, %d, %f, %lf, '%s')", (uint64_t)(1546300800000 + i * 1000), i, i, i, i*10000000, i*1.0, i*2.0, "hello"); sprintf(qstr, "insert into m1 values (%" PRId64 ", %d, %d, %d, %d, %f, %lf, '%s')",
(uint64_t)(1546300800000 + i * 1000), i, i, i, i * 10000000, i * 1.0, i * 2.0, "hello");
printf("qstr: %s\n", qstr); printf("qstr: %s\n", qstr);
// note: how do you wanna do if taos_query returns non-NULL // note: how do you wanna do if taos_query returns non-NULL
// if (taos_query(taos, qstr)) { // if (taos_query(taos, qstr)) {
// printf("insert row: %i, reason:%s\n", i, taos_errstr(taos)); // printf("insert row: %i, reason:%s\n", i, taos_errstr(taos));
// } // }
TAOS_RES *result1 = taos_query(taos, qstr); TAOS_RES *result1 = taos_query(taos, qstr);
if (result1 == NULL || taos_errno(result1) != 0) { if (result1 == NULL || taos_errno(result1) != 0) {
printf("failed to insert row, reason:%s\n", taos_errstr(result1)); printf("failed to insert row, reason:%s\n", taos_errstr(result1));
taos_free_result(result1); taos_free_result(result1);
exit(1); exit(1);
} else { } else {
...@@ -107,7 +109,7 @@ void Test(TAOS *taos, char *qstr, int index) { ...@@ -107,7 +109,7 @@ void Test(TAOS *taos, char *qstr, int index) {
sprintf(qstr, "SELECT * FROM m1"); sprintf(qstr, "SELECT * FROM m1");
result = taos_query(taos, qstr); result = taos_query(taos, qstr);
if (result == NULL || taos_errno(result) != 0) { if (result == NULL || taos_errno(result) != 0) {
printf("failed to select, reason:%s\n", taos_errstr(result)); printf("failed to select, reason:%s\n", taos_errstr(result));
taos_free_result(result); taos_free_result(result);
exit(1); exit(1);
} }
...@@ -130,4 +132,3 @@ void Test(TAOS *taos, char *qstr, int index) { ...@@ -130,4 +132,3 @@ void Test(TAOS *taos, char *qstr, int index) {
taos_free_result(result); taos_free_result(result);
printf("====demo end====\n\n"); printf("====demo end====\n\n");
} }
...@@ -21,103 +21,101 @@ ...@@ -21,103 +21,101 @@
#ifdef __APPLE__ #ifdef __APPLE__
#include "osEok.h" #include "osEok.h"
#else // __APPLE__ #else // __APPLE__
#include <sys/epoll.h> #include <sys/epoll.h>
#endif // __APPLE__ #endif // __APPLE__
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h> #include <arpa/inet.h>
#include <fcntl.h>
#include <errno.h> #include <errno.h>
#include <string.h> #include <fcntl.h>
#include <arpa/inet.h>
#include <libgen.h> #include <libgen.h>
#include <locale.h> #include <locale.h>
#include <netdb.h> #include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#define D(fmt, ...) fprintf(stderr, "%s[%d]%s(): " fmt "\n", basename(__FILE__), __LINE__, __func__, ##__VA_ARGS__) #define D(fmt, ...) fprintf(stderr, "%s[%d]%s(): " fmt "\n", basename(__FILE__), __LINE__, __func__, ##__VA_ARGS__)
#define A(statement, fmt, ...) do { \ #define A(statement, fmt, ...) \
if (statement) break; \ do { \
fprintf(stderr, "%s[%d]%s(): assert [%s] failed: %d[%s]: " fmt "\n", \ if (statement) break; \
basename(__FILE__), __LINE__, __func__, \ fprintf(stderr, "%s[%d]%s(): assert [%s] failed: %d[%s]: " fmt "\n", basename(__FILE__), __LINE__, __func__, \
#statement, errno, strerror(errno), \ #statement, errno, strerror(errno), ##__VA_ARGS__); \
##__VA_ARGS__); \ abort(); \
abort(); \ } while (0)
} while (0)
#define E(fmt, ...) do { \ #define E(fmt, ...) \
fprintf(stderr, "%s[%d]%s(): %d[%s]: " fmt "\n", \ do { \
basename(__FILE__), __LINE__, __func__, \ fprintf(stderr, "%s[%d]%s(): %d[%s]: " fmt "\n", basename(__FILE__), __LINE__, __func__, errno, strerror(errno), \
errno, strerror(errno), \ ##__VA_ARGS__); \
##__VA_ARGS__); \ } while (0)
} while (0)
#include "os.h" #include "os.h"
typedef struct ep_s ep_t; typedef struct ep_s ep_t;
struct ep_s { struct ep_s {
int ep; int ep;
pthread_mutex_t lock; pthread_mutex_t lock;
int sv[2]; // 0 for read, 1 for write; int sv[2]; // 0 for read, 1 for write;
pthread_t thread; pthread_t thread;
volatile unsigned int stopping:1; volatile unsigned int stopping : 1;
volatile unsigned int waiting:1; volatile unsigned int waiting : 1;
volatile unsigned int wakenup:1; volatile unsigned int wakenup : 1;
}; };
static int ep_dummy = 0; static int ep_dummy = 0;
static ep_t* ep_create(void); static ep_t *ep_create(void);
static void ep_destroy(ep_t *ep); static void ep_destroy(ep_t *ep);
static void* routine(void* arg); static void *routine(void *arg);
static int open_listen(unsigned short port); static int open_listen(unsigned short port);
typedef struct fde_s fde_t; typedef struct fde_s fde_t;
struct fde_s { struct fde_s {
int skt; int skt;
void (*on_event)(ep_t *ep, struct epoll_event *events, fde_t *client); void (*on_event)(ep_t *ep, struct epoll_event *events, fde_t *client);
}; };
static void listen_event(ep_t *ep, struct epoll_event *ev, fde_t *client); static void listen_event(ep_t *ep, struct epoll_event *ev, fde_t *client);
static void null_event(ep_t *ep, struct epoll_event *ev, fde_t *client); static void null_event(ep_t *ep, struct epoll_event *ev, fde_t *client);
#define usage(arg0, fmt, ...) do { \ #define usage(arg0, fmt, ...) \
if (fmt[0]) { \ do { \
fprintf(stderr, "" fmt "\n", ##__VA_ARGS__); \ if (fmt[0]) { \
} \ fprintf(stderr, "" fmt "\n", ##__VA_ARGS__); \
fprintf(stderr, "usage:\n"); \ } \
fprintf(stderr, " %s -l <port> : specify listenning port\n", arg0); \ fprintf(stderr, "usage:\n"); \
} while (0) fprintf(stderr, " %s -l <port> : specify listenning port\n", arg0); \
} while (0)
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
char *prg = basename(argv[0]); char *prg = basename(argv[0]);
if (argc==1) { if (argc == 1) {
usage(prg, ""); usage(prg, "");
return 0; return 0;
} }
ep_t* ep = ep_create(); ep_t *ep = ep_create();
A(ep, "failed"); A(ep, "failed");
for (int i=1; i<argc; ++i) { for (int i = 1; i < argc; ++i) {
const char *arg = argv[i]; const char *arg = argv[i];
if (0==strcmp(arg, "-l")) { if (0 == strcmp(arg, "-l")) {
++i; ++i;
if (i>=argc) { if (i >= argc) {
usage(prg, "expecting <port> after -l, but got nothing"); usage(prg, "expecting <port> after -l, but got nothing");
return 1; // confirmed potential leakage return 1; // confirmed potential leakage
} }
arg = argv[i]; arg = argv[i];
int port = atoi(arg); int port = atoi(arg);
int skt = open_listen(port); int skt = open_listen(port);
if (skt==-1) continue; if (skt == -1) continue;
fde_t *client = (fde_t*)calloc(1, sizeof(*client)); fde_t *client = (fde_t *)calloc(1, sizeof(*client));
if (!client) { if (!client) {
E("out of memory"); E("out of memory");
close(skt); close(skt);
...@@ -126,32 +124,32 @@ int main(int argc, char *argv[]) { ...@@ -126,32 +124,32 @@ int main(int argc, char *argv[]) {
client->skt = skt; client->skt = skt;
client->on_event = listen_event; client->on_event = listen_event;
struct epoll_event ev = {0}; struct epoll_event ev = {0};
ev.events = EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLRDHUP; ev.events = EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLRDHUP;
ev.data.ptr = client; ev.data.ptr = client;
A(0==epoll_ctl(ep->ep, EPOLL_CTL_ADD, skt, &ev), ""); A(0 == epoll_ctl(ep->ep, EPOLL_CTL_ADD, skt, &ev), "");
continue; continue;
} }
usage(prg, "unknown argument: [%s]", arg); usage(prg, "unknown argument: [%s]", arg);
return 1; return 1;
} }
char *line = NULL; char * line = NULL;
size_t linecap = 0; size_t linecap = 0;
ssize_t linelen; ssize_t linelen;
while ((linelen = getline(&line, &linecap, stdin)) > 0) { while ((linelen = getline(&line, &linecap, stdin)) > 0) {
line[strlen(line)-1] = '\0'; line[strlen(line) - 1] = '\0';
if (0==strcmp(line, "exit")) break; if (0 == strcmp(line, "exit")) break;
if (0==strcmp(line, "quit")) break; if (0 == strcmp(line, "quit")) break;
if (line==strstr(line, "close")) { if (line == strstr(line, "close")) {
int fd = 0; int fd = 0;
sscanf(line, "close %d", &fd); sscanf(line, "close %d", &fd);
if (fd<=2) { if (fd <= 2) {
fprintf(stderr, "fd [%d] invalid\n", fd); fprintf(stderr, "fd [%d] invalid\n", fd);
continue; continue;
} }
A(0==epoll_ctl(ep->ep, EPOLL_CTL_DEL, fd, NULL), ""); A(0 == epoll_ctl(ep->ep, EPOLL_CTL_DEL, fd, NULL), "");
continue; continue;
} }
if (strlen(line)==0) continue; if (strlen(line) == 0) continue;
fprintf(stderr, "unknown cmd:[%s]\n", line); fprintf(stderr, "unknown cmd:[%s]\n", line);
} }
ep_destroy(ep); ep_destroy(ep);
...@@ -159,69 +157,69 @@ int main(int argc, char *argv[]) { ...@@ -159,69 +157,69 @@ int main(int argc, char *argv[]) {
return 0; return 0;
} }
ep_t* ep_create(void) { ep_t *ep_create(void) {
ep_t *ep = (ep_t*)calloc(1, sizeof(*ep)); ep_t *ep = (ep_t *)calloc(1, sizeof(*ep));
A(ep, "out of memory"); A(ep, "out of memory");
A(-1!=(ep->ep = epoll_create(1)), ""); A(-1 != (ep->ep = epoll_create(1)), "");
ep->sv[0] = -1; ep->sv[0] = -1;
ep->sv[1] = -1; ep->sv[1] = -1;
A(0==socketpair(AF_LOCAL, SOCK_STREAM, 0, ep->sv), ""); A(0 == socketpair(AF_LOCAL, SOCK_STREAM, 0, ep->sv), "");
A(0==pthread_mutex_init(&ep->lock, NULL), ""); A(0 == pthread_mutex_init(&ep->lock, NULL), "");
A(0==pthread_mutex_lock(&ep->lock), ""); A(0 == pthread_mutex_lock(&ep->lock), "");
struct epoll_event ev = {0}; struct epoll_event ev = {0};
ev.events = EPOLLIN; ev.events = EPOLLIN;
ev.data.ptr = &ep_dummy; ev.data.ptr = &ep_dummy;
A(0==epoll_ctl(ep->ep, EPOLL_CTL_ADD, ep->sv[0], &ev), ""); A(0 == epoll_ctl(ep->ep, EPOLL_CTL_ADD, ep->sv[0], &ev), "");
A(0==pthread_create(&ep->thread, NULL, routine, ep), ""); A(0 == pthread_create(&ep->thread, NULL, routine, ep), "");
A(0==pthread_mutex_unlock(&ep->lock), ""); A(0 == pthread_mutex_unlock(&ep->lock), "");
return ep; return ep;
} }
static void ep_destroy(ep_t *ep) { static void ep_destroy(ep_t *ep) {
A(ep, "invalid argument"); A(ep, "invalid argument");
ep->stopping = 1; ep->stopping = 1;
A(1==send(ep->sv[1], "1", 1, 0), ""); A(1 == send(ep->sv[1], "1", 1, 0), "");
A(0==pthread_join(ep->thread, NULL), ""); A(0 == pthread_join(ep->thread, NULL), "");
A(0==pthread_mutex_destroy(&ep->lock), ""); A(0 == pthread_mutex_destroy(&ep->lock), "");
A(0==close(ep->sv[0]), ""); A(0 == close(ep->sv[0]), "");
A(0==close(ep->sv[1]), ""); A(0 == close(ep->sv[1]), "");
A(0==close(ep->ep), ""); A(0 == close(ep->ep), "");
free(ep); free(ep);
} }
static void* routine(void* arg) { static void *routine(void *arg) {
A(arg, "invalid argument"); A(arg, "invalid argument");
ep_t *ep = (ep_t*)arg; ep_t *ep = (ep_t *)arg;
while (!ep->stopping) { while (!ep->stopping) {
struct epoll_event evs[10]; struct epoll_event evs[10];
memset(evs, 0, sizeof(evs)); memset(evs, 0, sizeof(evs));
A(0==pthread_mutex_lock(&ep->lock), ""); A(0 == pthread_mutex_lock(&ep->lock), "");
A(ep->waiting==0, "internal logic error"); A(ep->waiting == 0, "internal logic error");
ep->waiting = 1; ep->waiting = 1;
A(0==pthread_mutex_unlock(&ep->lock), ""); A(0 == pthread_mutex_unlock(&ep->lock), "");
int r = epoll_wait(ep->ep, evs, sizeof(evs)/sizeof(evs[0]), -1); int r = epoll_wait(ep->ep, evs, sizeof(evs) / sizeof(evs[0]), -1);
A(r>0, "indefinite epoll_wait shall not timeout:[%d]", r); A(r > 0, "indefinite epoll_wait shall not timeout:[%d]", r);
A(0==pthread_mutex_lock(&ep->lock), ""); A(0 == pthread_mutex_lock(&ep->lock), "");
A(ep->waiting==1, "internal logic error"); A(ep->waiting == 1, "internal logic error");
ep->waiting = 0; ep->waiting = 0;
A(0==pthread_mutex_unlock(&ep->lock), ""); A(0 == pthread_mutex_unlock(&ep->lock), "");
for (int i=0; i<r; ++i) { for (int i = 0; i < r; ++i) {
struct epoll_event *ev = evs + i; struct epoll_event *ev = evs + i;
if (ev->data.ptr == &ep_dummy) { if (ev->data.ptr == &ep_dummy) {
char c = '\0'; char c = '\0';
A(1==recv(ep->sv[0], &c, 1, 0), "internal logic error"); A(1 == recv(ep->sv[0], &c, 1, 0), "internal logic error");
A(0==pthread_mutex_lock(&ep->lock), ""); A(0 == pthread_mutex_lock(&ep->lock), "");
ep->wakenup = 0; ep->wakenup = 0;
A(0==pthread_mutex_unlock(&ep->lock), ""); A(0 == pthread_mutex_unlock(&ep->lock), "");
continue; continue;
} }
A(ev->data.ptr, "internal logic error"); A(ev->data.ptr, "internal logic error");
fde_t *client = (fde_t*)ev->data.ptr; fde_t *client = (fde_t *)ev->data.ptr;
client->on_event(ep, ev, client); client->on_event(ep, ev, client);
continue; continue;
} }
...@@ -232,7 +230,7 @@ static void* routine(void* arg) { ...@@ -232,7 +230,7 @@ static void* routine(void* arg) {
static int open_listen(unsigned short port) { static int open_listen(unsigned short port) {
int r = 0; int r = 0;
int skt = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); int skt = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (skt==-1) { if (skt == -1) {
E("socket() failed"); E("socket() failed");
return -1; return -1;
} }
...@@ -241,7 +239,7 @@ static int open_listen(unsigned short port) { ...@@ -241,7 +239,7 @@ static int open_listen(unsigned short port) {
si.sin_family = AF_INET; si.sin_family = AF_INET;
si.sin_addr.s_addr = inet_addr("0.0.0.0"); si.sin_addr.s_addr = inet_addr("0.0.0.0");
si.sin_port = htons(port); si.sin_port = htons(port);
r = bind(skt, (struct sockaddr*)&si, sizeof(si)); r = bind(skt, (struct sockaddr *)&si, sizeof(si));
if (r) { if (r) {
E("bind(%u) failed", port); E("bind(%u) failed", port);
break; break;
...@@ -257,7 +255,7 @@ static int open_listen(unsigned short port) { ...@@ -257,7 +255,7 @@ static int open_listen(unsigned short port) {
if (r) { if (r) {
E("getsockname() failed"); E("getsockname() failed");
} }
A(len==sizeof(si), "internal logic error"); A(len == sizeof(si), "internal logic error");
D("listenning at: %d", ntohs(si.sin_port)); D("listenning at: %d", ntohs(si.sin_port));
return skt; return skt;
} while (0); } while (0);
...@@ -268,10 +266,10 @@ static int open_listen(unsigned short port) { ...@@ -268,10 +266,10 @@ static int open_listen(unsigned short port) {
static void listen_event(ep_t *ep, struct epoll_event *ev, fde_t *client) { static void listen_event(ep_t *ep, struct epoll_event *ev, fde_t *client) {
A(ev->events & EPOLLIN, "internal logic error"); A(ev->events & EPOLLIN, "internal logic error");
struct sockaddr_in si = {0}; struct sockaddr_in si = {0};
socklen_t silen = sizeof(si); socklen_t silen = sizeof(si);
int skt = accept(client->skt, (struct sockaddr*)&si, &silen); int skt = accept(client->skt, (struct sockaddr *)&si, &silen);
A(skt!=-1, "internal logic error"); A(skt != -1, "internal logic error");
fde_t *server = (fde_t*)calloc(1, sizeof(*server)); fde_t *server = (fde_t *)calloc(1, sizeof(*server));
if (!server) { if (!server) {
close(skt); close(skt);
return; return;
...@@ -279,26 +277,25 @@ static void listen_event(ep_t *ep, struct epoll_event *ev, fde_t *client) { ...@@ -279,26 +277,25 @@ static void listen_event(ep_t *ep, struct epoll_event *ev, fde_t *client) {
server->skt = skt; server->skt = skt;
server->on_event = null_event; server->on_event = null_event;
struct epoll_event ee = {0}; struct epoll_event ee = {0};
ee.events = EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLRDHUP; ee.events = EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLRDHUP;
ee.data.ptr = server; ee.data.ptr = server;
A(0==epoll_ctl(ep->ep, EPOLL_CTL_ADD, skt, &ee), ""); A(0 == epoll_ctl(ep->ep, EPOLL_CTL_ADD, skt, &ee), "");
} }
static void null_event(ep_t *ep, struct epoll_event *ev, fde_t *client) { static void null_event(ep_t *ep, struct epoll_event *ev, fde_t *client) {
if (ev->events & EPOLLIN) { if (ev->events & EPOLLIN) {
char buf[8192]; char buf[8192];
int n = recv(client->skt, buf, sizeof(buf), 0); int n = recv(client->skt, buf, sizeof(buf), 0);
A(n>=0 && n<=sizeof(buf), "internal logic error:[%d]", n); A(n >= 0 && n <= sizeof(buf), "internal logic error:[%d]", n);
A(n==fwrite(buf, 1, n, stdout), "internal logic error"); A(n == fwrite(buf, 1, n, stdout), "internal logic error");
} }
if (ev->events & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) { if (ev->events & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) {
A(0==pthread_mutex_lock(&ep->lock), ""); A(0 == pthread_mutex_lock(&ep->lock), "");
A(0==epoll_ctl(ep->ep, EPOLL_CTL_DEL, client->skt, NULL), ""); A(0 == epoll_ctl(ep->ep, EPOLL_CTL_DEL, client->skt, NULL), "");
A(0==pthread_mutex_unlock(&ep->lock), ""); A(0 == pthread_mutex_unlock(&ep->lock), "");
close(client->skt); close(client->skt);
client->skt = -1; client->skt = -1;
client->on_event = NULL; client->on_event = NULL;
free(client); free(client);
} }
} }
...@@ -6,8 +6,13 @@ TARGET=exe ...@@ -6,8 +6,13 @@ TARGET=exe
LFLAGS = '-Wl,-rpath,/usr/local/taos/driver/' -ltaos -lpthread -lm -lrt LFLAGS = '-Wl,-rpath,/usr/local/taos/driver/' -ltaos -lpthread -lm -lrt
CFLAGS = -O3 -g -Wall -Wno-deprecated -fPIC -Wno-unused-result -Wconversion \ CFLAGS = -O3 -g -Wall -Wno-deprecated -fPIC -Wno-unused-result -Wconversion \
-Wno-char-subscripts -D_REENTRANT -Wno-format -D_REENTRANT -DLINUX \ -Wno-char-subscripts -D_REENTRANT -Wno-format -D_REENTRANT -DLINUX \
-Wno-unused-function -D_M_X64 -I/usr/local/taos/include -std=gnu99 \ -Wno-unused-function -D_M_X64 -I/usr/local/taos/include -std=gnu99 \
-I../../../deps/cJson/inc -I../../../deps/cJson/inc
-Wno-unused-function -D_M_X64 -I/usr/local/taos/include -std=gnu99
-fsanitize=address -fsanitize=undefined -fno-sanitize-recover=all -fsanitize=float-divide-by-zero -fsanitize=float-cast-overflow -fno-sanitize=null -fno-sanitize=alignment
all: $(TARGET) all: $(TARGET)
exe: exe:
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
...@@ -14,10 +14,10 @@ void print_result(TAOS_RES* res, int blockFetch) { ...@@ -14,10 +14,10 @@ void print_result(TAOS_RES* res, int blockFetch) {
int num_fields = taos_num_fields(res); int num_fields = taos_num_fields(res);
TAOS_FIELD* fields = taos_fetch_fields(res); TAOS_FIELD* fields = taos_fetch_fields(res);
int nRows = 0; int nRows = 0;
if (blockFetch) { if (blockFetch) {
nRows = taos_fetch_block(res, &row); nRows = taos_fetch_block(res, &row);
//for (int i = 0; i < nRows; i++) { // for (int i = 0; i < nRows; i++) {
// taos_print_row(buf, row + i, fields, num_fields); // taos_print_row(buf, row + i, fields, num_fields);
// puts(buf); // puts(buf);
//} //}
...@@ -34,15 +34,11 @@ void print_result(TAOS_RES* res, int blockFetch) { ...@@ -34,15 +34,11 @@ void print_result(TAOS_RES* res, int blockFetch) {
printf("%d rows consumed.\n", nRows); printf("%d rows consumed.\n", nRows);
} }
void subscribe_callback(TAOS_SUB* tsub, TAOS_RES* res, void* param, int code) { print_result(res, *(int*)param); }
void subscribe_callback(TAOS_SUB* tsub, TAOS_RES *res, void* param, int code) {
print_result(res, *(int*)param);
}
void check_row_count(int line, TAOS_RES* res, int expected) { void check_row_count(int line, TAOS_RES* res, int expected) {
int actual = 0; int actual = 0;
TAOS_ROW row; TAOS_ROW row;
while ((row = taos_fetch_row(res))) { while ((row = taos_fetch_row(res))) {
actual++; actual++;
} }
...@@ -53,16 +49,14 @@ void check_row_count(int line, TAOS_RES* res, int expected) { ...@@ -53,16 +49,14 @@ void check_row_count(int line, TAOS_RES* res, int expected) {
} }
} }
void do_query(TAOS* taos, const char* sql) { void do_query(TAOS* taos, const char* sql) {
TAOS_RES* res = taos_query(taos, sql); TAOS_RES* res = taos_query(taos, sql);
taos_free_result(res); taos_free_result(res);
} }
void run_test(TAOS* taos) { void run_test(TAOS* taos) {
do_query(taos, "drop database if exists test;"); do_query(taos, "drop database if exists test;");
usleep(100000); usleep(100000);
do_query(taos, "create database test;"); do_query(taos, "create database test;");
usleep(100000); usleep(100000);
...@@ -161,14 +155,13 @@ void run_test(TAOS* taos) { ...@@ -161,14 +155,13 @@ void run_test(TAOS* taos) {
taos_unsubscribe(tsub, 0); taos_unsubscribe(tsub, 0);
} }
int main(int argc, char* argv[]) {
int main(int argc, char *argv[]) {
const char* host = "127.0.0.1"; const char* host = "127.0.0.1";
const char* user = "root"; const char* user = "root";
const char* passwd = "taosdata"; const char* passwd = "taosdata";
const char* sql = "select * from meters;"; const char* sql = "select * from meters;";
const char* topic = "test-multiple"; const char* topic = "test-multiple";
int async = 1, restart = 0, keep = 1, test = 0, blockFetch = 0; int async = 1, restart = 0, keep = 1, test = 0, blockFetch = 0;
for (int i = 1; i < argc; i++) { for (int i = 1; i < argc; i++) {
if (strncmp(argv[i], "-h=", 3) == 0) { if (strncmp(argv[i], "-h=", 3) == 0) {
...@@ -240,20 +233,21 @@ int main(int argc, char *argv[]) { ...@@ -240,20 +233,21 @@ int main(int argc, char *argv[]) {
if (tsub == NULL) { if (tsub == NULL) {
printf("failed to create subscription.\n"); printf("failed to create subscription.\n");
exit(0); exit(0);
} }
if (async) { if (async) {
getchar(); getchar();
} else while(1) { } else
TAOS_RES* res = taos_consume(tsub); while (1) {
if (res == NULL) { TAOS_RES* res = taos_consume(tsub);
printf("failed to consume data."); if (res == NULL) {
break; printf("failed to consume data.");
} else { break;
print_result(res, blockFetch); } else {
getchar(); print_result(res, blockFetch);
getchar();
}
} }
}
printf("total rows consumed: %d\n", nTotalRows); printf("total rows consumed: %d\n", nTotalRows);
taos_unsubscribe(tsub, keep); taos_unsubscribe(tsub, keep);
......
#!/bin/bash
for N in -1 0 1 10000 10001
do
for l in 1023 1024 1073741824 1073741825
do
for S in udp tcp
do
taos -n speed -h BCC-2 -P 6030 -N $N -l $l -S $S 2>&1 | tee -a result.txt
done
done
done
此差异已折叠。
...@@ -36,6 +36,7 @@ class TDTestCase: ...@@ -36,6 +36,7 @@ class TDTestCase:
else: else:
tdLog.exit("sql:%s, row:%d col:%d data:%d != expect:%d " % (sql, 0, 0, version, expectedVersion)) tdLog.exit("sql:%s, row:%d col:%d data:%d != expect:%d " % (sql, 0, 0, version, expectedVersion))
sql = "select client_version()" sql = "select client_version()"
ret = tdSql.query(sql) ret = tdSql.query(sql)
version = floor(float(tdSql.getData(0, 0)[0:3])) version = floor(float(tdSql.getData(0, 0)[0:3]))
......
...@@ -134,7 +134,8 @@ cDebugFlag 135 ...@@ -134,7 +134,8 @@ cDebugFlag 135
rpcDebugFlag 135 rpcDebugFlag 135
qDebugFlag 135 qDebugFlag 135
# httpDebugFlag 143 # httpDebugFlag 143
# asyncLog 0 asyncLog 0
debugflag 143
# tables 10 # tables 10
maxtablesPerVnode 10 maxtablesPerVnode 10
rpcMaxTime 101 rpcMaxTime 101
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册