From 298c4b48128cd9c3cc99a3f766eaf89c837a8f9b Mon Sep 17 00:00:00 2001 From: Minglei Jin Date: Thu, 15 Aug 2024 09:28:32 +0800 Subject: [PATCH] feat(stmt2): initial commit for stmt2 --- include/client/taos.h | 99 +- include/common/tdataformat.h | 12 + include/libs/parser/parser.h | 58 +- source/client/inc/clientStmt2.h | 233 +++ source/client/src/clientMain.c | 234 ++- source/client/src/clientStmt2.c | 1895 ++++++++++++++++++++++++ source/common/src/tdataformat.c | 137 ++ source/libs/parser/src/parInsertStmt.c | 347 ++++- source/libs/parser/src/parser.c | 116 +- 9 files changed, 3029 insertions(+), 102 deletions(-) create mode 100644 source/client/inc/clientStmt2.h create mode 100644 source/client/src/clientStmt2.c diff --git a/include/client/taos.h b/include/client/taos.h index 73ab52357a..9bd1517d38 100644 --- a/include/client/taos.h +++ b/include/client/taos.h @@ -51,7 +51,7 @@ typedef void TAOS_SUB; #define TSDB_DATA_TYPE_BLOB 18 // binary #define TSDB_DATA_TYPE_MEDIUMBLOB 19 #define TSDB_DATA_TYPE_BINARY TSDB_DATA_TYPE_VARCHAR // string -#define TSDB_DATA_TYPE_GEOMETRY 20 // geometry +#define TSDB_DATA_TYPE_GEOMETRY 20 // geometry #define TSDB_DATA_TYPE_MAX 21 typedef enum { @@ -168,7 +168,7 @@ DLL_EXPORT const char *taos_data_type(int type); DLL_EXPORT TAOS_STMT *taos_stmt_init(TAOS *taos); DLL_EXPORT TAOS_STMT *taos_stmt_init_with_reqid(TAOS *taos, int64_t reqid); -DLL_EXPORT TAOS_STMT *taos_stmt_init_with_options(TAOS *taos, TAOS_STMT_OPTIONS* options); +DLL_EXPORT TAOS_STMT *taos_stmt_init_with_options(TAOS *taos, TAOS_STMT_OPTIONS *options); DLL_EXPORT int taos_stmt_prepare(TAOS_STMT *stmt, const char *sql, unsigned long length); DLL_EXPORT int taos_stmt_set_tbname_tags(TAOS_STMT *stmt, const char *name, TAOS_MULTI_BIND *tags); DLL_EXPORT int taos_stmt_set_tbname(TAOS_STMT *stmt, const char *name); @@ -193,6 +193,49 @@ DLL_EXPORT char *taos_stmt_errstr(TAOS_STMT *stmt); DLL_EXPORT int taos_stmt_affected_rows(TAOS_STMT *stmt); DLL_EXPORT int taos_stmt_affected_rows_once(TAOS_STMT *stmt); +typedef void TAOS_STMT2; + +typedef enum { + TAOS_FIELD_COL = 1, + TAOS_FIELD_TAG, + TAOS_FIELD_QUERY, +} TAOS_FIELD_T; + +typedef struct { + int64_t reqid; + bool singleStbInsert; + bool singleTableBindOnce; + __taos_async_fn_t asyncExecFn; + void *userdata; +} TAOS_STMT2_OPTION; + +typedef struct { + int buffer_type; + void *buffer; + uintptr_t buffer_length; + int32_t *length; + char *is_null; + int num; +} TAOS_STMT2_BIND; + +typedef struct { + int count; + char **tbnames; + TAOS_STMT2_BIND **tags; + TAOS_STMT2_BIND **bind_cols; +} TAOS_STMT2_BINDV; + +DLL_EXPORT TAOS_STMT2 *taos_stmt2_init(TAOS *taos, TAOS_STMT2_OPTION *option); +DLL_EXPORT int taos_stmt2_prepare(TAOS_STMT2 *stmt, const char *sql, unsigned long length); +DLL_EXPORT int taos_stmt2_bind_param(TAOS_STMT2 *stmt, TAOS_STMT2_BINDV *bindv, int32_t col_idx); +DLL_EXPORT int taos_stmt2_exec(TAOS_STMT2 *stmt, int *affected_rows); +DLL_EXPORT int taos_stmt2_close(TAOS_STMT2 *stmt); +DLL_EXPORT int taos_stmt2_is_insert(TAOS_STMT2 *stmt, int *insert); +DLL_EXPORT int taos_stmt2_get_fields(TAOS_STMT2 *stmt, TAOS_FIELD_T field_type, int *count, TAOS_FIELD_E **fields); +DLL_EXPORT void taos_stmt2_free_fields(TAOS_STMT2 *stmt, TAOS_FIELD_E *fields); +DLL_EXPORT TAOS_RES *taos_stmt2_result(TAOS_STMT2 *stmt); +DLL_EXPORT char *taos_stmt2_error(TAOS_STMT2 *stmt); + DLL_EXPORT TAOS_RES *taos_query(TAOS *taos, const char *sql); DLL_EXPORT TAOS_RES *taos_query_with_reqid(TAOS *taos, const char *sql, int64_t reqId); @@ -245,14 +288,15 @@ DLL_EXPORT void taos_set_hb_quit(int8_t quitByKill); DLL_EXPORT int taos_set_notify_cb(TAOS *taos, __taos_notify_fn_t fp, void *param, int type); -typedef void (*__taos_async_whitelist_fn_t)(void *param, int code, TAOS *taos, int numOfWhiteLists, uint64_t* pWhiteLists); +typedef void (*__taos_async_whitelist_fn_t)(void *param, int code, TAOS *taos, int numOfWhiteLists, + uint64_t *pWhiteLists); DLL_EXPORT void taos_fetch_whitelist_a(TAOS *taos, __taos_async_whitelist_fn_t fp, void *param); typedef enum { TAOS_CONN_MODE_BI = 0, } TAOS_CONN_MODE; -DLL_EXPORT int taos_set_conn_mode(TAOS* taos, int mode, int value); +DLL_EXPORT int taos_set_conn_mode(TAOS *taos, int mode, int value); /* --------------------------schemaless INTERFACE------------------------------- */ DLL_EXPORT TAOS_RES *taos_schemaless_insert(TAOS *taos, char *lines[], int numLines, int protocol, int precision); @@ -270,10 +314,13 @@ DLL_EXPORT TAOS_RES *taos_schemaless_insert_raw_ttl(TAOS *taos, char *lines, int int precision, int32_t ttl); DLL_EXPORT TAOS_RES *taos_schemaless_insert_raw_ttl_with_reqid(TAOS *taos, char *lines, int len, int32_t *totalRows, int protocol, int precision, int32_t ttl, int64_t reqid); -DLL_EXPORT TAOS_RES *taos_schemaless_insert_raw_ttl_with_reqid_tbname_key(TAOS *taos, char *lines, int len, int32_t *totalRows, - int protocol, int precision, int32_t ttl, int64_t reqid, char *tbnameKey); -DLL_EXPORT TAOS_RES *taos_schemaless_insert_ttl_with_reqid_tbname_key(TAOS *taos, char *lines[], int numLines, int protocol, - int precision, int32_t ttl, int64_t reqid, char *tbnameKey); +DLL_EXPORT TAOS_RES *taos_schemaless_insert_raw_ttl_with_reqid_tbname_key(TAOS *taos, char *lines, int len, + int32_t *totalRows, int protocol, + int precision, int32_t ttl, int64_t reqid, + char *tbnameKey); +DLL_EXPORT TAOS_RES *taos_schemaless_insert_ttl_with_reqid_tbname_key(TAOS *taos, char *lines[], int numLines, + int protocol, int precision, int32_t ttl, + int64_t reqid, char *tbnameKey); /* --------------------------TMQ INTERFACE------------------------------- */ typedef struct tmq_t tmq_t; @@ -319,14 +366,17 @@ DLL_EXPORT int32_t tmq_unsubscribe(tmq_t *tmq); DLL_EXPORT int32_t tmq_subscription(tmq_t *tmq, tmq_list_t **topics); DLL_EXPORT TAOS_RES *tmq_consumer_poll(tmq_t *tmq, int64_t timeout); DLL_EXPORT int32_t tmq_consumer_close(tmq_t *tmq); -DLL_EXPORT int32_t tmq_commit_sync(tmq_t *tmq, const TAOS_RES *msg); //Commit the msg’s offset + 1 +DLL_EXPORT int32_t tmq_commit_sync(tmq_t *tmq, const TAOS_RES *msg); // Commit the msg’s offset + 1 DLL_EXPORT void tmq_commit_async(tmq_t *tmq, const TAOS_RES *msg, tmq_commit_cb *cb, void *param); DLL_EXPORT int32_t tmq_commit_offset_sync(tmq_t *tmq, const char *pTopicName, int32_t vgId, int64_t offset); -DLL_EXPORT void tmq_commit_offset_async(tmq_t *tmq, const char *pTopicName, int32_t vgId, int64_t offset, tmq_commit_cb *cb, void *param); -DLL_EXPORT int32_t tmq_get_topic_assignment(tmq_t *tmq, const char *pTopicName, tmq_topic_assignment **assignment,int32_t *numOfAssignment); -DLL_EXPORT void tmq_free_assignment(tmq_topic_assignment* pAssignment); +DLL_EXPORT void tmq_commit_offset_async(tmq_t *tmq, const char *pTopicName, int32_t vgId, int64_t offset, + tmq_commit_cb *cb, void *param); +DLL_EXPORT int32_t tmq_get_topic_assignment(tmq_t *tmq, const char *pTopicName, tmq_topic_assignment **assignment, + int32_t *numOfAssignment); +DLL_EXPORT void tmq_free_assignment(tmq_topic_assignment *pAssignment); DLL_EXPORT int32_t tmq_offset_seek(tmq_t *tmq, const char *pTopicName, int32_t vgId, int64_t offset); -DLL_EXPORT int64_t tmq_position(tmq_t *tmq, const char *pTopicName, int32_t vgId); // The current offset is the offset of the last consumed message + 1 +DLL_EXPORT int64_t tmq_position(tmq_t *tmq, const char *pTopicName, + int32_t vgId); // The current offset is the offset of the last consumed message + 1 DLL_EXPORT int64_t tmq_committed(tmq_t *tmq, const char *pTopicName, int32_t vgId); DLL_EXPORT TAOS *tmq_get_connect(tmq_t *tmq); @@ -335,7 +385,7 @@ DLL_EXPORT tmq_res_t tmq_get_res_type(TAOS_RES *res); DLL_EXPORT const char *tmq_get_topic_name(TAOS_RES *res); DLL_EXPORT const char *tmq_get_db_name(TAOS_RES *res); DLL_EXPORT int32_t tmq_get_vgroup_id(TAOS_RES *res); -DLL_EXPORT int64_t tmq_get_vgroup_offset(TAOS_RES* res); +DLL_EXPORT int64_t tmq_get_vgroup_offset(TAOS_RES *res); DLL_EXPORT const char *tmq_err2str(int32_t code); /* ------------------------------ TAOSX -----------------------------------*/ @@ -345,15 +395,16 @@ typedef struct tmq_raw_data { uint16_t raw_type; } tmq_raw_data; -DLL_EXPORT int32_t tmq_get_raw(TAOS_RES *res, tmq_raw_data *raw); -DLL_EXPORT int32_t tmq_write_raw(TAOS *taos, tmq_raw_data raw); -DLL_EXPORT int taos_write_raw_block(TAOS *taos, int numOfRows, char *pData, const char *tbname); -DLL_EXPORT int taos_write_raw_block_with_reqid(TAOS *taos, int numOfRows, char *pData, const char *tbname, int64_t reqid); -DLL_EXPORT int taos_write_raw_block_with_fields(TAOS *taos, int rows, char *pData, const char *tbname, - TAOS_FIELD *fields, int numFields); -DLL_EXPORT int taos_write_raw_block_with_fields_with_reqid(TAOS *taos, int rows, char *pData, const char *tbname, - TAOS_FIELD *fields, int numFields, int64_t reqid); -DLL_EXPORT void tmq_free_raw(tmq_raw_data raw); +DLL_EXPORT int32_t tmq_get_raw(TAOS_RES *res, tmq_raw_data *raw); +DLL_EXPORT int32_t tmq_write_raw(TAOS *taos, tmq_raw_data raw); +DLL_EXPORT int taos_write_raw_block(TAOS *taos, int numOfRows, char *pData, const char *tbname); +DLL_EXPORT int taos_write_raw_block_with_reqid(TAOS *taos, int numOfRows, char *pData, const char *tbname, + int64_t reqid); +DLL_EXPORT int taos_write_raw_block_with_fields(TAOS *taos, int rows, char *pData, const char *tbname, + TAOS_FIELD *fields, int numFields); +DLL_EXPORT int taos_write_raw_block_with_fields_with_reqid(TAOS *taos, int rows, char *pData, const char *tbname, + TAOS_FIELD *fields, int numFields, int64_t reqid); +DLL_EXPORT void tmq_free_raw(tmq_raw_data raw); // Returning null means error. Returned result need to be freed by tmq_free_json_meta DLL_EXPORT char *tmq_get_json_meta(TAOS_RES *res); @@ -369,7 +420,7 @@ typedef enum { } TSDB_SERVER_STATUS; DLL_EXPORT TSDB_SERVER_STATUS taos_check_server_status(const char *fqdn, int port, char *details, int maxlen); -DLL_EXPORT char* getBuildInfo(); +DLL_EXPORT char *getBuildInfo(); #ifdef __cplusplus } #endif diff --git a/include/common/tdataformat.h b/include/common/tdataformat.h index 0acb28fabd..cb4f6972f0 100644 --- a/include/common/tdataformat.h +++ b/include/common/tdataformat.h @@ -378,6 +378,18 @@ typedef struct { int32_t tRowBuildFromBind(SBindInfo *infos, int32_t numOfInfos, bool infoSorted, const STSchema *pTSchema, SArray *rowArray); +// stmt2 binding +int32_t tColDataAddValueByBind2(SColData *pColData, TAOS_STMT2_BIND *pBind, int32_t buffMaxLen); + +typedef struct { + int32_t columnId; + int32_t type; + TAOS_STMT2_BIND *bind; +} SBindInfo2; + +int32_t tRowBuildFromBind2(SBindInfo2 *infos, int32_t numOfInfos, bool infoSorted, const STSchema *pTSchema, + SArray *rowArray); + #endif #ifdef __cplusplus diff --git a/include/libs/parser/parser.h b/include/libs/parser/parser.h index cefce8a9c0..5025da14d3 100644 --- a/include/libs/parser/parser.h +++ b/include/libs/parser/parser.h @@ -20,9 +20,9 @@ extern "C" { #endif +#include "catalog.h" #include "query.h" #include "querynodes.h" -#include "catalog.h" typedef struct SStmtCallback { TAOS_STMT* pStmt; @@ -37,15 +37,15 @@ typedef enum { } SParseResType; typedef struct SParseSchemaRes { - int8_t precision; - int32_t numOfCols; - SSchema* pSchema; + int8_t precision; + int32_t numOfCols; + SSchema* pSchema; } SParseSchemaRes; typedef struct SParseQueryRes { - SNode* pQuery; - SCatalogReq* pCatalogReq; - SMetaData meta; + SNode* pQuery; + SCatalogReq* pCatalogReq; + SMetaData meta; } SParseQueryRes; typedef struct SParseSqlRes { @@ -121,11 +121,13 @@ int32_t qSetSTableIdForRsma(SNode* pStmt, int64_t uid); int32_t qInitKeywordsTable(); void qCleanupKeywordsTable(); -int32_t qAppendStmtTableOutput(SQuery* pQuery, SHashObj* pAllVgHash, STableColsData* pTbData, STableDataCxt* pTbCtx, SStbInterlaceInfo* pBuildInfo); -int32_t qBuildStmtFinOutput(SQuery* pQuery, SHashObj* pAllVgHash, SArray* pVgDataBlocks); -//int32_t qBuildStmtOutputFromTbList(SQuery* pQuery, SHashObj* pVgHash, SArray* pBlockList, STableDataCxt* pTbCtx, int32_t tbNum); +int32_t qAppendStmtTableOutput(SQuery* pQuery, SHashObj* pAllVgHash, STableColsData* pTbData, STableDataCxt* pTbCtx, + SStbInterlaceInfo* pBuildInfo); +int32_t qBuildStmtFinOutput(SQuery* pQuery, SHashObj* pAllVgHash, SArray* pVgDataBlocks); +// int32_t qBuildStmtOutputFromTbList(SQuery* pQuery, SHashObj* pVgHash, SArray* pBlockList, STableDataCxt* pTbCtx, +// int32_t tbNum); int32_t qBuildStmtOutput(SQuery* pQuery, SHashObj* pVgHash, SHashObj* pBlockHash); -int32_t qResetStmtColumns(SArray* pCols, bool deepClear); +int32_t qResetStmtColumns(SArray* pCols, bool deepClear); int32_t qResetStmtDataBlock(STableDataCxt* block, bool keepBuf); int32_t qCloneStmtDataBlock(STableDataCxt** pDst, STableDataCxt* pSrc, bool reset); int32_t qRebuildStmtDataBlock(STableDataCxt** pDst, STableDataCxt* pSrc, uint64_t uid, uint64_t suid, int32_t vgId, @@ -136,39 +138,51 @@ int32_t qCloneCurrentTbData(STableDataCxt* pDataBlock, SSubmitTbData** pData int32_t qStmtBindParams(SQuery* pQuery, TAOS_MULTI_BIND* pParams, int32_t colIdx); int32_t qStmtParseQuerySql(SParseContext* pCxt, SQuery* pQuery); -int32_t qBindStmtStbColsValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen, STSchema** pTSchema, SBindInfo* pBindInfos); +int32_t qBindStmtStbColsValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen, + STSchema** pTSchema, SBindInfo* pBindInfos); int32_t qBindStmtColsValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen); -int32_t qBindStmtSingleColValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen, int32_t colIdx, - int32_t rowNum); +int32_t qBindStmtSingleColValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen, + int32_t colIdx, int32_t rowNum); int32_t qBuildStmtColFields(void* pDataBlock, int32_t* fieldNum, TAOS_FIELD_E** fields); int32_t qBuildStmtTagFields(void* pBlock, void* boundTags, int32_t* fieldNum, TAOS_FIELD_E** fields); int32_t qBindStmtTagsValue(void* pBlock, void* boundTags, int64_t suid, const char* sTableName, char* tName, TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen); + +int32_t qStmtBindParams2(SQuery* pQuery, TAOS_STMT2_BIND* pParams, int32_t colIdx); +int32_t qBindStmtStbColsValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen, + STSchema** pTSchema, SBindInfo2* pBindInfos); +int32_t qBindStmtColsValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen); +int32_t qBindStmtSingleColValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen, + int32_t colIdx, int32_t rowNum); +int32_t qBindStmtTagsValue2(void* pBlock, void* boundTags, int64_t suid, const char* sTableName, char* tName, + TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen); + void destroyBoundColumnInfo(void* pBoundInfo); int32_t qCreateSName(SName* pName, const char* pTableName, int32_t acctId, char* dbName, char* msgBuf, int32_t msgBufLen); void qDestroyBoundColInfo(void* pInfo); -int32_t smlInitHandle(SQuery** query); -int32_t smlBuildRow(STableDataCxt* pTableCxt); -int32_t smlBuildCol(STableDataCxt* pTableCxt, SSchema* schema, void* kv, int32_t index); -int32_t smlInitTableDataCtx(SQuery* query, STableMeta* pTableMeta, STableDataCxt** cxt); +int32_t smlInitHandle(SQuery** query); +int32_t smlBuildRow(STableDataCxt* pTableCxt); +int32_t smlBuildCol(STableDataCxt* pTableCxt, SSchema* schema, void* kv, int32_t index); +int32_t smlInitTableDataCtx(SQuery* query, STableMeta* pTableMeta, STableDataCxt** cxt); void clearColValArraySml(SArray* pCols); int32_t smlBindData(SQuery* handle, bool dataFormat, SArray* tags, SArray* colsSchema, SArray* cols, STableMeta* pTableMeta, char* tableName, const char* sTableName, int32_t sTableNameLen, int32_t ttl, char* msgBuf, int32_t msgBufLen); int32_t smlBuildOutput(SQuery* handle, SHashObj* pVgHash); -int rawBlockBindData(SQuery *query, STableMeta* pTableMeta, void* data, SVCreateTbReq** pCreateTb, TAOS_FIELD *fields, - int numFields, bool needChangeLength, char* errstr, int32_t errstrLen); +int rawBlockBindData(SQuery* query, STableMeta* pTableMeta, void* data, SVCreateTbReq** pCreateTb, TAOS_FIELD* fields, + int numFields, bool needChangeLength, char* errstr, int32_t errstrLen); int32_t rewriteToVnodeModifyOpStmt(SQuery* pQuery, SArray* pBufArray); int32_t serializeVgroupsCreateTableBatch(SHashObj* pVgroupHashmap, SArray** pOut); int32_t serializeVgroupsDropTableBatch(SHashObj* pVgroupHashmap, SArray** pOut); -void destoryCatalogReq(SCatalogReq *pCatalogReq); +void destoryCatalogReq(SCatalogReq* pCatalogReq); bool isPrimaryKeyImpl(SNode* pExpr); -int32_t insAppendStmtTableDataCxt(SHashObj* pAllVgHash, STableColsData* pTbData, STableDataCxt* pTbCtx, SStbInterlaceInfo* pBuildInfo); +int32_t insAppendStmtTableDataCxt(SHashObj* pAllVgHash, STableColsData* pTbData, STableDataCxt* pTbCtx, + SStbInterlaceInfo* pBuildInfo); #ifdef __cplusplus } diff --git a/source/client/inc/clientStmt2.h b/source/client/inc/clientStmt2.h new file mode 100644 index 0000000000..e54ac03c55 --- /dev/null +++ b/source/client/inc/clientStmt2.h @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2019 TAOS Data, Inc. + * + * This program is free software: you can use, redistribute, and/or modify + * it under the terms of the GNU Affero General Public License, version 3 + * or later ("AGPL"), as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#ifndef TDENGINE_CLIENTSTMT2_H +#define TDENGINE_CLIENTSTMT2_H + +#ifdef __cplusplus +extern "C" { +#endif +#include "catalog.h" +/* +typedef enum { +STMT_TYPE_INSERT = 1, +STMT_TYPE_MULTI_INSERT, +STMT_TYPE_QUERY, +} STMT_TYPE; + +typedef enum { +STMT_INIT = 1, +STMT_PREPARE, +STMT_SETTBNAME, +STMT_SETTAGS, +STMT_FETCH_FIELDS, +STMT_BIND, +STMT_BIND_COL, +STMT_ADD_BATCH, +STMT_EXECUTE, +STMT_MAX, +} STMT_STATUS; + +#define STMT_TABLE_COLS_NUM 1000 + +typedef struct SStmtTableCache { +STableDataCxt *pDataCtx; +void *boundTags; +} SStmtTableCache; + +typedef struct SStmtQueryResInfo { +TAOS_FIELD *fields; +TAOS_FIELD *userFields; +uint32_t numOfCols; +int32_t precision; +} SStmtQueryResInfo; + +typedef struct SStmtBindInfo { +bool needParse; +bool inExecCache; +uint64_t tbUid; +uint64_t tbSuid; +int32_t tbVgId; +int32_t sBindRowNum; +int32_t sBindLastIdx; +int8_t tbType; +bool tagsCached; +void *boundTags; +char tbName[TSDB_TABLE_FNAME_LEN]; +char tbFName[TSDB_TABLE_FNAME_LEN]; +char stbFName[TSDB_TABLE_FNAME_LEN]; +SName sname; + +char statbName[TSDB_TABLE_FNAME_LEN]; +} SStmtBindInfo; + +typedef struct SStmtAsyncParam { +STableColsData *pTbData; +void* pStmt; +} SStmtAsyncParam; + +typedef struct SStmtExecInfo { +int32_t affectedRows; +SRequestObj *pRequest; +SHashObj *pBlockHash; +STableDataCxt *pCurrBlock; +SSubmitTbData *pCurrTbData; +} SStmtExecInfo; +*/ +typedef struct { + bool stbInterlaceMode; + STMT_TYPE type; + STMT_STATUS status; + uint64_t suid; + uint64_t runTimes; + SHashObj *pTableCache; // SHash + SQuery *pQuery; + char *sqlStr; + int32_t sqlLen; + SArray *nodeList; + SStmtQueryResInfo queryRes; + bool autoCreateTbl; + SHashObj *pVgHash; + SBindInfo2 *pBindInfo; + + SStbInterlaceInfo siInfo; +} SStmtSQLInfo2; +/* +typedef struct SStmtStatInfo { +int64_t ctgGetTbMetaNum; +int64_t getCacheTbInfo; +int64_t parseSqlNum; +int64_t bindDataNum; +int64_t setTbNameUs; +int64_t bindDataUs1; +int64_t bindDataUs2; +int64_t bindDataUs3; +int64_t bindDataUs4; +int64_t addBatchUs; +int64_t execWaitUs; +int64_t execUseUs; +} SStmtStatInfo; + +typedef struct SStmtQNode { +bool restoreTbCols; +STableColsData tblData; +struct SStmtQNode* next; +} SStmtQNode; + +typedef struct SStmtQueue { +bool stopQueue; +SStmtQNode* head; +SStmtQNode* tail; +uint64_t qRemainNum; +} SStmtQueue; +*/ + +typedef struct { + STscObj *taos; + SCatalog *pCatalog; + int32_t affectedRows; + uint32_t seqId; + uint32_t seqIds[STMT_MAX]; + bool bindThreadInUse; + TdThread bindThread; + TAOS_STMT2_OPTION options; + bool stbInterlaceMode; + SStmtQueue queue; + + SStmtSQLInfo2 sql; + SStmtExecInfo exec; + SStmtBindInfo bInfo; + + int64_t reqid; + int32_t errCode; + + SStmtStatInfo stat; +} STscStmt2; +/* +extern char *gStmtStatusStr[]; + +#define STMT_LOG_SEQ(n) \ +do { \ + (pStmt)->seqId++; \ + (pStmt)->seqIds[n]++; \ + STMT_DLOG("the %dth:%d %s", (pStmt)->seqIds[n], (pStmt)->seqId, gStmtStatusStr[n]); \ +} while (0) + +#define STMT_STATUS_NE(S) (pStmt->sql.status != STMT_##S) +#define STMT_STATUS_EQ(S) (pStmt->sql.status == STMT_##S) + +#define STMT_ERR_RET(c) \ +do { \ + int32_t _code = c; \ + if (_code != TSDB_CODE_SUCCESS) { \ + terrno = _code; \ + pStmt->errCode = _code; \ + return _code; \ + } \ +} while (0) +#define STMT_RET(c) \ +do { \ + int32_t _code = c; \ + if (_code != TSDB_CODE_SUCCESS) { \ + terrno = _code; \ + pStmt->errCode = _code; \ + } \ + return _code; \ +} while (0) +#define STMT_ERR_JRET(c) \ +do { \ + code = c; \ + if (code != TSDB_CODE_SUCCESS) { \ + terrno = code; \ + pStmt->errCode = code; \ + goto _return; \ + } \ +} while (0) +#define STMT_ERRI_JRET(c) \ +do { \ + code = c; \ + if (code != TSDB_CODE_SUCCESS) { \ + terrno = code; \ + goto _return; \ + } \ +} while (0) + + +#define STMT_FLOG(param, ...) qFatal("stmt:%p " param, pStmt, __VA_ARGS__) +#define STMT_ELOG(param, ...) qError("stmt:%p " param, pStmt, __VA_ARGS__) +#define STMT_DLOG(param, ...) qDebug("stmt:%p " param, pStmt, __VA_ARGS__) + +#define STMT_ELOG_E(param) qError("stmt:%p " param, pStmt) +#define STMT_DLOG_E(param) qDebug("stmt:%p " param, pStmt) +*/ +TAOS_STMT2 *stmtInit2(STscObj *taos, TAOS_STMT2_OPTION *pOptions); +int stmtClose2(TAOS_STMT2 *stmt); +int stmtExec2(TAOS_STMT2 *stmt, int *affected_rows); +int stmtPrepare2(TAOS_STMT2 *stmt, const char *sql, unsigned long length); +int stmtSetTbName2(TAOS_STMT2 *stmt, const char *tbName); +int stmtSetTbTags2(TAOS_STMT2 *stmt, TAOS_STMT2_BIND *tags); +int stmtGetTagFields2(TAOS_STMT2 *stmt, int *nums, TAOS_FIELD_E **fields); +int stmtGetColFields2(TAOS_STMT2 *stmt, int *nums, TAOS_FIELD_E **fields); +int stmtIsInsert2(TAOS_STMT2 *stmt, int *insert); +int stmtGetParamNum2(TAOS_STMT2 *stmt, int *nums); +TAOS_RES *stmtUseResult2(TAOS_STMT2 *stmt); +int stmtBindBatch2(TAOS_STMT2 *stmt, TAOS_STMT2_BIND *bind, int32_t colIdx); +const char *stmtErrstr2(TAOS_STMT2 *stmt); + +#ifdef __cplusplus +} +#endif + +#endif // TDENGINE_CLIENTSTMT2_H diff --git a/source/client/src/clientMain.c b/source/client/src/clientMain.c index 12702a93f3..52895bb24b 100644 --- a/source/client/src/clientMain.c +++ b/source/client/src/clientMain.c @@ -16,19 +16,20 @@ #include "catalog.h" #include "clientInt.h" #include "clientLog.h" -#include "clientStmt.h" #include "clientMonitor.h" +#include "clientStmt.h" +#include "clientStmt2.h" #include "functionMgt.h" #include "os.h" #include "query.h" #include "scheduler.h" +#include "tcompare.h" #include "tdatablock.h" #include "tglobal.h" #include "tmsg.h" #include "tref.h" #include "trpc.h" #include "version.h" -#include "tcompare.h" #define TSC_VAR_NOT_RELEASE 1 #define TSC_VAR_RELEASED 0 @@ -124,7 +125,7 @@ TAOS *taos_connect(const char *ip, const char *user, const char *pass, const cha } STscObj *pObj = NULL; - int32_t code = taos_connect_internal(ip, user, pass, NULL, db, port, CONN_TYPE__QUERY, &pObj); + int32_t code = taos_connect_internal(ip, user, pass, NULL, db, port, CONN_TYPE__QUERY, &pObj); if (TSDB_CODE_SUCCESS == code) { int64_t *rid = taosMemoryCalloc(1, sizeof(int64_t)); if (NULL == rid) { @@ -187,15 +188,15 @@ int taos_set_notify_cb(TAOS *taos, __taos_notify_fn_t fp, void *param, int type) return 0; } -typedef struct SFetchWhiteListInfo{ - int64_t connId; +typedef struct SFetchWhiteListInfo { + int64_t connId; __taos_async_whitelist_fn_t userCbFn; - void* userParam; + void *userParam; } SFetchWhiteListInfo; -int32_t fetchWhiteListCallbackFn(void* param, SDataBuf* pMsg, int32_t code) { - SFetchWhiteListInfo* pInfo = (SFetchWhiteListInfo*)param; - TAOS* taos = &pInfo->connId; +int32_t fetchWhiteListCallbackFn(void *param, SDataBuf *pMsg, int32_t code) { + SFetchWhiteListInfo *pInfo = (SFetchWhiteListInfo *)param; + TAOS *taos = &pInfo->connId; if (code != TSDB_CODE_SUCCESS) { pInfo->userCbFn(pInfo->userParam, code, taos, 0, NULL); taosMemoryFree(pMsg->pData); @@ -213,7 +214,7 @@ int32_t fetchWhiteListCallbackFn(void* param, SDataBuf* pMsg, int32_t code) { return terrno; } - uint64_t* pWhiteLists = taosMemoryMalloc(wlRsp.numWhiteLists * sizeof(uint64_t)); + uint64_t *pWhiteLists = taosMemoryMalloc(wlRsp.numWhiteLists * sizeof(uint64_t)); if (pWhiteLists == NULL) { taosMemoryFree(pMsg->pData); taosMemoryFree(pMsg->pEpSet); @@ -242,7 +243,7 @@ void taos_fetch_whitelist_a(TAOS *taos, __taos_async_whitelist_fn_t fp, void *pa return; } - int64_t connId = *(int64_t*)taos; + int64_t connId = *(int64_t *)taos; STscObj *pTsc = acquireTscObj(connId); if (NULL == pTsc) { @@ -259,7 +260,7 @@ void taos_fetch_whitelist_a(TAOS *taos, __taos_async_whitelist_fn_t fp, void *pa return; } - void* pReq = taosMemoryMalloc(msgLen); + void *pReq = taosMemoryMalloc(msgLen); if (pReq == NULL) { fp(param, TSDB_CODE_OUT_OF_MEMORY, taos, 0, NULL); releaseTscObj(connId); @@ -273,7 +274,7 @@ void taos_fetch_whitelist_a(TAOS *taos, __taos_async_whitelist_fn_t fp, void *pa return; } - SFetchWhiteListInfo* pParam = taosMemoryMalloc(sizeof(SFetchWhiteListInfo)); + SFetchWhiteListInfo *pParam = taosMemoryMalloc(sizeof(SFetchWhiteListInfo)); if (pParam == NULL) { fp(param, TSDB_CODE_OUT_OF_MEMORY, taos, 0, NULL); taosMemoryFree(pReq); @@ -284,9 +285,9 @@ void taos_fetch_whitelist_a(TAOS *taos, __taos_async_whitelist_fn_t fp, void *pa pParam->connId = connId; pParam->userCbFn = fp; pParam->userParam = param; - SMsgSendInfo* pSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo)); + SMsgSendInfo *pSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo)); if (pSendInfo == NULL) { - fp(param, TSDB_CODE_OUT_OF_MEMORY, taos, 0, NULL); + fp(param, TSDB_CODE_OUT_OF_MEMORY, taos, 0, NULL); taosMemoryFree(pParam); taosMemoryFree(pReq); releaseTscObj(connId); @@ -301,7 +302,7 @@ void taos_fetch_whitelist_a(TAOS *taos, __taos_async_whitelist_fn_t fp, void *pa pSendInfo->msgType = TDMT_MND_GET_USER_WHITELIST; int64_t transportId = 0; - SEpSet epSet = getEpSet_s(&pTsc->pAppInfo->mgmtEp); + SEpSet epSet = getEpSet_s(&pTsc->pAppInfo->mgmtEp); if (TSDB_CODE_SUCCESS != asyncSendMsgToServer(pTsc->pAppInfo->pTransporter, &epSet, &transportId, pSendInfo)) { tscWarn("failed to async send msg to server"); } @@ -447,7 +448,7 @@ TAOS_ROW taos_fetch_row(TAOS_RES *res) { return NULL; } - if(pRequest->inCallback) { + if (pRequest->inCallback) { tscError("can not call taos_fetch_row before query callback ends."); terrno = TSDB_CODE_TSC_INVALID_OPERATION; return NULL; @@ -458,7 +459,7 @@ TAOS_ROW taos_fetch_row(TAOS_RES *res) { SMqRspObj *msg = ((SMqRspObj *)res); SReqResultInfo *pResultInfo = NULL; if (msg->common.resIter == -1) { - if(tmqGetNextResInfo(res, true, &pResultInfo) != 0){ + if (tmqGetNextResInfo(res, true, &pResultInfo) != 0) { return NULL; } } else { @@ -470,7 +471,7 @@ TAOS_ROW taos_fetch_row(TAOS_RES *res) { pResultInfo->current += 1; return pResultInfo->row; } else { - if (tmqGetNextResInfo(res, true, &pResultInfo) != 0){ + if (tmqGetNextResInfo(res, true, &pResultInfo) != 0) { return NULL; } @@ -545,22 +546,23 @@ int taos_print_row(char *str, TAOS_ROW row, TAOS_FIELD *fields, int num_fields) len += sprintf(str + len, "%lf", dv); } break; - case TSDB_DATA_TYPE_VARBINARY:{ - void* data = NULL; + case TSDB_DATA_TYPE_VARBINARY: { + void *data = NULL; uint32_t size = 0; - int32_t charLen = varDataLen((char *)row[i] - VARSTR_HEADER_SIZE); - if(taosAscii2Hex(row[i], charLen, &data, &size) < 0){ + int32_t charLen = varDataLen((char *)row[i] - VARSTR_HEADER_SIZE); + if (taosAscii2Hex(row[i], charLen, &data, &size) < 0) { break; } (void)memcpy(str + len, data, size); len += size; taosMemoryFree(data); - }break; + } break; case TSDB_DATA_TYPE_BINARY: case TSDB_DATA_TYPE_NCHAR: case TSDB_DATA_TYPE_GEOMETRY: { int32_t charLen = varDataLen((char *)row[i] - VARSTR_HEADER_SIZE); - if (fields[i].type == TSDB_DATA_TYPE_BINARY || fields[i].type == TSDB_DATA_TYPE_VARBINARY || fields[i].type == TSDB_DATA_TYPE_GEOMETRY) { + if (fields[i].type == TSDB_DATA_TYPE_BINARY || fields[i].type == TSDB_DATA_TYPE_VARBINARY || + fields[i].type == TSDB_DATA_TYPE_GEOMETRY) { if (ASSERT(charLen <= fields[i].bytes && charLen >= 0)) { tscError("taos_print_row error binary. charLen:%d, fields[i].bytes:%d", charLen, fields[i].bytes); } @@ -667,7 +669,8 @@ const char *taos_get_client_info() { return version; } // return int32_t int taos_affected_rows(TAOS_RES *res) { - if (res == NULL || TD_RES_TMQ(res) || TD_RES_TMQ_META(res) || TD_RES_TMQ_METADATA(res) || TD_RES_TMQ_BATCH_META(res)) { + if (res == NULL || TD_RES_TMQ(res) || TD_RES_TMQ_META(res) || TD_RES_TMQ_METADATA(res) || + TD_RES_TMQ_BATCH_META(res)) { return 0; } @@ -678,7 +681,8 @@ int taos_affected_rows(TAOS_RES *res) { // return int64_t int64_t taos_affected_rows64(TAOS_RES *res) { - if (res == NULL || TD_RES_TMQ(res) || TD_RES_TMQ_META(res) || TD_RES_TMQ_METADATA(res) || TD_RES_TMQ_BATCH_META(res)) { + if (res == NULL || TD_RES_TMQ(res) || TD_RES_TMQ_META(res) || TD_RES_TMQ_METADATA(res) || + TD_RES_TMQ_BATCH_META(res)) { return 0; } @@ -728,7 +732,8 @@ int taos_select_db(TAOS *taos, const char *db) { } void taos_stop_query(TAOS_RES *res) { - if (res == NULL || TD_RES_TMQ(res) || TD_RES_TMQ_META(res) || TD_RES_TMQ_METADATA(res) || TD_RES_TMQ_BATCH_META(res)) { + if (res == NULL || TD_RES_TMQ(res) || TD_RES_TMQ_META(res) || TD_RES_TMQ_METADATA(res) || + TD_RES_TMQ_BATCH_META(res)) { return; } @@ -787,7 +792,7 @@ int taos_fetch_block_s(TAOS_RES *res, int *numOfRows, TAOS_ROW *rows) { return pRequest->code; } else if (TD_RES_TMQ(res) || TD_RES_TMQ_METADATA(res)) { SReqResultInfo *pResultInfo = NULL; - int32_t code = tmqGetNextResInfo(res, true, &pResultInfo); + int32_t code = tmqGetNextResInfo(res, true, &pResultInfo); if (code != 0) return code; pResultInfo->current = pResultInfo->numOfRows; @@ -810,7 +815,7 @@ int taos_fetch_raw_block(TAOS_RES *res, int *numOfRows, void **pData) { if (TD_RES_TMQ(res) || TD_RES_TMQ_METADATA(res)) { SReqResultInfo *pResultInfo = NULL; - int32_t code = tmqGetNextResInfo(res, false, &pResultInfo); + int32_t code = tmqGetNextResInfo(res, false, &pResultInfo); if (code != 0) { (*numOfRows) = 0; return 0; @@ -956,7 +961,7 @@ static void doAsyncQueryFromAnalyse(SMetaData *pResultMeta, void *param, int32_t (void)memcpy(&pRequest->parseMeta, pResultMeta, sizeof(*pResultMeta)); (void)memset(pResultMeta, 0, sizeof(*pResultMeta)); } - + handleQueryAnslyseRes(pWrapper, pResultMeta, code); } @@ -1002,7 +1007,7 @@ void handleSubQueryFromAnalyse(SSqlCallbackWrapper *pWrapper, SMetaData *pResult } pNewRequest->pQuery = NULL; - code = nodesMakeNode(QUERY_NODE_QUERY, (SNode**)&pNewRequest->pQuery); + code = nodesMakeNode(QUERY_NODE_QUERY, (SNode **)&pNewRequest->pQuery); if (pNewRequest->pQuery) { pNewRequest->pQuery->pRoot = pRoot; pRoot = NULL; @@ -1274,7 +1279,7 @@ void doAsyncQuery(SRequestObj *pRequest, bool updateMetaForce) { if (NEED_CLIENT_HANDLE_ERROR(code)) { tscDebug("0x%" PRIx64 " client retry to handle the error, code:%d - %s, tryCount:%d, reqId:0x%" PRIx64, pRequest->self, code, tstrerror(code), pRequest->retry, pRequest->requestId); - (void)refreshMeta(pRequest->pTscObj, pRequest); //ignore return code,try again + (void)refreshMeta(pRequest->pTscObj, pRequest); // ignore return code,try again pRequest->prevCode = code; doAsyncQuery(pRequest, true); return; @@ -1288,7 +1293,7 @@ void doAsyncQuery(SRequestObj *pRequest, bool updateMetaForce) { void restartAsyncQuery(SRequestObj *pRequest, int32_t code) { tscInfo("restart request: %s p: %p", pRequest->sqlstr, pRequest); - SRequestObj* pUserReq = pRequest; + SRequestObj *pUserReq = pRequest; (void)acquireRequest(pRequest->self); while (pUserReq) { if (pUserReq->self == pUserReq->relation.userRefId || pUserReq->relation.userRefId == 0) { @@ -1634,7 +1639,6 @@ TAOS_STMT *taos_stmt_init_with_options(TAOS *taos, TAOS_STMT_OPTIONS *options) { return pStmt; } - int taos_stmt_prepare(TAOS_STMT *stmt, const char *sql, unsigned long length) { if (stmt == NULL || sql == NULL) { tscError("NULL parameter for %s", __FUNCTION__); @@ -1877,7 +1881,161 @@ int taos_stmt_close(TAOS_STMT *stmt) { return stmtClose(stmt); } -int taos_set_conn_mode(TAOS* taos, int mode, int value) { +TAOS_STMT2 *taos_stmt2_init(TAOS *taos, TAOS_STMT2_OPTION *option) { + STscObj *pObj = acquireTscObj(*(int64_t *)taos); + if (NULL == pObj) { + tscError("invalid parameter for %s", __FUNCTION__); + terrno = TSDB_CODE_TSC_DISCONNECTED; + return NULL; + } + + TAOS_STMT2 *pStmt = stmtInit2(pObj, option); + + releaseTscObj(*(int64_t *)taos); + + return pStmt; +} + +int taos_stmt2_prepare(TAOS_STMT2 *stmt, const char *sql, unsigned long length) { + if (stmt == NULL || sql == NULL) { + tscError("NULL parameter for %s", __FUNCTION__); + terrno = TSDB_CODE_INVALID_PARA; + return terrno; + } + + return stmtPrepare2(stmt, sql, length); +} + +int taos_stmt2_bind_param(TAOS_STMT2 *stmt, TAOS_STMT2_BINDV *bindv, int32_t col_idx) { + if (stmt == NULL) { + tscError("NULL parameter for %s", __FUNCTION__); + terrno = TSDB_CODE_INVALID_PARA; + return terrno; + } + + int32_t code = 0; + for (int i = 0; i < bindv->count; ++i) { + char *tbname = bindv->tbnames[i]; + TAOS_STMT2_BIND *tags = bindv->tags[i]; + TAOS_STMT2_BIND *bind = bindv->bind_cols[i]; + + if (tbname) { + code = stmtSetTbName2(stmt, tbname); + if (code) { + return code; + } + } + + if (tags) { + code = stmtSetTbTags2(stmt, tags); + if (code) { + return code; + } + } + + if (bind) { + if (bind->num <= 0 || bind->num > INT16_MAX) { + tscError("invalid bind num %d", bind->num); + terrno = TSDB_CODE_INVALID_PARA; + return terrno; + } + + int32_t insert = 0; + (void)stmtIsInsert(stmt, &insert); + if (0 == insert && bind->num > 1) { + tscError("only one row data allowed for query"); + terrno = TSDB_CODE_INVALID_PARA; + return terrno; + } + + code = stmtBindBatch2(stmt, bind, col_idx); + if (TSDB_CODE_SUCCESS != code) { + return code; + } + } + } + + return TSDB_CODE_SUCCESS; +} + +int taos_stmt2_exec(TAOS_STMT2 *stmt, int *affected_rows) { + if (stmt == NULL) { + tscError("NULL parameter for %s", __FUNCTION__); + terrno = TSDB_CODE_INVALID_PARA; + return terrno; + } + + return stmtExec2(stmt, affected_rows); +} + +int taos_stmt2_close(TAOS_STMT2 *stmt) { + if (stmt == NULL) { + tscError("NULL parameter for %s", __FUNCTION__); + terrno = TSDB_CODE_INVALID_PARA; + return terrno; + } + + return stmtClose2(stmt); +} +/* +int taos_stmt2_param_count(TAOS_STMT2 *stmt, int *nums) { + if (stmt == NULL || nums == NULL) { + tscError("NULL parameter for %s", __FUNCTION__); + terrno = TSDB_CODE_INVALID_PARA; + return terrno; + } + return stmtGetParamNum2(stmt, nums); +} +*/ +int taos_stmt2_is_insert(TAOS_STMT2 *stmt, int *insert) { + if (stmt == NULL || insert == NULL) { + tscError("NULL parameter for %s", __FUNCTION__); + terrno = TSDB_CODE_INVALID_PARA; + return terrno; + } + + return stmtIsInsert2(stmt, insert); +} + +int taos_stmt2_get_fields(TAOS_STMT2 *stmt, TAOS_FIELD_T field_type, int *count, TAOS_FIELD_E **fields) { + if (stmt == NULL || NULL == count) { + tscError("NULL parameter for %s", __FUNCTION__); + terrno = TSDB_CODE_INVALID_PARA; + return terrno; + } + + if (field_type == TAOS_FIELD_COL) { + return stmtGetColFields2(stmt, count, fields); + } else if (field_type == TAOS_FIELD_TAG) { + return stmtGetTagFields2(stmt, count, fields); + } else if (field_type == TAOS_FIELD_QUERY) { + return stmtGetParamNum2(stmt, count); + } else { + tscError("invalid parameter for %s", __FUNCTION__); + terrno = TSDB_CODE_INVALID_PARA; + return terrno; + } +} + +void taos_stmt2_free_fields(TAOS_STMT2 *stmt, TAOS_FIELD_E *fields) { + (void)stmt; + if (!fields) return; + taosMemoryFree(fields); +} + +TAOS_RES *taos_stmt2_result(TAOS_STMT2 *stmt) { + if (stmt == NULL) { + tscError("NULL parameter for %s", __FUNCTION__); + terrno = TSDB_CODE_INVALID_PARA; + return NULL; + } + + return stmtUseResult2(stmt); +} + +char *taos_stmt2_error(TAOS_STMT2 *stmt) { return (char *)stmtErrstr2(stmt); } + +int taos_set_conn_mode(TAOS *taos, int mode, int value) { if (taos == NULL) { terrno = TSDB_CODE_INVALID_PARA; return terrno; @@ -1900,6 +2058,4 @@ int taos_set_conn_mode(TAOS* taos, int mode, int value) { return 0; } -char* getBuildInfo(){ - return buildinfo; -} +char *getBuildInfo() { return buildinfo; } diff --git a/source/client/src/clientStmt2.c b/source/client/src/clientStmt2.c new file mode 100644 index 0000000000..5f7abefa85 --- /dev/null +++ b/source/client/src/clientStmt2.c @@ -0,0 +1,1895 @@ +#include "clientInt.h" +#include "clientLog.h" +#include "tdef.h" + +#include "clientStmt.h" +#include "clientStmt2.h" +/* +char* gStmtStatusStr[] = {"unknown", "init", "prepare", "settbname", "settags", + "fetchFields", "bind", "bindCol", "addBatch", "exec"}; +*/ +static FORCE_INLINE int32_t stmtAllocQNodeFromBuf(STableBufInfo* pTblBuf, void** pBuf) { + if (pTblBuf->buffOffset < pTblBuf->buffSize) { + *pBuf = (char*)pTblBuf->pCurBuff + pTblBuf->buffOffset; + pTblBuf->buffOffset += pTblBuf->buffUnit; + } else if (pTblBuf->buffIdx < taosArrayGetSize(pTblBuf->pBufList)) { + pTblBuf->pCurBuff = taosArrayGetP(pTblBuf->pBufList, pTblBuf->buffIdx++); + if (NULL == pTblBuf->pCurBuff) { + return TAOS_GET_TERRNO(TSDB_CODE_OUT_OF_MEMORY); + } + *pBuf = pTblBuf->pCurBuff; + pTblBuf->buffOffset = pTblBuf->buffUnit; + } else { + void* buff = taosMemoryMalloc(pTblBuf->buffSize); + if (NULL == buff) { + return terrno; + } + + if (taosArrayPush(pTblBuf->pBufList, &buff) == NULL) { + return terrno; + } + + pTblBuf->buffIdx++; + pTblBuf->pCurBuff = buff; + *pBuf = buff; + pTblBuf->buffOffset = pTblBuf->buffUnit; + } + + return TSDB_CODE_SUCCESS; +} + +static bool stmtDequeue(STscStmt2* pStmt, SStmtQNode** param) { + while (0 == atomic_load_64(&pStmt->queue.qRemainNum)) { + taosUsleep(1); + return false; + } + + SStmtQNode* orig = pStmt->queue.head; + + SStmtQNode* node = pStmt->queue.head->next; + pStmt->queue.head = pStmt->queue.head->next; + + // taosMemoryFreeClear(orig); + + *param = node; + + (void)atomic_sub_fetch_64(&pStmt->queue.qRemainNum, 1); + + return true; +} + +static void stmtEnqueue(STscStmt2* pStmt, SStmtQNode* param) { + pStmt->queue.tail->next = param; + pStmt->queue.tail = param; + + pStmt->stat.bindDataNum++; + (void)atomic_add_fetch_64(&pStmt->queue.qRemainNum, 1); +} + +static int32_t stmtCreateRequest(STscStmt2* pStmt) { + int32_t code = 0; + + if (pStmt->exec.pRequest == NULL) { + code = buildRequest(pStmt->taos->id, pStmt->sql.sqlStr, pStmt->sql.sqlLen, NULL, false, &pStmt->exec.pRequest, + pStmt->reqid); + if (pStmt->reqid != 0) { + pStmt->reqid++; + } + if (TSDB_CODE_SUCCESS == code) { + pStmt->exec.pRequest->syncQuery = true; + pStmt->exec.pRequest->isStmtBind = true; + } + } + + return code; +} + +static int32_t stmtSwitchStatus(STscStmt2* pStmt, STMT_STATUS newStatus) { + int32_t code = 0; + + if (newStatus >= STMT_INIT && newStatus < STMT_MAX) { + STMT_LOG_SEQ(newStatus); + } + + if (pStmt->errCode && newStatus != STMT_PREPARE) { + STMT_DLOG("stmt already failed with err: %s", tstrerror(pStmt->errCode)); + return pStmt->errCode; + } + + switch (newStatus) { + case STMT_PREPARE: + pStmt->errCode = 0; + break; + case STMT_SETTBNAME: + if (STMT_STATUS_EQ(INIT)) { + code = TSDB_CODE_TSC_STMT_API_ERROR; + } + if (!pStmt->sql.stbInterlaceMode && (STMT_STATUS_EQ(BIND) || STMT_STATUS_EQ(BIND_COL))) { + code = TSDB_CODE_TSC_STMT_API_ERROR; + } + break; + case STMT_SETTAGS: + if (STMT_STATUS_NE(SETTBNAME) && STMT_STATUS_NE(FETCH_FIELDS)) { + code = TSDB_CODE_TSC_STMT_API_ERROR; + } + break; + case STMT_FETCH_FIELDS: + if (STMT_STATUS_EQ(INIT)) { + code = TSDB_CODE_TSC_STMT_API_ERROR; + } + break; + case STMT_BIND: + if (STMT_STATUS_EQ(INIT) || STMT_STATUS_EQ(BIND_COL)) { + code = TSDB_CODE_TSC_STMT_API_ERROR; + } + /* + if ((pStmt->sql.type == STMT_TYPE_MULTI_INSERT) && ()) { + code = TSDB_CODE_TSC_STMT_API_ERROR; + } + */ + break; + case STMT_BIND_COL: + if (STMT_STATUS_EQ(INIT) || STMT_STATUS_EQ(BIND)) { + code = TSDB_CODE_TSC_STMT_API_ERROR; + } + break; + case STMT_ADD_BATCH: + if (STMT_STATUS_NE(BIND) && STMT_STATUS_NE(BIND_COL) && STMT_STATUS_NE(FETCH_FIELDS)) { + code = TSDB_CODE_TSC_STMT_API_ERROR; + } + break; + case STMT_EXECUTE: + if (STMT_TYPE_QUERY == pStmt->sql.type) { + if (STMT_STATUS_NE(ADD_BATCH) && STMT_STATUS_NE(FETCH_FIELDS) && STMT_STATUS_NE(BIND) && + STMT_STATUS_NE(BIND_COL)) { + code = TSDB_CODE_TSC_STMT_API_ERROR; + } + } else { + if (STMT_STATUS_NE(ADD_BATCH) && STMT_STATUS_NE(FETCH_FIELDS)) { + code = TSDB_CODE_TSC_STMT_API_ERROR; + } + } + break; + default: + code = TSDB_CODE_APP_ERROR; + break; + } + + STMT_ERR_RET(code); + + pStmt->sql.status = newStatus; + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtGetTbName(TAOS_STMT2* stmt, char** tbName) { + STscStmt2* pStmt = (STscStmt2*)stmt; + + pStmt->sql.type = STMT_TYPE_MULTI_INSERT; + + if ('\0' == pStmt->bInfo.tbName[0]) { + tscError("no table name set"); + STMT_ERR_RET(TSDB_CODE_TSC_STMT_TBNAME_ERROR); + } + + *tbName = pStmt->bInfo.tbName; + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtBackupQueryFields(STscStmt2* pStmt) { + SStmtQueryResInfo* pRes = &pStmt->sql.queryRes; + pRes->numOfCols = pStmt->exec.pRequest->body.resInfo.numOfCols; + pRes->precision = pStmt->exec.pRequest->body.resInfo.precision; + + int32_t size = pRes->numOfCols * sizeof(TAOS_FIELD); + pRes->fields = taosMemoryMalloc(size); + pRes->userFields = taosMemoryMalloc(size); + if (NULL == pRes->fields || NULL == pRes->userFields) { + STMT_ERR_RET(TSDB_CODE_OUT_OF_MEMORY); + } + (void)memcpy(pRes->fields, pStmt->exec.pRequest->body.resInfo.fields, size); + (void)memcpy(pRes->userFields, pStmt->exec.pRequest->body.resInfo.userFields, size); + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtRestoreQueryFields(STscStmt2* pStmt) { + SStmtQueryResInfo* pRes = &pStmt->sql.queryRes; + int32_t size = pRes->numOfCols * sizeof(TAOS_FIELD); + + pStmt->exec.pRequest->body.resInfo.numOfCols = pRes->numOfCols; + pStmt->exec.pRequest->body.resInfo.precision = pRes->precision; + + if (NULL == pStmt->exec.pRequest->body.resInfo.fields) { + pStmt->exec.pRequest->body.resInfo.fields = taosMemoryMalloc(size); + if (NULL == pStmt->exec.pRequest->body.resInfo.fields) { + STMT_ERR_RET(TSDB_CODE_OUT_OF_MEMORY); + } + (void)memcpy(pStmt->exec.pRequest->body.resInfo.fields, pRes->fields, size); + } + + if (NULL == pStmt->exec.pRequest->body.resInfo.userFields) { + pStmt->exec.pRequest->body.resInfo.userFields = taosMemoryMalloc(size); + if (NULL == pStmt->exec.pRequest->body.resInfo.userFields) { + STMT_ERR_RET(TSDB_CODE_OUT_OF_MEMORY); + } + (void)memcpy(pStmt->exec.pRequest->body.resInfo.userFields, pRes->userFields, size); + } + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtUpdateBindInfo(TAOS_STMT2* stmt, STableMeta* pTableMeta, void* tags, SName* tbName, + const char* sTableName, bool autoCreateTbl) { + STscStmt2* pStmt = (STscStmt2*)stmt; + char tbFName[TSDB_TABLE_FNAME_LEN]; + int32_t code = tNameExtractFullName(tbName, tbFName); + if (code != 0) { + return code; + } + + (void)memcpy(&pStmt->bInfo.sname, tbName, sizeof(*tbName)); + (void)strncpy(pStmt->bInfo.tbFName, tbFName, sizeof(pStmt->bInfo.tbFName) - 1); + pStmt->bInfo.tbFName[sizeof(pStmt->bInfo.tbFName) - 1] = 0; + + pStmt->bInfo.tbUid = autoCreateTbl ? 0 : pTableMeta->uid; + pStmt->bInfo.tbSuid = pTableMeta->suid; + pStmt->bInfo.tbVgId = pTableMeta->vgId; + pStmt->bInfo.tbType = pTableMeta->tableType; + pStmt->bInfo.boundTags = tags; + pStmt->bInfo.tagsCached = false; + tstrncpy(pStmt->bInfo.stbFName, sTableName, sizeof(pStmt->bInfo.stbFName)); + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtUpdateExecInfo(TAOS_STMT2* stmt, SHashObj* pVgHash, SHashObj* pBlockHash) { + STscStmt2* pStmt = (STscStmt2*)stmt; + + pStmt->sql.pVgHash = pVgHash; + pStmt->exec.pBlockHash = pBlockHash; + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtUpdateInfo(TAOS_STMT2* stmt, STableMeta* pTableMeta, void* tags, SName* tbName, bool autoCreateTbl, + SHashObj* pVgHash, SHashObj* pBlockHash, const char* sTableName) { + STscStmt2* pStmt = (STscStmt2*)stmt; + + STMT_ERR_RET(stmtUpdateBindInfo(stmt, pTableMeta, tags, tbName, sTableName, autoCreateTbl)); + STMT_ERR_RET(stmtUpdateExecInfo(stmt, pVgHash, pBlockHash)); + + pStmt->sql.autoCreateTbl = autoCreateTbl; + if (pStmt->sql.autoCreateTbl) { + pStmt->sql.stbInterlaceMode = false; + } + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtGetExecInfo(TAOS_STMT2* stmt, SHashObj** pVgHash, SHashObj** pBlockHash) { + STscStmt2* pStmt = (STscStmt2*)stmt; + + *pVgHash = pStmt->sql.pVgHash; + pStmt->sql.pVgHash = NULL; + + *pBlockHash = pStmt->exec.pBlockHash; + pStmt->exec.pBlockHash = NULL; + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtCacheBlock(STscStmt2* pStmt) { + if (pStmt->sql.type != STMT_TYPE_MULTI_INSERT) { + return TSDB_CODE_SUCCESS; + } + + uint64_t uid = pStmt->bInfo.tbUid; + uint64_t cacheUid = (TSDB_CHILD_TABLE == pStmt->bInfo.tbType) ? pStmt->bInfo.tbSuid : uid; + + if (taosHashGet(pStmt->sql.pTableCache, &cacheUid, sizeof(cacheUid))) { + return TSDB_CODE_SUCCESS; + } + + STableDataCxt** pSrc = taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName)); + if (!pSrc) { + return TSDB_CODE_OUT_OF_MEMORY; + } + STableDataCxt* pDst = NULL; + + STMT_ERR_RET(qCloneStmtDataBlock(&pDst, *pSrc, true)); + + SStmtTableCache cache = { + .pDataCtx = pDst, + .boundTags = pStmt->bInfo.boundTags, + }; + + if (taosHashPut(pStmt->sql.pTableCache, &cacheUid, sizeof(cacheUid), &cache, sizeof(cache))) { + return TSDB_CODE_OUT_OF_MEMORY; + } + + if (pStmt->sql.autoCreateTbl) { + pStmt->bInfo.tagsCached = true; + } else { + pStmt->bInfo.boundTags = NULL; + } + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtParseSql(STscStmt2* pStmt) { + pStmt->exec.pCurrBlock = NULL; + + SStmtCallback stmtCb = { + .pStmt = pStmt, + .getTbNameFn = stmtGetTbName, + .setInfoFn = stmtUpdateInfo, + .getExecInfoFn = stmtGetExecInfo, + }; + + STMT_ERR_RET(stmtCreateRequest(pStmt)); + + pStmt->stat.parseSqlNum++; + STMT_ERR_RET(parseSql(pStmt->exec.pRequest, false, &pStmt->sql.pQuery, &stmtCb)); + pStmt->sql.siInfo.pQuery = pStmt->sql.pQuery; + + pStmt->bInfo.needParse = false; + + if (pStmt->sql.pQuery->pRoot && 0 == pStmt->sql.type) { + pStmt->sql.type = STMT_TYPE_INSERT; + pStmt->sql.stbInterlaceMode = false; + } else if (pStmt->sql.pQuery->pPrepareRoot) { + pStmt->sql.type = STMT_TYPE_QUERY; + pStmt->sql.stbInterlaceMode = false; + + return TSDB_CODE_SUCCESS; + } + + STableDataCxt** pSrc = + (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName)); + if (NULL == pSrc || NULL == *pSrc) { + return TSDB_CODE_OUT_OF_MEMORY; + } + + STableDataCxt* pTableCtx = *pSrc; + if (pStmt->sql.stbInterlaceMode) { + int16_t lastIdx = -1; + + for (int32_t i = 0; i < pTableCtx->boundColsInfo.numOfBound; ++i) { + if (pTableCtx->boundColsInfo.pColIndex[i] < lastIdx) { + pStmt->sql.stbInterlaceMode = false; + break; + } + + lastIdx = pTableCtx->boundColsInfo.pColIndex[i]; + } + } + + if (NULL == pStmt->sql.pBindInfo) { + pStmt->sql.pBindInfo = taosMemoryMalloc(pTableCtx->boundColsInfo.numOfBound * sizeof(*pStmt->sql.pBindInfo)); + if (NULL == pStmt->sql.pBindInfo) { + return TSDB_CODE_OUT_OF_MEMORY; + } + } + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtCleanBindInfo(STscStmt2* pStmt) { + pStmt->bInfo.tbUid = 0; + pStmt->bInfo.tbSuid = 0; + pStmt->bInfo.tbVgId = -1; + pStmt->bInfo.tbType = 0; + pStmt->bInfo.needParse = true; + pStmt->bInfo.inExecCache = false; + + pStmt->bInfo.tbName[0] = 0; + pStmt->bInfo.tbFName[0] = 0; + if (!pStmt->bInfo.tagsCached) { + qDestroyBoundColInfo(pStmt->bInfo.boundTags); + taosMemoryFreeClear(pStmt->bInfo.boundTags); + } + pStmt->bInfo.stbFName[0] = 0; + + return TSDB_CODE_SUCCESS; +} + +static void stmtFreeTableBlkList(STableColsData* pTb) { + (void)qResetStmtColumns(pTb->aCol, true); + taosArrayDestroy(pTb->aCol); +} + +static void stmtResetQueueTableBuf(STableBufInfo* pTblBuf, SStmtQueue* pQueue) { + pTblBuf->pCurBuff = taosArrayGetP(pTblBuf->pBufList, 0); + if (NULL == pTblBuf->pCurBuff) { + tscError("QInfo:%p, failed to get buffer from list", pTblBuf); + return; + } + pTblBuf->buffIdx = 1; + pTblBuf->buffOffset = sizeof(*pQueue->head); + + pQueue->head = pQueue->tail = pTblBuf->pCurBuff; + pQueue->qRemainNum = 0; + pQueue->head->next = NULL; +} + +static int32_t stmtCleanExecInfo(STscStmt2* pStmt, bool keepTable, bool deepClean) { + if (pStmt->sql.stbInterlaceMode) { + if (deepClean) { + taosHashCleanup(pStmt->exec.pBlockHash); + pStmt->exec.pBlockHash = NULL; + + if (NULL != pStmt->exec.pCurrBlock) { + taosMemoryFreeClear(pStmt->exec.pCurrBlock->pData); + qDestroyStmtDataBlock(pStmt->exec.pCurrBlock); + } + } else { + pStmt->sql.siInfo.pTableColsIdx = 0; + stmtResetQueueTableBuf(&pStmt->sql.siInfo.tbBuf, &pStmt->queue); + } + } else { + if (STMT_TYPE_QUERY != pStmt->sql.type || deepClean) { + taos_free_result(pStmt->exec.pRequest); + pStmt->exec.pRequest = NULL; + } + + size_t keyLen = 0; + void* pIter = taosHashIterate(pStmt->exec.pBlockHash, NULL); + while (pIter) { + STableDataCxt* pBlocks = *(STableDataCxt**)pIter; + char* key = taosHashGetKey(pIter, &keyLen); + STableMeta* pMeta = qGetTableMetaInDataBlock(pBlocks); + + if (keepTable && pBlocks == pStmt->exec.pCurrBlock) { + TSWAP(pBlocks->pData, pStmt->exec.pCurrTbData); + STMT_ERR_RET(qResetStmtDataBlock(pBlocks, false)); + + pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter); + continue; + } + + qDestroyStmtDataBlock(pBlocks); + STMT_ERR_RET(taosHashRemove(pStmt->exec.pBlockHash, key, keyLen)); + + pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter); + } + + if (keepTable) { + return TSDB_CODE_SUCCESS; + } + + taosHashCleanup(pStmt->exec.pBlockHash); + pStmt->exec.pBlockHash = NULL; + + tDestroySubmitTbData(pStmt->exec.pCurrTbData, TSDB_MSG_FLG_ENCODE); + taosMemoryFreeClear(pStmt->exec.pCurrTbData); + } + + STMT_ERR_RET(stmtCleanBindInfo(pStmt)); + + return TSDB_CODE_SUCCESS; +} + +static void stmtFreeTbBuf(void* buf) { + void* pBuf = *(void**)buf; + taosMemoryFree(pBuf); +} + +static void stmtFreeTbCols(void* buf) { + SArray* pCols = *(SArray**)buf; + taosArrayDestroy(pCols); +} + +static int32_t stmtCleanSQLInfo(STscStmt2* pStmt) { + STMT_DLOG_E("start to free SQL info"); + + taosMemoryFree(pStmt->sql.pBindInfo); + taosMemoryFree(pStmt->sql.queryRes.fields); + taosMemoryFree(pStmt->sql.queryRes.userFields); + taosMemoryFree(pStmt->sql.sqlStr); + qDestroyQuery(pStmt->sql.pQuery); + taosArrayDestroy(pStmt->sql.nodeList); + taosHashCleanup(pStmt->sql.pVgHash); + pStmt->sql.pVgHash = NULL; + + void* pIter = taosHashIterate(pStmt->sql.pTableCache, NULL); + while (pIter) { + SStmtTableCache* pCache = (SStmtTableCache*)pIter; + + qDestroyStmtDataBlock(pCache->pDataCtx); + qDestroyBoundColInfo(pCache->boundTags); + taosMemoryFreeClear(pCache->boundTags); + + pIter = taosHashIterate(pStmt->sql.pTableCache, pIter); + } + taosHashCleanup(pStmt->sql.pTableCache); + pStmt->sql.pTableCache = NULL; + + STMT_ERR_RET(stmtCleanExecInfo(pStmt, false, true)); + STMT_ERR_RET(stmtCleanBindInfo(pStmt)); + + taos_free_result(pStmt->sql.siInfo.pRequest); + taosHashCleanup(pStmt->sql.siInfo.pVgroupHash); + tSimpleHashCleanup(pStmt->sql.siInfo.pTableHash); + taosArrayDestroyEx(pStmt->sql.siInfo.tbBuf.pBufList, stmtFreeTbBuf); + taosMemoryFree(pStmt->sql.siInfo.pTSchema); + qDestroyStmtDataBlock(pStmt->sql.siInfo.pDataCtx); + taosArrayDestroyEx(pStmt->sql.siInfo.pTableCols, stmtFreeTbCols); + + (void)memset(&pStmt->sql, 0, sizeof(pStmt->sql)); + pStmt->sql.siInfo.tableColsReady = true; + + STMT_DLOG_E("end to free SQL info"); + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtTryAddTableVgroupInfo(STscStmt2* pStmt, int32_t* vgId) { + if (*vgId >= 0 && taosHashGet(pStmt->sql.pVgHash, (const char*)vgId, sizeof(*vgId))) { + return TSDB_CODE_SUCCESS; + } + + SVgroupInfo vgInfo = {0}; + SRequestConnInfo conn = {.pTrans = pStmt->taos->pAppInfo->pTransporter, + .requestId = pStmt->exec.pRequest->requestId, + .requestObjRefId = pStmt->exec.pRequest->self, + .mgmtEps = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp)}; + + int32_t code = catalogGetTableHashVgroup(pStmt->pCatalog, &conn, &pStmt->bInfo.sname, &vgInfo); + if (TSDB_CODE_SUCCESS != code) { + return code; + } + + code = + taosHashPut(pStmt->sql.pVgHash, (const char*)&vgInfo.vgId, sizeof(vgInfo.vgId), (char*)&vgInfo, sizeof(vgInfo)); + if (TSDB_CODE_SUCCESS != code) { + return code; + } + + *vgId = vgInfo.vgId; + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtRebuildDataBlock(STscStmt2* pStmt, STableDataCxt* pDataBlock, STableDataCxt** newBlock, uint64_t uid, + uint64_t suid, int32_t vgId) { + STMT_ERR_RET(stmtTryAddTableVgroupInfo(pStmt, &vgId)); + STMT_ERR_RET(qRebuildStmtDataBlock(newBlock, pDataBlock, uid, suid, vgId, pStmt->sql.autoCreateTbl)); + + STMT_DLOG("tableDataCxt rebuilt, uid:%" PRId64 ", vgId:%d", uid, vgId); + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtGetFromCache(STscStmt2* pStmt) { + if (pStmt->sql.stbInterlaceMode && pStmt->sql.siInfo.pDataCtx) { + pStmt->bInfo.needParse = false; + pStmt->bInfo.inExecCache = false; + return TSDB_CODE_SUCCESS; + } + + pStmt->bInfo.needParse = true; + pStmt->bInfo.inExecCache = false; + + STableDataCxt** pCxtInExec = taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName)); + if (pCxtInExec) { + pStmt->bInfo.needParse = false; + pStmt->bInfo.inExecCache = true; + + pStmt->exec.pCurrBlock = *pCxtInExec; + + if (pStmt->sql.autoCreateTbl) { + tscDebug("reuse stmt block for tb %s in execBlock", pStmt->bInfo.tbFName); + return TSDB_CODE_SUCCESS; + } + } + + if (NULL == pStmt->pCatalog) { + STMT_ERR_RET(catalogGetHandle(pStmt->taos->pAppInfo->clusterId, &pStmt->pCatalog)); + pStmt->sql.siInfo.pCatalog = pStmt->pCatalog; + } + + if (NULL == pStmt->sql.pTableCache || taosHashGetSize(pStmt->sql.pTableCache) <= 0) { + if (pStmt->bInfo.inExecCache) { + pStmt->bInfo.needParse = false; + tscDebug("reuse stmt block for tb %s in execBlock", pStmt->bInfo.tbFName); + return TSDB_CODE_SUCCESS; + } + + tscDebug("no stmt block cache for tb %s", pStmt->bInfo.tbFName); + return TSDB_CODE_SUCCESS; + } + + if (pStmt->sql.autoCreateTbl) { + SStmtTableCache* pCache = taosHashGet(pStmt->sql.pTableCache, &pStmt->bInfo.tbSuid, sizeof(pStmt->bInfo.tbSuid)); + if (pCache) { + pStmt->bInfo.needParse = false; + pStmt->bInfo.tbUid = 0; + + STableDataCxt* pNewBlock = NULL; + STMT_ERR_RET(stmtRebuildDataBlock(pStmt, pCache->pDataCtx, &pNewBlock, 0, pStmt->bInfo.tbSuid, -1)); + + if (taosHashPut(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName), &pNewBlock, + POINTER_BYTES)) { + STMT_ERR_RET(TSDB_CODE_OUT_OF_MEMORY); + } + + pStmt->exec.pCurrBlock = pNewBlock; + + tscDebug("reuse stmt block for tb %s in sqlBlock, suid:0x%" PRIx64, pStmt->bInfo.tbFName, pStmt->bInfo.tbSuid); + + return TSDB_CODE_SUCCESS; + } + + STMT_RET(stmtCleanBindInfo(pStmt)); + } + + uint64_t uid, suid; + int32_t vgId; + int8_t tableType; + + STableMeta* pTableMeta = NULL; + SRequestConnInfo conn = {.pTrans = pStmt->taos->pAppInfo->pTransporter, + .requestId = pStmt->exec.pRequest->requestId, + .requestObjRefId = pStmt->exec.pRequest->self, + .mgmtEps = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp)}; + int32_t code = catalogGetTableMeta(pStmt->pCatalog, &conn, &pStmt->bInfo.sname, &pTableMeta); + + pStmt->stat.ctgGetTbMetaNum++; + + if (TSDB_CODE_PAR_TABLE_NOT_EXIST == code) { + tscDebug("tb %s not exist", pStmt->bInfo.tbFName); + STMT_ERR_RET(stmtCleanBindInfo(pStmt)); + + STMT_ERR_RET(code); + } + + STMT_ERR_RET(code); + + uid = pTableMeta->uid; + suid = pTableMeta->suid; + tableType = pTableMeta->tableType; + pStmt->bInfo.tbVgId = pTableMeta->vgId; + vgId = pTableMeta->vgId; + + taosMemoryFree(pTableMeta); + + uint64_t cacheUid = (TSDB_CHILD_TABLE == tableType) ? suid : uid; + + if (uid == pStmt->bInfo.tbUid) { + pStmt->bInfo.needParse = false; + + tscDebug("tb %s is current table", pStmt->bInfo.tbFName); + + return TSDB_CODE_SUCCESS; + } + + if (pStmt->bInfo.inExecCache) { + SStmtTableCache* pCache = taosHashGet(pStmt->sql.pTableCache, &cacheUid, sizeof(cacheUid)); + if (NULL == pCache) { + tscError("table [%s, %" PRIx64 ", %" PRIx64 "] found in exec blockHash, but not in sql blockHash", + pStmt->bInfo.tbFName, uid, cacheUid); + + STMT_ERR_RET(TSDB_CODE_APP_ERROR); + } + + pStmt->bInfo.needParse = false; + + pStmt->bInfo.tbUid = uid; + pStmt->bInfo.tbSuid = suid; + pStmt->bInfo.tbType = tableType; + pStmt->bInfo.boundTags = pCache->boundTags; + pStmt->bInfo.tagsCached = true; + + tscDebug("tb %s in execBlock list, set to current", pStmt->bInfo.tbFName); + + return TSDB_CODE_SUCCESS; + } + + SStmtTableCache* pCache = taosHashGet(pStmt->sql.pTableCache, &cacheUid, sizeof(cacheUid)); + if (pCache) { + pStmt->bInfo.needParse = false; + + pStmt->bInfo.tbUid = uid; + pStmt->bInfo.tbSuid = suid; + pStmt->bInfo.tbType = tableType; + pStmt->bInfo.boundTags = pCache->boundTags; + pStmt->bInfo.tagsCached = true; + + STableDataCxt* pNewBlock = NULL; + STMT_ERR_RET(stmtRebuildDataBlock(pStmt, pCache->pDataCtx, &pNewBlock, uid, suid, vgId)); + + if (taosHashPut(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName), &pNewBlock, + POINTER_BYTES)) { + STMT_ERR_RET(TSDB_CODE_OUT_OF_MEMORY); + } + + pStmt->exec.pCurrBlock = pNewBlock; + + tscDebug("tb %s in sqlBlock list, set to current", pStmt->bInfo.tbFName); + + return TSDB_CODE_SUCCESS; + } + + STMT_ERR_RET(stmtCleanBindInfo(pStmt)); + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtResetStmt(STscStmt2* pStmt) { + STMT_ERR_RET(stmtCleanSQLInfo(pStmt)); + + pStmt->sql.pTableCache = taosHashInit(100, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK); + if (NULL == pStmt->sql.pTableCache) { + terrno = TSDB_CODE_OUT_OF_MEMORY; + STMT_ERR_RET(terrno); + } + + pStmt->sql.status = STMT_INIT; + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtAsyncOutput(STscStmt2* pStmt, void* param) { + SStmtQNode* pParam = (SStmtQNode*)param; + + if (pParam->restoreTbCols) { + for (int32_t i = 0; i < pStmt->sql.siInfo.pTableColsIdx; ++i) { + SArray** p = (SArray**)TARRAY_GET_ELEM(pStmt->sql.siInfo.pTableCols, i); + *p = taosArrayInit(20, POINTER_BYTES); + if (*p == NULL) { + STMT_ERR_RET(TSDB_CODE_OUT_OF_MEMORY); + } + } + + atomic_store_8((int8_t*)&pStmt->sql.siInfo.tableColsReady, true); + } else { + STMT_ERR_RET(qAppendStmtTableOutput(pStmt->sql.pQuery, pStmt->sql.pVgHash, &pParam->tblData, pStmt->exec.pCurrBlock, + &pStmt->sql.siInfo)); + + // taosMemoryFree(pParam->pTbData); + + (void)atomic_sub_fetch_64(&pStmt->sql.siInfo.tbRemainNum, 1); + } + return TSDB_CODE_SUCCESS; +} + +static void* stmtBindThreadFunc(void* param) { + setThreadName("stmtBind"); + + qInfo("stmt bind thread started"); + + STscStmt2* pStmt = (STscStmt2*)param; + + while (true) { + if (atomic_load_8((int8_t*)&pStmt->queue.stopQueue)) { + break; + } + + SStmtQNode* asyncParam = NULL; + if (!stmtDequeue(pStmt, &asyncParam)) { + continue; + } + + (void)stmtAsyncOutput(pStmt, asyncParam); + } + + qInfo("stmt bind thread stopped"); + + return NULL; +} + +static int32_t stmtStartBindThread(STscStmt2* pStmt) { + TdThreadAttr thAttr; + if (taosThreadAttrInit(&thAttr) != 0) { + return TSDB_CODE_TSC_INTERNAL_ERROR; + } + if (taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE) != 0) { + return TSDB_CODE_TSC_INTERNAL_ERROR; + } + + if (taosThreadCreate(&pStmt->bindThread, &thAttr, stmtBindThreadFunc, pStmt) != 0) { + terrno = TAOS_SYSTEM_ERROR(errno); + STMT_ERR_RET(terrno); + } + + pStmt->bindThreadInUse = true; + + (void)taosThreadAttrDestroy(&thAttr); + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtInitQueue(STscStmt2* pStmt) { + STMT_ERR_RET(stmtAllocQNodeFromBuf(&pStmt->sql.siInfo.tbBuf, (void**)&pStmt->queue.head)); + pStmt->queue.tail = pStmt->queue.head; + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtInitTableBuf(STableBufInfo* pTblBuf) { + pTblBuf->buffUnit = sizeof(SStmtQNode); + pTblBuf->buffSize = pTblBuf->buffUnit * 1000; + pTblBuf->pBufList = taosArrayInit(100, POINTER_BYTES); + if (NULL == pTblBuf->pBufList) { + return TSDB_CODE_OUT_OF_MEMORY; + } + void* buff = taosMemoryMalloc(pTblBuf->buffSize); + if (NULL == buff) { + return TSDB_CODE_OUT_OF_MEMORY; + } + + if (taosArrayPush(pTblBuf->pBufList, &buff) == NULL) { + return TSDB_CODE_OUT_OF_MEMORY; + } + + pTblBuf->pCurBuff = buff; + pTblBuf->buffIdx = 1; + pTblBuf->buffOffset = 0; + + return TSDB_CODE_SUCCESS; +} + +TAOS_STMT2* stmtInit2(STscObj* taos, TAOS_STMT2_OPTION* pOptions) { + STscObj* pObj = (STscObj*)taos; + STscStmt2* pStmt = NULL; + int32_t code = 0; + + pStmt = taosMemoryCalloc(1, sizeof(STscStmt2)); + if (NULL == pStmt) { + terrno = TSDB_CODE_OUT_OF_MEMORY; + return NULL; + } + + pStmt->sql.pTableCache = taosHashInit(100, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK); + if (NULL == pStmt->sql.pTableCache) { + terrno = TSDB_CODE_OUT_OF_MEMORY; + taosMemoryFree(pStmt); + return NULL; + } + + pStmt->taos = pObj; + pStmt->bInfo.needParse = true; + pStmt->sql.status = STMT_INIT; + pStmt->errCode = TSDB_CODE_SUCCESS; + + if (NULL != pOptions) { + (void)memcpy(&pStmt->options, pOptions, sizeof(pStmt->options)); + if (pOptions->singleStbInsert && pOptions->singleTableBindOnce) { + pStmt->stbInterlaceMode = true; + } + + pStmt->reqid = pOptions->reqid; + } + + if (pStmt->stbInterlaceMode) { + pStmt->sql.siInfo.transport = taos->pAppInfo->pTransporter; + pStmt->sql.siInfo.acctId = taos->acctId; + pStmt->sql.siInfo.dbname = taos->db; + pStmt->sql.siInfo.mgmtEpSet = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp); + pStmt->sql.siInfo.pTableHash = tSimpleHashInit(100, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY)); + if (NULL == pStmt->sql.siInfo.pTableHash) { + terrno = TSDB_CODE_OUT_OF_MEMORY; + (void)stmtClose(pStmt); + return NULL; + } + pStmt->sql.siInfo.pTableCols = taosArrayInit(STMT_TABLE_COLS_NUM, POINTER_BYTES); + if (NULL == pStmt->sql.siInfo.pTableCols) { + terrno = TSDB_CODE_OUT_OF_MEMORY; + (void)stmtClose(pStmt); + return NULL; + } + + code = stmtInitTableBuf(&pStmt->sql.siInfo.tbBuf); + if (TSDB_CODE_SUCCESS == code) { + code = stmtInitQueue(pStmt); + } + if (TSDB_CODE_SUCCESS == code) { + code = stmtStartBindThread(pStmt); + } + if (TSDB_CODE_SUCCESS != code) { + terrno = code; + (void)stmtClose(pStmt); + return NULL; + } + } + + pStmt->sql.siInfo.tableColsReady = true; + + STMT_LOG_SEQ(STMT_INIT); + + tscDebug("stmt:%p initialized", pStmt); + + return pStmt; +} + +static int stmtSetDbName2(TAOS_STMT2* stmt, const char* dbName) { + STscStmt2* pStmt = (STscStmt2*)stmt; + + STMT_DLOG("start to set dbName: %s", dbName); + + STMT_ERR_RET(stmtCreateRequest(pStmt)); + + // The SQL statement specifies a database name, overriding the previously specified database + taosMemoryFreeClear(pStmt->exec.pRequest->pDb); + pStmt->exec.pRequest->pDb = taosStrdup(dbName); + if (pStmt->exec.pRequest->pDb == NULL) { + return TSDB_CODE_OUT_OF_MEMORY; + } + return TSDB_CODE_SUCCESS; +} + +int stmtPrepare2(TAOS_STMT2* stmt, const char* sql, unsigned long length) { + STscStmt2* pStmt = (STscStmt2*)stmt; + + STMT_DLOG_E("start to prepare"); + + if (pStmt->errCode != TSDB_CODE_SUCCESS) { + return pStmt->errCode; + } + + if (pStmt->sql.status >= STMT_PREPARE) { + STMT_ERR_RET(stmtResetStmt(pStmt)); + } + + STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_PREPARE)); + + if (length <= 0) { + length = strlen(sql); + } + + pStmt->sql.sqlStr = strndup(sql, length); + pStmt->sql.sqlLen = length; + pStmt->sql.stbInterlaceMode = pStmt->stbInterlaceMode; + + char* dbName = NULL; + if (qParseDbName(sql, length, &dbName)) { + STMT_ERR_RET(stmtSetDbName2(stmt, dbName)); + taosMemoryFreeClear(dbName); + } + + return TSDB_CODE_SUCCESS; +} + +static int32_t stmtInitStbInterlaceTableInfo(STscStmt2* pStmt) { + STableDataCxt** pSrc = taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName)); + if (!pSrc) { + return TSDB_CODE_OUT_OF_MEMORY; + } + STableDataCxt* pDst = NULL; + + STMT_ERR_RET(qCloneStmtDataBlock(&pDst, *pSrc, true)); + pStmt->sql.siInfo.pDataCtx = pDst; + + SArray* pTblCols = NULL; + for (int32_t i = 0; i < STMT_TABLE_COLS_NUM; i++) { + pTblCols = taosArrayInit(20, POINTER_BYTES); + if (NULL == pTblCols) { + return TSDB_CODE_OUT_OF_MEMORY; + } + + if (taosArrayPush(pStmt->sql.siInfo.pTableCols, &pTblCols) == NULL) { + return TSDB_CODE_OUT_OF_MEMORY; + } + } + + pStmt->sql.siInfo.boundTags = pStmt->bInfo.boundTags; + + return TSDB_CODE_SUCCESS; +} + +int stmtSetTbName2(TAOS_STMT2* stmt, const char* tbName) { + STscStmt2* pStmt = (STscStmt2*)stmt; + + int64_t startUs = taosGetTimestampUs(); + + STMT_DLOG("start to set tbName: %s", tbName); + + if (pStmt->errCode != TSDB_CODE_SUCCESS) { + return pStmt->errCode; + } + + STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_SETTBNAME)); + + int32_t insert = 0; + STMT_ERR_RET(stmtIsInsert(stmt, &insert)); + if (0 == insert) { + tscError("set tb name not available for none insert statement"); + STMT_ERR_RET(TSDB_CODE_TSC_STMT_API_ERROR); + } + + if (!pStmt->sql.stbInterlaceMode || NULL == pStmt->sql.siInfo.pDataCtx) { + STMT_ERR_RET(stmtCreateRequest(pStmt)); + + STMT_ERR_RET(qCreateSName(&pStmt->bInfo.sname, tbName, pStmt->taos->acctId, pStmt->exec.pRequest->pDb, + pStmt->exec.pRequest->msgBuf, pStmt->exec.pRequest->msgBufLen)); + STMT_ERR_RET(tNameExtractFullName(&pStmt->bInfo.sname, pStmt->bInfo.tbFName)); + + STMT_ERR_RET(stmtGetFromCache(pStmt)); + + if (pStmt->bInfo.needParse) { + (void)strncpy(pStmt->bInfo.tbName, tbName, sizeof(pStmt->bInfo.tbName) - 1); + pStmt->bInfo.tbName[sizeof(pStmt->bInfo.tbName) - 1] = 0; + + STMT_ERR_RET(stmtParseSql(pStmt)); + } + } else { + (void)strncpy(pStmt->bInfo.tbName, tbName, sizeof(pStmt->bInfo.tbName) - 1); + pStmt->bInfo.tbName[sizeof(pStmt->bInfo.tbName) - 1] = 0; + pStmt->exec.pRequest->requestId++; + pStmt->bInfo.needParse = false; + } + + if (pStmt->sql.stbInterlaceMode && NULL == pStmt->sql.siInfo.pDataCtx) { + STMT_ERR_RET(stmtInitStbInterlaceTableInfo(pStmt)); + } + + int64_t startUs2 = taosGetTimestampUs(); + pStmt->stat.setTbNameUs += startUs2 - startUs; + + return TSDB_CODE_SUCCESS; +} + +int stmtSetTbTags2(TAOS_STMT2* stmt, TAOS_STMT2_BIND* tags) { + STscStmt2* pStmt = (STscStmt2*)stmt; + + STMT_DLOG_E("start to set tbTags"); + + if (pStmt->errCode != TSDB_CODE_SUCCESS) { + return pStmt->errCode; + } + + STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_SETTAGS)); + + SBoundColInfo* tags_info = (SBoundColInfo*)pStmt->bInfo.boundTags; + if (tags_info->numOfBound <= 0 || tags_info->numOfCols <= 0) { + tscWarn("no tags bound in sql, will not bound tags"); + return TSDB_CODE_SUCCESS; + } + + if (pStmt->bInfo.inExecCache) { + return TSDB_CODE_SUCCESS; + } + + STableDataCxt** pDataBlock = + (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName)); + if (NULL == pDataBlock) { + tscError("table %s not found in exec blockHash", pStmt->bInfo.tbFName); + STMT_ERR_RET(TSDB_CODE_APP_ERROR); + } + + tscDebug("start to bind stmt tag values"); + STMT_ERR_RET(qBindStmtTagsValue2(*pDataBlock, pStmt->bInfo.boundTags, pStmt->bInfo.tbSuid, pStmt->bInfo.stbFName, + pStmt->bInfo.sname.tname, tags, pStmt->exec.pRequest->msgBuf, + pStmt->exec.pRequest->msgBufLen)); + + return TSDB_CODE_SUCCESS; +} + +int stmtFetchTagFields2(STscStmt2* pStmt, int32_t* fieldNum, TAOS_FIELD_E** fields) { + if (pStmt->errCode != TSDB_CODE_SUCCESS) { + return pStmt->errCode; + } + + if (STMT_TYPE_QUERY == pStmt->sql.type) { + tscError("invalid operation to get query tag fileds"); + STMT_ERR_RET(TSDB_CODE_TSC_STMT_API_ERROR); + } + + STableDataCxt** pDataBlock = + (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName)); + if (NULL == pDataBlock) { + tscError("table %s not found in exec blockHash", pStmt->bInfo.tbFName); + STMT_ERR_RET(TSDB_CODE_APP_ERROR); + } + + STMT_ERR_RET(qBuildStmtTagFields(*pDataBlock, pStmt->bInfo.boundTags, fieldNum, fields)); + + return TSDB_CODE_SUCCESS; +} + +int stmtFetchColFields2(STscStmt2* pStmt, int32_t* fieldNum, TAOS_FIELD_E** fields) { + if (pStmt->errCode != TSDB_CODE_SUCCESS) { + return pStmt->errCode; + } + + if (STMT_TYPE_QUERY == pStmt->sql.type) { + tscError("invalid operation to get query column fileds"); + STMT_ERR_RET(TSDB_CODE_TSC_STMT_API_ERROR); + } + + STableDataCxt** pDataBlock = NULL; + + if (pStmt->sql.stbInterlaceMode) { + pDataBlock = &pStmt->sql.siInfo.pDataCtx; + } else { + pDataBlock = + (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName)); + if (NULL == pDataBlock) { + tscError("table %s not found in exec blockHash", pStmt->bInfo.tbFName); + STMT_ERR_RET(TSDB_CODE_APP_ERROR); + } + } + + STMT_ERR_RET(qBuildStmtColFields(*pDataBlock, fieldNum, fields)); + + return TSDB_CODE_SUCCESS; +} + +/* +SArray* stmtGetFreeCol(STscStmt2* pStmt, int32_t* idx) { + while (true) { + if (pStmt->exec.smInfo.pColIdx >= STMT_COL_BUF_SIZE) { + pStmt->exec.smInfo.pColIdx = 0; + } + + if ((pStmt->exec.smInfo.pColIdx + 1) == atomic_load_32(&pStmt->exec.smInfo.pColFreeIdx)) { + taosUsleep(1); + continue; + } + + *idx = pStmt->exec.smInfo.pColIdx; + return pStmt->exec.smInfo.pCols[pStmt->exec.smInfo.pColIdx++]; + } +} +*/ + +static int32_t stmtAppendTablePostHandle(STscStmt2* pStmt, SStmtQNode* param) { + if (NULL == pStmt->sql.siInfo.pVgroupHash) { + pStmt->sql.siInfo.pVgroupHash = + taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_ENTRY_LOCK); + } + if (NULL == pStmt->sql.siInfo.pVgroupList) { + pStmt->sql.siInfo.pVgroupList = taosArrayInit(64, POINTER_BYTES); + } + + if (NULL == pStmt->sql.siInfo.pRequest) { + STMT_ERR_RET(buildRequest(pStmt->taos->id, pStmt->sql.sqlStr, pStmt->sql.sqlLen, NULL, false, + (SRequestObj**)&pStmt->sql.siInfo.pRequest, pStmt->reqid)); + + if (pStmt->reqid != 0) { + pStmt->reqid++; + } + pStmt->exec.pRequest->syncQuery = true; + + pStmt->sql.siInfo.requestId = ((SRequestObj*)pStmt->sql.siInfo.pRequest)->requestId; + pStmt->sql.siInfo.requestSelf = ((SRequestObj*)pStmt->sql.siInfo.pRequest)->self; + } + + if (!pStmt->sql.siInfo.tbFromHash && pStmt->sql.siInfo.firstName[0] && + 0 == strcmp(pStmt->sql.siInfo.firstName, pStmt->bInfo.tbName)) { + pStmt->sql.siInfo.tbFromHash = true; + } + + if (0 == pStmt->sql.siInfo.firstName[0]) { + (void)strcpy(pStmt->sql.siInfo.firstName, pStmt->bInfo.tbName); + } + + param->tblData.getFromHash = pStmt->sql.siInfo.tbFromHash; + param->next = NULL; + + (void)atomic_add_fetch_64(&pStmt->sql.siInfo.tbRemainNum, 1); + + stmtEnqueue(pStmt, param); + + return TSDB_CODE_SUCCESS; +} + +static FORCE_INLINE int32_t stmtGetTableColsFromCache(STscStmt2* pStmt, SArray** pTableCols) { + while (true) { + if (pStmt->sql.siInfo.pTableColsIdx < taosArrayGetSize(pStmt->sql.siInfo.pTableCols)) { + *pTableCols = (SArray*)taosArrayGetP(pStmt->sql.siInfo.pTableCols, pStmt->sql.siInfo.pTableColsIdx++); + break; + } else { + SArray* pTblCols = NULL; + for (int32_t i = 0; i < 100; i++) { + pTblCols = taosArrayInit(20, POINTER_BYTES); + if (NULL == pTblCols) { + return TSDB_CODE_OUT_OF_MEMORY; + } + + if (taosArrayPush(pStmt->sql.siInfo.pTableCols, &pTblCols) == NULL) { + return TSDB_CODE_OUT_OF_MEMORY; + } + } + } + } + + return TSDB_CODE_SUCCESS; +} + +static int stmtAddBatch2(TAOS_STMT2* stmt) { + STscStmt2* pStmt = (STscStmt2*)stmt; + + int64_t startUs = taosGetTimestampUs(); + + STMT_DLOG_E("start to add batch"); + + if (pStmt->errCode != TSDB_CODE_SUCCESS) { + return pStmt->errCode; + } + + STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_ADD_BATCH)); + + if (pStmt->sql.stbInterlaceMode) { + int64_t startUs2 = taosGetTimestampUs(); + pStmt->stat.addBatchUs += startUs2 - startUs; + + pStmt->sql.siInfo.tableColsReady = false; + + SStmtQNode* param = NULL; + STMT_ERR_RET(stmtAllocQNodeFromBuf(&pStmt->sql.siInfo.tbBuf, (void**)¶m)); + param->restoreTbCols = true; + param->next = NULL; + + stmtEnqueue(pStmt, param); + + return TSDB_CODE_SUCCESS; + } + + STMT_ERR_RET(stmtCacheBlock(pStmt)); + + return TSDB_CODE_SUCCESS; +} + +int stmtBindBatch2(TAOS_STMT2* stmt, TAOS_STMT2_BIND* bind, int32_t colIdx) { + STscStmt2* pStmt = (STscStmt2*)stmt; + int32_t code = 0; + + int64_t startUs = taosGetTimestampUs(); + + STMT_DLOG("start to bind stmt data, colIdx: %d", colIdx); + + if (pStmt->errCode != TSDB_CODE_SUCCESS) { + return pStmt->errCode; + } + + STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_BIND)); + + if (pStmt->bInfo.needParse && pStmt->sql.runTimes && pStmt->sql.type > 0 && + STMT_TYPE_MULTI_INSERT != pStmt->sql.type) { + pStmt->bInfo.needParse = false; + } + + if (pStmt->exec.pRequest && STMT_TYPE_QUERY == pStmt->sql.type && pStmt->sql.runTimes) { + taos_free_result(pStmt->exec.pRequest); + pStmt->exec.pRequest = NULL; + } + + STMT_ERR_RET(stmtCreateRequest(pStmt)); + + if (pStmt->bInfo.needParse) { + STMT_ERR_RET(stmtParseSql(pStmt)); + } + + if (STMT_TYPE_QUERY == pStmt->sql.type) { + STMT_ERR_RET(qStmtBindParams2(pStmt->sql.pQuery, bind, colIdx)); + + SParseContext ctx = {.requestId = pStmt->exec.pRequest->requestId, + .acctId = pStmt->taos->acctId, + .db = pStmt->exec.pRequest->pDb, + .topicQuery = false, + .pSql = pStmt->sql.sqlStr, + .sqlLen = pStmt->sql.sqlLen, + .pMsg = pStmt->exec.pRequest->msgBuf, + .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE, + .pTransporter = pStmt->taos->pAppInfo->pTransporter, + .pStmtCb = NULL, + .pUser = pStmt->taos->user}; + ctx.mgmtEpSet = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp); + STMT_ERR_RET(catalogGetHandle(pStmt->taos->pAppInfo->clusterId, &ctx.pCatalog)); + + STMT_ERR_RET(qStmtParseQuerySql(&ctx, pStmt->sql.pQuery)); + + if (pStmt->sql.pQuery->haveResultSet) { + STMT_ERR_RET(setResSchemaInfo(&pStmt->exec.pRequest->body.resInfo, pStmt->sql.pQuery->pResSchema, + pStmt->sql.pQuery->numOfResCols)); + taosMemoryFreeClear(pStmt->sql.pQuery->pResSchema); + setResPrecision(&pStmt->exec.pRequest->body.resInfo, pStmt->sql.pQuery->precision); + } + + TSWAP(pStmt->exec.pRequest->dbList, pStmt->sql.pQuery->pDbList); + TSWAP(pStmt->exec.pRequest->tableList, pStmt->sql.pQuery->pTableList); + TSWAP(pStmt->exec.pRequest->targetTableList, pStmt->sql.pQuery->pTargetTableList); + + // if (STMT_TYPE_QUERY == pStmt->sql.queryRes) { + // STMT_ERR_RET(stmtRestoreQueryFields(pStmt)); + // } + + // STMT_ERR_RET(stmtBackupQueryFields(pStmt)); + + return TSDB_CODE_SUCCESS; + } + + if (pStmt->sql.stbInterlaceMode && NULL == pStmt->sql.siInfo.pDataCtx) { + STMT_ERR_RET(stmtInitStbInterlaceTableInfo(pStmt)); + } + + STableDataCxt** pDataBlock = NULL; + + if (pStmt->exec.pCurrBlock) { + pDataBlock = &pStmt->exec.pCurrBlock; + } else { + pDataBlock = + (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName)); + if (NULL == pDataBlock) { + tscError("table %s not found in exec blockHash", pStmt->bInfo.tbFName); + STMT_ERR_RET(TSDB_CODE_TSC_STMT_CACHE_ERROR); + } + pStmt->exec.pCurrBlock = *pDataBlock; + if (pStmt->sql.stbInterlaceMode) { + taosArrayDestroy(pStmt->exec.pCurrBlock->pData->aCol); + pStmt->exec.pCurrBlock->pData->aCol = NULL; + } + } + + int64_t startUs2 = taosGetTimestampUs(); + pStmt->stat.bindDataUs1 += startUs2 - startUs; + + SStmtQNode* param = NULL; + if (pStmt->sql.stbInterlaceMode) { + STMT_ERR_RET(stmtAllocQNodeFromBuf(&pStmt->sql.siInfo.tbBuf, (void**)¶m)); + STMT_ERR_RET(stmtGetTableColsFromCache(pStmt, ¶m->tblData.aCol)); + taosArrayClear(param->tblData.aCol); + + // param->tblData.aCol = taosArrayInit(20, POINTER_BYTES); + + param->restoreTbCols = false; + (void)strcpy(param->tblData.tbName, pStmt->bInfo.tbName); + } + + int64_t startUs3 = taosGetTimestampUs(); + pStmt->stat.bindDataUs2 += startUs3 - startUs2; + + SArray* pCols = pStmt->sql.stbInterlaceMode ? param->tblData.aCol : (*pDataBlock)->pData->aCol; + + if (colIdx < 0) { + if (pStmt->sql.stbInterlaceMode) { + (*pDataBlock)->pData->flags = 0; + code = qBindStmtStbColsValue2(*pDataBlock, pCols, bind, pStmt->exec.pRequest->msgBuf, + pStmt->exec.pRequest->msgBufLen, &pStmt->sql.siInfo.pTSchema, pStmt->sql.pBindInfo); + } else { + code = + qBindStmtColsValue2(*pDataBlock, pCols, bind, pStmt->exec.pRequest->msgBuf, pStmt->exec.pRequest->msgBufLen); + } + + if (code) { + tscError("qBindStmtColsValue failed, error:%s", tstrerror(code)); + STMT_ERR_RET(code); + } + } else { + if (pStmt->sql.stbInterlaceMode) { + tscError("bind single column not allowed in stb insert mode"); + STMT_ERR_RET(TSDB_CODE_TSC_STMT_API_ERROR); + } + + if (colIdx != (pStmt->bInfo.sBindLastIdx + 1) && colIdx != 0) { + tscError("bind column index not in sequence"); + STMT_ERR_RET(TSDB_CODE_APP_ERROR); + } + + pStmt->bInfo.sBindLastIdx = colIdx; + + if (0 == colIdx) { + pStmt->bInfo.sBindRowNum = bind->num; + } + + code = qBindStmtSingleColValue2(*pDataBlock, pCols, bind, pStmt->exec.pRequest->msgBuf, + pStmt->exec.pRequest->msgBufLen, colIdx, pStmt->bInfo.sBindRowNum); + if (code) { + tscError("qBindStmtSingleColValue failed, error:%s", tstrerror(code)); + STMT_ERR_RET(code); + } + } + + int64_t startUs4 = taosGetTimestampUs(); + pStmt->stat.bindDataUs3 += startUs4 - startUs3; + + if (pStmt->sql.stbInterlaceMode) { + STMT_ERR_RET(stmtAppendTablePostHandle(pStmt, param)); + } + + STMT_ERR_RET(stmtAddBatch2(pStmt)); + + pStmt->stat.bindDataUs4 += taosGetTimestampUs() - startUs4; + + return TSDB_CODE_SUCCESS; +} +/* +int stmtUpdateTableUid(STscStmt2* pStmt, SSubmitRsp* pRsp) { + tscDebug("stmt start to update tbUid, blockNum: %d", pRsp->nBlocks); + + int32_t code = 0; + int32_t finalCode = 0; + size_t keyLen = 0; + void* pIter = taosHashIterate(pStmt->exec.pBlockHash, NULL); + while (pIter) { + STableDataCxt* pBlock = *(STableDataCxt**)pIter; + char* key = taosHashGetKey(pIter, &keyLen); + + STableMeta* pMeta = qGetTableMetaInDataBlock(pBlock); + if (pMeta->uid) { + pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter); + continue; + } + + SSubmitBlkRsp* blkRsp = NULL; + int32_t i = 0; + for (; i < pRsp->nBlocks; ++i) { + blkRsp = pRsp->pBlocks + i; + if (strlen(blkRsp->tblFName) != keyLen) { + continue; + } + + if (strncmp(blkRsp->tblFName, key, keyLen)) { + continue; + } + + break; + } + + if (i < pRsp->nBlocks) { + tscDebug("auto created table %s uid updated from %" PRIx64 " to %" PRIx64, blkRsp->tblFName, pMeta->uid, + blkRsp->uid); + + pMeta->uid = blkRsp->uid; + pStmt->bInfo.tbUid = blkRsp->uid; + } else { + tscDebug("table %s not found in submit rsp, will update from catalog", pStmt->bInfo.tbFName); + if (NULL == pStmt->pCatalog) { + code = catalogGetHandle(pStmt->taos->pAppInfo->clusterId, &pStmt->pCatalog); + if (code) { + pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter); + finalCode = code; + continue; + } + } + + code = stmtCreateRequest(pStmt); + if (code) { + pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter); + finalCode = code; + continue; + } + + STableMeta* pTableMeta = NULL; + SRequestConnInfo conn = {.pTrans = pStmt->taos->pAppInfo->pTransporter, + .requestId = pStmt->exec.pRequest->requestId, + .requestObjRefId = pStmt->exec.pRequest->self, + .mgmtEps = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp)}; + code = catalogGetTableMeta(pStmt->pCatalog, &conn, &pStmt->bInfo.sname, &pTableMeta); + + pStmt->stat.ctgGetTbMetaNum++; + + taos_free_result(pStmt->exec.pRequest); + pStmt->exec.pRequest = NULL; + + if (code || NULL == pTableMeta) { + pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter); + finalCode = code; + taosMemoryFree(pTableMeta); + continue; + } + + pMeta->uid = pTableMeta->uid; + pStmt->bInfo.tbUid = pTableMeta->uid; + taosMemoryFree(pTableMeta); + } + + pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter); + } + + return finalCode; +} +*/ +/* +int stmtStaticModeExec(TAOS_STMT* stmt) { + STscStmt2* pStmt = (STscStmt2*)stmt; + int32_t code = 0; + SSubmitRsp* pRsp = NULL; + if (pStmt->sql.staticMode) { + return TSDB_CODE_TSC_STMT_API_ERROR; + } + + STMT_DLOG_E("start to exec"); + + STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_EXECUTE)); + + STMT_ERR_RET(qBuildStmtOutputFromTbList(pStmt->sql.pQuery, pStmt->sql.pVgHash, pStmt->exec.pTbBlkList, +pStmt->exec.pCurrBlock, pStmt->exec.tbBlkNum)); + + launchQueryImpl(pStmt->exec.pRequest, pStmt->sql.pQuery, true, NULL); + + if (pStmt->exec.pRequest->code && NEED_CLIENT_HANDLE_ERROR(pStmt->exec.pRequest->code)) { + code = refreshMeta(pStmt->exec.pRequest->pTscObj, pStmt->exec.pRequest); + if (code) { + pStmt->exec.pRequest->code = code; + } else { + tFreeSSubmitRsp(pRsp); + STMT_ERR_RET(stmtResetStmt(pStmt)); + STMT_ERR_RET(TSDB_CODE_NEED_RETRY); + } + } + + STMT_ERR_JRET(pStmt->exec.pRequest->code); + + pStmt->exec.affectedRows = taos_affected_rows(pStmt->exec.pRequest); + pStmt->affectedRows += pStmt->exec.affectedRows; + +_return: + + stmtCleanExecInfo(pStmt, (code ? false : true), false); + + tFreeSSubmitRsp(pRsp); + + ++pStmt->sql.runTimes; + + STMT_RET(code); +} +*/ + +static int32_t createParseContext(const SRequestObj* pRequest, SParseContext** pCxt, SSqlCallbackWrapper* pWrapper) { + const STscObj* pTscObj = pRequest->pTscObj; + + *pCxt = taosMemoryCalloc(1, sizeof(SParseContext)); + if (*pCxt == NULL) { + return TSDB_CODE_OUT_OF_MEMORY; + } + + **pCxt = (SParseContext){.requestId = pRequest->requestId, + .requestRid = pRequest->self, + .acctId = pTscObj->acctId, + .db = pRequest->pDb, + .topicQuery = false, + .pSql = pRequest->sqlstr, + .sqlLen = pRequest->sqlLen, + .pMsg = pRequest->msgBuf, + .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE, + .pTransporter = pTscObj->pAppInfo->pTransporter, + .pStmtCb = NULL, + .pUser = pTscObj->user, + .pEffectiveUser = pRequest->effectiveUser, + .isSuperUser = (0 == strcmp(pTscObj->user, TSDB_DEFAULT_USER)), + .enableSysInfo = pTscObj->sysInfo, + .async = true, + .svrVer = pTscObj->sVer, + .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes), + .allocatorId = pRequest->allocatorRefId, + .parseSqlFp = clientParseSql, + .parseSqlParam = pWrapper}; + int8_t biMode = atomic_load_8(&((STscObj*)pTscObj)->biMode); + (*pCxt)->biMode = biMode; + return TSDB_CODE_SUCCESS; +} + +int stmtExec2(TAOS_STMT2* stmt, int* affected_rows) { + STscStmt2* pStmt = (STscStmt2*)stmt; + int32_t code = 0; + SSubmitRsp* pRsp = NULL; + + int64_t startUs = taosGetTimestampUs(); + + STMT_DLOG_E("start to exec"); + + if (pStmt->errCode != TSDB_CODE_SUCCESS) { + return pStmt->errCode; + } + + STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_EXECUTE)); + + if (STMT_TYPE_QUERY != pStmt->sql.type) { + if (pStmt->sql.stbInterlaceMode) { + int64_t startTs = taosGetTimestampUs(); + while (atomic_load_64(&pStmt->sql.siInfo.tbRemainNum)) { + taosUsleep(1); + } + pStmt->stat.execWaitUs += taosGetTimestampUs() - startTs; + + STMT_ERR_RET(qBuildStmtFinOutput(pStmt->sql.pQuery, pStmt->sql.pVgHash, pStmt->sql.siInfo.pVgroupList)); + taosHashCleanup(pStmt->sql.siInfo.pVgroupHash); + pStmt->sql.siInfo.pVgroupHash = NULL; + pStmt->sql.siInfo.pVgroupList = NULL; + } else { + tDestroySubmitTbData(pStmt->exec.pCurrTbData, TSDB_MSG_FLG_ENCODE); + taosMemoryFreeClear(pStmt->exec.pCurrTbData); + + STMT_ERR_RET(qCloneCurrentTbData(pStmt->exec.pCurrBlock, &pStmt->exec.pCurrTbData)); + + STMT_ERR_RET(qBuildStmtOutput(pStmt->sql.pQuery, pStmt->sql.pVgHash, pStmt->exec.pBlockHash)); + } + } + + (void)launchQueryImpl(pStmt->exec.pRequest, pStmt->sql.pQuery, true, NULL); + + /* + SSqlCallbackWrapper* pWrapper = taosMemoryCalloc(1, sizeof(SSqlCallbackWrapper)); + if (pWrapper == NULL) { + code = TSDB_CODE_OUT_OF_MEMORY; + } else { + pWrapper->pRequest = pStmt->exec.pRequest; + pStmt->exec.pRequest->pWrapper = pWrapper; + //*ppWrapper = pWrapper; + } + if (TSDB_CODE_SUCCESS == code) { + code = createParseContext(pStmt->exec.pRequest, &pWrapper->pParseCtx, pWrapper); + } + pStmt->exec.pRequest->syncQuery = false; + pStmt->exec.pRequest->body.queryFp = fp; + ((SSyncQueryParam*)(pStmt->exec.pRequest)->body.interParam)->userParam = param; + launchAsyncQuery(pStmt->exec.pRequest, pStmt->sql.pQuery, NULL, pWrapper); + */ + + if (pStmt->exec.pRequest->code && NEED_CLIENT_HANDLE_ERROR(pStmt->exec.pRequest->code)) { + code = refreshMeta(pStmt->exec.pRequest->pTscObj, pStmt->exec.pRequest); + if (code) { + pStmt->exec.pRequest->code = code; + } else { + tFreeSSubmitRsp(pRsp); + STMT_ERR_RET(stmtResetStmt(pStmt)); + STMT_ERR_RET(TSDB_CODE_NEED_RETRY); + } + } + + STMT_ERR_JRET(pStmt->exec.pRequest->code); + + pStmt->exec.affectedRows = taos_affected_rows(pStmt->exec.pRequest); + pStmt->affectedRows += pStmt->exec.affectedRows; + +_return: + + while (0 == atomic_load_8((int8_t*)&pStmt->sql.siInfo.tableColsReady)) { + taosUsleep(1); + } + + STMT_ERR_RET(stmtCleanExecInfo(pStmt, (code ? false : true), false)); + + tFreeSSubmitRsp(pRsp); + + ++pStmt->sql.runTimes; + + int64_t startUs2 = taosGetTimestampUs(); + pStmt->stat.execUseUs += startUs2 - startUs; + + STMT_RET(code); +} + +int stmtClose2(TAOS_STMT2* stmt) { + STscStmt2* pStmt = (STscStmt2*)stmt; + + STMT_DLOG_E("start to free stmt"); + + pStmt->queue.stopQueue = true; + + if (pStmt->bindThreadInUse) { + (void)taosThreadJoin(pStmt->bindThread, NULL); + pStmt->bindThreadInUse = false; + } + + STMT_DLOG("stmt %p closed, stbInterlaceMode: %d, statInfo: ctgGetTbMetaNum=>%" PRId64 ", getCacheTbInfo=>%" PRId64 + ", parseSqlNum=>%" PRId64 ", pStmt->stat.bindDataNum=>%" PRId64 + ", settbnameAPI:%u, bindAPI:%u, addbatchAPI:%u, execAPI:%u" + ", setTbNameUs:%" PRId64 ", bindDataUs:%" PRId64 ",%" PRId64 ",%" PRId64 ",%" PRId64 " addBatchUs:%" PRId64 + ", execWaitUs:%" PRId64 ", execUseUs:%" PRId64, + pStmt, pStmt->sql.stbInterlaceMode, pStmt->stat.ctgGetTbMetaNum, pStmt->stat.getCacheTbInfo, + pStmt->stat.parseSqlNum, pStmt->stat.bindDataNum, pStmt->seqIds[STMT_SETTBNAME], pStmt->seqIds[STMT_BIND], + pStmt->seqIds[STMT_ADD_BATCH], pStmt->seqIds[STMT_EXECUTE], pStmt->stat.setTbNameUs, + pStmt->stat.bindDataUs1, pStmt->stat.bindDataUs2, pStmt->stat.bindDataUs3, pStmt->stat.bindDataUs4, + pStmt->stat.addBatchUs, pStmt->stat.execWaitUs, pStmt->stat.execUseUs); + + STMT_ERR_RET(stmtCleanSQLInfo(pStmt)); + taosMemoryFree(stmt); + + return TSDB_CODE_SUCCESS; +} + +const char* stmtErrstr2(TAOS_STMT2* stmt) { + STscStmt2* pStmt = (STscStmt2*)stmt; + + if (stmt == NULL || NULL == pStmt->exec.pRequest) { + return (char*)tstrerror(terrno); + } + + pStmt->exec.pRequest->code = terrno; + + return taos_errstr(pStmt->exec.pRequest); +} +/* +int stmtAffectedRows(TAOS_STMT* stmt) { return ((STscStmt2*)stmt)->affectedRows; } + +int stmtAffectedRowsOnce(TAOS_STMT* stmt) { return ((STscStmt2*)stmt)->exec.affectedRows; } +*/ +int stmtIsInsert2(TAOS_STMT2* stmt, int* insert) { + STscStmt2* pStmt = (STscStmt2*)stmt; + + STMT_DLOG_E("start is insert"); + + if (pStmt->sql.type) { + *insert = (STMT_TYPE_INSERT == pStmt->sql.type || STMT_TYPE_MULTI_INSERT == pStmt->sql.type); + } else { + *insert = qIsInsertValuesSql(pStmt->sql.sqlStr, pStmt->sql.sqlLen); + } + + return TSDB_CODE_SUCCESS; +} + +int stmtGetTagFields2(TAOS_STMT2* stmt, int* nums, TAOS_FIELD_E** fields) { + int32_t code = 0; + STscStmt2* pStmt = (STscStmt2*)stmt; + int32_t preCode = pStmt->errCode; + + STMT_DLOG_E("start to get tag fields"); + + if (pStmt->errCode != TSDB_CODE_SUCCESS) { + return pStmt->errCode; + } + + if (STMT_TYPE_QUERY == pStmt->sql.type) { + STMT_ERRI_JRET(TSDB_CODE_TSC_STMT_API_ERROR); + } + + STMT_ERRI_JRET(stmtSwitchStatus(pStmt, STMT_FETCH_FIELDS)); + + if (pStmt->bInfo.needParse && pStmt->sql.runTimes && pStmt->sql.type > 0 && + STMT_TYPE_MULTI_INSERT != pStmt->sql.type) { + pStmt->bInfo.needParse = false; + } + + if (pStmt->exec.pRequest && STMT_TYPE_QUERY == pStmt->sql.type && pStmt->sql.runTimes) { + taos_free_result(pStmt->exec.pRequest); + pStmt->exec.pRequest = NULL; + } + + STMT_ERRI_JRET(stmtCreateRequest(pStmt)); + + if (pStmt->bInfo.needParse) { + STMT_ERRI_JRET(stmtParseSql(pStmt)); + } + + STMT_ERRI_JRET(stmtFetchTagFields2(stmt, nums, fields)); + +_return: + + pStmt->errCode = preCode; + + return code; +} + +int stmtGetColFields2(TAOS_STMT2* stmt, int* nums, TAOS_FIELD_E** fields) { + int32_t code = 0; + STscStmt2* pStmt = (STscStmt2*)stmt; + int32_t preCode = pStmt->errCode; + + STMT_DLOG_E("start to get col fields"); + + if (pStmt->errCode != TSDB_CODE_SUCCESS) { + return pStmt->errCode; + } + + if (STMT_TYPE_QUERY == pStmt->sql.type) { + STMT_ERRI_JRET(TSDB_CODE_TSC_STMT_API_ERROR); + } + + STMT_ERRI_JRET(stmtSwitchStatus(pStmt, STMT_FETCH_FIELDS)); + + if (pStmt->bInfo.needParse && pStmt->sql.runTimes && pStmt->sql.type > 0 && + STMT_TYPE_MULTI_INSERT != pStmt->sql.type) { + pStmt->bInfo.needParse = false; + } + + if (pStmt->exec.pRequest && STMT_TYPE_QUERY == pStmt->sql.type && pStmt->sql.runTimes) { + taos_free_result(pStmt->exec.pRequest); + pStmt->exec.pRequest = NULL; + STMT_ERR_RET(stmtCreateRequest(pStmt)); + } + + STMT_ERRI_JRET(stmtCreateRequest(pStmt)); + + if (pStmt->bInfo.needParse) { + STMT_ERRI_JRET(stmtParseSql(pStmt)); + } + + STMT_ERRI_JRET(stmtFetchColFields2(stmt, nums, fields)); + +_return: + + pStmt->errCode = preCode; + + return code; +} + +int stmtGetParamNum2(TAOS_STMT2* stmt, int* nums) { + STscStmt2* pStmt = (STscStmt2*)stmt; + + STMT_DLOG_E("start to get param num"); + + if (pStmt->errCode != TSDB_CODE_SUCCESS) { + return pStmt->errCode; + } + + STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_FETCH_FIELDS)); + + if (pStmt->bInfo.needParse && pStmt->sql.runTimes && pStmt->sql.type > 0 && + STMT_TYPE_MULTI_INSERT != pStmt->sql.type) { + pStmt->bInfo.needParse = false; + } + + if (pStmt->exec.pRequest && STMT_TYPE_QUERY == pStmt->sql.type && pStmt->sql.runTimes) { + taos_free_result(pStmt->exec.pRequest); + pStmt->exec.pRequest = NULL; + } + + STMT_ERR_RET(stmtCreateRequest(pStmt)); + + if (pStmt->bInfo.needParse) { + STMT_ERR_RET(stmtParseSql(pStmt)); + } + + if (STMT_TYPE_QUERY == pStmt->sql.type) { + *nums = taosArrayGetSize(pStmt->sql.pQuery->pPlaceholderValues); + } else { + STMT_ERR_RET(stmtFetchColFields2(stmt, nums, NULL)); + } + + return TSDB_CODE_SUCCESS; +} +/* +int stmtGetParam(TAOS_STMT* stmt, int idx, int* type, int* bytes) { + STscStmt2* pStmt = (STscStmt2*)stmt; + + STMT_DLOG_E("start to get param"); + + if (pStmt->errCode != TSDB_CODE_SUCCESS) { + return pStmt->errCode; + } + + if (STMT_TYPE_QUERY == pStmt->sql.type) { + STMT_RET(TSDB_CODE_TSC_STMT_API_ERROR); + } + + STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_FETCH_FIELDS)); + + if (pStmt->bInfo.needParse && pStmt->sql.runTimes && pStmt->sql.type > 0 && + STMT_TYPE_MULTI_INSERT != pStmt->sql.type) { + pStmt->bInfo.needParse = false; + } + + if (pStmt->exec.pRequest && STMT_TYPE_QUERY == pStmt->sql.type && pStmt->sql.runTimes) { + taos_free_result(pStmt->exec.pRequest); + pStmt->exec.pRequest = NULL; + } + + STMT_ERR_RET(stmtCreateRequest(pStmt)); + + if (pStmt->bInfo.needParse) { + STMT_ERR_RET(stmtParseSql(pStmt)); + } + + int32_t nums = 0; + TAOS_FIELD_E* pField = NULL; + STMT_ERR_RET(stmtFetchColFields(stmt, &nums, &pField)); + if (idx >= nums) { + tscError("idx %d is too big", idx); + taosMemoryFree(pField); + STMT_ERR_RET(TSDB_CODE_INVALID_PARA); + } + + *type = pField[idx].type; + *bytes = pField[idx].bytes; + + taosMemoryFree(pField); + + return TSDB_CODE_SUCCESS; +} +*/ +TAOS_RES* stmtUseResult2(TAOS_STMT2* stmt) { + STscStmt2* pStmt = (STscStmt2*)stmt; + + STMT_DLOG_E("start to use result"); + + if (STMT_TYPE_QUERY != pStmt->sql.type) { + tscError("useResult only for query statement"); + return NULL; + } + + return pStmt->exec.pRequest; +} diff --git a/source/common/src/tdataformat.c b/source/common/src/tdataformat.c index 5caf93de65..02279ff06f 100644 --- a/source/common/src/tdataformat.c +++ b/source/common/src/tdataformat.c @@ -3119,6 +3119,143 @@ _exit: return code; } +int32_t tColDataAddValueByBind2(SColData *pColData, TAOS_STMT2_BIND *pBind, int32_t buffMaxLen) { + int32_t code = 0; + + if (!(pBind->num == 1 && pBind->is_null && *pBind->is_null)) { + ASSERT(pColData->type == pBind->buffer_type); + } + + if (IS_VAR_DATA_TYPE(pColData->type)) { // var-length data type + for (int32_t i = 0; i < pBind->num; ++i) { + if (pBind->is_null && pBind->is_null[i]) { + if (pColData->cflag & COL_IS_KEY) { + code = TSDB_CODE_PAR_PRIMARY_KEY_IS_NULL; + goto _exit; + } + code = tColDataAppendValueImpl[pColData->flag][CV_FLAG_NULL](pColData, NULL, 0); + if (code) goto _exit; + } else if (pBind->length[i] > buffMaxLen) { + uError("var data length too big, len:%d, max:%d", pBind->length[i], buffMaxLen); + return TSDB_CODE_INVALID_PARA; + } else { + code = tColDataAppendValueImpl[pColData->flag][CV_FLAG_VALUE]( + pColData, (uint8_t *)pBind->buffer + pBind->buffer_length * i, pBind->length[i]); + } + } + } else { // fixed-length data type + bool allValue; + bool allNull; + if (pBind->is_null) { + bool same = (memcmp(pBind->is_null, pBind->is_null + 1, pBind->num - 1) == 0); + allNull = (same && pBind->is_null[0] != 0); + allValue = (same && pBind->is_null[0] == 0); + } else { + allNull = false; + allValue = true; + } + + if ((pColData->cflag & COL_IS_KEY) && !allValue) { + code = TSDB_CODE_PAR_PRIMARY_KEY_IS_NULL; + goto _exit; + } + + if (allValue) { + // optimize (todo) + for (int32_t i = 0; i < pBind->num; ++i) { + code = tColDataAppendValueImpl[pColData->flag][CV_FLAG_VALUE]( + pColData, (uint8_t *)pBind->buffer + TYPE_BYTES[pColData->type] * i, pBind->buffer_length); + } + } else if (allNull) { + // optimize (todo) + for (int32_t i = 0; i < pBind->num; ++i) { + code = tColDataAppendValueImpl[pColData->flag][CV_FLAG_NULL](pColData, NULL, 0); + if (code) goto _exit; + } + } else { + for (int32_t i = 0; i < pBind->num; ++i) { + if (pBind->is_null[i]) { + code = tColDataAppendValueImpl[pColData->flag][CV_FLAG_NULL](pColData, NULL, 0); + if (code) goto _exit; + } else { + code = tColDataAppendValueImpl[pColData->flag][CV_FLAG_VALUE]( + pColData, (uint8_t *)pBind->buffer + TYPE_BYTES[pColData->type] * i, pBind->buffer_length); + } + } + } + } + +_exit: + return code; +} + +/* build rows to `rowArray` from bind + * `infos` is the bind information array + * `numOfInfos` is the number of bind information + * `infoSorted` is whether the bind information is sorted by column id + * `pTSchema` is the schema of the table + * `rowArray` is the array to store the rows + */ +int32_t tRowBuildFromBind2(SBindInfo2 *infos, int32_t numOfInfos, bool infoSorted, const STSchema *pTSchema, + SArray *rowArray) { + if (infos == NULL || numOfInfos <= 0 || numOfInfos > pTSchema->numOfCols || pTSchema == NULL || rowArray == NULL) { + return TSDB_CODE_INVALID_PARA; + } + + if (!infoSorted) { + taosqsort_r(infos, numOfInfos, sizeof(SBindInfo), NULL, tBindInfoCompare); + } + + int32_t code = 0; + int32_t numOfRows = infos[0].bind->num; + SArray *colValArray; + SColVal colVal; + + if ((colValArray = taosArrayInit(numOfInfos, sizeof(SColVal))) == NULL) { + return terrno; + } + + for (int32_t iRow = 0; iRow < numOfRows; iRow++) { + taosArrayClear(colValArray); + + for (int32_t iInfo = 0; iInfo < numOfInfos; iInfo++) { + if (infos[iInfo].bind->is_null && infos[iInfo].bind->is_null[iRow]) { + colVal = COL_VAL_NULL(infos[iInfo].columnId, infos[iInfo].type); + } else { + SValue value = { + .type = infos[iInfo].type, + }; + if (IS_VAR_DATA_TYPE(infos[iInfo].type)) { + value.nData = infos[iInfo].bind->length[iRow]; + value.pData = (uint8_t *)infos[iInfo].bind->buffer + infos[iInfo].bind->buffer_length * iRow; + } else { + (void)memcpy(&value.val, (uint8_t *)infos[iInfo].bind->buffer + infos[iInfo].bind->buffer_length * iRow, + infos[iInfo].bind->buffer_length); + } + colVal = COL_VAL_VALUE(infos[iInfo].columnId, value); + } + if (taosArrayPush(colValArray, &colVal) == NULL) { + code = TSDB_CODE_OUT_OF_MEMORY; + goto _exit; + } + } + + SRow *row; + if ((code = tRowBuild(colValArray, pTSchema, &row))) { + goto _exit; + } + + if ((taosArrayPush(rowArray, &row)) == NULL) { + code = TSDB_CODE_OUT_OF_MEMORY; + goto _exit; + } + } + +_exit: + taosArrayDestroy(colValArray); + return code; +} + static int32_t tColDataCopyRowCell(SColData *pFromColData, int32_t iFromRow, SColData *pToColData, int32_t iToRow) { int32_t code = TSDB_CODE_SUCCESS; diff --git a/source/libs/parser/src/parInsertStmt.c b/source/libs/parser/src/parInsertStmt.c index 025459a8c9..62a52f522f 100644 --- a/source/libs/parser/src/parInsertStmt.c +++ b/source/libs/parser/src/parInsertStmt.c @@ -448,7 +448,348 @@ int32_t qBindStmtSingleColValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bi pBind = bind; } - code = tColDataAddValueByBind(pCol, pBind, IS_VAR_DATA_TYPE(pColSchema->type) ? pColSchema->bytes - VARSTR_HEADER_SIZE : -1); + code = tColDataAddValueByBind(pCol, pBind, + IS_VAR_DATA_TYPE(pColSchema->type) ? pColSchema->bytes - VARSTR_HEADER_SIZE : -1); + + qDebug("stmt col %d bind %d rows data", colIdx, rowNum); + +_return: + + taosMemoryFree(ncharBind.buffer); + taosMemoryFree(ncharBind.length); + + return code; +} + +static int32_t convertStmtNcharCol2(SMsgBuf* pMsgBuf, SSchema* pSchema, TAOS_STMT2_BIND* src, TAOS_STMT2_BIND* dst) { + int32_t output = 0; + int32_t newBuflen = (pSchema->bytes - VARSTR_HEADER_SIZE) * src->num; + if (dst->buffer_length < newBuflen) { + dst->buffer = taosMemoryRealloc(dst->buffer, newBuflen); + if (NULL == dst->buffer) { + return TSDB_CODE_OUT_OF_MEMORY; + } + } + + if (NULL == dst->length) { + dst->length = taosMemoryRealloc(dst->length, sizeof(int32_t) * src->num); + if (NULL == dst->length) { + taosMemoryFreeClear(dst->buffer); + return TSDB_CODE_OUT_OF_MEMORY; + } + } + + dst->buffer_length = pSchema->bytes - VARSTR_HEADER_SIZE; + + for (int32_t i = 0; i < src->num; ++i) { + if (src->is_null && src->is_null[i]) { + continue; + } + + if (!taosMbsToUcs4(((char*)src->buffer) + src->buffer_length * i, src->length[i], + (TdUcs4*)(((char*)dst->buffer) + dst->buffer_length * i), dst->buffer_length, &output)) { + if (errno == E2BIG) { + return generateSyntaxErrMsg(pMsgBuf, TSDB_CODE_PAR_VALUE_TOO_LONG, pSchema->name); + } + char buf[512] = {0}; + snprintf(buf, tListLen(buf), "%s", strerror(errno)); + return buildSyntaxErrMsg(pMsgBuf, buf, NULL); + } + + dst->length[i] = output; + } + + dst->buffer_type = src->buffer_type; + dst->is_null = src->is_null; + dst->num = src->num; + + return TSDB_CODE_SUCCESS; +} + +int32_t qBindStmtStbColsValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen, + STSchema** pTSchema, SBindInfo2* pBindInfos) { + STableDataCxt* pDataBlock = (STableDataCxt*)pBlock; + SSchema* pSchema = getTableColumnSchema(pDataBlock->pMeta); + SBoundColInfo* boundInfo = &pDataBlock->boundColsInfo; + SMsgBuf pBuf = {.buf = msgBuf, .len = msgBufLen}; + int32_t rowNum = bind->num; + TAOS_STMT2_BIND ncharBind = {0}; + TAOS_STMT2_BIND* pBind = NULL; + int32_t code = 0; + int16_t lastColId = -1; + bool colInOrder = true; + + if (NULL == *pTSchema) { + *pTSchema = tBuildTSchema(pSchema, pDataBlock->pMeta->tableInfo.numOfColumns, pDataBlock->pMeta->sversion); + } + + for (int c = 0; c < boundInfo->numOfBound; ++c) { + SSchema* pColSchema = &pSchema[boundInfo->pColIndex[c]]; + if (pColSchema->colId <= lastColId) { + colInOrder = false; + } else { + lastColId = pColSchema->colId; + } + // SColData* pCol = taosArrayGet(pCols, c); + + if (bind[c].num != rowNum) { + code = buildInvalidOperationMsg(&pBuf, "row number in each bind param should be the same"); + goto _return; + } + + if ((!(rowNum == 1 && bind[c].is_null && *bind[c].is_null)) && + bind[c].buffer_type != pColSchema->type) { // for rowNum ==1 , connector may not set buffer_type + code = buildInvalidOperationMsg(&pBuf, "column type mis-match with buffer type"); + goto _return; + } + + if (TSDB_DATA_TYPE_NCHAR == pColSchema->type) { + code = convertStmtNcharCol2(&pBuf, pColSchema, bind + c, &ncharBind); + if (code) { + goto _return; + } + pBind = &ncharBind; + } else { + pBind = bind + c; + } + + pBindInfos[c].columnId = pColSchema->colId; + pBindInfos[c].bind = pBind; + pBindInfos[c].type = pColSchema->type; + + // code = tColDataAddValueByBind(pCol, pBind, IS_VAR_DATA_TYPE(pColSchema->type) ? pColSchema->bytes - + // VARSTR_HEADER_SIZE: -1); if (code) { + // goto _return; + // } + } + + code = tRowBuildFromBind2(pBindInfos, boundInfo->numOfBound, colInOrder, *pTSchema, pCols); + + qDebug("stmt all %d columns bind %d rows data", boundInfo->numOfBound, rowNum); + +_return: + + taosMemoryFree(ncharBind.buffer); + taosMemoryFree(ncharBind.length); + + return code; +} + +int32_t qBindStmtTagsValue2(void* pBlock, void* boundTags, int64_t suid, const char* sTableName, char* tName, + TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen) { + STableDataCxt* pDataBlock = (STableDataCxt*)pBlock; + SMsgBuf pBuf = {.buf = msgBuf, .len = msgBufLen}; + int32_t code = TSDB_CODE_SUCCESS; + SBoundColInfo* tags = (SBoundColInfo*)boundTags; + if (NULL == tags) { + return TSDB_CODE_APP_ERROR; + } + + SArray* pTagArray = taosArrayInit(tags->numOfBound, sizeof(STagVal)); + if (!pTagArray) { + return buildInvalidOperationMsg(&pBuf, "out of memory"); + } + + SArray* tagName = taosArrayInit(8, TSDB_COL_NAME_LEN); + if (!tagName) { + code = buildInvalidOperationMsg(&pBuf, "out of memory"); + goto end; + } + + SSchema* pSchema = getTableTagSchema(pDataBlock->pMeta); + + bool isJson = false; + STag* pTag = NULL; + + for (int c = 0; c < tags->numOfBound; ++c) { + if (bind[c].is_null && bind[c].is_null[0]) { + continue; + } + + SSchema* pTagSchema = &pSchema[tags->pColIndex[c]]; + int32_t colLen = pTagSchema->bytes; + if (IS_VAR_DATA_TYPE(pTagSchema->type)) { + colLen = bind[c].length[0]; + if ((colLen + VARSTR_HEADER_SIZE) > pTagSchema->bytes) { + code = buildInvalidOperationMsg(&pBuf, "tag length is too big"); + goto end; + } + } + if (NULL == taosArrayPush(tagName, pTagSchema->name)) { + code = TSDB_CODE_OUT_OF_MEMORY; + goto end; + } + if (pTagSchema->type == TSDB_DATA_TYPE_JSON) { + if (colLen > (TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE) { + code = buildSyntaxErrMsg(&pBuf, "json string too long than 4095", bind[c].buffer); + goto end; + } + + isJson = true; + char* tmp = taosMemoryCalloc(1, colLen + 1); + memcpy(tmp, bind[c].buffer, colLen); + code = parseJsontoTagData(tmp, pTagArray, &pTag, &pBuf); + taosMemoryFree(tmp); + if (code != TSDB_CODE_SUCCESS) { + goto end; + } + } else { + STagVal val = {.cid = pTagSchema->colId, .type = pTagSchema->type}; + // strcpy(val.colName, pTagSchema->name); + if (pTagSchema->type == TSDB_DATA_TYPE_BINARY || pTagSchema->type == TSDB_DATA_TYPE_VARBINARY || + pTagSchema->type == TSDB_DATA_TYPE_GEOMETRY) { + val.pData = (uint8_t*)bind[c].buffer; + val.nData = colLen; + } else if (pTagSchema->type == TSDB_DATA_TYPE_NCHAR) { + int32_t output = 0; + void* p = taosMemoryCalloc(1, colLen * TSDB_NCHAR_SIZE); + if (p == NULL) { + code = TSDB_CODE_OUT_OF_MEMORY; + goto end; + } + if (!taosMbsToUcs4(bind[c].buffer, colLen, (TdUcs4*)(p), colLen * TSDB_NCHAR_SIZE, &output)) { + if (errno == E2BIG) { + taosMemoryFree(p); + code = generateSyntaxErrMsg(&pBuf, TSDB_CODE_PAR_VALUE_TOO_LONG, pTagSchema->name); + goto end; + } + char buf[512] = {0}; + snprintf(buf, tListLen(buf), " taosMbsToUcs4 error:%s", strerror(errno)); + taosMemoryFree(p); + code = buildSyntaxErrMsg(&pBuf, buf, bind[c].buffer); + goto end; + } + val.pData = p; + val.nData = output; + } else { + memcpy(&val.i64, bind[c].buffer, colLen); + } + if (NULL == taosArrayPush(pTagArray, &val)) { + code = TSDB_CODE_OUT_OF_MEMORY; + goto end; + } + } + } + + if (!isJson && (code = tTagNew(pTagArray, 1, false, &pTag)) != TSDB_CODE_SUCCESS) { + goto end; + } + + if (NULL == pDataBlock->pData->pCreateTbReq) { + pDataBlock->pData->pCreateTbReq = taosMemoryCalloc(1, sizeof(SVCreateTbReq)); + if (NULL == pDataBlock->pData->pCreateTbReq) { + code = TSDB_CODE_OUT_OF_MEMORY; + goto end; + } + } + + insBuildCreateTbReq(pDataBlock->pData->pCreateTbReq, tName, pTag, suid, sTableName, tagName, + pDataBlock->pMeta->tableInfo.numOfTags, TSDB_DEFAULT_TABLE_TTL); + pTag = NULL; + +end: + for (int i = 0; i < taosArrayGetSize(pTagArray); ++i) { + STagVal* p = (STagVal*)taosArrayGet(pTagArray, i); + if (p->type == TSDB_DATA_TYPE_NCHAR) { + taosMemoryFreeClear(p->pData); + } + } + taosArrayDestroy(pTagArray); + taosArrayDestroy(tagName); + taosMemoryFree(pTag); + + return code; +} + +int32_t qBindStmtColsValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen) { + STableDataCxt* pDataBlock = (STableDataCxt*)pBlock; + SSchema* pSchema = getTableColumnSchema(pDataBlock->pMeta); + SBoundColInfo* boundInfo = &pDataBlock->boundColsInfo; + SMsgBuf pBuf = {.buf = msgBuf, .len = msgBufLen}; + int32_t rowNum = bind->num; + TAOS_STMT2_BIND ncharBind = {0}; + TAOS_STMT2_BIND* pBind = NULL; + int32_t code = 0; + + for (int c = 0; c < boundInfo->numOfBound; ++c) { + SSchema* pColSchema = &pSchema[boundInfo->pColIndex[c]]; + SColData* pCol = taosArrayGet(pCols, c); + + if (bind[c].num != rowNum) { + code = buildInvalidOperationMsg(&pBuf, "row number in each bind param should be the same"); + goto _return; + } + + if ((!(rowNum == 1 && bind[c].is_null && *bind[c].is_null)) && + bind[c].buffer_type != pColSchema->type) { // for rowNum ==1 , connector may not set buffer_type + code = buildInvalidOperationMsg(&pBuf, "column type mis-match with buffer type"); + goto _return; + } + + if (TSDB_DATA_TYPE_NCHAR == pColSchema->type) { + code = convertStmtNcharCol2(&pBuf, pColSchema, bind + c, &ncharBind); + if (code) { + goto _return; + } + pBind = &ncharBind; + } else { + pBind = bind + c; + } + + code = tColDataAddValueByBind2(pCol, pBind, + IS_VAR_DATA_TYPE(pColSchema->type) ? pColSchema->bytes - VARSTR_HEADER_SIZE : -1); + if (code) { + goto _return; + } + } + + qDebug("stmt all %d columns bind %d rows data", boundInfo->numOfBound, rowNum); + +_return: + + taosMemoryFree(ncharBind.buffer); + taosMemoryFree(ncharBind.length); + + return code; +} + +int32_t qBindStmtSingleColValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen, + int32_t colIdx, int32_t rowNum) { + STableDataCxt* pDataBlock = (STableDataCxt*)pBlock; + SSchema* pSchema = getTableColumnSchema(pDataBlock->pMeta); + SBoundColInfo* boundInfo = &pDataBlock->boundColsInfo; + SMsgBuf pBuf = {.buf = msgBuf, .len = msgBufLen}; + SSchema* pColSchema = &pSchema[boundInfo->pColIndex[colIdx]]; + SColData* pCol = taosArrayGet(pCols, colIdx); + TAOS_STMT2_BIND ncharBind = {0}; + TAOS_STMT2_BIND* pBind = NULL; + int32_t code = 0; + + if (bind->num != rowNum) { + return buildInvalidOperationMsg(&pBuf, "row number in each bind param should be the same"); + } + + // Column index exceeds the number of columns + if (colIdx >= pCols->size && pCol == NULL) { + return buildInvalidOperationMsg(&pBuf, "column index exceeds the number of columns"); + } + + if (bind->buffer_type != pColSchema->type) { + return buildInvalidOperationMsg(&pBuf, "column type mis-match with buffer type"); + } + + if (TSDB_DATA_TYPE_NCHAR == pColSchema->type) { + code = convertStmtNcharCol2(&pBuf, pColSchema, bind, &ncharBind); + if (code) { + goto _return; + } + pBind = &ncharBind; + } else { + pBind = bind; + } + + code = tColDataAddValueByBind2(pCol, pBind, + IS_VAR_DATA_TYPE(pColSchema->type) ? pColSchema->bytes - VARSTR_HEADER_SIZE : -1); qDebug("stmt col %d bind %d rows data", colIdx, rowNum); @@ -533,7 +874,7 @@ int32_t qResetStmtColumns(SArray* pCols, bool deepClear) { for (int32_t i = 0; i < colNum; ++i) { SColData* pCol = (SColData*)taosArrayGet(pCols, i); - if (pCol == NULL){ + if (pCol == NULL) { qError("qResetStmtColumns column is NULL"); return TSDB_CODE_OUT_OF_MEMORY; } @@ -553,7 +894,7 @@ int32_t qResetStmtDataBlock(STableDataCxt* block, bool deepClear) { for (int32_t i = 0; i < colNum; ++i) { SColData* pCol = (SColData*)taosArrayGet(pBlock->pData->aCol, i); - if (pCol == NULL){ + if (pCol == NULL) { qError("qResetStmtDataBlock column is NULL"); return TSDB_CODE_OUT_OF_MEMORY; } diff --git a/source/libs/parser/src/parser.c b/source/libs/parser/src/parser.c index e96aaf52ed..b78cd36f0e 100644 --- a/source/libs/parser/src/parser.c +++ b/source/libs/parser/src/parser.c @@ -76,33 +76,33 @@ bool qIsCreateTbFromFileSql(const char* pStr, size_t length) { } bool qParseDbName(const char* pStr, size_t length, char** pDbName) { - (void) length; + (void)length; int32_t index = 0; - SToken t; + SToken t; if (NULL == pStr) { *pDbName = NULL; return false; } - t = tStrGetToken((char *) pStr, &index, false, NULL); + t = tStrGetToken((char*)pStr, &index, false, NULL); if (TK_INSERT != t.type && TK_IMPORT != t.type) { *pDbName = NULL; return false; } - t = tStrGetToken((char *) pStr, &index, false, NULL); + t = tStrGetToken((char*)pStr, &index, false, NULL); if (TK_INTO != t.type) { *pDbName = NULL; return false; } - t = tStrGetToken((char *) pStr, &index, false, NULL); + t = tStrGetToken((char*)pStr, &index, false, NULL); if (t.n == 0 || t.z == NULL) { *pDbName = NULL; return false; } - char *dotPos = strnchr(t.z, '.', t.n, true); + char* dotPos = strnchr(t.z, '.', t.n, true); if (dotPos != NULL) { int dbNameLen = dotPos - t.z; *pDbName = taosMemoryMalloc(dbNameLen + 1); @@ -331,13 +331,12 @@ int32_t qContinueParsePostQuery(SParseContext* pCxt, SQuery* pQuery, SSDataBlock return code; } - -static void destoryTablesReq(void *p) { - STablesReq *pRes = (STablesReq *)p; +static void destoryTablesReq(void* p) { + STablesReq* pRes = (STablesReq*)p; taosArrayDestroy(pRes->pTables); } -void destoryCatalogReq(SCatalogReq *pCatalogReq) { +void destoryCatalogReq(SCatalogReq* pCatalogReq) { if (NULL == pCatalogReq) { return; } @@ -369,7 +368,6 @@ void destoryCatalogReq(SCatalogReq *pCatalogReq) { taosArrayDestroy(pCatalogReq->pTableTag); } - void tfreeSParseQueryRes(void* p) { if (NULL == p) { return; @@ -410,9 +408,7 @@ int32_t qSetSTableIdForRsma(SNode* pStmt, int64_t uid) { return TSDB_CODE_FAILED; } -int32_t qInitKeywordsTable() { - return taosInitKeywordsTable(); -} +int32_t qInitKeywordsTable() { return taosInitKeywordsTable(); } void qCleanupKeywordsTable() { taosCleanupKeywordsTable(); } @@ -445,6 +441,98 @@ int32_t qStmtBindParams(SQuery* pQuery, TAOS_MULTI_BIND* pParams, int32_t colIdx return code; } +static int32_t setValueByBindParam2(SValueNode* pVal, TAOS_STMT2_BIND* pParam) { + if (IS_VAR_DATA_TYPE(pVal->node.resType.type)) { + taosMemoryFreeClear(pVal->datum.p); + } + + if (pParam->is_null && 1 == *(pParam->is_null)) { + pVal->node.resType.type = TSDB_DATA_TYPE_NULL; + pVal->node.resType.bytes = tDataTypes[TSDB_DATA_TYPE_NULL].bytes; + return TSDB_CODE_SUCCESS; + } + + int32_t inputSize = (NULL != pParam->length ? *(pParam->length) : tDataTypes[pParam->buffer_type].bytes); + pVal->node.resType.type = pParam->buffer_type; + pVal->node.resType.bytes = inputSize; + + switch (pParam->buffer_type) { + case TSDB_DATA_TYPE_VARBINARY: + pVal->datum.p = taosMemoryCalloc(1, pVal->node.resType.bytes + VARSTR_HEADER_SIZE + 1); + if (NULL == pVal->datum.p) { + return TSDB_CODE_OUT_OF_MEMORY; + } + varDataSetLen(pVal->datum.p, pVal->node.resType.bytes); + memcpy(varDataVal(pVal->datum.p), pParam->buffer, pVal->node.resType.bytes); + pVal->node.resType.bytes += VARSTR_HEADER_SIZE; + break; + case TSDB_DATA_TYPE_VARCHAR: + case TSDB_DATA_TYPE_GEOMETRY: + pVal->datum.p = taosMemoryCalloc(1, pVal->node.resType.bytes + VARSTR_HEADER_SIZE + 1); + if (NULL == pVal->datum.p) { + return TSDB_CODE_OUT_OF_MEMORY; + } + varDataSetLen(pVal->datum.p, pVal->node.resType.bytes); + strncpy(varDataVal(pVal->datum.p), (const char*)pParam->buffer, pVal->node.resType.bytes); + pVal->node.resType.bytes += VARSTR_HEADER_SIZE; + break; + case TSDB_DATA_TYPE_NCHAR: { + pVal->node.resType.bytes *= TSDB_NCHAR_SIZE; + pVal->datum.p = taosMemoryCalloc(1, pVal->node.resType.bytes + VARSTR_HEADER_SIZE + 1); + if (NULL == pVal->datum.p) { + return TSDB_CODE_OUT_OF_MEMORY; + } + + int32_t output = 0; + if (!taosMbsToUcs4(pParam->buffer, inputSize, (TdUcs4*)varDataVal(pVal->datum.p), pVal->node.resType.bytes, + &output)) { + return errno; + } + varDataSetLen(pVal->datum.p, output); + pVal->node.resType.bytes = output + VARSTR_HEADER_SIZE; + break; + } + default: { + int32_t code = nodesSetValueNodeValue(pVal, pParam->buffer); + if (code) { + return code; + } + break; + } + } + pVal->translate = true; + return TSDB_CODE_SUCCESS; +} + +int32_t qStmtBindParams2(SQuery* pQuery, TAOS_STMT2_BIND* pParams, int32_t colIdx) { + int32_t code = TSDB_CODE_SUCCESS; + + if (colIdx < 0) { + int32_t size = taosArrayGetSize(pQuery->pPlaceholderValues); + for (int32_t i = 0; i < size; ++i) { + code = setValueByBindParam2((SValueNode*)taosArrayGetP(pQuery->pPlaceholderValues, i), pParams + i); + if (TSDB_CODE_SUCCESS != code) { + return code; + } + } + } else { + code = setValueByBindParam2((SValueNode*)taosArrayGetP(pQuery->pPlaceholderValues, colIdx), pParams); + } + + if (TSDB_CODE_SUCCESS == code && (colIdx < 0 || colIdx + 1 == pQuery->placeholderNum)) { + nodesDestroyNode(pQuery->pRoot); + pQuery->pRoot = NULL; + code = nodesCloneNode(pQuery->pPrepareRoot, &pQuery->pRoot); + if (NULL == pQuery->pRoot) { + code = code; + } + } + if (TSDB_CODE_SUCCESS == code) { + rewriteExprAlias(pQuery->pRoot); + } + return code; +} + int32_t qStmtParseQuerySql(SParseContext* pCxt, SQuery* pQuery) { int32_t code = translate(pCxt, pQuery, NULL); if (TSDB_CODE_SUCCESS == code) {