• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

taosdata / TDengine / #5055

17 May 2026 01:15AM UTC coverage: 73.355% (-0.003%) from 73.358%
#5055

push

travis-ci

web-flow
feat (TDgpt): Dynamic Model Synchronization Enhancements (#35344)

* refactor: do some internal refactor.

* fix: fix multiprocess sync issue.

* feat: add dynamic anomaly detection and forecasting services

* fix: log error message for undeploying model in exception handling

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* fix: handle undeploy when model exists only on disk

Agent-Logs-Url: https://github.com/taosdata/TDengine/sessions/286aafa0-c3ce-4c27-b803-2707571e9dc1

Co-authored-by: hjxilinx <8252296+hjxilinx@users.noreply.github.com>

* fix: guard dynamic registry concurrent access

Agent-Logs-Url: https://github.com/taosdata/TDengine/sessions/5e4db858-6458-40f4-ac28-d1b1b7f97c18

Co-authored-by: hjxilinx <8252296+hjxilinx@users.noreply.github.com>

* fix: tighten service list locking scope

Agent-Logs-Url: https://github.com/taosdata/TDengine/sessions/5e4db858-6458-40f4-ac28-d1b1b7f97c18

Co-authored-by: hjxilinx <8252296+hjxilinx@users.noreply.github.com>

* fix: restore prophet support and update tests per review feedback

Agent-Logs-Url: https://github.com/taosdata/TDengine/sessions/92298ae1-7da6-4d07-b20e-101c7cd0b26b

Co-authored-by: hjxilinx <8252296+hjxilinx@users.noreply.github.com>

* fix: improve test name and move copy inside lock scope

Agent-Logs-Url: https://github.com/taosdata/TDengine/sessions/92298ae1-7da6-4d07-b20e-101c7cd0b26b

Co-authored-by: hjxilinx <8252296+hjxilinx@users.noreply.github.com>

* Potential fix for pull request finding

Co-au... (continued)

281532 of 383795 relevant lines covered (73.35%)

135557734.7 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

73.7
/source/client/src/clientStmt2.c
1
#include "clientInt.h"
2
#include "clientLog.h"
3
#include "taoserror.h"
4
#include "tdef.h"
5
#include "tglobal.h"
6
#include "tname.h"
7

8
#include "clientStmt.h"
9
#include "clientStmt2.h"
10
#include "querynodes.h"
11
#include "tencode.h"
12
#include "tmsg.h"
13
#include "tname.h"
14
#include "trow.h"
15

16
char* gStmt2StatusStr[] = {"unknown",     "init", "prepare", "settbname", "settags",
17
                           "fetchFields", "bind", "bindCol", "addBatch",  "exec"};
18

19
static FORCE_INLINE int32_t stmtAllocQNodeFromBuf(STableBufInfo* pTblBuf, void** pBuf) {
20
  if (pTblBuf->buffOffset < pTblBuf->buffSize) {
1,863,399✔
21
    *pBuf = (char*)pTblBuf->pCurBuff + pTblBuf->buffOffset;
1,863,623✔
22
    pTblBuf->buffOffset += pTblBuf->buffUnit;
1,863,559✔
23
  } else if (pTblBuf->buffIdx < taosArrayGetSize(pTblBuf->pBufList)) {
×
24
    pTblBuf->pCurBuff = taosArrayGetP(pTblBuf->pBufList, pTblBuf->buffIdx++);
×
25
    if (NULL == pTblBuf->pCurBuff) {
×
26
      return TAOS_GET_TERRNO(TSDB_CODE_OUT_OF_MEMORY);
×
27
    }
28
    *pBuf = pTblBuf->pCurBuff;
×
29
    pTblBuf->buffOffset = pTblBuf->buffUnit;
×
30
  } else {
31
    void* buff = taosMemoryMalloc(pTblBuf->buffSize);
×
32
    if (NULL == buff) {
×
33
      return terrno;
×
34
    }
35

36
    if (taosArrayPush(pTblBuf->pBufList, &buff) == NULL) {
×
37
      return terrno;
×
38
    }
39

40
    pTblBuf->buffIdx++;
×
41
    pTblBuf->pCurBuff = buff;
×
42
    *pBuf = buff;
×
43
    pTblBuf->buffOffset = pTblBuf->buffUnit;
×
44
  }
45

46
  return TSDB_CODE_SUCCESS;
1,863,074✔
47
}
48

49
static bool stmtDequeue(STscStmt2* pStmt, SStmtQNode** param) {
1,863,335✔
50
  int i = 0;
1,863,335✔
51
  while (0 == atomic_load_64((int64_t*)&pStmt->queue.qRemainNum)) {
8,361,308✔
52
    if (pStmt->queue.stopQueue) {
6,517,747✔
53
      return false;
18,996✔
54
    }
55
    if (i < 10) {
6,498,606✔
56
      taosUsleep(1);
6,093,400✔
57
      i++;
6,092,182✔
58
    } else {
59
      (void)taosThreadMutexLock(&pStmt->queue.mutex);
405,206✔
60
      if (pStmt->queue.stopQueue) {
405,893✔
61
        (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
×
62
        return false;
×
63
      }
64
      if (0 == atomic_load_64((int64_t*)&pStmt->queue.qRemainNum)) {
405,893✔
65
        (void)taosThreadCondWait(&pStmt->queue.waitCond, &pStmt->queue.mutex);
405,735✔
66
      }
67
      (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
405,778✔
68
    }
69
  }
70

71
  if (pStmt->queue.stopQueue && 0 == atomic_load_64((int64_t*)&pStmt->queue.qRemainNum)) {
1,843,368✔
72
    return false;
×
73
  }
74

75
  (void)taosThreadMutexLock(&pStmt->queue.mutex);
1,843,368✔
76
  if (pStmt->queue.head == pStmt->queue.tail) {
1,844,241✔
77
    pStmt->queue.qRemainNum = 0;
×
78
    (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
×
79
    STMT2_ELOG_E("interlace queue is empty, cannot dequeue");
×
80
    return false;
×
81
  }
82

83
  SStmtQNode* node = pStmt->queue.head->next;
1,844,301✔
84
  pStmt->queue.head->next = node->next;
1,844,361✔
85
  if (pStmt->queue.tail == node) {
1,844,293✔
86
    pStmt->queue.tail = pStmt->queue.head;
1,063,684✔
87
  }
88
  node->next = NULL;
1,844,353✔
89
  *param = node;
1,844,293✔
90

91
  (void)atomic_sub_fetch_64((int64_t*)&pStmt->queue.qRemainNum, 1);
1,844,293✔
92
  (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
1,844,434✔
93

94
  STMT2_TLOG("dequeue success, node:%p, remainNum:%" PRId64, node, pStmt->queue.qRemainNum);
1,844,340✔
95

96
  return true;
1,844,233✔
97
}
98

99
static void stmtEnqueue(STscStmt2* pStmt, SStmtQNode* param) {
1,843,869✔
100
  if (param == NULL) {
1,843,869✔
101
    STMT2_ELOG_E("enqueue param is NULL");
×
102
    return;
×
103
  }
104

105
  param->next = NULL;
1,843,869✔
106

107
  (void)taosThreadMutexLock(&pStmt->queue.mutex);
1,844,179✔
108

109
  pStmt->queue.tail->next = param;
1,844,185✔
110
  pStmt->queue.tail = param;
1,844,245✔
111
  pStmt->stat.bindDataNum++;
1,844,245✔
112

113
  (void)atomic_add_fetch_64(&pStmt->queue.qRemainNum, 1);
1,844,060✔
114
  (void)taosThreadCondSignal(&(pStmt->queue.waitCond));
1,844,482✔
115

116
  (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
1,844,362✔
117

118
  STMT2_TLOG("enqueue param:%p, remainNum:%" PRId64 ", restoreTbCols:%d", param, pStmt->queue.qRemainNum,
1,844,324✔
119
             param->restoreTbCols);
120
}
121

122
static int32_t stmtCreateRequest(STscStmt2* pStmt) {
3,816,814✔
123
  int32_t code = 0;
3,816,814✔
124

125
  if (pStmt->exec.pRequest == NULL) {
3,816,814✔
126
    code = buildRequest(pStmt->taos->id, pStmt->sql.sqlStr, pStmt->sql.sqlLen, NULL, false, &pStmt->exec.pRequest,
198,886✔
127
                        pStmt->reqid);
128
    if (pStmt->reqid != 0) {
198,799✔
129
      pStmt->reqid++;
10✔
130
    }
131
    pStmt->exec.pRequest->type = RES_TYPE__QUERY;
198,799✔
132
    if (pStmt->db != NULL) {
198,840✔
133
      taosMemoryFreeClear(pStmt->exec.pRequest->pDb);
190,534✔
134
      pStmt->exec.pRequest->pDb = taosStrdup(pStmt->db);
190,509✔
135
    }
136
    if (TSDB_CODE_SUCCESS == code) {
198,248✔
137
      pStmt->exec.pRequest->syncQuery = true;
198,665✔
138
      pStmt->exec.pRequest->stmtBindVersion = 2;
198,846✔
139
    }
140
    STMT2_DLOG("create request:0x%" PRIx64 ", QID:0x%" PRIx64, pStmt->exec.pRequest->self,
198,339✔
141
               pStmt->exec.pRequest->requestId);
142
  }
143

144
  return code;
3,817,408✔
145
}
146

147
static int32_t stmtSwitchStatus(STscStmt2* pStmt, STMT_STATUS newStatus) {
5,208,726✔
148
  int32_t code = 0;
5,208,726✔
149

150
  if (newStatus >= STMT_INIT && newStatus < STMT_MAX) {
5,208,726✔
151
    STMT2_LOG_SEQ(newStatus);
5,210,401✔
152
  }
153

154
  if (pStmt->errCode && newStatus != STMT_PREPARE) {
5,209,854✔
155
    STMT2_ELOG("stmt already failed with err:%s, please use stmt prepare", tstrerror(pStmt->errCode));
×
156
    return pStmt->errCode;
×
157
  }
158

159
  switch (newStatus) {
5,210,015✔
160
    case STMT_PREPARE:
179,766✔
161
      pStmt->errCode = 0;
179,766✔
162
      break;
177,342✔
163
    case STMT_SETTBNAME:
1,290,931✔
164
      if (STMT_STATUS_EQ(INIT)) {
1,290,931✔
165
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
166
      }
167
      if (!pStmt->sql.stbInterlaceMode && (STMT_STATUS_EQ(BIND) || STMT_STATUS_EQ(BIND_COL))) {
1,291,055✔
168
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
169
      }
170
      break;
1,290,859✔
171
    case STMT_SETTAGS:
662,004✔
172
      if (STMT_STATUS_EQ(INIT)) {
662,004✔
173
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
174
      }
175
      break;
662,004✔
176
    case STMT_FETCH_FIELDS:
10,013✔
177
      if (STMT_STATUS_EQ(INIT)) {
10,013✔
178
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
179
      }
180
      break;
10,013✔
181
    case STMT_BIND:
1,453,684✔
182
      if (STMT_STATUS_EQ(INIT) || STMT_STATUS_EQ(BIND_COL)) {
1,453,684✔
183
        code = TSDB_CODE_TSC_STMT_API_ERROR;
102✔
184
      }
185
      /*
186
            if ((pStmt->sql.type == STMT_TYPE_MULTI_INSERT) && ()) {
187
              code = TSDB_CODE_TSC_STMT_API_ERROR;
188
            }
189
      */
190
      break;
1,454,334✔
191
    case STMT_BIND_COL:
×
192
      if (STMT_STATUS_EQ(INIT) || STMT_STATUS_EQ(BIND)) {
×
193
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
194
      }
195
      break;
×
196
    case STMT_ADD_BATCH:
822,762✔
197
      if (STMT_STATUS_NE(BIND) && STMT_STATUS_NE(BIND_COL) && STMT_STATUS_NE(FETCH_FIELDS)) {
822,762✔
198
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
199
      }
200
      break;
823,056✔
201
    case STMT_EXECUTE:
790,855✔
202
      if (STMT_TYPE_QUERY == pStmt->sql.type) {
790,855✔
203
        if (STMT_STATUS_NE(ADD_BATCH) && STMT_STATUS_NE(FETCH_FIELDS) && STMT_STATUS_NE(BIND) &&
7,533✔
204
            STMT_STATUS_NE(BIND_COL)) {
456✔
205
          code = TSDB_CODE_TSC_STMT_API_ERROR;
456✔
206
        }
207
      } else {
208
        if (STMT_STATUS_NE(ADD_BATCH) && STMT_STATUS_NE(FETCH_FIELDS)) {
782,883✔
209
          code = TSDB_CODE_TSC_STMT_API_ERROR;
×
210
        }
211
      }
212
      break;
790,429✔
213
    default:
×
214
      code = TSDB_CODE_APP_ERROR;
×
215
      break;
×
216
  }
217

218
  STMT_ERR_RET(code);
5,208,037✔
219

220
  pStmt->sql.status = newStatus;
5,207,479✔
221

222
  return TSDB_CODE_SUCCESS;
5,209,406✔
223
}
224

225
static int32_t stmtGetTbName(TAOS_STMT2* stmt, char** tbName) {
27,588✔
226
  STscStmt2* pStmt = (STscStmt2*)stmt;
27,588✔
227

228
  pStmt->sql.type = STMT_TYPE_MULTI_INSERT;
27,588✔
229

230
  if ('\0' == pStmt->bInfo.tbName[0]) {
27,572✔
231
    tscWarn("no table name set, OK if it is a stmt get fields");
4,513✔
232
    STMT_ERR_RET(TSDB_CODE_TSC_STMT_TBNAME_ERROR);
4,513✔
233
  }
234

235
  *tbName = pStmt->bInfo.tbName;
23,059✔
236

237
  return TSDB_CODE_SUCCESS;
23,120✔
238
}
239

240
static int32_t stmtUpdateBindInfo(TAOS_STMT2* stmt, STableMeta* pTableMeta, void* tags, SSHashObj** cols, SName* tbName,
171,538✔
241
                                  const char* sTableName, bool autoCreateTbl, int8_t tbNameFlag) {
242
  STscStmt2* pStmt = (STscStmt2*)stmt;
171,538✔
243
  char       tbFName[TSDB_TABLE_FNAME_LEN];
146,143✔
244
  int32_t    code = tNameExtractFullName(tbName, tbFName);
171,770✔
245
  if (code != 0) {
171,901✔
246
    return code;
×
247
  }
248

249
  if ((tags != NULL && ((SBoundColInfo*)tags)->numOfCols == 0) || !autoCreateTbl) {
171,901✔
250
    pStmt->sql.autoCreateTbl = false;
160,435✔
251
  }
252

253
  (void)memcpy(&pStmt->bInfo.sname, tbName, sizeof(*tbName));
171,824✔
254
  tstrncpy(pStmt->bInfo.tbFName, tbFName, sizeof(pStmt->bInfo.tbFName));
171,824✔
255
  pStmt->bInfo.tbFName[sizeof(pStmt->bInfo.tbFName) - 1] = 0;
171,585✔
256

257
  pStmt->bInfo.tbUid = autoCreateTbl ? 0 : pTableMeta->uid;
171,507✔
258
  pStmt->bInfo.tbSuid = pTableMeta->suid;
171,694✔
259
  pStmt->bInfo.tbVgId = pTableMeta->vgId;
171,525✔
260
  pStmt->bInfo.tbType = pTableMeta->tableType;
171,470✔
261

262
  if (!pStmt->bInfo.tagsCached) {
171,714✔
263
    qDestroyBoundColInfo(pStmt->bInfo.boundTags);
171,137✔
264
    taosMemoryFreeClear(pStmt->bInfo.boundTags);
171,213✔
265
  }
266

267
  // transfer ownership of cols to stmt
268
  if (cols) {
171,568✔
269
    pStmt->bInfo.fixedValueCols = *cols;
171,567✔
270
    *cols = NULL;
171,815✔
271
  }
272

273
  pStmt->bInfo.boundTags = tags;
171,506✔
274
  pStmt->bInfo.tagsCached = false;
171,764✔
275
  pStmt->bInfo.tbNameFlag = tbNameFlag;
171,688✔
276
  tstrncpy(pStmt->bInfo.stbFName, sTableName, sizeof(pStmt->bInfo.stbFName));
171,435✔
277

278
  if (pTableMeta->tableType != TSDB_CHILD_TABLE && pTableMeta->tableType != TSDB_SUPER_TABLE) {
171,516✔
279
    pStmt->sql.stbInterlaceMode = false;
7,005✔
280
  }
281

282
  return TSDB_CODE_SUCCESS;
171,556✔
283
}
284

285
static int32_t stmtUpdateExecInfo(TAOS_STMT2* stmt, SHashObj* pVgHash, SHashObj* pBlockHash) {
171,489✔
286
  STscStmt2* pStmt = (STscStmt2*)stmt;
171,489✔
287

288
  pStmt->sql.pVgHash = pVgHash;
171,489✔
289
  pStmt->exec.pBlockHash = pBlockHash;
171,783✔
290

291
  return TSDB_CODE_SUCCESS;
171,458✔
292
}
293

294
static int32_t stmtUpdateInfo(TAOS_STMT2* stmt, STableMeta* pTableMeta, void* tags, SSHashObj** cols, SName* tbName,
171,566✔
295
                              bool autoCreateTbl, SHashObj* pVgHash, SHashObj* pBlockHash, const char* sTableName,
296
                              uint8_t tbNameFlag) {
297
  STscStmt2* pStmt = (STscStmt2*)stmt;
171,566✔
298

299
  STMT_ERR_RET(stmtUpdateBindInfo(stmt, pTableMeta, tags, cols, tbName, sTableName, autoCreateTbl, tbNameFlag));
171,566✔
300
  STMT_ERR_RET(stmtUpdateExecInfo(stmt, pVgHash, pBlockHash));
171,707✔
301

302
  pStmt->sql.autoCreateTbl = autoCreateTbl;
171,485✔
303

304
  return TSDB_CODE_SUCCESS;
171,733✔
305
}
306

307
static int32_t stmtGetExecInfo(TAOS_STMT2* stmt, SHashObj** pVgHash, SHashObj** pBlockHash) {
1,861✔
308
  STscStmt2* pStmt = (STscStmt2*)stmt;
1,861✔
309

310
  *pVgHash = pStmt->sql.pVgHash;
1,861✔
311
  pStmt->sql.pVgHash = NULL;
1,861✔
312

313
  *pBlockHash = pStmt->exec.pBlockHash;
1,861✔
314
  pStmt->exec.pBlockHash = NULL;
1,861✔
315

316
  return TSDB_CODE_SUCCESS;
1,861✔
317
}
318

319
static int32_t stmtParseSql(STscStmt2* pStmt) {
180,529✔
320
  pStmt->exec.pCurrBlock = NULL;
180,529✔
321

322
  SStmtCallback stmtCb = {
180,848✔
323
      .pStmt = pStmt,
324
      .getTbNameFn = stmtGetTbName,
325
      .setInfoFn = stmtUpdateInfo,
326
      .getExecInfoFn = stmtGetExecInfo,
327
  };
328

329
  STMT_ERR_RET(stmtCreateRequest(pStmt));
181,092✔
330
  pStmt->exec.pRequest->stmtBindVersion = 2;
180,782✔
331

332
  pStmt->stat.parseSqlNum++;
181,354✔
333

334
  STMT2_DLOG("start to parse, QID:0x%" PRIx64, pStmt->exec.pRequest->requestId);
180,807✔
335
  STMT_ERR_RET(parseSql(pStmt->exec.pRequest, false, &pStmt->sql.pQuery, &stmtCb));
180,807✔
336

337
  pStmt->sql.siInfo.pQuery = pStmt->sql.pQuery;
178,800✔
338

339
  pStmt->bInfo.needParse = false;
179,027✔
340

341
  if (pStmt->sql.type == 0) {
178,738✔
342
    if (pStmt->sql.pQuery->pRoot && LEGAL_INSERT(nodeType(pStmt->sql.pQuery->pRoot))) {
152,141✔
343
      pStmt->sql.type = STMT_TYPE_INSERT;
145,001✔
344
      pStmt->sql.stbInterlaceMode = false;
145,001✔
345
    } else if (pStmt->sql.pQuery->pPrepareRoot && LEGAL_SELECT(nodeType(pStmt->sql.pQuery->pPrepareRoot))) {
7,314✔
346
      pStmt->sql.type = STMT_TYPE_QUERY;
6,771✔
347
      pStmt->sql.stbInterlaceMode = false;
6,771✔
348

349
      return TSDB_CODE_SUCCESS;
6,771✔
350
    } else {
351
      STMT2_ELOG_E("only support select or insert sql");
456✔
352
      if (pStmt->exec.pRequest->msgBuf) {
456✔
353
        tstrncpy(pStmt->exec.pRequest->msgBuf, "stmt only support select or insert", pStmt->exec.pRequest->msgBufLen);
456✔
354
      }
355
      return TSDB_CODE_PAR_SYNTAX_ERROR;
456✔
356
    }
357
  } else if (pStmt->sql.type == STMT_TYPE_QUERY) {
26,839✔
358
    pStmt->sql.stbInterlaceMode = false;
×
359
    return TSDB_CODE_SUCCESS;
×
360
  } else if (pStmt->sql.type == STMT_TYPE_INSERT) {
26,823✔
361
    pStmt->sql.stbInterlaceMode = false;
×
362
  }
363

364
  STableDataCxt** pSrc =
365
      (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
171,760✔
366
  if (NULL == pSrc || NULL == *pSrc) {
171,943✔
367
    STMT2_ELOG("fail to get exec.pBlockHash, maybe parse failed, tbFName:%s", pStmt->bInfo.tbFName);
×
368
    STMT_ERR_RET(TSDB_CODE_TSC_STMT_CACHE_ERROR);
×
369
  }
370

371
  STableDataCxt* pTableCtx = *pSrc;
171,649✔
372
  if (pStmt->sql.stbInterlaceMode && pTableCtx->pData->pCreateTbReq && (pStmt->bInfo.tbNameFlag & USING_CLAUSE) == 0) {
171,610✔
373
    STMT2_TLOG("destroy pCreateTbReq for no-using insert, tbFName:%s", pStmt->bInfo.tbFName);
2,142✔
374
    tdDestroySVCreateTbReq(pTableCtx->pData->pCreateTbReq);
2,142✔
375
    taosMemoryFreeClear(pTableCtx->pData->pCreateTbReq);
2,142✔
376
    pTableCtx->pData->pCreateTbReq = NULL;
2,142✔
377
  }
378
  // if (pStmt->sql.stbInterlaceMode) {
379
  //   int16_t lastIdx = -1;
380

381
  //   for (int32_t i = 0; i < pTableCtx->boundColsInfo.numOfBound; ++i) {
382
  //     if (pTableCtx->boundColsInfo.pColIndex[i] < lastIdx) {
383
  //       pStmt->sql.stbInterlaceMode = false;
384
  //       break;
385
  //     }
386

387
  //     lastIdx = pTableCtx->boundColsInfo.pColIndex[i];
388
  //   }
389
  // }
390

391
  if (NULL == pStmt->sql.pBindInfo) {
171,943✔
392
    pStmt->sql.pBindInfo = taosMemoryMalloc(pTableCtx->boundColsInfo.numOfBound * sizeof(*pStmt->sql.pBindInfo));
170,065✔
393
    if (NULL == pStmt->sql.pBindInfo) {
169,760✔
394
      STMT2_ELOG_E("fail to malloc pBindInfo");
×
395
      return terrno;
×
396
    }
397
  }
398

399
  return TSDB_CODE_SUCCESS;
171,573✔
400
}
401

402
static int32_t stmtPrintBindv(TAOS_STMT2* stmt, TAOS_STMT2_BIND* bindv, int32_t col_idx, bool isTags) {
×
403
  STscStmt2* pStmt = (STscStmt2*)stmt;
×
404
  int32_t    count = 0;
×
405
  int32_t    code = 0;
×
406

407
  if (bindv == NULL) {
×
408
    STMT2_TLOG("bindv is NULL, col_idx:%d, isTags:%d", col_idx, isTags);
×
409
    return TSDB_CODE_SUCCESS;
×
410
  }
411

412
  if (col_idx >= 0) {
×
413
    count = 1;
×
414
    STMT2_TLOG("single col bind, col_idx:%d", col_idx);
×
415
  } else {
416
    if (STMT_TYPE_INSERT == pStmt->sql.type || STMT_TYPE_MULTI_INSERT == pStmt->sql.type ||
×
417
        (pStmt->sql.type == 0 && stmt2IsInsert(stmt))) {
×
418
      if (pStmt->sql.placeholderOfTags == 0 && pStmt->sql.placeholderOfCols == 0) {
×
419
        code = stmtGetStbColFields2(pStmt, NULL, NULL);
×
420
        if (code != TSDB_CODE_SUCCESS) {
×
421
          return code;
×
422
        }
423
      }
424
      if (isTags) {
×
425
        count = pStmt->sql.placeholderOfTags;
×
426
        STMT2_TLOG("print tags bindv, cols:%d", count);
×
427
      } else {
428
        count = pStmt->sql.placeholderOfCols;
×
429
        STMT2_TLOG("print cols bindv, cols:%d", count);
×
430
      }
431
    } else if (STMT_TYPE_QUERY == pStmt->sql.type || (pStmt->sql.type == 0 && stmt2IsSelect(stmt))) {
×
432
      count = taosArrayGetSize(pStmt->sql.pQuery->pPlaceholderValues);
×
433
      STMT2_TLOG("print query bindv, cols:%d", count);
×
434
    }
435
  }
436

437
  if (code != TSDB_CODE_SUCCESS) {
×
438
    STMT2_ELOG("failed to get param count, code:%d", code);
×
439
    return code;
×
440
  }
441

442
  for (int i = 0; i < count; i++) {
×
443
    int32_t type = bindv[i].buffer_type;
×
444
    int32_t num = bindv[i].num;
×
445
    char*   current_buf = (char*)bindv[i].buffer;
×
446

447
    for (int j = 0; j < num; j++) {
×
448
      char    buf[256] = {0};
×
449
      int32_t len = 0;
×
450
      bool    isNull = (bindv[i].is_null && bindv[i].is_null[j]);
×
451

452
      if (IS_VAR_DATA_TYPE(type) && bindv[i].length) {
×
453
        len = bindv[i].length[j];
×
454
      } else {
455
        len = tDataTypes[type].bytes;
×
456
      }
457

458
      if (isNull) {
×
459
        snprintf(buf, sizeof(buf), "NULL");
×
460
      } else {
461
        if (current_buf == NULL) {
×
462
          snprintf(buf, sizeof(buf), "NULL(Buf)");
×
463
        } else {
464
          switch (type) {
×
465
            case TSDB_DATA_TYPE_BOOL:
×
466
              snprintf(buf, sizeof(buf), "%d", *(int8_t*)current_buf);
×
467
              break;
×
468
            case TSDB_DATA_TYPE_TINYINT:
×
469
              snprintf(buf, sizeof(buf), "%d", *(int8_t*)current_buf);
×
470
              break;
×
471
            case TSDB_DATA_TYPE_SMALLINT:
×
472
              snprintf(buf, sizeof(buf), "%d", *(int16_t*)current_buf);
×
473
              break;
×
474
            case TSDB_DATA_TYPE_INT:
×
475
              snprintf(buf, sizeof(buf), "%d", *(int32_t*)current_buf);
×
476
              break;
×
477
            case TSDB_DATA_TYPE_BIGINT:
×
478
              snprintf(buf, sizeof(buf), "%" PRId64, *(int64_t*)current_buf);
×
479
              break;
×
480
            case TSDB_DATA_TYPE_FLOAT:
×
481
              snprintf(buf, sizeof(buf), "%f", *(float*)current_buf);
×
482
              break;
×
483
            case TSDB_DATA_TYPE_DOUBLE:
×
484
              snprintf(buf, sizeof(buf), "%f", *(double*)current_buf);
×
485
              break;
×
486
            case TSDB_DATA_TYPE_BINARY:
×
487
            case TSDB_DATA_TYPE_NCHAR:
488
            case TSDB_DATA_TYPE_GEOMETRY:
489
            case TSDB_DATA_TYPE_VARBINARY:
490
              snprintf(buf, sizeof(buf), "len:%d, val:%.*s", len, len, current_buf);
×
491
              break;
×
492
            case TSDB_DATA_TYPE_TIMESTAMP:
×
493
              snprintf(buf, sizeof(buf), "%" PRId64, *(int64_t*)current_buf);
×
494
              break;
×
495
            case TSDB_DATA_TYPE_UTINYINT:
×
496
              snprintf(buf, sizeof(buf), "%u", *(uint8_t*)current_buf);
×
497
              break;
×
498
            case TSDB_DATA_TYPE_USMALLINT:
×
499
              snprintf(buf, sizeof(buf), "%u", *(uint16_t*)current_buf);
×
500
              break;
×
501
            case TSDB_DATA_TYPE_UINT:
×
502
              snprintf(buf, sizeof(buf), "%u", *(uint32_t*)current_buf);
×
503
              break;
×
504
            case TSDB_DATA_TYPE_UBIGINT:
×
505
              snprintf(buf, sizeof(buf), "%" PRIu64, *(uint64_t*)current_buf);
×
506
              break;
×
507
            default:
×
508
              snprintf(buf, sizeof(buf), "UnknownType:%d", type);
×
509
              break;
×
510
          }
511
        }
512
      }
513

514
      STMT2_TLOG("bindv[%d] row[%d]: type:%s, val:%s", i, j, tDataTypes[type].name, buf);
×
515

516
      if (!isNull && current_buf) {
×
517
        current_buf += len;
×
518
      }
519
    }
520
  }
521

522
  return TSDB_CODE_SUCCESS;
×
523
}
524

525
static void resetRequest(STscStmt2* pStmt) {
354,503✔
526
  if (pStmt->exec.pRequest) {
354,503✔
527
    taos_free_result(pStmt->exec.pRequest);
196,297✔
528
    pStmt->exec.pRequest = NULL;
196,324✔
529
  }
530
  pStmt->asyncResultAvailable = false;
354,590✔
531
}
354,503✔
532

533
static int32_t stmtCleanBindInfo(STscStmt2* pStmt) {
974,182✔
534
  pStmt->bInfo.tbUid = 0;
974,182✔
535
  pStmt->bInfo.tbVgId = -1;
974,232✔
536
  pStmt->bInfo.tbType = 0;
974,045✔
537
  pStmt->bInfo.needParse = true;
974,143✔
538
  pStmt->bInfo.inExecCache = false;
974,087✔
539

540
  pStmt->bInfo.tbName[0] = 0;
974,207✔
541
  pStmt->bInfo.tbFName[0] = 0;
974,112✔
542
  if (!pStmt->bInfo.tagsCached) {
974,087✔
543
    qDestroyBoundColInfo(pStmt->bInfo.boundTags);
738,538✔
544
    taosMemoryFreeClear(pStmt->bInfo.boundTags);
738,486✔
545
    pStmt->bInfo.boundTags = NULL;
738,486✔
546
  }
547

548
  if (!pStmt->bInfo.boundColsCached) {
973,806✔
549
    tSimpleHashCleanup(pStmt->bInfo.fixedValueCols);
364,217✔
550
    pStmt->bInfo.fixedValueCols = NULL;
364,157✔
551
  }
552

553
  if (!pStmt->sql.autoCreateTbl) {
974,035✔
554
    pStmt->bInfo.stbFName[0] = 0;
735,761✔
555
    pStmt->bInfo.tbSuid = 0;
736,121✔
556
  }
557

558
  STMT2_TLOG("finish clean bind info, tagsCached:%d, autoCreateTbl:%d", pStmt->bInfo.tagsCached,
974,345✔
559
             pStmt->sql.autoCreateTbl);
560

561
  return TSDB_CODE_SUCCESS;
974,132✔
562
}
563

564
static void stmtFreeTableBlkList(STableColsData* pTb) {
×
565
  (void)qResetStmtColumns(pTb->aCol, true);
×
566
  taosArrayDestroy(pTb->aCol);
×
567
}
×
568

569
static void stmtResetQueueTableBuf(STableBufInfo* pTblBuf, SStmtQueue* pQueue) {
609,852✔
570
  pTblBuf->pCurBuff = taosArrayGetP(pTblBuf->pBufList, 0);
609,852✔
571
  if (NULL == pTblBuf->pCurBuff) {
610,068✔
572
    tscError("QInfo:%p, fail to get buffer from list", pTblBuf);
148✔
573
    return;
×
574
  }
575
  pTblBuf->buffIdx = 1;
609,920✔
576
  pTblBuf->buffOffset = sizeof(*pQueue->head);
609,920✔
577

578
  pQueue->head = pQueue->tail = pTblBuf->pCurBuff;
609,920✔
579
  pQueue->qRemainNum = 0;
609,791✔
580
  pQueue->head->next = NULL;
609,920✔
581
}
582

583
static int32_t stmtCleanExecInfo(STscStmt2* pStmt, bool keepTable, bool deepClean) {
969,654✔
584
  if (pStmt->sql.stbInterlaceMode) {
969,654✔
585
    if (deepClean) {
619,550✔
586
      taosHashCleanup(pStmt->exec.pBlockHash);
9,821✔
587
      pStmt->exec.pBlockHash = NULL;
9,821✔
588

589
      if (NULL != pStmt->exec.pCurrBlock) {
9,821✔
590
        taosMemoryFreeClear(pStmt->exec.pCurrBlock->boundColsInfo.pColIndex);
9,515✔
591
        taosMemoryFreeClear(pStmt->exec.pCurrBlock->pData);
9,515✔
592
        qDestroyStmtDataBlock(pStmt->exec.pCurrBlock);
9,515✔
593
        pStmt->exec.pCurrBlock = NULL;
9,515✔
594
      }
595
      if (STMT_TYPE_QUERY != pStmt->sql.type) {
9,821✔
596
        resetRequest(pStmt);
9,821✔
597
      }
598
    } else {
599
      pStmt->sql.siInfo.pTableColsIdx = 0;
609,729✔
600
      stmtResetQueueTableBuf(&pStmt->sql.siInfo.tbBuf, &pStmt->queue);
609,864✔
601
      tSimpleHashClear(pStmt->sql.siInfo.pTableRowDataHash);
609,798✔
602
    }
603
    if (NULL != pStmt->exec.pRequest) {
619,929✔
604
      pStmt->exec.pRequest->body.resInfo.numOfRows = 0;
610,108✔
605
    }
606
  } else {
607
    if (STMT_TYPE_QUERY != pStmt->sql.type || deepClean) {
350,104✔
608
      resetRequest(pStmt);
342,948✔
609
    }
610

611
    size_t keyLen = 0;
350,075✔
612
    void*  pIter = taosHashIterate(pStmt->exec.pBlockHash, NULL);
350,075✔
613
    while (pIter) {
720,031✔
614
      STableDataCxt* pBlocks = *(STableDataCxt**)pIter;
369,952✔
615
      char*          key = taosHashGetKey(pIter, &keyLen);
369,952✔
616
      STableMeta*    pMeta = qGetTableMetaInDataBlock(pBlocks);
369,890✔
617

618
      if (keepTable && pBlocks == pStmt->exec.pCurrBlock) {
369,683✔
619
        TSWAP(pBlocks->pData, pStmt->exec.pCurrTbData);
172,890✔
620
        STMT_ERR_RET(qResetStmtDataBlock(pBlocks, false));
193,393✔
621

622
        pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter);
172,708✔
623
        continue;
172,890✔
624
      }
625

626
      qDestroyStmtDataBlock(pBlocks);
196,793✔
627
      STMT_ERR_RET(taosHashRemove(pStmt->exec.pBlockHash, key, keyLen));
197,062✔
628

629
      pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter);
197,062✔
630
    }
631

632
    if (keepTable) {
350,079✔
633
      STMT2_TLOG("finish clean exec info, stbInterlaceMode:%d, keepTable:%d, deepClean:%d", pStmt->sql.stbInterlaceMode,
179,967✔
634
                 keepTable, deepClean);
635
      return TSDB_CODE_SUCCESS;
179,967✔
636
    }
637

638
    taosHashCleanup(pStmt->exec.pBlockHash);
170,112✔
639
    pStmt->exec.pBlockHash = NULL;
170,112✔
640

641
    tDestroySubmitTbData(pStmt->exec.pCurrTbData, TSDB_MSG_FLG_ENCODE);
170,112✔
642
    taosMemoryFreeClear(pStmt->exec.pCurrTbData);
170,112✔
643
  }
644

645
  STMT_ERR_RET(stmtCleanBindInfo(pStmt));
790,041✔
646
  STMT2_TLOG("finish clean exec info, stbInterlaceMode:%d, keepTable:%d, deepClean:%d", pStmt->sql.stbInterlaceMode,
789,729✔
647
             keepTable, deepClean);
648

649
  return TSDB_CODE_SUCCESS;
789,815✔
650
}
651

652
static void stmtFreeSingleVgDataBlock(void* p) {
867,350✔
653
  SVgDataBlocks* pVg = *(SVgDataBlocks**)p;
867,350✔
654
  if (pVg) {
867,590✔
655
    taosMemoryFree(pVg->pData);
867,656✔
656
    taosMemoryFree(pVg);
867,515✔
657
  }
658
}
867,643✔
659

660
static void stmtFreeVgDataBlocksForRetry(STscStmt2* pStmt) {
962,336✔
661
  if (pStmt->pVgDataBlocksForRetry) {
962,336✔
662
    taosArrayDestroyEx(pStmt->pVgDataBlocksForRetry, stmtFreeSingleVgDataBlock);
782,492✔
663
    pStmt->pVgDataBlocksForRetry = NULL;
782,510✔
664
  }
665
}
962,319✔
666

667
static int32_t stmtSaveVgDataBlocksForRetry(STscStmt2* pStmt) {
782,237✔
668
  stmtFreeVgDataBlocksForRetry(pStmt);
782,237✔
669

670
  SVnodeModifyOpStmt* pModif = (SVnodeModifyOpStmt*)pStmt->sql.pQuery->pRoot;
782,831✔
671
  if (!pModif || !pModif->pDataBlocks || taosArrayGetSize(pModif->pDataBlocks) == 0) {
782,562✔
672
    return TSDB_CODE_SUCCESS;
×
673
  }
674

675
  int32_t num = taosArrayGetSize(pModif->pDataBlocks);
782,999✔
676
  pStmt->pVgDataBlocksForRetry = taosArrayInit(num, POINTER_BYTES);
783,143✔
677
  if (!pStmt->pVgDataBlocksForRetry) {
783,096✔
678
    return terrno;
×
679
  }
680

681
  for (int32_t i = 0; i < num; i++) {
1,650,734✔
682
    SVgDataBlocks* pSrc = taosArrayGetP(pModif->pDataBlocks, i);
867,595✔
683
    SVgDataBlocks* pDst = taosMemoryMalloc(sizeof(SVgDataBlocks));
867,798✔
684
    if (!pDst) {
867,591✔
685
      stmtFreeVgDataBlocksForRetry(pStmt);
×
686
      return terrno;
×
687
    }
688
    *pDst = *pSrc;
867,591✔
689
    pDst->pData = taosMemoryMalloc(pSrc->size);
867,591✔
690
    if (!pDst->pData) {
868,073✔
691
      taosMemoryFree(pDst);
×
692
      stmtFreeVgDataBlocksForRetry(pStmt);
×
693
      return terrno;
×
694
    }
695
    (void)memcpy(pDst->pData, pSrc->pData, pSrc->size);
867,988✔
696
    if (NULL == taosArrayPush(pStmt->pVgDataBlocksForRetry, &pDst)) {
1,736,385✔
697
      taosMemoryFree(pDst->pData);
×
698
      taosMemoryFree(pDst);
×
699
      stmtFreeVgDataBlocksForRetry(pStmt);
×
700
      return terrno;
×
701
    }
702
  }
703
  return TSDB_CODE_SUCCESS;
783,139✔
704
}
705

706
static int32_t stmtRestoreVgDataBlocksForRetry(STscStmt2* pStmt) {
306✔
707
  SVnodeModifyOpStmt* pModif = (SVnodeModifyOpStmt*)pStmt->sql.pQuery->pRoot;
306✔
708
  if (!pModif || !pStmt->pVgDataBlocksForRetry) {
306✔
709
    return TSDB_CODE_SUCCESS;
×
710
  }
711
  // The planner owns pDataBlocks after createQueryPlan (via TSWAP); it has already freed
712
  // the old array. We simply restore a new clone here.
713
  pModif->pDataBlocks = pStmt->pVgDataBlocksForRetry;
306✔
714
  pStmt->pVgDataBlocksForRetry = NULL;
306✔
715
  return TSDB_CODE_SUCCESS;
306✔
716
}
717

718
static STableMeta* stmtCloneTableMetaForRetry(const STableMeta* pSrc) {
204✔
719
  int32_t sz = (int32_t)TABLE_META_FULL_SIZE(pSrc);
204✔
720
  if (sz <= 0) {
204✔
721
    return NULL;
×
722
  }
723
  STableMeta* p = taosMemoryMalloc(sz);
204✔
724
  if (p == NULL) {
204✔
725
    return NULL;
×
726
  }
727
  (void)memcpy(p, pSrc, sz);
204✔
728
  tableMetaResetPointers(p);
204✔
729
  return p;
204✔
730
}
731

732
static void stmtFreeUidTableMetaHash(SHashObj* pHash) {
102✔
733
  if (pHash == NULL) {
102✔
734
    return;
×
735
  }
736
  void* pIter = NULL;
102✔
737
  while ((pIter = taosHashIterate(pHash, pIter)) != NULL) {
306✔
738
    STableMeta* pMeta = *(STableMeta**)pIter;
204✔
739
    taosMemoryFree(pMeta);
204✔
740
  }
741
  taosHashCleanup(pHash);
102✔
742
}
743

744
// tRowGet may succeed with a wrong prefix schema but leave VAR column pointers outside the SRow allocation;
745
// tRowBuild would then memcpy OOB. Require all VAR payloads to lie within [pRow, pRow + pRow->len).
746
static bool stmtScolValVarPayloadInRow(const SRow* pRow, const SColVal* pCv, int8_t colType) {
816✔
747
  if (!COL_VAL_IS_VALUE(pCv) || !IS_VAR_DATA_TYPE(colType)) {
816✔
748
    return true;
408✔
749
  }
750
  if (pCv->value.nData == 0) {
408✔
751
    return true;
×
752
  }
753
  if (pCv->value.pData == NULL) {
408✔
754
    return false;
×
755
  }
756
  const uint8_t* rbeg = (const uint8_t*)pRow;
408✔
757
  const uint8_t* rend = rbeg + pRow->len;
408✔
758
  const uint8_t* p = (const uint8_t*)pCv->value.pData;
408✔
759
  return (p >= rbeg) && (p + pCv->value.nData <= rend);
408✔
760
}
761

762
// Infer decode STSchema: full column count when row sver matches catalog; else try prefix column counts (ADD COLUMN).
763
static int32_t stmtFindDecodeSchemaForRow(SRow* pRow, const STableMeta* pMeta, STSchema** ppOld, int32_t* pnOldCols) {
204✔
764
  uint16_t oldSver = pRow->sver;
204✔
765
  int32_t  nMax = pMeta->tableInfo.numOfColumns;
204✔
766
  SSchema* base = (SSchema*)&pMeta->schema[0];
204✔
767

768
  if ((int32_t)oldSver == pMeta->sversion) {
204✔
769
    STSchema* p = tBuildTSchema(base, nMax, (int32_t)oldSver);
×
770
    if (p == NULL) {
×
771
      return terrno;
×
772
    }
773
    bool ok = true;
×
774
    for (int32_t i = 0; i < nMax; ++i) {
×
775
      SColVal cv = {0};
×
776
      if (tRowGet(pRow, p, i, &cv) != 0) {
×
777
        ok = false;
×
778
        break;
×
779
      }
780
      if (!stmtScolValVarPayloadInRow(pRow, &cv, p->columns[i].type)) {
×
781
        ok = false;
×
782
        break;
×
783
      }
784
    }
785
    if (ok) {
×
786
      *ppOld = p;
×
787
      *pnOldCols = nMax;
×
788
      return TSDB_CODE_SUCCESS;
×
789
    }
790
    tDestroyTSchema(p);
×
791
    return TSDB_CODE_INVALID_PARA;
×
792
  }
793

794
  for (int32_t n = nMax; n >= 1; --n) {
408✔
795
    STSchema* pTry = tBuildTSchema(base, n, (int32_t)oldSver);
408✔
796
    if (pTry == NULL) {
408✔
797
      return terrno;
×
798
    }
799
    bool ok = true;
408✔
800
    for (int32_t i = 0; i < n; ++i) {
1,020✔
801
      SColVal cv = {0};
816✔
802
      if (tRowGet(pRow, pTry, i, &cv) != 0) {
816✔
803
        ok = false;
×
804
        break;
204✔
805
      }
806
      if (!stmtScolValVarPayloadInRow(pRow, &cv, pTry->columns[i].type)) {
816✔
807
        ok = false;
204✔
808
        break;
204✔
809
      }
810
    }
811
    if (ok) {
408✔
812
      *ppOld = pTry;
204✔
813
      *pnOldCols = n;
204✔
814
      return TSDB_CODE_SUCCESS;
204✔
815
    }
816
    tDestroyTSchema(pTry);
204✔
817
  }
818
  return TSDB_CODE_INVALID_PARA;
×
819
}
820

821
static int32_t stmtRebuildOneRowToLatestSchema(SRow* pOldRow, const STableMeta* pMeta, SRow** ppNewRow) {
204✔
822
  STSchema* pOldSch = NULL;
204✔
823
  int32_t   nOldCols = 0;
204✔
824
  int32_t   code = stmtFindDecodeSchemaForRow(pOldRow, pMeta, &pOldSch, &nOldCols);
204✔
825
  if (code != TSDB_CODE_SUCCESS) {
204✔
826
    return code;
×
827
  }
828

829
  int32_t   nNewCols = pMeta->tableInfo.numOfColumns;
204✔
830
  STSchema* pNewSch = tBuildTSchema((SSchema*)&pMeta->schema[0], nNewCols, pMeta->sversion);
204✔
831
  if (pNewSch == NULL) {
204✔
832
    tDestroyTSchema(pOldSch);
×
833
    return terrno;
×
834
  }
835

836
  for (int32_t j = 0; j < nOldCols && j < nNewCols; ++j) {
612✔
837
    if (pOldSch->columns[j].colId != pNewSch->columns[j].colId) {
408✔
838
      tDestroyTSchema(pOldSch);
×
839
      tDestroyTSchema(pNewSch);
×
840
      return TSDB_CODE_INVALID_PARA;
×
841
    }
842
  }
843

844
  SArray* aColVal = taosArrayInit(pNewSch->numOfCols, sizeof(SColVal));
204✔
845
  if (aColVal == NULL) {
204✔
846
    tDestroyTSchema(pOldSch);
×
847
    tDestroyTSchema(pNewSch);
×
848
    return terrno;
×
849
  }
850

851
  for (int32_t j = 0; j < pNewSch->numOfCols; ++j) {
816✔
852
    SColVal cv = {0};
612✔
853
    if (j < nOldCols) {
612✔
854
      code = tRowGet(pOldRow, pOldSch, j, &cv);
408✔
855
      if (code != TSDB_CODE_SUCCESS) {
408✔
856
        taosArrayDestroy(aColVal);
×
857
        tDestroyTSchema(pOldSch);
×
858
        tDestroyTSchema(pNewSch);
×
859
        return code;
×
860
      }
861
    } else {
862
      STColumn* pc = &pNewSch->columns[j];
204✔
863
      cv = COL_VAL_NONE(pc->colId, pc->type);
204✔
864
    }
865
    if (taosArrayPush(aColVal, &cv) == NULL) {
612✔
866
      code = terrno;
×
867
      taosArrayDestroy(aColVal);
×
868
      tDestroyTSchema(pOldSch);
×
869
      tDestroyTSchema(pNewSch);
×
870
      return code;
×
871
    }
872
  }
873

874
  SRowBuildScanInfo sinfo = {0};
204✔
875
  code = tRowBuild(aColVal, pNewSch, ppNewRow, &sinfo);
204✔
876
  taosArrayDestroy(aColVal);
204✔
877
  tDestroyTSchema(pOldSch);
204✔
878
  tDestroyTSchema(pNewSch);
204✔
879
  return code;
204✔
880
}
881

882
static void stmtFreeHeapPatchRowsArray(SArray* aHeapRows) {
102✔
883
  if (aHeapRows == NULL) {
102✔
884
    return;
×
885
  }
886
  int32_t n = (int32_t)taosArrayGetSize(aHeapRows);
102✔
887
  for (int32_t i = 0; i < n; ++i) {
306✔
888
    SRow* p = taosArrayGetP(aHeapRows, i);
204✔
889
    tRowDestroy(p);
204✔
890
  }
891
  taosArrayDestroy(aHeapRows);
102✔
892
}
893

894
// After refreshMeta: set sver from catalog; decode each row with inferred old schema and tRowBuild with latest schema.
895
// aHeapRows: receives pointers from tRowBuild so they can be freed before tDestroySubmitReq (decode path does not free
896
// rows).
897
static void stmtPatchOneSubmitTbDataSchemaVer(SSubmitTbData* pTb, SHashObj* pUidMetaHash, SArray* aHeapRows) {
102✔
898
  if (pTb->uid == 0) {
102✔
899
    return;
×
900
  }
901
  void* pMv = taosHashGet(pUidMetaHash, &pTb->uid, sizeof(uint64_t));
102✔
902
  if (pMv == NULL) {
102✔
903
    return;
×
904
  }
905
  STableMeta* pMeta = *(STableMeta**)pMv;
102✔
906
  pTb->sver = pMeta->sversion;
102✔
907
  if (pTb->flags & SUBMIT_REQ_COLUMN_DATA_FORMAT) {
102✔
908
    return;
×
909
  }
910
  if (pTb->aRowP == NULL) {
102✔
911
    return;
×
912
  }
913
  if (pTb->pBlobSet != NULL) {
102✔
914
    int32_t nRow = (int32_t)TARRAY_SIZE(pTb->aRowP);
×
915
    SRow**  rows = (SRow**)TARRAY_DATA(pTb->aRowP);
×
916
    for (int32_t i = 0; i < nRow; ++i) {
×
917
      if (rows[i] != NULL) {
×
918
        rows[i]->sver = (uint16_t)pMeta->sversion;
×
919
      }
920
    }
921
    return;
×
922
  }
923

924
  int32_t nRow = (int32_t)TARRAY_SIZE(pTb->aRowP);
102✔
925
  for (int32_t i = 0; i < nRow; ++i) {
306✔
926
    SRow* pRow = taosArrayGetP(pTb->aRowP, i);
204✔
927
    if (pRow == NULL) {
204✔
928
      continue;
×
929
    }
930
    if ((uint16_t)pMeta->sversion == pRow->sver) {
204✔
931
      continue;
×
932
    }
933
    if (pRow->flag & HAS_BLOB) {
204✔
934
      pRow->sver = (uint16_t)pMeta->sversion;
×
935
      continue;
×
936
    }
937
    SRow* pNew = NULL;
204✔
938
    if (stmtRebuildOneRowToLatestSchema(pRow, pMeta, &pNew) == TSDB_CODE_SUCCESS && pNew != NULL) {
204✔
939
      // pRow points into the decoded submit payload (tDecodeBinaryWithSize); do not tRowDestroy it.
940
      if (aHeapRows != NULL && taosArrayPush(aHeapRows, &pNew) == NULL) {
408✔
941
        tRowDestroy(pNew);
×
942
        // Cannot record heap row for destroy before tDestroySubmitReq; keep embedded row, bump sver only.
943
        pRow->sver = (uint16_t)pMeta->sversion;
×
944
      } else {
945
        (void)taosArraySet(pTb->aRowP, i, &pNew);
204✔
946
      }
947
    } else {
948
      pRow->sver = (uint16_t)pMeta->sversion;
×
949
    }
950
  }
951
}
952

953
static int32_t stmtBuildUidToTableMetaHash(STscStmt2* pStmt, SRequestObj* pRequest, SHashObj** ppHash) {
102✔
954
  int32_t code = TSDB_CODE_SUCCESS;
102✔
955
  *ppHash = NULL;
102✔
956

957
  if (NULL == pStmt->pCatalog) {
102✔
958
    code = catalogGetHandle(pStmt->taos->pAppInfo->clusterId, &pStmt->pCatalog);
×
959
    if (code != TSDB_CODE_SUCCESS) {
×
960
      return code;
×
961
    }
962
  }
963

964
  SHashObj* pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_UBIGINT), false, HASH_NO_LOCK);
102✔
965
  if (pHash == NULL) {
102✔
966
    return terrno;
×
967
  }
968

969
  SRequestConnInfo conn = {.pTrans = pStmt->taos->pAppInfo->pTransporter,
102✔
970
                           .requestId = pRequest->requestId,
102✔
971
                           .requestObjRefId = pRequest->self,
102✔
972
                           .mgmtEps = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp)};
102✔
973

974
  int32_t tblNum = pRequest->tableList ? (int32_t)taosArrayGetSize(pRequest->tableList) : 0;
102✔
975
  for (int32_t i = 0; i < tblNum; ++i) {
306✔
976
    SName*      pName = taosArrayGet(pRequest->tableList, i);
204✔
977
    STableMeta* pMeta = NULL;
204✔
978
    int32_t     c = catalogGetTableMeta(pStmt->pCatalog, &conn, pName, &pMeta);
204✔
979
    if (c != TSDB_CODE_SUCCESS) {
204✔
980
      if (pMeta != NULL) {
×
981
        taosMemoryFree(pMeta);
×
982
      }
983
      taosHashCleanup(pHash);
×
984
      return c;
×
985
    }
986
    if (pMeta != NULL) {
204✔
987
      STableMeta* pDup = stmtCloneTableMetaForRetry(pMeta);
204✔
988
      taosMemoryFree(pMeta);
204✔
989
      pMeta = NULL;
204✔
990
      if (pDup != NULL) {
204✔
991
        int32_t putCode = taosHashPut(pHash, &pDup->uid, sizeof(uint64_t), &pDup, POINTER_BYTES);
204✔
992
        if (putCode != TSDB_CODE_SUCCESS) {
204✔
993
          STMT2_ELOG("stmtBuildUidToTableMetaHash taosHashPut failed uid:%" PRIu64 ", code:%s", (uint64_t)pDup->uid,
×
994
                     tstrerror(putCode));
995
          taosMemoryFree(pDup);
×
996
          taosHashCleanup(pHash);
×
997
          return putCode;
×
998
        }
999
      }
1000
    }
1001
  }
1002

1003
  if (taosHashGetSize(pHash) == 0 && pStmt->bInfo.sname.type != 0) {
102✔
1004
    STableMeta* pMeta = NULL;
×
1005
    code = catalogGetTableMeta(pStmt->pCatalog, &conn, &pStmt->bInfo.sname, &pMeta);
×
1006
    if (code == TSDB_CODE_SUCCESS && pMeta != NULL) {
×
1007
      STableMeta* pDup = stmtCloneTableMetaForRetry(pMeta);
×
1008
      taosMemoryFree(pMeta);
×
1009
      pMeta = NULL;
×
1010
      if (pDup != NULL) {
×
1011
        int32_t putCode = taosHashPut(pHash, &pDup->uid, sizeof(uint64_t), &pDup, POINTER_BYTES);
×
1012
        if (putCode != TSDB_CODE_SUCCESS) {
×
1013
          STMT2_ELOG("stmtBuildUidToTableMetaHash taosHashPut failed uid:%" PRIu64 ", code:%s", (uint64_t)pDup->uid,
×
1014
                     tstrerror(putCode));
1015
          taosMemoryFree(pDup);
×
1016
          taosHashCleanup(pHash);
×
1017
          return putCode;
×
1018
        }
1019
      }
1020
    } else if (pMeta != NULL) {
×
1021
      taosMemoryFree(pMeta);
×
1022
    }
1023
  }
1024

1025
  *ppHash = pHash;
102✔
1026
  return TSDB_CODE_SUCCESS;
102✔
1027
}
1028

1029
static int32_t stmtUpdateVgDataBlocksSchemaVer(STscStmt2* pStmt, SRequestObj* pRequest) {
102✔
1030
  if (pStmt->pVgDataBlocksForRetry == NULL || taosArrayGetSize(pStmt->pVgDataBlocksForRetry) == 0) {
102✔
1031
    return TSDB_CODE_SUCCESS;
×
1032
  }
1033

1034
  SHashObj* pUidMetaHash = NULL;
102✔
1035
  int32_t   code = stmtBuildUidToTableMetaHash(pStmt, pRequest, &pUidMetaHash);
102✔
1036
  if (code != TSDB_CODE_SUCCESS) {
102✔
1037
    return code;
×
1038
  }
1039
  if (pUidMetaHash == NULL || taosHashGetSize(pUidMetaHash) == 0) {
102✔
1040
    if (pUidMetaHash != NULL) {
×
1041
      stmtFreeUidTableMetaHash(pUidMetaHash);
×
1042
    }
1043
    return TSDB_CODE_SUCCESS;
×
1044
  }
1045

1046
  const int32_t headSz = (int32_t)sizeof(SSubmitReq2Msg);
102✔
1047
  int32_t       nBlk = (int32_t)taosArrayGetSize(pStmt->pVgDataBlocksForRetry);
102✔
1048

1049
  for (int32_t b = 0; b < nBlk; ++b) {
204✔
1050
    SVgDataBlocks* pVg = *(SVgDataBlocks**)taosArrayGet(pStmt->pVgDataBlocksForRetry, b);
102✔
1051
    if (pVg == NULL || pVg->pData == NULL || pVg->size <= headSz) {
102✔
1052
      continue;
×
1053
    }
1054

1055
    SDecoder    decoder = {0};
102✔
1056
    int32_t     bodyLen = pVg->size - headSz;
102✔
1057
    SSubmitReq2 req = {0};
102✔
1058

1059
    tDecoderInit(&decoder, (uint8_t*)pVg->pData + headSz, bodyLen);
102✔
1060
    code = tDecodeSubmitReq(&decoder, &req, NULL);
102✔
1061
    tDecoderClear(&decoder);
102✔
1062
    if (code != TSDB_CODE_SUCCESS) {
102✔
1063
      STMT2_ELOG("tDecodeSubmitReq failed when patching schema ver for retry, code:%s", tstrerror(code));
×
1064
      stmtFreeUidTableMetaHash(pUidMetaHash);
×
1065
      return code;
×
1066
    }
1067
    if (req.raw) {
102✔
1068
      tDestroySubmitReq(&req, TSDB_MSG_FLG_DECODE);
×
1069
      continue;
×
1070
    }
1071

1072
    SArray* aHeapRows = taosArrayInit(8, POINTER_BYTES);
102✔
1073
    if (aHeapRows == NULL) {
102✔
1074
      tDestroySubmitReq(&req, TSDB_MSG_FLG_DECODE);
×
1075
      stmtFreeUidTableMetaHash(pUidMetaHash);
×
1076
      return terrno;
×
1077
    }
1078

1079
    int32_t nTb = (int32_t)taosArrayGetSize(req.aSubmitTbData);
102✔
1080
    for (int32_t t = 0; t < nTb; ++t) {
204✔
1081
      stmtPatchOneSubmitTbDataSchemaVer(taosArrayGet(req.aSubmitTbData, t), pUidMetaHash, aHeapRows);
102✔
1082
    }
1083

1084
    int32_t encCap = 0;
102✔
1085
    int32_t szRet = 0;
102✔
1086
    tEncodeSize(tEncodeSubmitReq, &req, encCap, szRet);
102✔
1087
    if (szRet != 0) {
102✔
1088
      stmtFreeHeapPatchRowsArray(aHeapRows);
×
1089
      tDestroySubmitReq(&req, TSDB_MSG_FLG_DECODE);
×
1090
      stmtFreeUidTableMetaHash(pUidMetaHash);
×
1091
      return TSDB_CODE_INVALID_PARA;
×
1092
    }
1093

1094
    int32_t allocLen = headSz + encCap;
102✔
1095
    void*   pNew = taosMemoryMalloc(allocLen);
102✔
1096
    if (pNew == NULL) {
102✔
1097
      stmtFreeHeapPatchRowsArray(aHeapRows);
×
1098
      tDestroySubmitReq(&req, TSDB_MSG_FLG_DECODE);
×
1099
      stmtFreeUidTableMetaHash(pUidMetaHash);
×
1100
      return terrno;
×
1101
    }
1102

1103
    (void)memcpy(pNew, pVg->pData, headSz);
102✔
1104
    ((SSubmitReq2Msg*)pNew)->header.vgId = htonl(pVg->vg.vgId);
102✔
1105
    ((SSubmitReq2Msg*)pNew)->version = htobe64(1);
102✔
1106

1107
    SEncoder encoder = {0};
102✔
1108
    tEncoderInit(&encoder, (uint8_t*)pNew + headSz, encCap);
102✔
1109
    code = tEncodeSubmitReq(&encoder, &req);
102✔
1110
    int32_t bodyWritten = (int32_t)encoder.pos;
102✔
1111
    tEncoderClear(&encoder);
102✔
1112
    stmtFreeHeapPatchRowsArray(aHeapRows);
102✔
1113
    tDestroySubmitReq(&req, TSDB_MSG_FLG_DECODE);
102✔
1114

1115
    if (code != TSDB_CODE_SUCCESS) {
102✔
1116
      taosMemoryFree(pNew);
×
1117
      stmtFreeUidTableMetaHash(pUidMetaHash);
×
1118
      return code;
×
1119
    }
1120

1121
    int32_t totalLen = headSz + bodyWritten;
102✔
1122
    ((SSubmitReq2Msg*)pNew)->header.contLen = htonl(totalLen);
102✔
1123

1124
    taosMemoryFree(pVg->pData);
102✔
1125
    pVg->pData = pNew;
102✔
1126
    pVg->size = totalLen;
102✔
1127
  }
1128

1129
  stmtFreeUidTableMetaHash(pUidMetaHash);
102✔
1130
  return TSDB_CODE_SUCCESS;
102✔
1131
}
1132

1133
typedef struct SStmtRetryTbPatch {
1134
  uint64_t uid;
1135
  uint64_t suid;
1136
  int32_t  sver;
1137
} SStmtRetryTbPatch;
1138

1139
// After refreshMeta, drop cached tbName->uid from stmt2 interlace bind so insGetStmtTableVgUid refetches from catalog.
1140
static void stmtInvalidateStbInterlaceTableUidCache(STscStmt2* pStmt) {
306✔
1141
  if (pStmt->sql.stbInterlaceMode && pStmt->sql.siInfo.pTableHash != NULL) {
306✔
1142
    tSimpleHashClear(pStmt->sql.siInfo.pTableHash);
306✔
1143
  }
1144
}
306✔
1145

1146
// Super-table catalog meta uses uid == suid (see queryCreateTableMetaFromMsg); that must not be written onto
1147
// child-table SSubmitTbData. Only use child/normal/virtual-child meta here.
1148
static bool stmtRetryTbMetaIsSuperTable(const STableMeta* pMeta) {
408✔
1149
  return (pMeta != NULL && pMeta->tableType == TSDB_SUPER_TABLE);
408✔
1150
}
1151

1152
// Resolve uid/suid/sver for one SSubmitTbData after catalog refresh. tbIdx is the index within this submit req.
1153
static int32_t stmtFetchOneRetryTbMetaPatch(STscStmt2* pStmt, SRequestObj* pRequest, SSubmitTbData* pTb, int32_t tbIdx,
204✔
1154
                                            int32_t nSubmitTb, SStmtRetryTbPatch* pPatch) {
1155
  if (NULL == pStmt->pCatalog) {
204✔
1156
    int32_t c = catalogGetHandle(pStmt->taos->pAppInfo->clusterId, &pStmt->pCatalog);
×
1157
    if (c != TSDB_CODE_SUCCESS) {
×
1158
      return c;
×
1159
    }
1160
  }
1161

1162
  SRequestConnInfo conn = {.pTrans = pStmt->taos->pAppInfo->pTransporter,
204✔
1163
                           .requestId = pRequest->requestId,
204✔
1164
                           .requestObjRefId = pRequest->self,
204✔
1165
                           .mgmtEps = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp)};
204✔
1166

1167
  // 1) Auto-create child: look up by child table name (never use STB-only name without child name).
1168
  if (pTb->pCreateTbReq != NULL && pTb->pCreateTbReq->name != NULL) {
204✔
1169
    SName       nm = {0};
×
1170
    int32_t     nc = TSDB_CODE_SUCCESS;
×
1171
    STableMeta* pMeta = NULL;
×
1172
    if (pStmt->bInfo.sname.type != 0) {
×
1173
      tNameAssign(&nm, &pStmt->bInfo.sname);
×
1174
      nc = tNameAddTbName(&nm, pTb->pCreateTbReq->name, strlen(pTb->pCreateTbReq->name));
×
1175
    } else if (pRequest->tableList != NULL && taosArrayGetSize(pRequest->tableList) > 0) {
×
1176
      SName* p0 = taosArrayGet(pRequest->tableList, 0);
×
1177
      tNameAssign(&nm, p0);
×
1178
      nc = tNameAddTbName(&nm, pTb->pCreateTbReq->name, strlen(pTb->pCreateTbReq->name));
×
1179
    } else {
1180
      STMT2_ELOG_E("retry patch: no db/sname context for createTbReq name");
×
1181
      return TSDB_CODE_TDB_TABLE_NOT_EXIST;
×
1182
    }
1183
    if (nc != TSDB_CODE_SUCCESS) {
×
1184
      return nc;
×
1185
    }
1186
    nc = catalogGetTableMeta(pStmt->pCatalog, &conn, &nm, &pMeta);
×
1187
    if (nc != TSDB_CODE_SUCCESS) {
×
1188
      taosMemoryFreeClear(pMeta);
×
1189
      return nc;
×
1190
    }
1191
    if (pMeta == NULL) {
×
1192
      return TSDB_CODE_INTERNAL_ERROR;
×
1193
    }
1194
    if (stmtRetryTbMetaIsSuperTable(pMeta)) {
×
1195
      taosMemoryFree(pMeta);
×
1196
      STMT2_ELOG_E("retry patch: createTbReq resolved to super table meta (unexpected)");
×
1197
      return TSDB_CODE_TDB_TABLE_NOT_EXIST;
×
1198
    }
1199
    pPatch->uid = pMeta->uid;
×
1200
    pPatch->suid = pMeta->suid;
×
1201
    pPatch->sver = pMeta->sversion;
×
1202
    taosMemoryFree(pMeta);
×
1203
    return TSDB_CODE_SUCCESS;
×
1204
  }
1205

1206
  // 2) request->tableList: align tbIdx with the tbIdx-th non-super-table entry (skip super table names).
1207
  if (pRequest->tableList != NULL) {
204✔
1208
    int32_t nList = (int32_t)taosArrayGetSize(pRequest->tableList);
204✔
1209
    int32_t nonStbOrd = 0;
204✔
1210
    for (int32_t li = 0; li < nList; ++li) {
408✔
1211
      SName*      pName = taosArrayGet(pRequest->tableList, li);
408✔
1212
      STableMeta* pMeta = NULL;
408✔
1213
      int32_t     c = catalogGetTableMeta(pStmt->pCatalog, &conn, pName, &pMeta);
408✔
1214
      if (c != TSDB_CODE_SUCCESS) {
408✔
1215
        taosMemoryFreeClear(pMeta);
×
1216
        return c;
204✔
1217
      }
1218
      if (pMeta == NULL) {
408✔
1219
        return TSDB_CODE_INTERNAL_ERROR;
×
1220
      }
1221
      if (stmtRetryTbMetaIsSuperTable(pMeta)) {
408✔
1222
        taosMemoryFree(pMeta);
204✔
1223
        continue;
204✔
1224
      }
1225
      if (nonStbOrd == tbIdx) {
204✔
1226
        pPatch->uid = pMeta->uid;
204✔
1227
        pPatch->suid = pMeta->suid;
204✔
1228
        pPatch->sver = pMeta->sversion;
204✔
1229
        taosMemoryFree(pMeta);
204✔
1230
        return TSDB_CODE_SUCCESS;
204✔
1231
      }
1232
      taosMemoryFree(pMeta);
×
1233
      nonStbOrd++;
×
1234
    }
1235
  }
1236

1237
  // 3) Single-table statement: bInfo.sname
1238
  if (nSubmitTb == 1 && pStmt->bInfo.sname.type != 0) {
×
1239
    STableMeta* pMeta = NULL;
×
1240
    int32_t     c = catalogGetTableMeta(pStmt->pCatalog, &conn, &pStmt->bInfo.sname, &pMeta);
×
1241
    if (c != TSDB_CODE_SUCCESS) {
×
1242
      taosMemoryFreeClear(pMeta);
×
1243
      return c;
×
1244
    }
1245
    if (pMeta == NULL) {
×
1246
      return TSDB_CODE_INTERNAL_ERROR;
×
1247
    }
1248
    if (stmtRetryTbMetaIsSuperTable(pMeta)) {
×
1249
      taosMemoryFree(pMeta);
×
1250
      STMT2_ELOG_E("retry patch: bInfo.sname resolved to super table meta; need child table name");
×
1251
      return TSDB_CODE_TDB_TABLE_NOT_EXIST;
×
1252
    }
1253
    pPatch->uid = pMeta->uid;
×
1254
    pPatch->suid = pMeta->suid;
×
1255
    pPatch->sver = pMeta->sversion;
×
1256
    taosMemoryFree(pMeta);
×
1257
    return TSDB_CODE_SUCCESS;
×
1258
  }
1259

1260
  STMT2_ELOG("retry patch: cannot resolve catalog meta for submit block (tb idx %d, uid %" PRId64 ")", tbIdx,
×
1261
             (int64_t)pTb->uid);
1262
  return TSDB_CODE_TDB_TABLE_NOT_EXIST;
×
1263
}
1264

1265
// TSDB_CODE_TDB_TABLE_NOT_EXIST: refresh child table uid/suid/sver in serialized submit from catalog.
1266
static int32_t stmtUpdateVgDataBlocksTbMetaFromCatalog(STscStmt2* pStmt, SRequestObj* pRequest) {
204✔
1267
  if (pStmt->pVgDataBlocksForRetry == NULL || taosArrayGetSize(pStmt->pVgDataBlocksForRetry) == 0) {
204✔
1268
    return TSDB_CODE_SUCCESS;
×
1269
  }
1270

1271
  const int32_t headSz = (int32_t)sizeof(SSubmitReq2Msg);
204✔
1272
  int32_t       nBlk = (int32_t)taosArrayGetSize(pStmt->pVgDataBlocksForRetry);
204✔
1273

1274
  for (int32_t b = 0; b < nBlk; ++b) {
408✔
1275
    SVgDataBlocks* pVg = *(SVgDataBlocks**)taosArrayGet(pStmt->pVgDataBlocksForRetry, b);
204✔
1276
    if (pVg == NULL || pVg->pData == NULL || pVg->size <= headSz) {
204✔
1277
      continue;
×
1278
    }
1279

1280
    SDecoder    decoder = {0};
204✔
1281
    int32_t     bodyLen = pVg->size - headSz;
204✔
1282
    SSubmitReq2 req = {0};
204✔
1283
    int32_t     code = 0;
204✔
1284

1285
    tDecoderInit(&decoder, (uint8_t*)pVg->pData + headSz, bodyLen);
204✔
1286
    code = tDecodeSubmitReq(&decoder, &req, NULL);
204✔
1287
    tDecoderClear(&decoder);
204✔
1288
    if (code != TSDB_CODE_SUCCESS) {
204✔
1289
      STMT2_ELOG("tDecodeSubmitReq failed when patching table meta for retry, code:%s", tstrerror(code));
×
1290
      return code;
×
1291
    }
1292
    if (req.raw) {
204✔
1293
      tDestroySubmitReq(&req, TSDB_MSG_FLG_DECODE);
×
1294
      continue;
×
1295
    }
1296

1297
    int32_t nTb = (int32_t)taosArrayGetSize(req.aSubmitTbData);
204✔
1298
    for (int32_t t = 0; t < nTb; ++t) {
408✔
1299
      SStmtRetryTbPatch patch = {0};
204✔
1300
      code = stmtFetchOneRetryTbMetaPatch(pStmt, pRequest, taosArrayGet(req.aSubmitTbData, t), t, nTb, &patch);
204✔
1301
      if (code != TSDB_CODE_SUCCESS) {
204✔
1302
        tDestroySubmitReq(&req, TSDB_MSG_FLG_DECODE);
×
1303
        return code;
×
1304
      }
1305
      SSubmitTbData* pRow = taosArrayGet(req.aSubmitTbData, t);
204✔
1306
      pRow->uid = (int64_t)patch.uid;
204✔
1307
      pRow->suid = (int64_t)patch.suid;
204✔
1308
      pRow->sver = patch.sver;
204✔
1309
    }
1310

1311
    int32_t encCap = 0;
204✔
1312
    int32_t szRet = 0;
204✔
1313
    tEncodeSize(tEncodeSubmitReq, &req, encCap, szRet);
204✔
1314
    if (szRet != 0) {
204✔
1315
      tDestroySubmitReq(&req, TSDB_MSG_FLG_DECODE);
×
1316
      return TSDB_CODE_INVALID_PARA;
×
1317
    }
1318

1319
    int32_t allocLen = headSz + encCap;
204✔
1320
    void*   pNew = taosMemoryMalloc(allocLen);
204✔
1321
    if (pNew == NULL) {
204✔
1322
      tDestroySubmitReq(&req, TSDB_MSG_FLG_DECODE);
×
1323
      return terrno;
×
1324
    }
1325

1326
    (void)memcpy(pNew, pVg->pData, headSz);
204✔
1327
    ((SSubmitReq2Msg*)pNew)->header.vgId = htonl(pVg->vg.vgId);
204✔
1328
    ((SSubmitReq2Msg*)pNew)->version = htobe64(1);
204✔
1329

1330
    SEncoder encoder = {0};
204✔
1331
    tEncoderInit(&encoder, (uint8_t*)pNew + headSz, encCap);
204✔
1332
    code = tEncodeSubmitReq(&encoder, &req);
204✔
1333
    int32_t bodyWritten = (int32_t)encoder.pos;
204✔
1334
    tEncoderClear(&encoder);
204✔
1335
    tDestroySubmitReq(&req, TSDB_MSG_FLG_DECODE);
204✔
1336

1337
    if (code != TSDB_CODE_SUCCESS) {
204✔
1338
      taosMemoryFree(pNew);
×
1339
      return code;
×
1340
    }
1341

1342
    int32_t totalLen = headSz + bodyWritten;
204✔
1343
    ((SSubmitReq2Msg*)pNew)->header.contLen = htonl(totalLen);
204✔
1344

1345
    taosMemoryFree(pVg->pData);
204✔
1346
    pVg->pData = pNew;
204✔
1347
    pVg->size = totalLen;
204✔
1348
  }
1349

1350
  return TSDB_CODE_SUCCESS;
204✔
1351
}
1352

1353
static bool stmtIsSchemaVersionRetryError(int32_t err) {
102✔
1354
  return (bool)(NEED_CLIENT_REFRESH_TBLMETA_ERROR(err) || err == TSDB_CODE_TDB_IVD_TB_SCHEMA_VERSION);
102✔
1355
}
1356

1357
static void stmtFreeTbBuf(void* buf) {
18,996✔
1358
  void* pBuf = *(void**)buf;
18,996✔
1359
  taosMemoryFree(pBuf);
18,996✔
1360
}
18,996✔
1361

1362
static void stmtFreeTbCols(void* buf) {
9,515,000✔
1363
  SArray* pCols = *(SArray**)buf;
9,515,000✔
1364
  taosArrayDestroy(pCols);
9,515,000✔
1365
}
9,515,000✔
1366

1367
static int32_t stmtCleanSQLInfo(STscStmt2* pStmt) {
179,685✔
1368
  STMT2_TLOG_E("start to free SQL info");
179,685✔
1369

1370
  taosMemoryFree(pStmt->sql.pBindInfo);
179,685✔
1371
  taosMemoryFree(pStmt->sql.queryRes.fields);
179,933✔
1372
  taosMemoryFree(pStmt->sql.queryRes.userFields);
179,933✔
1373
  taosMemoryFree(pStmt->sql.sqlStr);
179,873✔
1374
  qDestroyQuery(pStmt->sql.pQuery);
179,813✔
1375
  taosArrayDestroy(pStmt->sql.nodeList);
179,848✔
1376
  taosHashCleanup(pStmt->sql.pVgHash);
179,908✔
1377
  pStmt->sql.pVgHash = NULL;
179,933✔
1378
  if (pStmt->sql.fixValueTags) {
179,933✔
1379
    pStmt->sql.fixValueTags = false;
1,820✔
1380
    tdDestroySVCreateTbReq(pStmt->sql.fixValueTbReq);
1,820✔
1381
    taosMemoryFreeClear(pStmt->sql.fixValueTbReq);
1,820✔
1382
    pStmt->sql.fixValueTbReq = NULL;
1,820✔
1383
  }
1384

1385
  void* pIter = taosHashIterate(pStmt->sql.pTableCache, NULL);
179,933✔
1386
  while (pIter) {
192,615✔
1387
    SStmtTableCache* pCache = (SStmtTableCache*)pIter;
12,746✔
1388

1389
    qDestroyStmtDataBlock(pCache->pDataCtx);
12,746✔
1390
    qDestroyBoundColInfo(pCache->boundTags);
12,694✔
1391
    taosMemoryFreeClear(pCache->boundTags);
12,746✔
1392

1393
    pIter = taosHashIterate(pStmt->sql.pTableCache, pIter);
12,746✔
1394
  }
1395
  taosHashCleanup(pStmt->sql.pTableCache);
179,869✔
1396
  pStmt->sql.pTableCache = NULL;
179,933✔
1397

1398
  STMT_ERR_RET(stmtCleanExecInfo(pStmt, false, true));
179,933✔
1399
  STMT_ERR_RET(stmtCleanBindInfo(pStmt));
179,848✔
1400
  stmtFreeVgDataBlocksForRetry(pStmt);
179,908✔
1401

1402
  taos_free_result(pStmt->sql.siInfo.pRequest);
179,848✔
1403
  taosHashCleanup(pStmt->sql.siInfo.pVgroupHash);
179,933✔
1404
  tSimpleHashCleanup(pStmt->sql.siInfo.pTableHash);
179,933✔
1405
  tSimpleHashCleanup(pStmt->sql.siInfo.pTableRowDataHash);
179,873✔
1406
  taosArrayDestroyEx(pStmt->sql.siInfo.tbBuf.pBufList, stmtFreeTbBuf);
179,873✔
1407
  taosMemoryFree(pStmt->sql.siInfo.pTSchema);
179,873✔
1408
  qDestroyStmtDataBlock(pStmt->sql.siInfo.pDataCtx);
179,873✔
1409
  taosArrayDestroyEx(pStmt->sql.siInfo.pTableCols, stmtFreeTbCols);
179,873✔
1410
  pStmt->sql.siInfo.pTableCols = NULL;
179,873✔
1411

1412
  (void)memset(&pStmt->sql, 0, sizeof(pStmt->sql));
179,933✔
1413
  pStmt->sql.siInfo.tableColsReady = true;
179,908✔
1414

1415
  STMT2_TLOG_E("end to free SQL info");
179,788✔
1416

1417
  return TSDB_CODE_SUCCESS;
179,788✔
1418
}
1419

1420
static int32_t stmtTryAddTableVgroupInfo(STscStmt2* pStmt, int32_t* vgId) {
686,965✔
1421
  if (*vgId >= 0 && taosHashGet(pStmt->sql.pVgHash, (const char*)vgId, sizeof(*vgId))) {
686,965✔
1422
    return TSDB_CODE_SUCCESS;
30,438✔
1423
  }
1424

1425
  SVgroupInfo      vgInfo = {0};
656,527✔
1426
  SRequestConnInfo conn = {.pTrans = pStmt->taos->pAppInfo->pTransporter,
656,527✔
1427
                           .requestId = pStmt->exec.pRequest->requestId,
656,527✔
1428
                           .requestObjRefId = pStmt->exec.pRequest->self,
656,527✔
1429
                           .mgmtEps = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp)};
656,527✔
1430

1431
  int32_t code = catalogGetTableHashVgroup(pStmt->pCatalog, &conn, &pStmt->bInfo.sname, &vgInfo);
656,783✔
1432
  if (TSDB_CODE_SUCCESS != code) {
656,755✔
1433
    STMT2_ELOG("fail to get vgroup info from catalog, code:%d", code);
×
1434
    return code;
×
1435
  }
1436

1437
  code =
1438
      taosHashPut(pStmt->sql.pVgHash, (const char*)&vgInfo.vgId, sizeof(vgInfo.vgId), (char*)&vgInfo, sizeof(vgInfo));
656,755✔
1439
  if (TSDB_CODE_SUCCESS != code) {
656,701✔
1440
    STMT2_ELOG("fail to put vgroup info, code:%d", code);
×
1441
    return code;
×
1442
  }
1443

1444
  *vgId = vgInfo.vgId;
656,728✔
1445

1446
  return TSDB_CODE_SUCCESS;
656,728✔
1447
}
1448

1449
int32_t stmtGetTableMetaAndValidate(STscStmt2* pStmt, uint64_t* uid, uint64_t* suid, int32_t* vgId, int8_t* tableType) {
49,038✔
1450
  STableMeta*      pTableMeta = NULL;
49,038✔
1451
  SRequestConnInfo conn = {.pTrans = pStmt->taos->pAppInfo->pTransporter,
49,038✔
1452
                           .requestId = pStmt->exec.pRequest->requestId,
49,038✔
1453
                           .requestObjRefId = pStmt->exec.pRequest->self,
49,038✔
1454
                           .mgmtEps = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp)};
49,038✔
1455
  int32_t          code = catalogGetTableMeta(pStmt->pCatalog, &conn, &pStmt->bInfo.sname, &pTableMeta);
49,050✔
1456

1457
  pStmt->stat.ctgGetTbMetaNum++;
49,050✔
1458

1459
  if (TSDB_CODE_PAR_TABLE_NOT_EXIST == code) {
49,050✔
1460
    STMT2_ELOG("tb %s not exist", pStmt->bInfo.tbFName);
510✔
1461
    (void)stmtCleanBindInfo(pStmt);
510✔
1462

1463
    if (!pStmt->sql.autoCreateTbl) {
510✔
1464
      STMT2_ELOG("table %s does not exist and autoCreateTbl is disabled", pStmt->bInfo.tbFName);
510✔
1465
      STMT_ERR_RET(TSDB_CODE_PAR_TABLE_NOT_EXIST);
510✔
1466
    }
1467

1468
    STMT_ERR_RET(code);
×
1469
  }
1470

1471
  STMT_ERR_RET(code);
48,540✔
1472

1473
  *uid = pTableMeta->uid;
48,540✔
1474
  *suid = pTableMeta->suid;
48,540✔
1475
  *tableType = pTableMeta->tableType;
48,540✔
1476
  pStmt->bInfo.tbVgId = pTableMeta->vgId;
48,540✔
1477
  *vgId = pTableMeta->vgId;
48,540✔
1478

1479
  taosMemoryFree(pTableMeta);
48,540✔
1480

1481
  return TSDB_CODE_SUCCESS;
48,540✔
1482
}
1483

1484
static int32_t stmtRebuildDataBlock(STscStmt2* pStmt, STableDataCxt* pDataBlock, STableDataCxt** newBlock, uint64_t uid,
39,147✔
1485
                                    uint64_t suid, int32_t vgId) {
1486
  STMT_ERR_RET(stmtTryAddTableVgroupInfo(pStmt, &vgId));
39,147✔
1487
  STMT_ERR_RET(qRebuildStmtDataBlock(newBlock, pDataBlock, uid, suid, vgId, pStmt->sql.autoCreateTbl));
39,147✔
1488

1489
  STMT2_DLOG("uid:%" PRId64 ", rebuild table data context, vgId:%d", uid, vgId);
39,147✔
1490

1491
  return TSDB_CODE_SUCCESS;
39,147✔
1492
}
1493

1494
static int32_t stmtGetFromCache(STscStmt2* pStmt) {
65,752✔
1495
  if (pStmt->sql.stbInterlaceMode && pStmt->sql.siInfo.pDataCtx) {
65,752✔
1496
    pStmt->bInfo.needParse = false;
×
1497
    pStmt->bInfo.inExecCache = false;
×
1498
    return TSDB_CODE_SUCCESS;
×
1499
  }
1500

1501
  pStmt->bInfo.needParse = true;
65,978✔
1502
  pStmt->bInfo.inExecCache = false;
65,978✔
1503

1504
  STableDataCxt** pCxtInExec = taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
65,918✔
1505
  if (pCxtInExec) {
65,955✔
1506
    pStmt->bInfo.needParse = false;
3,570✔
1507
    pStmt->bInfo.inExecCache = true;
3,570✔
1508

1509
    pStmt->exec.pCurrBlock = *pCxtInExec;
3,570✔
1510

1511
    if (pStmt->sql.autoCreateTbl) {
3,570✔
1512
      STMT2_DLOG("reuse stmt block for tb %s in execBlock", pStmt->bInfo.tbFName);
3,060✔
1513
      return TSDB_CODE_SUCCESS;
3,060✔
1514
    }
1515
  }
1516

1517
  if (NULL == pStmt->pCatalog) {
62,895✔
1518
    STMT_ERR_RET(catalogGetHandle(pStmt->taos->pAppInfo->clusterId, &pStmt->pCatalog));
20,509✔
1519
    pStmt->sql.siInfo.pCatalog = pStmt->pCatalog;
20,518✔
1520
  }
1521

1522
  if (NULL == pStmt->sql.pTableCache || taosHashGetSize(pStmt->sql.pTableCache) <= 0) {
62,840✔
1523
    if (pStmt->bInfo.inExecCache) {
23,090✔
1524
      pStmt->bInfo.needParse = false;
×
1525
      STMT2_DLOG("reuse stmt block for tb %s in execBlock", pStmt->bInfo.tbFName);
×
1526
      return TSDB_CODE_SUCCESS;
×
1527
    }
1528

1529
    STMT2_DLOG("no stmt block cache for tb %s", pStmt->bInfo.tbFName);
23,143✔
1530

1531
    return TSDB_CODE_SUCCESS;
23,023✔
1532
  }
1533

1534
  if (pStmt->sql.autoCreateTbl) {
39,759✔
1535
    SStmtTableCache* pCache = taosHashGet(pStmt->sql.pTableCache, &pStmt->bInfo.tbSuid, sizeof(pStmt->bInfo.tbSuid));
6,282✔
1536
    if (pCache) {
6,282✔
1537
      pStmt->bInfo.needParse = false;
6,282✔
1538
      pStmt->bInfo.tbUid = 0;
6,282✔
1539

1540
      STableDataCxt* pNewBlock = NULL;
6,282✔
1541
      STMT_ERR_RET(stmtRebuildDataBlock(pStmt, pCache->pDataCtx, &pNewBlock, 0, pStmt->bInfo.tbSuid, -1));
6,282✔
1542

1543
      if (taosHashPut(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName), &pNewBlock,
6,282✔
1544
                      POINTER_BYTES)) {
1545
        STMT_ERR_RET(terrno);
×
1546
      }
1547

1548
      pStmt->exec.pCurrBlock = pNewBlock;
6,282✔
1549

1550
      STMT2_DLOG("reuse stmt block for tb %s in sqlBlock, suid:0x%" PRIx64, pStmt->bInfo.tbFName, pStmt->bInfo.tbSuid);
6,282✔
1551

1552
      return TSDB_CODE_SUCCESS;
6,282✔
1553
    }
1554

1555
    STMT_RET(stmtCleanBindInfo(pStmt));
×
1556
  }
1557

1558
  uint64_t uid, suid;
31,641✔
1559
  int32_t  vgId;
31,641✔
1560
  int8_t   tableType;
31,641✔
1561

1562
  STMT_ERR_RET(stmtGetTableMetaAndValidate(pStmt, &uid, &suid, &vgId, &tableType));
33,477✔
1563

1564
  uint64_t cacheUid = (TSDB_CHILD_TABLE == tableType) ? suid : uid;
33,375✔
1565

1566
  if (uid == pStmt->bInfo.tbUid) {
33,375✔
1567
    pStmt->bInfo.needParse = false;
×
1568

1569
    STMT2_DLOG("tb %s is current table", pStmt->bInfo.tbFName);
×
1570

1571
    return TSDB_CODE_SUCCESS;
×
1572
  }
1573

1574
  if (pStmt->bInfo.inExecCache) {
33,375✔
1575
    SStmtTableCache* pCache = taosHashGet(pStmt->sql.pTableCache, &cacheUid, sizeof(cacheUid));
510✔
1576
    if (NULL == pCache) {
510✔
1577
      STMT2_ELOG("table [%s, %" PRIx64 ", %" PRIx64 "] found in exec blockHash, but not in sql blockHash",
×
1578
                 pStmt->bInfo.tbFName, uid, cacheUid);
1579

1580
      STMT_ERR_RET(TSDB_CODE_APP_ERROR);
×
1581
    }
1582

1583
    pStmt->bInfo.needParse = false;
510✔
1584

1585
    pStmt->bInfo.tbUid = uid;
510✔
1586
    pStmt->bInfo.tbSuid = suid;
510✔
1587
    pStmt->bInfo.tbType = tableType;
510✔
1588
    pStmt->bInfo.boundTags = pCache->boundTags;
510✔
1589
    pStmt->bInfo.tagsCached = true;
510✔
1590

1591
    STMT2_DLOG("tb %s in execBlock list, set to current", pStmt->bInfo.tbFName);
510✔
1592

1593
    return TSDB_CODE_SUCCESS;
510✔
1594
  }
1595

1596
  SStmtTableCache* pCache = taosHashGet(pStmt->sql.pTableCache, &cacheUid, sizeof(cacheUid));
32,865✔
1597
  if (pCache) {
32,865✔
1598
    pStmt->bInfo.needParse = false;
32,865✔
1599

1600
    pStmt->bInfo.tbUid = uid;
32,865✔
1601
    pStmt->bInfo.tbSuid = suid;
32,865✔
1602
    pStmt->bInfo.tbType = tableType;
32,865✔
1603
    pStmt->bInfo.boundTags = pCache->boundTags;
32,865✔
1604
    pStmt->bInfo.tagsCached = true;
32,865✔
1605

1606
    STableDataCxt* pNewBlock = NULL;
32,865✔
1607
    STMT_ERR_RET(stmtRebuildDataBlock(pStmt, pCache->pDataCtx, &pNewBlock, uid, suid, vgId));
32,865✔
1608

1609
    if (taosHashPut(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName), &pNewBlock,
32,865✔
1610
                    POINTER_BYTES)) {
1611
      STMT_ERR_RET(terrno);
×
1612
    }
1613

1614
    pStmt->exec.pCurrBlock = pNewBlock;
32,865✔
1615

1616
    tscDebug("tb %s in sqlBlock list, set to current", pStmt->bInfo.tbFName);
32,865✔
1617

1618
    return TSDB_CODE_SUCCESS;
32,865✔
1619
  }
1620

1621
  STMT_ERR_RET(stmtCleanBindInfo(pStmt));
×
1622

1623
  return TSDB_CODE_SUCCESS;
×
1624
}
1625

1626
static int32_t stmtResetStmt(STscStmt2* pStmt) {
×
1627
  STMT_ERR_RET(stmtCleanSQLInfo(pStmt));
×
1628

1629
  pStmt->sql.pTableCache = taosHashInit(100, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
×
1630
  if (NULL == pStmt->sql.pTableCache) {
×
1631
    STMT2_ELOG("fail to allocate memory for pTableCache in stmtResetStmt:%s", tstrerror(terrno));
×
1632
    STMT_ERR_RET(terrno);
×
1633
  }
1634

1635
  pStmt->sql.status = STMT_INIT;
×
1636

1637
  return TSDB_CODE_SUCCESS;
×
1638
}
1639

1640
static void stmtAsyncOutput(STscStmt2* pStmt, void* param) {
1,844,221✔
1641
  SStmtQNode* pParam = (SStmtQNode*)param;
1,844,221✔
1642

1643
  if (pParam->restoreTbCols) {
1,844,221✔
1644
    for (int32_t i = 0; i < pStmt->sql.siInfo.pTableColsIdx; ++i) {
1,843,832✔
1645
      SArray** p = (SArray**)TARRAY_GET_ELEM(pStmt->sql.siInfo.pTableCols, i);
1,233,757✔
1646
      *p = taosArrayInit(20, POINTER_BYTES);
1,233,757✔
1647
      if (*p == NULL) {
1,233,596✔
1648
        pStmt->errCode = terrno;
1✔
1649
      }
1650
    }
1651
    atomic_store_8((int8_t*)&pStmt->sql.siInfo.tableColsReady, true);
610,135✔
1652
    STMT2_TLOG_E("restore pTableCols finished");
610,151✔
1653
  } else {
1654
    int code = qAppendStmt2TableOutput(pStmt->sql.pQuery, pStmt->sql.pVgHash, &pParam->tblData, pStmt->exec.pCurrBlock,
1,234,044✔
1655
                                       &pStmt->sql.siInfo, pParam->pCreateTbReq);
1656
    // taosMemoryFree(pParam->pTbData);
1657
    if (code != TSDB_CODE_SUCCESS) {
1,233,869✔
1658
      STMT2_ELOG("async append stmt output failed, tbname:%s, err:%s", pParam->tblData.tbName, tstrerror(code));
102✔
1659
      pStmt->errCode = code;
102✔
1660
    }
1661
    (void)atomic_sub_fetch_64(&pStmt->sql.siInfo.tbRemainNum, 1);
1,233,869✔
1662
  }
1663
}
1,844,396✔
1664

1665
static void* stmtBindThreadFunc(void* param) {
19,098✔
1666
  setThreadName("stmt2Bind");
19,098✔
1667

1668
  STscStmt2* pStmt = (STscStmt2*)param;
19,098✔
1669
  STMT2_DLOG_E("stmt2 bind thread started");
19,098✔
1670

1671
  while (true) {
1,844,383✔
1672
    SStmtQNode* asyncParam = NULL;
1,863,481✔
1673

1674
    if (!stmtDequeue(pStmt, &asyncParam)) {
1,863,481✔
1675
      if (pStmt->queue.stopQueue && 0 == atomic_load_64((int64_t*)&pStmt->queue.qRemainNum)) {
18,996✔
1676
        STMT2_DLOG_E("queue is empty and stopQueue is set, thread will exit");
18,996✔
1677
        break;
18,996✔
1678
      }
1679
      continue;
×
1680
    }
1681

1682
    stmtAsyncOutput(pStmt, asyncParam);
1,844,074✔
1683
  }
1684

1685
  STMT2_DLOG_E("stmt2 bind thread stopped");
18,996✔
1686
  return NULL;
18,996✔
1687
}
1688

1689
static int32_t stmtStartBindThread(STscStmt2* pStmt) {
19,098✔
1690
  TdThreadAttr thAttr;
8,967✔
1691
  if (taosThreadAttrInit(&thAttr) != 0) {
19,098✔
1692
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1693
  }
1694
  if (taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE) != 0) {
19,098✔
1695
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1696
  }
1697

1698
  if (taosThreadCreate(&pStmt->bindThread, &thAttr, stmtBindThreadFunc, pStmt) != 0) {
19,098✔
1699
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
1700
    STMT_ERR_RET(terrno);
×
1701
  }
1702

1703
  pStmt->bindThreadInUse = true;
19,098✔
1704

1705
  (void)taosThreadAttrDestroy(&thAttr);
19,098✔
1706
  return TSDB_CODE_SUCCESS;
19,098✔
1707
}
1708

1709
static int32_t stmtInitQueue(STscStmt2* pStmt) {
19,098✔
1710
  (void)taosThreadCondInit(&pStmt->queue.waitCond, NULL);
19,098✔
1711
  (void)taosThreadMutexInit(&pStmt->queue.mutex, NULL);
19,098✔
1712
  STMT_ERR_RET(stmtAllocQNodeFromBuf(&pStmt->sql.siInfo.tbBuf, (void**)&pStmt->queue.head));
38,196✔
1713
  pStmt->queue.tail = pStmt->queue.head;
19,098✔
1714

1715
  return TSDB_CODE_SUCCESS;
19,098✔
1716
}
1717

1718
static int32_t stmtIniAsyncBind(STscStmt2* pStmt) {
179,215✔
1719
  (void)taosThreadCondInit(&pStmt->asyncBindParam.waitCond, NULL);
179,215✔
1720
  (void)taosThreadMutexInit(&pStmt->asyncBindParam.mutex, NULL);
179,215✔
1721
  pStmt->asyncBindParam.asyncBindNum = 0;
179,192✔
1722

1723
  return TSDB_CODE_SUCCESS;
179,461✔
1724
}
1725

1726
static int32_t stmtInitTableBuf(STableBufInfo* pTblBuf) {
19,098✔
1727
  pTblBuf->buffUnit = sizeof(SStmtQNode);
19,098✔
1728
  pTblBuf->buffSize = pTblBuf->buffUnit * 1000;
19,098✔
1729
  pTblBuf->pBufList = taosArrayInit(100, POINTER_BYTES);
19,098✔
1730
  if (NULL == pTblBuf->pBufList) {
19,098✔
1731
    return terrno;
×
1732
  }
1733
  void* buff = taosMemoryMalloc(pTblBuf->buffSize);
19,098✔
1734
  if (NULL == buff) {
19,098✔
1735
    return terrno;
×
1736
  }
1737

1738
  if (taosArrayPush(pTblBuf->pBufList, &buff) == NULL) {
38,196✔
1739
    return terrno;
×
1740
  }
1741

1742
  pTblBuf->pCurBuff = buff;
19,098✔
1743
  pTblBuf->buffIdx = 1;
19,098✔
1744
  pTblBuf->buffOffset = 0;
19,098✔
1745

1746
  return TSDB_CODE_SUCCESS;
19,098✔
1747
}
1748

1749
TAOS_STMT2* stmtInit2(STscObj* taos, TAOS_STMT2_OPTION* pOptions) {
176,221✔
1750
  STscObj*   pObj = (STscObj*)taos;
176,221✔
1751
  STscStmt2* pStmt = NULL;
176,221✔
1752
  int32_t    code = 0;
176,221✔
1753

1754
  pStmt = taosMemoryCalloc(1, sizeof(STscStmt2));
176,221✔
1755
  if (NULL == pStmt) {
176,319✔
1756
    STMT2_ELOG_E("fail to allocate memory for pStmt");
×
1757
    return NULL;
×
1758
  }
1759

1760
  pStmt->sql.pTableCache = taosHashInit(100, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
176,319✔
1761
  if (NULL == pStmt->sql.pTableCache) {
176,237✔
1762
    STMT2_ELOG("fail to allocate memory for pTableCache in stmtInit2:%s", tstrerror(terrno));
×
1763
    taosMemoryFree(pStmt);
×
1764
    return NULL;
×
1765
  }
1766

1767
  pStmt->taos = pObj;
176,237✔
1768
  if (taos->db[0] != '\0') {
176,237✔
1769
    pStmt->db = taosStrdup(taos->db);
167,882✔
1770
  }
1771
  pStmt->bInfo.needParse = true;
175,945✔
1772
  pStmt->sql.status = STMT_INIT;
176,214✔
1773
  pStmt->errCode = TSDB_CODE_SUCCESS;
176,214✔
1774

1775
  if (NULL != pOptions) {
176,214✔
1776
    (void)memcpy(&pStmt->options, pOptions, sizeof(pStmt->options));
172,679✔
1777
    if (pOptions->singleStbInsert && pOptions->singleTableBindOnce) {
172,410✔
1778
      pStmt->stbInterlaceMode = true;
16,161✔
1779
    }
1780

1781
    pStmt->reqid = pOptions->reqid;
172,410✔
1782
  }
1783

1784
  if (pStmt->stbInterlaceMode) {
176,191✔
1785
    pStmt->sql.siInfo.transport = taos->pAppInfo->pTransporter;
16,161✔
1786
    pStmt->sql.siInfo.acctId = taos->acctId;
16,161✔
1787
    pStmt->sql.siInfo.dbname = taos->db;
16,161✔
1788
    pStmt->sql.siInfo.mgmtEpSet = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp);
16,161✔
1789

1790
    pStmt->sql.siInfo.pTableHash = tSimpleHashInit(100, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY));
16,161✔
1791
    if (NULL == pStmt->sql.siInfo.pTableHash) {
16,161✔
1792
      STMT2_ELOG("fail to allocate memory for pTableHash:%s", tstrerror(terrno));
×
1793
      (void)stmtClose2(pStmt);
×
1794
      return NULL;
×
1795
    }
1796

1797
    pStmt->sql.siInfo.pTableRowDataHash = tSimpleHashInit(100, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY));
16,161✔
1798
    if (NULL == pStmt->sql.siInfo.pTableRowDataHash) {
16,161✔
1799
      STMT2_ELOG("fail to allocate memory for pTableRowDataHash:%s", tstrerror(terrno));
×
1800
      (void)stmtClose2(pStmt);
×
1801
      return NULL;
×
1802
    }
1803

1804
    pStmt->sql.siInfo.pTableCols = taosArrayInit(STMT_TABLE_COLS_NUM, POINTER_BYTES);
16,161✔
1805
    if (NULL == pStmt->sql.siInfo.pTableCols) {
16,161✔
1806
      STMT2_ELOG("fail to allocate memory for pTableCols:%s", tstrerror(terrno));
×
1807
      (void)stmtClose2(pStmt);
×
1808
      return NULL;
×
1809
    }
1810

1811
    code = stmtInitTableBuf(&pStmt->sql.siInfo.tbBuf);
16,161✔
1812
    if (TSDB_CODE_SUCCESS == code) {
16,161✔
1813
      code = stmtInitQueue(pStmt);
16,161✔
1814
    }
1815
    if (TSDB_CODE_SUCCESS == code) {
16,161✔
1816
      code = stmtStartBindThread(pStmt);
16,161✔
1817
    }
1818
    if (TSDB_CODE_SUCCESS != code) {
16,161✔
1819
      terrno = code;
×
1820
      STMT2_ELOG("fail to init stmt2 bind thread:%s", tstrerror(code));
×
1821
      (void)stmtClose2(pStmt);
×
1822
      return NULL;
×
1823
    }
1824
  }
1825

1826
  pStmt->sql.siInfo.tableColsReady = true;
176,237✔
1827
  if (pStmt->options.asyncExecFn) {
176,506✔
1828
    if (tsem_init(&pStmt->asyncExecSem, 0, 1) != 0) {
1,326✔
1829
      terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
1830
      STMT2_ELOG("fail to init asyncExecSem:%s", tstrerror(terrno));
×
1831
      (void)stmtClose2(pStmt);
×
1832
      return NULL;
×
1833
    }
1834
  }
1835
  code = stmtIniAsyncBind(pStmt);
176,237✔
1836
  if (TSDB_CODE_SUCCESS != code) {
176,524✔
1837
    terrno = code;
×
1838
    STMT2_ELOG("fail to start init asyncExecSem:%s", tstrerror(code));
×
1839

1840
    (void)stmtClose2(pStmt);
×
1841
    return NULL;
×
1842
  }
1843

1844
  pStmt->execSemWaited = false;
176,524✔
1845

1846
  // STMT_LOG_SEQ(STMT_INIT);
1847

1848
  STMT2_DLOG("stmt2 initialize finished, seqId:%d, db:%s, interlaceMode:%d, asyncExec:%d", pStmt->seqId, pStmt->db,
176,524✔
1849
             pStmt->stbInterlaceMode, pStmt->options.asyncExecFn != NULL);
1850

1851
  return pStmt;
176,278✔
1852
}
1853

1854
static int stmtSetDbName2(TAOS_STMT2* stmt, const char* dbName) {
153,684✔
1855
  STscStmt2* pStmt = (STscStmt2*)stmt;
153,684✔
1856
  if (dbName == NULL || dbName[0] == '\0') {
153,684✔
1857
    STMT2_ELOG_E("dbname in sql is illegal");
×
1858
    return TSDB_CODE_TSC_SQL_SYNTAX_ERROR;
×
1859
  }
1860

1861
  STMT2_DLOG("dbname is specified in sql:%s", dbName);
153,725✔
1862
  if (pStmt->db == NULL || pStmt->db[0] == '\0') {
153,725✔
1863
    taosMemoryFreeClear(pStmt->db);
7,747✔
1864
    STMT2_DLOG("dbname:%s is by sql, not by taosconnect", dbName);
7,747✔
1865
    pStmt->db = taosStrdup(dbName);
7,747✔
1866
    (void)strdequote(pStmt->db);
7,747✔
1867
  }
1868
  STMT_ERR_RET(stmtCreateRequest(pStmt));
153,725✔
1869

1870
  // The SQL statement specifies a database name, overriding the previously specified database
1871
  taosMemoryFreeClear(pStmt->exec.pRequest->pDb);
153,953✔
1872
  pStmt->exec.pRequest->pDb = taosStrdup(dbName);
153,766✔
1873
  (void)strdequote(pStmt->exec.pRequest->pDb);
153,725✔
1874
  if (pStmt->exec.pRequest->pDb == NULL) {
153,766✔
1875
    return terrno;
41✔
1876
  }
1877
  if (pStmt->sql.stbInterlaceMode) {
153,725✔
1878
    pStmt->sql.siInfo.dbname = pStmt->exec.pRequest->pDb;
9,787✔
1879
  }
1880
  return TSDB_CODE_SUCCESS;
153,725✔
1881
}
1882
static int32_t stmtResetStbInterlaceCache(STscStmt2* pStmt) {
2,937✔
1883
  int32_t code = TSDB_CODE_SUCCESS;
2,937✔
1884

1885
  pStmt->sql.siInfo.pTableHash = tSimpleHashInit(100, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY));
2,937✔
1886
  if (NULL == pStmt->sql.siInfo.pTableHash) {
2,937✔
1887
    return terrno;
×
1888
  }
1889

1890
  pStmt->sql.siInfo.pTableRowDataHash = tSimpleHashInit(100, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY));
2,937✔
1891
  if (NULL == pStmt->sql.siInfo.pTableRowDataHash) {
2,937✔
1892
    return terrno;
×
1893
  }
1894

1895
  pStmt->sql.siInfo.pTableCols = taosArrayInit(STMT_TABLE_COLS_NUM, POINTER_BYTES);
2,937✔
1896
  if (NULL == pStmt->sql.siInfo.pTableCols) {
2,937✔
1897
    return terrno;
×
1898
  }
1899

1900
  code = stmtInitTableBuf(&pStmt->sql.siInfo.tbBuf);
2,937✔
1901

1902
  if (TSDB_CODE_SUCCESS == code) {
2,937✔
1903
    code = stmtInitQueue(pStmt);
2,937✔
1904
    pStmt->queue.stopQueue = false;
2,937✔
1905
  }
1906
  if (TSDB_CODE_SUCCESS == code) {
2,937✔
1907
    code = stmtStartBindThread(pStmt);
2,937✔
1908
  }
1909
  if (TSDB_CODE_SUCCESS != code) {
2,937✔
1910
    return code;
×
1911
  }
1912

1913
  return TSDB_CODE_SUCCESS;
2,937✔
1914
}
1915

1916
static int32_t stmtDeepReset(STscStmt2* pStmt) {
3,753✔
1917
  // Save state that needs to be preserved
1918
  char*             db = pStmt->db;
3,753✔
1919
  TAOS_STMT2_OPTION options = pStmt->options;
3,753✔
1920
  uint32_t          reqid = pStmt->reqid;
3,753✔
1921
  bool              stbInterlaceMode = pStmt->stbInterlaceMode;
3,753✔
1922

1923
  pStmt->errCode = 0;
3,753✔
1924

1925
  // Wait for async execution to complete
1926
  if (pStmt->options.asyncExecFn && !pStmt->execSemWaited) {
3,753✔
1927
    if (tsem_wait(&pStmt->asyncExecSem) != 0) {
204✔
1928
      STMT2_ELOG_E("bind param wait asyncExecSem failed");
×
1929
    }
1930
    pStmt->execSemWaited = true;
204✔
1931
  }
1932

1933
  // Stop bind thread if in use (similar to stmtClose2)
1934
  if (stbInterlaceMode && pStmt->bindThreadInUse) {
3,753✔
1935
    while (0 == atomic_load_8((int8_t*)&pStmt->sql.siInfo.tableColsReady)) {
2,937✔
1936
      taosUsleep(1);
×
1937
    }
1938
    (void)taosThreadMutexLock(&pStmt->queue.mutex);
2,937✔
1939
    pStmt->queue.stopQueue = true;
2,937✔
1940
    (void)taosThreadCondSignal(&(pStmt->queue.waitCond));
2,937✔
1941
    (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
2,937✔
1942

1943
    (void)taosThreadJoin(pStmt->bindThread, NULL);
2,937✔
1944
    pStmt->bindThreadInUse = false;
2,937✔
1945
    pStmt->queue.head = NULL;
2,937✔
1946
    pStmt->queue.tail = NULL;
2,937✔
1947
    pStmt->queue.qRemainNum = 0;
2,937✔
1948

1949
    (void)taosThreadCondDestroy(&pStmt->queue.waitCond);
2,937✔
1950
    (void)taosThreadMutexDestroy(&pStmt->queue.mutex);
2,937✔
1951
  }
1952

1953
  // Clean all SQL and execution info (stmtCleanSQLInfo already handles most cleanup)
1954
  pStmt->bInfo.boundColsCached = false;
3,753✔
1955
  if (stbInterlaceMode) {
3,753✔
1956
    pStmt->bInfo.tagsCached = false;
2,937✔
1957
  }
1958
  STMT_ERR_RET(stmtCleanSQLInfo(pStmt));
3,753✔
1959

1960
  // Reinitialize resources (similar to stmtInit2)
1961
  if (stbInterlaceMode) {
3,753✔
1962
    pStmt->sql.siInfo.transport = pStmt->taos->pAppInfo->pTransporter;
2,937✔
1963
    pStmt->sql.siInfo.acctId = pStmt->taos->acctId;
2,937✔
1964
    pStmt->sql.siInfo.dbname = pStmt->taos->db;
2,937✔
1965
    pStmt->sql.siInfo.mgmtEpSet = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp);
2,937✔
1966

1967
    if (NULL == pStmt->pCatalog) {
2,937✔
1968
      STMT_ERR_RET(catalogGetHandle(pStmt->taos->pAppInfo->clusterId, &pStmt->pCatalog));
294✔
1969
    }
1970
    pStmt->sql.siInfo.pCatalog = pStmt->pCatalog;
2,937✔
1971

1972
    STMT_ERR_RET(stmtResetStbInterlaceCache(pStmt));
2,937✔
1973

1974
    int32_t code = stmtIniAsyncBind(pStmt);
2,937✔
1975
    if (TSDB_CODE_SUCCESS != code) {
2,937✔
1976
      STMT2_ELOG("fail to reinit async bind in stmtDeepReset:%s", tstrerror(code));
×
1977
      return code;
×
1978
    }
1979
  }
1980

1981
  // Restore preserved state
1982
  pStmt->db = db;
3,753✔
1983
  pStmt->options = options;
3,753✔
1984
  pStmt->reqid = reqid;
3,753✔
1985
  pStmt->stbInterlaceMode = stbInterlaceMode;
3,753✔
1986

1987
  pStmt->sql.pTableCache = taosHashInit(100, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
3,753✔
1988
  if (NULL == pStmt->sql.pTableCache) {
3,753✔
1989
    STMT2_ELOG("fail to allocate memory for pTableCache in stmtDeepReset:%s", tstrerror(terrno));
×
1990
    return terrno;
×
1991
  }
1992

1993
  pStmt->bInfo.needParse = true;
3,753✔
1994
  pStmt->sql.status = STMT_INIT;
3,753✔
1995
  pStmt->sql.siInfo.tableColsReady = true;
3,753✔
1996

1997
  return TSDB_CODE_SUCCESS;
3,753✔
1998
}
1999

2000
int stmtPrepare2(TAOS_STMT2* stmt, const char* sql, unsigned long length) {
179,711✔
2001
  STscStmt2* pStmt = (STscStmt2*)stmt;
179,711✔
2002
  int32_t    code = 0;
179,711✔
2003

2004
  STMT2_DLOG("start to prepare with sql:%s", sql);
179,711✔
2005

2006
  if (stmt == NULL || sql == NULL) {
179,711✔
2007
    STMT2_ELOG_E("stmt or sql is NULL");
×
2008
    return TSDB_CODE_INVALID_PARA;
×
2009
  }
2010

2011
  if (pStmt->sql.status >= STMT_PREPARE) {
179,827✔
2012
    STMT2_DLOG("stmt status is %d, need to reset stmt2 cache before prepare", pStmt->sql.status);
3,753✔
2013
    STMT_ERR_RET(stmtDeepReset(pStmt));
3,753✔
2014
  }
2015

2016
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
180,055✔
2017
    STMT2_ELOG("errCode is not success before, ErrCode: 0x%x, errorsyt: %s\n. ", pStmt->errCode,
102✔
2018
               tstrerror(pStmt->errCode));
2019
    return pStmt->errCode;
102✔
2020
  }
2021

2022
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_PREPARE));
179,683✔
2023

2024
  if (length <= 0) {
179,766✔
2025
    length = strlen(sql);
171,483✔
2026
  }
2027
  pStmt->sql.sqlStr = taosStrndup(sql, length);
179,766✔
2028
  if (!pStmt->sql.sqlStr) {
179,725✔
2029
    STMT2_ELOG("fail to allocate memory for sqlStr:%s", tstrerror(terrno));
×
2030
    STMT_ERR_RET(terrno);
×
2031
  }
2032
  pStmt->sql.sqlLen = length;
179,725✔
2033
  STMT_ERR_RET(stmtCreateRequest(pStmt));
179,725✔
2034

2035
  if (stmt2IsInsert(pStmt)) {
179,571✔
2036
    pStmt->sql.stbInterlaceMode = pStmt->stbInterlaceMode;
172,400✔
2037
    char* dbName = NULL;
172,340✔
2038
    if (qParseDbName(sql, length, &dbName)) {
172,400✔
2039
      STMT_ERR_RET(stmtSetDbName2(stmt, dbName));
153,725✔
2040
      taosMemoryFreeClear(dbName);
153,848✔
2041
    } else if (pStmt->db != NULL && pStmt->db[0] != '\0') {
18,231✔
2042
      taosMemoryFreeClear(pStmt->exec.pRequest->pDb);
18,210✔
2043
      pStmt->exec.pRequest->pDb = taosStrdup(pStmt->db);
18,209✔
2044
      if (pStmt->exec.pRequest->pDb == NULL) {
18,238✔
2045
        STMT_ERR_RET(terrno);
×
2046
      }
2047
      (void)strdequote(pStmt->exec.pRequest->pDb);
18,145✔
2048

2049
      if (pStmt->sql.stbInterlaceMode) {
18,222✔
2050
        pStmt->sql.siInfo.dbname = pStmt->exec.pRequest->pDb;
6,137✔
2051
      }
2052
    }
2053

2054
  } else if (stmt2IsSelect(pStmt)) {
7,607✔
2055
    pStmt->sql.stbInterlaceMode = false;
7,329✔
2056
    STMT_ERR_RET(stmtParseSql(pStmt));
7,329✔
2057
  } else {
2058
    return stmtBuildErrorMsgWithCode(pStmt, "stmt only support 'SELECT' or 'INSERT'", TSDB_CODE_PAR_SYNTAX_ERROR);
306✔
2059
  }
2060
  return TSDB_CODE_SUCCESS;
178,736✔
2061
}
2062

2063
static int32_t stmtInitStbInterlaceTableInfo(STscStmt2* pStmt) {
9,515✔
2064
  STableDataCxt** pSrc = taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
9,515✔
2065
  if (!pSrc) {
9,515✔
2066
    return terrno;
×
2067
  }
2068
  STableDataCxt* pDst = NULL;
9,515✔
2069

2070
  STMT_ERR_RET(qCloneStmtDataBlock(&pDst, *pSrc, true));
9,515✔
2071
  pStmt->sql.siInfo.pDataCtx = pDst;
9,503✔
2072

2073
  SArray* pTblCols = NULL;
9,503✔
2074
  for (int32_t i = 0; i < STMT_TABLE_COLS_NUM; i++) {
9,483,512✔
2075
    pTblCols = taosArrayInit(20, POINTER_BYTES);
9,474,010✔
2076
    if (NULL == pTblCols) {
9,470,197✔
2077
      return terrno;
×
2078
    }
2079

2080
    if (taosArrayPush(pStmt->sql.siInfo.pTableCols, &pTblCols) == NULL) {
18,938,967✔
2081
      return terrno;
×
2082
    }
2083
  }
2084

2085
  pStmt->sql.siInfo.boundTags = pStmt->bInfo.boundTags;
9,502✔
2086

2087
  STMT2_TLOG("init stb interlace table info, tbName:%s, pDataCtx:%p, boundTags:%p", pStmt->bInfo.tbFName,
9,502✔
2088
             pStmt->sql.siInfo.pDataCtx, pStmt->sql.siInfo.boundTags);
2089

2090
  return TSDB_CODE_SUCCESS;
9,515✔
2091
}
2092

2093
bool stmt2IsInsert(TAOS_STMT2* stmt) {
1,480,657✔
2094
  STscStmt2* pStmt = (STscStmt2*)stmt;
1,480,657✔
2095
  if (pStmt->sql.type) {
1,480,657✔
2096
    return (STMT_TYPE_INSERT == pStmt->sql.type || STMT_TYPE_MULTI_INSERT == pStmt->sql.type);
1,272,927✔
2097
  }
2098

2099
  return qIsInsertValuesSql(pStmt->sql.sqlStr, pStmt->sql.sqlLen);
207,785✔
2100
}
2101

2102
bool stmt2IsSelect(TAOS_STMT2* stmt) {
172,825✔
2103
  STscStmt2* pStmt = (STscStmt2*)stmt;
172,825✔
2104

2105
  if (pStmt->sql.type) {
172,825✔
2106
    return STMT_TYPE_QUERY == pStmt->sql.type;
×
2107
  }
2108
  return qIsSelectFromSql(pStmt->sql.sqlStr, pStmt->sql.sqlLen);
173,363✔
2109
}
2110

2111
int stmtSetTbName2(TAOS_STMT2* stmt, const char* tbName) {
1,290,877✔
2112
  STscStmt2* pStmt = (STscStmt2*)stmt;
1,290,877✔
2113

2114
  int64_t startUs = taosGetTimestampUs();
1,291,102✔
2115

2116
  STMT2_TLOG("start to set tbName:%s", tbName);
1,291,102✔
2117

2118
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
1,291,143✔
2119
    return pStmt->errCode;
×
2120
  }
2121

2122
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_SETTBNAME));
1,291,147✔
2123

2124
  int32_t insert = 0;
1,290,905✔
2125
  if (!stmt2IsInsert(stmt)) {
1,290,905✔
2126
    STMT2_ELOG_E("set tb name not available for no-insert statement");
×
2127
    STMT_ERR_RET(TSDB_CODE_TSC_STMT_API_ERROR);
×
2128
  }
2129
  // process tbname
2130
  STMT_ERR_RET(stmtCreateRequest(pStmt));
1,290,950✔
2131

2132
  STMT_ERR_RET(qCreateSName2(&pStmt->bInfo.sname, tbName, pStmt->taos->acctId, pStmt->exec.pRequest->pDb,
1,290,828✔
2133
                             pStmt->exec.pRequest->msgBuf, pStmt->exec.pRequest->msgBufLen));
2134
  STMT_ERR_RET(tNameExtractFullName(&pStmt->bInfo.sname, pStmt->bInfo.tbFName));
1,290,411✔
2135
  tstrncpy(pStmt->bInfo.tbName, (char*)tNameGetTableName(&pStmt->bInfo.sname), TSDB_TABLE_NAME_LEN);
1,290,335✔
2136

2137
  if (!pStmt->sql.stbInterlaceMode || NULL == pStmt->sql.siInfo.pDataCtx) {
1,290,409✔
2138
    STMT_ERR_RET(stmtGetFromCache(pStmt));
66,477✔
2139

2140
    if (pStmt->bInfo.needParse) {
65,770✔
2141
      STMT_ERR_RET(stmtParseSql(pStmt));
22,994✔
2142
      if (!pStmt->sql.autoCreateTbl) {
22,952✔
2143
        uint64_t uid, suid;
13,210✔
2144
        int32_t  vgId;
13,170✔
2145
        int8_t   tableType;
13,170✔
2146

2147
        int32_t code = stmtGetTableMetaAndValidate(pStmt, &uid, &suid, &vgId, &tableType);
15,515✔
2148
        if (code != TSDB_CODE_SUCCESS) {
15,550✔
2149
          return code;
408✔
2150
        }
2151
      }
2152
    }
2153

2154
  } else {
2155
    pStmt->exec.pRequest->requestId++;
1,224,150✔
2156
    pStmt->bInfo.needParse = false;
1,224,270✔
2157
  }
2158

2159
  if (pStmt->sql.stbInterlaceMode && NULL == pStmt->sql.siInfo.pDataCtx) {
1,289,452✔
2160
    STMT_ERR_RET(stmtInitStbInterlaceTableInfo(pStmt));
9,515✔
2161
  }
2162

2163
  int64_t startUs2 = taosGetTimestampUs();
1,289,836✔
2164
  pStmt->stat.setTbNameUs += startUs2 - startUs;
1,289,836✔
2165

2166
  return TSDB_CODE_SUCCESS;
1,289,821✔
2167
}
2168

2169
int stmtSetTbTags2(TAOS_STMT2* stmt, TAOS_STMT2_BIND* tags, SVCreateTbReq** pCreateTbReq) {
546,981✔
2170
  STscStmt2* pStmt = (STscStmt2*)stmt;
546,981✔
2171

2172
  STMT2_TLOG_E("start to set tbTags");
546,981✔
2173
  if (qDebugFlag & DEBUG_TRACE) {
546,981✔
2174
    (void)stmtPrintBindv(stmt, tags, -1, true);
×
2175
  }
2176

2177
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
546,981✔
2178
    return pStmt->errCode;
×
2179
  }
2180

2181
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_SETTAGS));
546,981✔
2182

2183
  if (pStmt->bInfo.needParse && pStmt->sql.runTimes && pStmt->sql.type > 0 &&
546,994✔
2184
      STMT_TYPE_MULTI_INSERT != pStmt->sql.type) {
×
2185
    pStmt->bInfo.needParse = false;
×
2186
  }
2187
  STMT_ERR_RET(stmtCreateRequest(pStmt));
546,994✔
2188

2189
  if (pStmt->bInfo.needParse) {
546,981✔
2190
    STMT_ERR_RET(stmtParseSql(pStmt));
204✔
2191
  }
2192
  if (pStmt->sql.stbInterlaceMode && NULL == pStmt->sql.siInfo.pDataCtx) {
546,981✔
2193
    STMT_ERR_RET(stmtInitStbInterlaceTableInfo(pStmt));
×
2194
  }
2195

2196
  SBoundColInfo* tags_info = (SBoundColInfo*)pStmt->bInfo.boundTags;
546,994✔
2197

2198
  STableDataCxt** pDataBlock = NULL;
546,994✔
2199
  if (pStmt->exec.pCurrBlock) {
546,994✔
2200
    pDataBlock = &pStmt->exec.pCurrBlock;
541,208✔
2201
  } else {
2202
    pDataBlock =
2203
        (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
5,786✔
2204
    if (NULL == pDataBlock) {
5,786✔
2205
      STMT2_ELOG("table %s not found in exec blockHash:%p", pStmt->bInfo.tbFName, pStmt->exec.pBlockHash);
×
2206
      STMT_ERR_RET(TSDB_CODE_TSC_STMT_CACHE_ERROR);
×
2207
    }
2208
    if (pStmt->sql.stbInterlaceMode && (*pDataBlock)->pData->pCreateTbReq) {
5,786✔
2209
      tdDestroySVCreateTbReq((*pDataBlock)->pData->pCreateTbReq);
204✔
2210
      taosMemoryFreeClear((*pDataBlock)->pData->pCreateTbReq);
204✔
2211
      (*pDataBlock)->pData->pCreateTbReq = NULL;
204✔
2212
    }
2213
  }
2214
  if (pStmt->bInfo.inExecCache && !pStmt->sql.autoCreateTbl) {
546,994✔
2215
    return TSDB_CODE_SUCCESS;
×
2216
  }
2217

2218
  STMT2_TLOG_E("start to bind stmt tag values");
546,994✔
2219

2220
  void* boundTags = NULL;
546,968✔
2221
  if (pStmt->sql.stbInterlaceMode) {
546,968✔
2222
    boundTags = pStmt->sql.siInfo.boundTags;
534,643✔
2223
    *pCreateTbReq = taosMemoryCalloc(1, sizeof(SVCreateTbReq));
534,643✔
2224
    if (NULL == pCreateTbReq) {
534,682✔
2225
      return terrno;
×
2226
    }
2227
    int32_t vgId = -1;
534,682✔
2228
    STMT_ERR_RET(stmtTryAddTableVgroupInfo(pStmt, &vgId));
534,682✔
2229
    (*pCreateTbReq)->uid = vgId;
534,786✔
2230
  } else {
2231
    boundTags = pStmt->bInfo.boundTags;
12,325✔
2232
  }
2233

2234
  STMT_ERR_RET(qBindStmtTagsValue2(*pDataBlock, boundTags, pStmt->bInfo.tbSuid, pStmt->bInfo.stbFName,
547,111✔
2235
                                   pStmt->bInfo.sname.tname, tags, pStmt->exec.pRequest->msgBuf,
2236
                                   pStmt->exec.pRequest->msgBufLen, pStmt->taos->optionInfo.charsetCxt, *pCreateTbReq));
2237

2238
  return TSDB_CODE_SUCCESS;
546,918✔
2239
}
2240

2241
int stmtCheckTags2(TAOS_STMT2* stmt, SVCreateTbReq** pCreateTbReq) {
114,968✔
2242
  STscStmt2* pStmt = (STscStmt2*)stmt;
114,968✔
2243

2244
  STMT2_TLOG_E("start to clone createTbRequest for fixed tags");
114,968✔
2245

2246
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
115,052✔
2247
    return pStmt->errCode;
×
2248
  }
2249

2250
  if (!pStmt->sql.stbInterlaceMode) {
115,052✔
2251
    return TSDB_CODE_SUCCESS;
×
2252
  }
2253

2254
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_SETTAGS));
115,052✔
2255

2256
  if (pStmt->sql.fixValueTags) {
114,982✔
2257
    STMT2_TLOG_E("tags are fixed, use one createTbReq");
113,162✔
2258
    STMT_ERR_RET(cloneSVreateTbReq(pStmt->sql.fixValueTbReq, pCreateTbReq));
113,162✔
2259
    if ((*pCreateTbReq)->name) {
113,204✔
2260
      taosMemoryFree((*pCreateTbReq)->name);
113,204✔
2261
    }
2262
    (*pCreateTbReq)->name = taosStrdup(pStmt->bInfo.tbName);
113,288✔
2263
    int32_t vgId = -1;
113,218✔
2264
    STMT_ERR_RET(stmtTryAddTableVgroupInfo(pStmt, &vgId));
113,218✔
2265
    (*pCreateTbReq)->uid = vgId;
113,260✔
2266
    return TSDB_CODE_SUCCESS;
113,260✔
2267
  }
2268

2269
  STMT_ERR_RET(stmtCreateRequest(pStmt));
1,820✔
2270
  if (pStmt->bInfo.needParse) {
1,820✔
2271
    STMT_ERR_RET(stmtParseSql(pStmt));
×
2272
    if (!pStmt->sql.autoCreateTbl) {
×
2273
      STMT2_WLOG_E("don't need to create table, will not check tags");
×
2274
      return TSDB_CODE_SUCCESS;
×
2275
    }
2276
  }
2277

2278
  if (pStmt->sql.stbInterlaceMode && NULL == pStmt->sql.siInfo.pDataCtx) {
1,820✔
2279
    STMT_ERR_RET(stmtInitStbInterlaceTableInfo(pStmt));
×
2280
  }
2281

2282
  STableDataCxt** pDataBlock = NULL;
1,820✔
2283
  if (pStmt->exec.pCurrBlock) {
1,820✔
2284
    pDataBlock = &pStmt->exec.pCurrBlock;
×
2285
  } else {
2286
    pDataBlock =
2287
        (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
1,820✔
2288
    if (NULL == pDataBlock) {
1,820✔
2289
      STMT2_ELOG("table %s not found in exec blockHash:%p", pStmt->bInfo.tbFName, pStmt->exec.pBlockHash);
×
2290
      STMT_ERR_RET(TSDB_CODE_TSC_STMT_CACHE_ERROR);
×
2291
    }
2292
  }
2293

2294
  if (!((*pDataBlock)->pData->flags & SUBMIT_REQ_AUTO_CREATE_TABLE)) {
1,820✔
2295
    STMT2_DLOG_E("don't need to create, will not check tags");
×
2296
    return TSDB_CODE_SUCCESS;
×
2297
  }
2298

2299
  if ((*pDataBlock)->pData->pCreateTbReq) {
1,820✔
2300
    STMT2_TLOG_E("tags are fixed, set createTbReq first time");
1,820✔
2301
    pStmt->sql.fixValueTags = true;
1,820✔
2302
    STMT_ERR_RET(cloneSVreateTbReq((*pDataBlock)->pData->pCreateTbReq, &pStmt->sql.fixValueTbReq));
1,820✔
2303
    STMT_ERR_RET(cloneSVreateTbReq(pStmt->sql.fixValueTbReq, pCreateTbReq));
1,820✔
2304
    (*pCreateTbReq)->uid = (*pDataBlock)->pMeta->vgId;
1,820✔
2305

2306
    // destroy the createTbReq in the data block
2307
    tdDestroySVCreateTbReq((*pDataBlock)->pData->pCreateTbReq);
1,820✔
2308
    taosMemoryFreeClear((*pDataBlock)->pData->pCreateTbReq);
1,820✔
2309
    (*pDataBlock)->pData->pCreateTbReq = NULL;
1,820✔
2310
  }
2311

2312
  return TSDB_CODE_SUCCESS;
1,820✔
2313
}
2314

2315
static int stmtFetchColFields2(STscStmt2* pStmt, int32_t* fieldNum, TAOS_FIELD_E** fields) {
×
2316
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
×
2317
    return pStmt->errCode;
×
2318
  }
2319

2320
  if (STMT_TYPE_QUERY == pStmt->sql.type) {
×
2321
    tscError("invalid operation to get query column fileds");
×
2322
    STMT_ERR_RET(TSDB_CODE_TSC_STMT_API_ERROR);
×
2323
  }
2324

2325
  STableDataCxt** pDataBlock = NULL;
×
2326

2327
  if (pStmt->sql.stbInterlaceMode) {
×
2328
    pDataBlock = &pStmt->sql.siInfo.pDataCtx;
×
2329
  } else {
2330
    pDataBlock =
2331
        (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
×
2332
    if (NULL == pDataBlock) {
×
2333
      STMT2_ELOG("table %s not found in exec blockHash:%p", pStmt->bInfo.tbFName, pStmt->exec.pBlockHash);
×
2334
      STMT_ERR_RET(TSDB_CODE_APP_ERROR);
×
2335
    }
2336
  }
2337

2338
  STMT_ERR_RET(qBuildStmtColFields(*pDataBlock, fieldNum, fields));
×
2339

2340
  return TSDB_CODE_SUCCESS;
×
2341
}
2342

2343
static int stmtFetchStbColFields2(STscStmt2* pStmt, int32_t* fieldNum, TAOS_FIELD_ALL** fields) {
5,533✔
2344
  int32_t code = 0;
5,533✔
2345
  int32_t preCode = pStmt->errCode;
5,533✔
2346

2347
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
5,533✔
2348
    return pStmt->errCode;
×
2349
  }
2350

2351
  if (STMT_TYPE_QUERY == pStmt->sql.type) {
5,533✔
2352
    STMT2_ELOG_E("stmtFetchStbColFields2 only for insert statement");
×
2353
    STMT_ERRI_JRET(TSDB_CODE_TSC_STMT_API_ERROR);
×
2354
  }
2355

2356
  STableDataCxt** pDataBlock = NULL;
5,533✔
2357
  bool            cleanStb = false;
5,533✔
2358

2359
  if (pStmt->sql.stbInterlaceMode && pStmt->sql.siInfo.pDataCtx != NULL) {
5,533✔
2360
    pDataBlock = &pStmt->sql.siInfo.pDataCtx;
612✔
2361
  } else {
2362
    cleanStb = true;
4,921✔
2363
    pDataBlock =
2364
        (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
4,921✔
2365
  }
2366

2367
  if (NULL == pDataBlock || NULL == *pDataBlock) {
5,533✔
2368
    STMT2_ELOG("table %s not found in exec blockHash:%p", pStmt->bInfo.tbFName, pStmt->exec.pBlockHash);
×
2369
    STMT_ERRI_JRET(TSDB_CODE_APP_ERROR);
×
2370
  }
2371

2372
  pStmt->sql.placeholderOfTags = 0;
5,533✔
2373
  pStmt->sql.placeholderOfCols = 0;
5,533✔
2374
  int32_t totalNum = 0;
5,533✔
2375
  STMT_ERRI_JRET(qBuildStmtStbColFields(*pDataBlock, pStmt->bInfo.boundTags, pStmt->bInfo.fixedValueCols,
5,533✔
2376
                                        pStmt->bInfo.tbNameFlag, &totalNum, fields, &pStmt->sql.placeholderOfTags,
2377
                                        &pStmt->sql.placeholderOfCols));
2378

2379
  if (pStmt->bInfo.tbType == TSDB_SUPER_TABLE && cleanStb) {
5,533✔
2380
    taosMemoryFreeClear((*pDataBlock)->boundColsInfo.pColIndex);
3,901✔
2381
    qDestroyStmtDataBlock(*pDataBlock);
3,901✔
2382
    *pDataBlock = NULL;
3,901✔
2383
    if (taosHashRemove(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName)) != 0) {
3,901✔
2384
      STMT2_ELOG("fail to remove remove stb:%s exec blockHash", pStmt->bInfo.tbFName);
×
2385
      STMT_ERRI_JRET(TSDB_CODE_APP_ERROR);
×
2386
    }
2387
    pStmt->sql.autoCreateTbl = false;
3,901✔
2388
    pStmt->bInfo.tagsCached = false;
3,901✔
2389
    pStmt->bInfo.sname = (SName){0};
3,901✔
2390
    STMT_ERR_RET(stmtCleanBindInfo(pStmt));
3,901✔
2391
  }
2392

2393
  if (fieldNum != NULL) {
5,533✔
2394
    *fieldNum = totalNum;
5,533✔
2395
  }
2396

2397
  STMT2_DLOG("get insert fields totalNum:%d, tagsNum:%d, colsNum:%d", totalNum, pStmt->sql.placeholderOfTags,
5,533✔
2398
             pStmt->sql.placeholderOfCols);
2399

2400
_return:
5,533✔
2401

2402
  pStmt->errCode = preCode;
5,533✔
2403

2404
  return code;
5,533✔
2405
}
2406
/*
2407
SArray* stmtGetFreeCol(STscStmt2* pStmt, int32_t* idx) {
2408
  while (true) {
2409
    if (pStmt->exec.smInfo.pColIdx >= STMT_COL_BUF_SIZE) {
2410
      pStmt->exec.smInfo.pColIdx = 0;
2411
    }
2412

2413
    if ((pStmt->exec.smInfo.pColIdx + 1) == atomic_load_32(&pStmt->exec.smInfo.pColFreeIdx)) {
2414
      taosUsleep(1);
2415
      continue;
2416
    }
2417

2418
    *idx = pStmt->exec.smInfo.pColIdx;
2419
    return pStmt->exec.smInfo.pCols[pStmt->exec.smInfo.pColIdx++];
2420
  }
2421
}
2422
*/
2423
static int32_t stmtAppendTablePostHandle(STscStmt2* pStmt, SStmtQNode* param) {
1,233,681✔
2424
  if (NULL == pStmt->sql.siInfo.pVgroupHash) {
1,233,681✔
2425
    pStmt->sql.siInfo.pVgroupHash =
610,483✔
2426
        taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_ENTRY_LOCK);
610,271✔
2427
  }
2428
  if (NULL == pStmt->sql.siInfo.pVgroupList) {
1,234,377✔
2429
    pStmt->sql.siInfo.pVgroupList = taosArrayInit(64, POINTER_BYTES);
610,444✔
2430
  }
2431

2432
  if (NULL == pStmt->sql.siInfo.pRequest) {
1,234,269✔
2433
    STMT_ERR_RET(buildRequest(pStmt->taos->id, pStmt->sql.sqlStr, pStmt->sql.sqlLen, NULL, false,
9,311✔
2434
                              (SRequestObj**)&pStmt->sql.siInfo.pRequest, pStmt->reqid));
2435

2436
    if (pStmt->reqid != 0) {
9,311✔
2437
      pStmt->reqid++;
10✔
2438
    }
2439
    pStmt->exec.pRequest->syncQuery = true;
9,311✔
2440

2441
    pStmt->sql.siInfo.requestId = ((SRequestObj*)pStmt->sql.siInfo.pRequest)->requestId;
9,311✔
2442
    pStmt->sql.siInfo.requestSelf = ((SRequestObj*)pStmt->sql.siInfo.pRequest)->self;
9,311✔
2443
  }
2444

2445
  if (!pStmt->sql.siInfo.tbFromHash && pStmt->sql.siInfo.firstName[0] &&
1,234,269✔
2446
      0 == strcmp(pStmt->sql.siInfo.firstName, pStmt->bInfo.tbName)) {
34,230✔
2447
    pStmt->sql.siInfo.tbFromHash = true;
4,045✔
2448
  }
2449

2450
  if (0 == pStmt->sql.siInfo.firstName[0]) {
1,234,144✔
2451
    tstrncpy(pStmt->sql.siInfo.firstName, pStmt->bInfo.tbName, TSDB_TABLE_NAME_LEN);
9,311✔
2452
  }
2453

2454
  param->tblData.getFromHash = pStmt->sql.siInfo.tbFromHash;
1,234,269✔
2455
  param->next = NULL;
1,234,269✔
2456

2457
  (void)atomic_add_fetch_64(&pStmt->sql.siInfo.tbRemainNum, 1);
1,234,204✔
2458

2459
  if (pStmt->queue.stopQueue) {
1,234,258✔
2460
    STMT2_ELOG_E("bind thread already stopped, cannot enqueue");
×
2461
    return TSDB_CODE_TSC_STMT_API_ERROR;
×
2462
  }
2463
  stmtEnqueue(pStmt, param);
1,234,193✔
2464

2465
  return TSDB_CODE_SUCCESS;
1,234,206✔
2466
}
2467

2468
static FORCE_INLINE int32_t stmtGetTableColsFromCache(STscStmt2* pStmt, SArray** pTableCols) {
2469
  while (true) {
2470
    if (pStmt->sql.siInfo.pTableColsIdx < taosArrayGetSize(pStmt->sql.siInfo.pTableCols)) {
1,234,001✔
2471
      *pTableCols = (SArray*)taosArrayGetP(pStmt->sql.siInfo.pTableCols, pStmt->sql.siInfo.pTableColsIdx++);
1,234,102✔
2472
      break;
1,234,084✔
2473
    } else {
2474
      SArray* pTblCols = NULL;
×
2475
      for (int32_t i = 0; i < 100; i++) {
×
2476
        pTblCols = taosArrayInit(20, POINTER_BYTES);
×
2477
        if (NULL == pTblCols) {
×
2478
          return terrno;
×
2479
        }
2480

2481
        if (taosArrayPush(pStmt->sql.siInfo.pTableCols, &pTblCols) == NULL) {
×
2482
          return terrno;
×
2483
        }
2484
      }
2485
    }
2486
  }
2487

2488
  return TSDB_CODE_SUCCESS;
1,234,084✔
2489
}
2490

2491
static int32_t stmtCacheBlock(STscStmt2* pStmt) {
212,699✔
2492
  if (pStmt->sql.type != STMT_TYPE_MULTI_INSERT) {
212,699✔
2493
    return TSDB_CODE_SUCCESS;
157,236✔
2494
  }
2495

2496
  uint64_t uid = pStmt->bInfo.tbUid;
55,463✔
2497
  uint64_t cacheUid = (TSDB_CHILD_TABLE == pStmt->bInfo.tbType) ? pStmt->bInfo.tbSuid : uid;
55,463✔
2498

2499
  if (taosHashGet(pStmt->sql.pTableCache, &cacheUid, sizeof(cacheUid))) {
55,463✔
2500
    STMT2_TLOG("table %s already cached, no need to cache again", pStmt->bInfo.tbFName);
42,615✔
2501
    return TSDB_CODE_SUCCESS;
42,615✔
2502
  }
2503

2504
  STableDataCxt** pSrc = taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
12,848✔
2505
  if (!pSrc) {
12,848✔
2506
    STMT2_ELOG("table %s not found in exec blockHash:%p", pStmt->bInfo.tbFName, pStmt->exec.pBlockHash);
×
2507
    return terrno;
×
2508
  }
2509
  STableDataCxt* pDst = NULL;
12,848✔
2510

2511
  STMT_ERR_RET(qCloneStmtDataBlock(&pDst, *pSrc, true));
12,848✔
2512

2513
  SStmtTableCache cache = {
12,832✔
2514
      .pDataCtx = pDst,
2515
      .boundTags = pStmt->bInfo.boundTags,
12,832✔
2516
  };
2517

2518
  if (taosHashPut(pStmt->sql.pTableCache, &cacheUid, sizeof(cacheUid), &cache, sizeof(cache))) {
12,832✔
2519
    STMT2_ELOG("fail to put table cache:%s", tstrerror(terrno));
×
2520
    return terrno;
×
2521
  }
2522

2523
  if (pStmt->sql.autoCreateTbl) {
12,848✔
2524
    pStmt->bInfo.tagsCached = true;
2,677✔
2525
  } else {
2526
    pStmt->bInfo.boundTags = NULL;
10,171✔
2527
  }
2528

2529
  return TSDB_CODE_SUCCESS;
12,848✔
2530
}
2531

2532
static int stmtAddBatch2(TAOS_STMT2* stmt) {
822,800✔
2533
  STscStmt2* pStmt = (STscStmt2*)stmt;
822,800✔
2534

2535
  int64_t startUs = taosGetTimestampUs();
823,143✔
2536

2537
  // STMT2_TLOG_E("start to add batch");
2538

2539
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
823,143✔
2540
    return pStmt->errCode;
×
2541
  }
2542

2543
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_ADD_BATCH));
823,208✔
2544

2545
  if (pStmt->sql.stbInterlaceMode) {
822,970✔
2546
    int64_t startUs2 = taosGetTimestampUs();
610,146✔
2547
    pStmt->stat.addBatchUs += startUs2 - startUs;
610,146✔
2548

2549
    pStmt->sql.siInfo.tableColsReady = false;
610,086✔
2550

2551
    SStmtQNode* param = NULL;
610,086✔
2552
    STMT_ERR_RET(stmtAllocQNodeFromBuf(&pStmt->sql.siInfo.tbBuf, (void**)&param));
1,220,185✔
2553
    param->restoreTbCols = true;
610,039✔
2554
    param->next = NULL;
610,099✔
2555

2556
    if (pStmt->sql.autoCreateTbl) {
610,224✔
2557
      pStmt->bInfo.tagsCached = true;
222,962✔
2558
    }
2559
    pStmt->bInfo.boundColsCached = true;
610,099✔
2560

2561
    if (pStmt->queue.stopQueue) {
610,104✔
2562
      STMT2_ELOG_E("stmt bind thread is stopped,cannot enqueue bind request");
×
2563
      return TSDB_CODE_TSC_STMT_API_ERROR;
×
2564
    }
2565

2566
    stmtEnqueue(pStmt, param);
610,039✔
2567

2568
    return TSDB_CODE_SUCCESS;
609,978✔
2569
  }
2570

2571
  STMT_ERR_RET(stmtCacheBlock(pStmt));
212,863✔
2572

2573
  return TSDB_CODE_SUCCESS;
212,414✔
2574
}
2575
/*
2576
static int32_t stmtBackupQueryFields(STscStmt2* pStmt) {
2577
  SStmtQueryResInfo* pRes = &pStmt->sql.queryRes;
2578
  pRes->numOfCols = pStmt->exec.pRequest->body.resInfo.numOfCols;
2579
  pRes->precision = pStmt->exec.pRequest->body.resInfo.precision;
2580

2581
  int32_t size = pRes->numOfCols * sizeof(TAOS_FIELD);
2582
  pRes->fields = taosMemoryMalloc(size);
2583
  pRes->userFields = taosMemoryMalloc(size);
2584
  if (NULL == pRes->fields || NULL == pRes->userFields) {
2585
    STMT_ERR_RET(terrno);
2586
  }
2587
  (void)memcpy(pRes->fields, pStmt->exec.pRequest->body.resInfo.fields, size);
2588
  (void)memcpy(pRes->userFields, pStmt->exec.pRequest->body.resInfo.userFields, size);
2589

2590
  return TSDB_CODE_SUCCESS;
2591
}
2592

2593
static int32_t stmtRestoreQueryFields(STscStmt2* pStmt) {
2594
  SStmtQueryResInfo* pRes = &pStmt->sql.queryRes;
2595
  int32_t            size = pRes->numOfCols * sizeof(TAOS_FIELD);
2596

2597
  pStmt->exec.pRequest->body.resInfo.numOfCols = pRes->numOfCols;
2598
  pStmt->exec.pRequest->body.resInfo.precision = pRes->precision;
2599

2600
  if (NULL == pStmt->exec.pRequest->body.resInfo.fields) {
2601
    pStmt->exec.pRequest->body.resInfo.fields = taosMemoryMalloc(size);
2602
    if (NULL == pStmt->exec.pRequest->body.resInfo.fields) {
2603
      STMT_ERR_RET(terrno);
2604
    }
2605
    (void)memcpy(pStmt->exec.pRequest->body.resInfo.fields, pRes->fields, size);
2606
  }
2607

2608
  if (NULL == pStmt->exec.pRequest->body.resInfo.userFields) {
2609
    pStmt->exec.pRequest->body.resInfo.userFields = taosMemoryMalloc(size);
2610
    if (NULL == pStmt->exec.pRequest->body.resInfo.userFields) {
2611
      STMT_ERR_RET(terrno);
2612
    }
2613
    (void)memcpy(pStmt->exec.pRequest->body.resInfo.userFields, pRes->userFields, size);
2614
  }
2615

2616
  return TSDB_CODE_SUCCESS;
2617
}
2618
*/
2619

2620
/**
2621
 * Fetch metadata for query statement after parameter binding.
2622
 * This function collects metadata requirements from the query (after binding),
2623
 * fetches metadata synchronously from catalog, and returns it for parsing.
2624
 *
2625
 * Note: We fetch metadata on every bind because:
2626
 * 1. Parameter values in WHERE conditions (e.g., dataname IN (?,?)) may change
2627
 * 2. Different parameter values may require different vgroup lists for virtual tables
2628
 * 3. Metadata requirements can only be determined after parameters are bound
2629
 *
2630
 * @param pStmt Statement handle
2631
 * @param pCxt Parse context (must have catalog handle initialized)
2632
 * @param pMetaData Output: Fetched metadata (caller responsible for cleanup)
2633
 * @return TSDB_CODE_SUCCESS on success, error code otherwise
2634
 */
2635
// Callback parameter structure for synchronous catalog metadata fetch
2636
typedef struct {
2637
  SMetaData* pRsp;
2638
  int32_t    code;
2639
  tsem_t     sem;
2640
} SCatalogSyncCbParam;
2641

2642
// Callback function for catalogAsyncGetAllMeta to make it synchronous
2643
static void stmtCatalogSyncGetAllMetaCb(SMetaData* pResultMeta, void* param, int32_t code) {
7,179✔
2644
  SCatalogSyncCbParam* pCbParam = (SCatalogSyncCbParam*)param;
7,179✔
2645
  if (TSDB_CODE_SUCCESS == code && pResultMeta) {
7,179✔
2646
    *pCbParam->pRsp = *pResultMeta;
7,179✔
2647
    TAOS_MEMSET(pResultMeta, 0, sizeof(SMetaData));  // Clear to avoid double free
7,179✔
2648
  }
2649
  pCbParam->code = code;
7,179✔
2650
  if (tsem_post(&pCbParam->sem) != 0) {
7,179✔
2651
    tscError("failed to post semaphore");
×
2652
  }
2653
}
7,179✔
2654

2655
static int32_t stmtFetchMetadataForQuery(STscStmt2* pStmt, SParseContext* pCxt, SMetaData* pMetaData) {
7,179✔
2656
  int32_t          code = 0;
7,179✔
2657
  SParseMetaCache  metaCache = {0};
7,179✔
2658
  SCatalogReq      catalogReq = {0};
7,179✔
2659
  SRequestConnInfo conn = {.pTrans = pCxt->pTransporter,
10,371✔
2660
                           .requestId = pCxt->requestId,
7,179✔
2661
                           .requestObjRefId = pCxt->requestRid,
7,179✔
2662
                           .mgmtEps = pCxt->mgmtEpSet};
2663

2664
  TAOS_MEMSET(pMetaData, 0, sizeof(SMetaData));
7,179✔
2665

2666
  code = collectMetaKey(pCxt, pStmt->sql.pQuery, &metaCache);
7,179✔
2667
  if (TSDB_CODE_SUCCESS == code) {
7,179✔
2668
    code = buildCatalogReq(&metaCache, &catalogReq);
7,179✔
2669
  }
2670
  if (TSDB_CODE_SUCCESS == code) {
7,179✔
2671
    SCatalogSyncCbParam cbParam = {.pRsp = pMetaData, .code = TSDB_CODE_SUCCESS};
7,179✔
2672
    if (tsem_init(&cbParam.sem, 0, 0) != 0) {
7,179✔
2673
      code = TSDB_CODE_CTG_INTERNAL_ERROR;
×
2674
    } else {
2675
      code = catalogAsyncGetAllMeta(pCxt->pCatalog, &conn, &catalogReq, stmtCatalogSyncGetAllMetaCb, &cbParam, NULL);
7,179✔
2676
      if (TSDB_CODE_SUCCESS == code) {
7,179✔
2677
        code = tsem_wait(&cbParam.sem);
7,179✔
2678
        if (code != TSDB_CODE_SUCCESS) {
7,179✔
2679
          catalogFreeMetaData(pMetaData);
×
2680
          TAOS_MEMSET(pMetaData, 0, sizeof(SMetaData));
×
2681
        } else {
2682
          code = cbParam.code;
7,179✔
2683
        }
2684
      }
2685

2686
      if (tsem_destroy(&cbParam.sem) != 0) {
7,179✔
2687
        tscError("failed to destroy semaphore");
×
2688
        code = TSDB_CODE_CTG_INTERNAL_ERROR;
×
2689
        catalogFreeMetaData(pMetaData);
×
2690
        TAOS_MEMSET(pMetaData, 0, sizeof(SMetaData));
×
2691
      }
2692
    }
2693
  }
2694

2695
  // metaCache currently holds "reserved/request" structures built by collectMetaKey/buildCatalogReq.
2696
  // It must be destroyed with request=true to release nested table-request hashes.
2697
  destoryParseMetaCache(&metaCache, true);
7,179✔
2698
  destoryCatalogReq(&catalogReq);
7,179✔
2699

2700
  if (TSDB_CODE_SUCCESS != code) {
7,179✔
2701
    catalogFreeMetaData(pMetaData);
×
2702
  }
2703

2704
  return code;
7,179✔
2705
}
2706

2707
int stmtBindBatch2(TAOS_STMT2* stmt, TAOS_STMT2_BIND* bind, int32_t colIdx, SVCreateTbReq* pCreateTbReq) {
1,453,479✔
2708
  STscStmt2* pStmt = (STscStmt2*)stmt;
1,453,479✔
2709
  int32_t    code = 0;
1,453,479✔
2710

2711
  int64_t startUs = taosGetTimestampUs();
1,454,371✔
2712

2713
  if (qDebugFlag & DEBUG_TRACE) {
1,454,371✔
2714
    (void)stmtPrintBindv(stmt, bind, colIdx, false);
×
2715
  }
2716

2717
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
1,454,426✔
2718
    return pStmt->errCode;
102✔
2719
  }
2720

2721
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_BIND));
1,454,144✔
2722

2723
  if (pStmt->bInfo.needParse && pStmt->sql.runTimes && pStmt->sql.type > 0 &&
1,454,048✔
2724
      STMT_TYPE_MULTI_INSERT != pStmt->sql.type) {
×
2725
    pStmt->bInfo.needParse = false;
×
2726
  }
2727

2728
  if (pStmt->exec.pRequest && STMT_TYPE_QUERY == pStmt->sql.type && pStmt->sql.runTimes) {
1,453,800✔
2729
    resetRequest(pStmt);
1,374✔
2730
  }
2731

2732
  STMT_ERR_RET(stmtCreateRequest(pStmt));
1,454,259✔
2733
  if (pStmt->bInfo.needParse) {
1,453,433✔
2734
    code = stmtParseSql(pStmt);
143,651✔
2735
    if (code != TSDB_CODE_SUCCESS) {
143,610✔
2736
      goto cleanup_root;
×
2737
    }
2738
  }
2739

2740
  if (STMT_TYPE_QUERY == pStmt->sql.type) {
1,453,545✔
2741
    code = qStmtBindParams2(pStmt->sql.pQuery, bind, colIdx, pStmt->taos->optionInfo.charsetCxt);
7,179✔
2742
    if (code != TSDB_CODE_SUCCESS) {
7,179✔
2743
      goto cleanup_root;
×
2744
    }
2745
    SParseContext ctx = {.requestId = pStmt->exec.pRequest->requestId,
7,179✔
2746
                         .acctId = pStmt->taos->acctId,
7,179✔
2747
                         .minSecLevel = pStmt->taos->minSecLevel,
7,179✔
2748
                         .maxSecLevel = pStmt->taos->maxSecLevel,
7,179✔
2749
                         .db = pStmt->exec.pRequest->pDb,
7,179✔
2750
                         .topicQuery = false,
2751
                         .pSql = pStmt->sql.sqlStr,
7,179✔
2752
                         .sqlLen = pStmt->sql.sqlLen,
7,179✔
2753
                         .pMsg = pStmt->exec.pRequest->msgBuf,
7,179✔
2754
                         .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
2755
                         .pTransporter = pStmt->taos->pAppInfo->pTransporter,
7,179✔
2756
                         .pStmtCb = NULL,
2757
                         .pUser = pStmt->taos->user,
7,179✔
2758
                         .stmtBindVersion = pStmt->exec.pRequest->stmtBindVersion};
7,179✔
2759
    ctx.mgmtEpSet = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp);
7,179✔
2760
    code = catalogGetHandle(pStmt->taos->pAppInfo->clusterId, &ctx.pCatalog);
7,179✔
2761
    if (code != TSDB_CODE_SUCCESS) {
7,179✔
2762
      goto cleanup_root;
×
2763
    }
2764

2765
    // Fetch metadata for query(vtable need)
2766
    SMetaData metaData = {0};
7,179✔
2767
    code = stmtFetchMetadataForQuery(pStmt, &ctx, &metaData);
7,179✔
2768
    if (TSDB_CODE_SUCCESS != code) {
7,179✔
2769
      goto cleanup_root;
×
2770
    }
2771

2772
    code = qStmtParseQuerySql(&ctx, pStmt->sql.pQuery, &metaData);
7,179✔
2773
    if (TSDB_CODE_SUCCESS == code) {
7,179✔
2774
      // Copy metaData to pRequest->parseMeta for potential future use
2775
      // Similar to doAsyncQueryFromAnalyse when parseOnly is true
2776
      (void)memcpy(&pStmt->exec.pRequest->parseMeta, &metaData, sizeof(SMetaData));
7,077✔
2777
      (void)memset(&metaData, 0, sizeof(SMetaData));  // Clear to avoid double free
7,077✔
2778
    } else {
2779
      // Clean up metaData on failure - free all arrays
2780
      if (metaData.pVStbRefDbs) {
102✔
2781
        taosArrayDestroy(metaData.pVStbRefDbs);
102✔
2782
        metaData.pVStbRefDbs = NULL;
102✔
2783
      }
2784
      // Note: Other fields in metaData are managed by catalog module if ctgFree is true
2785
      goto cleanup_root;
102✔
2786
    }
2787

2788
    if (pStmt->sql.pQuery->haveResultSet) {
7,077✔
2789
      STMT_ERR_RET(setResSchemaInfo(&pStmt->exec.pRequest->body.resInfo, pStmt->sql.pQuery->pResSchema,
11,064✔
2790
                                    pStmt->sql.pQuery->numOfResCols, pStmt->sql.pQuery->pResExtSchema, true));
2791
      taosMemoryFreeClear(pStmt->sql.pQuery->pResSchema);
7,077✔
2792
      taosMemoryFreeClear(pStmt->sql.pQuery->pResExtSchema);
7,077✔
2793
      setResPrecision(&pStmt->exec.pRequest->body.resInfo, pStmt->sql.pQuery->precision);
7,077✔
2794
    }
2795

2796
    TSWAP(pStmt->exec.pRequest->dbList, pStmt->sql.pQuery->pDbList);
7,077✔
2797
    TSWAP(pStmt->exec.pRequest->tableList, pStmt->sql.pQuery->pTableList);
7,077✔
2798
    TSWAP(pStmt->exec.pRequest->targetTableList, pStmt->sql.pQuery->pTargetTableList);
7,077✔
2799

2800
    // if (STMT_TYPE_QUERY == pStmt->sql.queryRes) {
2801
    //   STMT_ERR_RET(stmtRestoreQueryFields(pStmt));
2802
    // }
2803

2804
    // STMT_ERR_RET(stmtBackupQueryFields(pStmt));
2805

2806
    return TSDB_CODE_SUCCESS;
7,077✔
2807

2808
  cleanup_root:
102✔
2809
    STMT2_ELOG("parse query statment unexpected failed code:%d, need to clean node", code);
102✔
2810
    if (pStmt->sql.pQuery && pStmt->sql.pQuery->pRoot) {
102✔
2811
      nodesDestroyNode(pStmt->sql.pQuery->pRoot);
102✔
2812
      pStmt->sql.pQuery->pRoot = NULL;
102✔
2813
    }
2814
    STMT_ERR_RET(code);
102✔
2815
  }
2816

2817
  if (pStmt->sql.stbInterlaceMode && NULL == pStmt->sql.siInfo.pDataCtx) {
1,446,470✔
2818
    STMT_ERR_RET(stmtInitStbInterlaceTableInfo(pStmt));
×
2819
  }
2820

2821
  STableDataCxt** pDataBlock = NULL;
1,446,533✔
2822

2823
  if (pStmt->exec.pCurrBlock) {
1,446,533✔
2824
    pDataBlock = &pStmt->exec.pCurrBlock;
1,280,224✔
2825
  } else {
2826
    pDataBlock =
2827
        (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
166,283✔
2828
    if (NULL == pDataBlock) {
166,590✔
2829
      STMT2_ELOG("table %s not found in exec blockHash:%p", pStmt->bInfo.tbFName, pStmt->exec.pBlockHash);
×
2830
      STMT_ERR_RET(TSDB_CODE_TSC_STMT_CACHE_ERROR);
×
2831
    }
2832
    pStmt->exec.pCurrBlock = *pDataBlock;
166,590✔
2833
    if (pStmt->sql.stbInterlaceMode) {
166,590✔
2834
      taosArrayDestroy(pStmt->exec.pCurrBlock->pData->aCol);
9,503✔
2835
      (*pDataBlock)->pData->aCol = NULL;
9,515✔
2836
    }
2837
    if (colIdx < -1) {
166,517✔
2838
      pStmt->sql.bindRowFormat = true;
102✔
2839
      taosArrayDestroy((*pDataBlock)->pData->aCol);
102✔
2840
      (*pDataBlock)->pData->aCol = taosArrayInit(20, POINTER_BYTES);
102✔
2841
    }
2842
  }
2843

2844
  int64_t startUs2 = taosGetTimestampUs();
1,446,922✔
2845
  pStmt->stat.bindDataUs1 += startUs2 - startUs;
1,446,922✔
2846

2847
  SStmtQNode* param = NULL;
1,446,899✔
2848
  if (pStmt->sql.stbInterlaceMode) {
1,446,984✔
2849
    STMT_ERR_RET(stmtAllocQNodeFromBuf(&pStmt->sql.siInfo.tbBuf, (void**)&param));
2,468,211✔
2850
    STMT_ERR_RET(stmtGetTableColsFromCache(pStmt, &param->tblData.aCol));
2,468,021✔
2851
    taosArrayClear(param->tblData.aCol);
1,234,084✔
2852

2853
    // param->tblData.aCol = taosArrayInit(20, POINTER_BYTES);
2854

2855
    param->restoreTbCols = false;
1,233,401✔
2856
    param->tblData.isOrdered = true;
1,233,461✔
2857
    param->tblData.isDuplicateTs = false;
1,233,393✔
2858
    tstrncpy(param->tblData.tbName, pStmt->bInfo.tbName, TSDB_TABLE_NAME_LEN);
1,233,528✔
2859

2860
    param->pCreateTbReq = pCreateTbReq;
1,233,672✔
2861
  }
2862

2863
  int64_t startUs3 = taosGetTimestampUs();
1,446,653✔
2864
  pStmt->stat.bindDataUs2 += startUs3 - startUs2;
1,446,653✔
2865

2866
  SArray*   pCols = pStmt->sql.stbInterlaceMode ? param->tblData.aCol : (*pDataBlock)->pData->aCol;
1,446,721✔
2867
  SBlobSet* pBlob = NULL;
1,446,431✔
2868
  if (colIdx < 0) {
1,446,495✔
2869
    if (pStmt->sql.stbInterlaceMode) {
1,446,103✔
2870
      (*pDataBlock)->pData->flags &= ~SUBMIT_REQ_COLUMN_DATA_FORMAT;
1,233,980✔
2871
      code = qBindStmtStbColsValue2(*pDataBlock, pCols, pStmt->bInfo.fixedValueCols, bind, pStmt->exec.pRequest->msgBuf,
1,693,749✔
2872
                                    pStmt->exec.pRequest->msgBufLen, &pStmt->sql.siInfo.pTSchema, pStmt->sql.pBindInfo,
1,234,029✔
2873
                                    pStmt->taos->optionInfo.charsetCxt, &pBlob);
1,234,164✔
2874
      param->tblData.isOrdered = (*pDataBlock)->ordered;
1,233,945✔
2875
      param->tblData.isDuplicateTs = (*pDataBlock)->duplicateTs;
1,234,309✔
2876
    } else {
2877
      if (colIdx == -1) {
211,951✔
2878
        if (pStmt->sql.bindRowFormat) {
211,916✔
2879
          STMT2_ELOG_E("can't mix bind row format and bind column format");
102✔
2880
          STMT_ERR_RET(TSDB_CODE_TSC_STMT_API_ERROR);
102✔
2881
        }
2882
        code = qBindStmtColsValue2(*pDataBlock, pCols, pStmt->bInfo.fixedValueCols, bind, pStmt->exec.pRequest->msgBuf,
399,191✔
2883
                                   pStmt->exec.pRequest->msgBufLen, pStmt->taos->optionInfo.charsetCxt);
398,853✔
2884
      } else {
2885
        code =
2886
            qBindStmt2RowValue(*pDataBlock, (*pDataBlock)->pData->aRowP, pStmt->bInfo.fixedValueCols, bind,
248✔
2887
                               pStmt->exec.pRequest->msgBuf, pStmt->exec.pRequest->msgBufLen,
248✔
2888
                               &pStmt->sql.siInfo.pTSchema, pStmt->sql.pBindInfo, pStmt->taos->optionInfo.charsetCxt);
248✔
2889
      }
2890
    }
2891

2892
    if (code) {
1,446,222✔
2893
      STMT2_ELOG("bind cols or rows failed, error:%s", tstrerror(code));
204✔
2894
      STMT_ERR_RET(code);
204✔
2895
    }
2896
  } else {
2897
    if (pStmt->sql.stbInterlaceMode) {
612✔
2898
      STMT2_ELOG_E("bind single column not allowed in stb insert mode");
×
2899
      STMT_ERR_RET(TSDB_CODE_TSC_STMT_API_ERROR);
×
2900
    }
2901

2902
    if (pStmt->sql.bindRowFormat) {
612✔
2903
      STMT2_ELOG_E("can't mix bind row format and bind column format");
×
2904
      STMT_ERR_RET(TSDB_CODE_TSC_STMT_API_ERROR);
×
2905
    }
2906

2907
    if (colIdx != (pStmt->bInfo.sBindLastIdx + 1) && colIdx != 0) {
612✔
2908
      STMT2_ELOG_E("bind column index not in sequence");
×
2909
      STMT_ERR_RET(TSDB_CODE_TSC_STMT_API_ERROR);
×
2910
    }
2911

2912
    pStmt->bInfo.sBindLastIdx = colIdx;
612✔
2913

2914
    if (0 == colIdx) {
612✔
2915
      pStmt->bInfo.sBindRowNum = bind->num;
306✔
2916
    }
2917

2918
    code = qBindStmtSingleColValue2(*pDataBlock, pCols, bind, pStmt->exec.pRequest->msgBuf,
612✔
2919
                                    pStmt->exec.pRequest->msgBufLen, colIdx, pStmt->bInfo.sBindRowNum,
612✔
2920
                                    pStmt->taos->optionInfo.charsetCxt);
612✔
2921
    if (code) {
612✔
2922
      STMT2_ELOG("bind single col failed, error:%s", tstrerror(code));
×
2923
      STMT_ERR_RET(code);
×
2924
    }
2925
  }
2926

2927
  int64_t startUs4 = taosGetTimestampUs();
1,447,010✔
2928
  pStmt->stat.bindDataUs3 += startUs4 - startUs3;
1,447,010✔
2929

2930
  if (pStmt->stbInterlaceMode) {
1,446,934✔
2931
    if (param) param->tblData.pBlobSet = pBlob;
1,253,346✔
2932
  }
2933

2934
  if (pStmt->sql.stbInterlaceMode) {
1,446,870✔
2935
    STMT_ERR_RET(stmtAppendTablePostHandle(pStmt, param));
1,234,107✔
2936
  } else {
2937
    STMT_ERR_RET(stmtAddBatch2(pStmt));
212,903✔
2938
  }
2939

2940
  pStmt->stat.bindDataUs4 += taosGetTimestampUs() - startUs4;
1,446,581✔
2941
  return TSDB_CODE_SUCCESS;
1,447,135✔
2942
}
2943

2944
/*
2945
int stmtUpdateTableUid(STscStmt2* pStmt, SSubmitRsp* pRsp) {
2946
  tscDebug("stmt start to update tbUid, blockNum:%d", pRsp->nBlocks);
2947

2948
  int32_t code = 0;
2949
  int32_t finalCode = 0;
2950
  size_t  keyLen = 0;
2951
  void*   pIter = taosHashIterate(pStmt->exec.pBlockHash, NULL);
2952
  while (pIter) {
2953
    STableDataCxt* pBlock = *(STableDataCxt**)pIter;
2954
    char*          key = taosHashGetKey(pIter, &keyLen);
2955

2956
    STableMeta* pMeta = qGetTableMetaInDataBlock(pBlock);
2957
    if (pMeta->uid) {
2958
      pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter);
2959
      continue;
2960
    }
2961

2962
    SSubmitBlkRsp* blkRsp = NULL;
2963
    int32_t        i = 0;
2964
    for (; i < pRsp->nBlocks; ++i) {
2965
      blkRsp = pRsp->pBlocks + i;
2966
      if (strlen(blkRsp->tblFName) != keyLen) {
2967
        continue;
2968
      }
2969

2970
      if (strncmp(blkRsp->tblFName, key, keyLen)) {
2971
        continue;
2972
      }
2973

2974
      break;
2975
    }
2976

2977
    if (i < pRsp->nBlocks) {
2978
      tscDebug("auto created table %s uid updated from %" PRIx64 " to %" PRIx64, blkRsp->tblFName, pMeta->uid,
2979
               blkRsp->uid);
2980

2981
      pMeta->uid = blkRsp->uid;
2982
      pStmt->bInfo.tbUid = blkRsp->uid;
2983
    } else {
2984
      tscDebug("table %s not found in submit rsp, will update from catalog", pStmt->bInfo.tbFName);
2985
      if (NULL == pStmt->pCatalog) {
2986
        code = catalogGetHandle(pStmt->taos->pAppInfo->clusterId, &pStmt->pCatalog);
2987
        if (code) {
2988
          pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter);
2989
          finalCode = code;
2990
          continue;
2991
        }
2992
      }
2993

2994
      code = stmtCreateRequest(pStmt);
2995
      if (code) {
2996
        pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter);
2997
        finalCode = code;
2998
        continue;
2999
      }
3000

3001
      STableMeta*      pTableMeta = NULL;
3002
      SRequestConnInfo conn = {.pTrans = pStmt->taos->pAppInfo->pTransporter,
3003
                               .requestId = pStmt->exec.pRequest->requestId,
3004
                               .requestObjRefId = pStmt->exec.pRequest->self,
3005
                               .mgmtEps = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp)};
3006
      code = catalogGetTableMeta(pStmt->pCatalog, &conn, &pStmt->bInfo.sname, &pTableMeta);
3007

3008
      pStmt->stat.ctgGetTbMetaNum++;
3009

3010
      taos_free_result(pStmt->exec.pRequest);
3011
      pStmt->exec.pRequest = NULL;
3012

3013
      if (code || NULL == pTableMeta) {
3014
        pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter);
3015
        finalCode = code;
3016
        taosMemoryFree(pTableMeta);
3017
        continue;
3018
      }
3019

3020
      pMeta->uid = pTableMeta->uid;
3021
      pStmt->bInfo.tbUid = pTableMeta->uid;
3022
      taosMemoryFree(pTableMeta);
3023
    }
3024

3025
    pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter);
3026
  }
3027

3028
  return finalCode;
3029
}
3030
*/
3031
/*
3032
int stmtStaticModeExec(TAOS_STMT* stmt) {
3033
  STscStmt2*   pStmt = (STscStmt2*)stmt;
3034
  int32_t     code = 0;
3035
  SSubmitRsp* pRsp = NULL;
3036
  if (pStmt->sql.staticMode) {
3037
    return TSDB_CODE_TSC_STMT_API_ERROR;
3038
  }
3039

3040
  STMT_DLOG_E("start to exec");
3041

3042
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_EXECUTE));
3043

3044
  STMT_ERR_RET(qBuildStmtOutputFromTbList(pStmt->sql.pQuery, pStmt->sql.pVgHash, pStmt->exec.pTbBlkList,
3045
pStmt->exec.pCurrBlock, pStmt->exec.tbBlkNum));
3046

3047
  launchQueryImpl(pStmt->exec.pRequest, pStmt->sql.pQuery, true, NULL);
3048

3049
  if (pStmt->exec.pRequest->code && NEED_CLIENT_HANDLE_ERROR(pStmt->exec.pRequest->code)) {
3050
    code = refreshMeta(pStmt->exec.pRequest->pTscObj, pStmt->exec.pRequest);
3051
    if (code) {
3052
      pStmt->exec.pRequest->code = code;
3053
    } else {
3054
      tFreeSSubmitRsp(pRsp);
3055
      STMT_ERR_RET(stmtResetStmt(pStmt));
3056
      STMT_ERR_RET(TSDB_CODE_NEED_RETRY);
3057
    }
3058
  }
3059

3060
  STMT_ERR_JRET(pStmt->exec.pRequest->code);
3061

3062
  pStmt->exec.affectedRows = taos_affected_rows(pStmt->exec.pRequest);
3063
  pStmt->affectedRows += pStmt->exec.affectedRows;
3064

3065
_return:
3066

3067
  stmtCleanExecInfo(pStmt, (code ? false : true), false);
3068

3069
  tFreeSSubmitRsp(pRsp);
3070

3071
  ++pStmt->sql.runTimes;
3072

3073
  STMT_RET(code);
3074
}
3075
*/
3076

3077
static int32_t createParseContext(const SRequestObj* pRequest, SParseContext** pCxt, SSqlCallbackWrapper* pWrapper) {
2,856✔
3078
  const STscObj* pTscObj = pRequest->pTscObj;
2,856✔
3079

3080
  *pCxt = taosMemoryCalloc(1, sizeof(SParseContext));
2,856✔
3081
  if (*pCxt == NULL) {
2,856✔
3082
    return terrno;
×
3083
  }
3084

3085
  **pCxt = (SParseContext){.requestId = pRequest->requestId,
×
3086
                           .requestRid = pRequest->self,
2,856✔
3087
                           .acctId = pTscObj->acctId,
2,856✔
3088
                           .db = pRequest->pDb,
2,856✔
3089
                           .topicQuery = false,
3090
                           .pSql = pRequest->sqlstr,
2,856✔
3091
                           .sqlLen = pRequest->sqlLen,
2,856✔
3092
                           .pMsg = pRequest->msgBuf,
2,856✔
3093
                           .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
3094
                           .pTransporter = pTscObj->pAppInfo->pTransporter,
2,856✔
3095
                           .pStmtCb = NULL,
3096
                           .pUser = pTscObj->user,
2,856✔
3097
                           .userId = pTscObj->userId,
2,856✔
3098
                           .pEffectiveUser = pRequest->effectiveUser,
2,856✔
3099
                           .isSuperUser = (0 == strcmp(pTscObj->user, TSDB_DEFAULT_USER)),
2,856✔
3100
                           .enableSysInfo = pTscObj->sysInfo,
2,856✔
3101
                           .sodInitial = pTscObj->pAppInfo->serverCfg.sodInitial,
2,856✔
3102
                           .privInfo = pWrapper->pParseCtx ? pWrapper->pParseCtx->privInfo : 0,
2,856✔
3103
                           .async = true,
3104
                           .svrVer = pTscObj->sVer,
2,856✔
3105
                           .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes),
2,856✔
3106
                           .allocatorId = pRequest->allocatorRefId,
2,856✔
3107
                           .parseSqlFp = clientParseSql,
3108
                           .parseSqlParam = pWrapper};
3109
  int8_t biMode = atomic_load_8(&((STscObj*)pTscObj)->biMode);
2,856✔
3110
  (*pCxt)->biMode = biMode;
2,856✔
3111
  return TSDB_CODE_SUCCESS;
2,856✔
3112
}
3113

3114
static void asyncQueryCb(void* userdata, TAOS_RES* res, int code) {
2,856✔
3115
  STscStmt2*        pStmt = userdata;
2,856✔
3116
  __taos_async_fn_t fp = pStmt->options.asyncExecFn;
2,856✔
3117
  pStmt->asyncResultAvailable = true;
2,856✔
3118
  pStmt->exec.pRequest->inCallback = true;
2,856✔
3119

3120
  // NEED_CLIENT_HANDLE_ERROR: retry internally without notifying user; retry completion uses this same cb + fp once.
3121
  if (code != TSDB_CODE_SUCCESS && NEED_CLIENT_HANDLE_ERROR(code) && pStmt->pVgDataBlocksForRetry != NULL) {
2,958✔
3122
    int32_t origExecCode = code;
204✔
3123
    STMT2_ELOG("async exec got NEED_CLIENT_HANDLE_ERROR (code:%s), retrying internally", tstrerror(code));
204✔
3124

3125
    // Try to retry internally; completion uses asyncQueryCb so user fp runs once with the final result.
3126
    int32_t retryCode = refreshMeta(pStmt->exec.pRequest->pTscObj, pStmt->exec.pRequest);
204✔
3127
    if (retryCode == TSDB_CODE_SUCCESS) {
204✔
3128
      stmtInvalidateStbInterlaceTableUidCache(pStmt);
102✔
3129
      if (origExecCode == TSDB_CODE_TDB_TABLE_NOT_EXIST) {
102✔
3130
        retryCode = stmtUpdateVgDataBlocksTbMetaFromCatalog(pStmt, pStmt->exec.pRequest);
102✔
3131
      } else if (stmtIsSchemaVersionRetryError(origExecCode)) {
×
3132
        retryCode = stmtUpdateVgDataBlocksSchemaVer(pStmt, pStmt->exec.pRequest);
×
3133
      }
3134
    }
3135
    if (retryCode == TSDB_CODE_SUCCESS) {
204✔
3136
      (void)stmtRestoreVgDataBlocksForRetry(pStmt);
102✔
3137
      resetRequest(pStmt);
102✔
3138
      pStmt->asyncResultAvailable = false;
102✔
3139
      retryCode = stmtCreateRequest(pStmt);
102✔
3140
      if (retryCode == TSDB_CODE_SUCCESS) {
102✔
3141
        SRequestObj*         pNewReq = pStmt->exec.pRequest;
102✔
3142
        SSqlCallbackWrapper* pWrapper = taosMemoryCalloc(1, sizeof(SSqlCallbackWrapper));
102✔
3143
        if (pWrapper == NULL) {
102✔
3144
          retryCode = terrno;
×
3145
          resetRequest(pStmt);
×
3146
        } else {
3147
          pWrapper->pRequest = pNewReq;
102✔
3148
          pNewReq->pWrapper = pWrapper;
102✔
3149
          retryCode = createParseContext(pNewReq, &pWrapper->pParseCtx, pWrapper);
102✔
3150
          if (retryCode == TSDB_CODE_SUCCESS) {
102✔
3151
            pNewReq->syncQuery = false;
102✔
3152
            // Same as first exec: asyncQueryCb invokes user asyncExecFn once with userdata (not raw pStmt as fp's 1st
3153
            // arg).
3154
            pNewReq->body.queryFp = asyncQueryCb;
102✔
3155
            ((SSyncQueryParam*)(pNewReq)->body.interParam)->userParam = pStmt;
102✔
3156
            launchAsyncQuery(pNewReq, pStmt->sql.pQuery, NULL, pWrapper);
102✔
3157
            // Retry asyncQueryCb will call fp, stmtCleanExecInfo, and tsem_post(asyncExecSem).
3158
            return;
102✔
3159
          }
3160
          // Do not taosMemoryFree(pWrapper): destroyRequest frees it via destorySqlCallbackWrapper.
3161
          resetRequest(pStmt);
×
3162
        }
3163
      }
3164
    }
3165
    // Retry setup failed (did not return above): notify user once with the original error, then cleanup + post sem.
3166
    if (fp) {
102✔
3167
      fp(pStmt->options.userdata, res, code);
102✔
3168
    }
3169
  } else {
3170
    if (code == TSDB_CODE_SUCCESS) {
2,652✔
3171
      pStmt->exec.affectedRows = taos_affected_rows(res);
2,652✔
3172
      pStmt->affectedRows += pStmt->exec.affectedRows;
2,652✔
3173
    }
3174

3175
    if (fp) {
2,652✔
3176
      fp(pStmt->options.userdata, res, code);
2,652✔
3177
    }
3178
  }
3179

3180
  while (0 == atomic_load_8((int8_t*)&pStmt->sql.siInfo.tableColsReady)) {
2,856✔
3181
    taosUsleep(1);
102✔
3182
  }
3183
  (void)stmtCleanExecInfo(pStmt, (code ? false : true), false);
2,754✔
3184
  ++pStmt->sql.runTimes;
2,754✔
3185
  if (pStmt->exec.pRequest != NULL) {
2,754✔
3186
    pStmt->exec.pRequest->inCallback = false;
1,734✔
3187
  }
3188

3189
  if (tsem_post(&pStmt->asyncExecSem) != 0) {
2,754✔
3190
    STMT2_ELOG_E("fail to post asyncExecSem");
×
3191
  }
3192
}
3193

3194
int stmtExec2(TAOS_STMT2* stmt, int* affected_rows) {
790,420✔
3195
  STscStmt2* pStmt = (STscStmt2*)stmt;
790,420✔
3196
  int32_t    code = 0;
790,420✔
3197
  int64_t    startUs = taosGetTimestampUs();
790,885✔
3198

3199
  STMT2_DLOG_E("start to exec");
790,885✔
3200

3201
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
790,859✔
3202
    return pStmt->errCode;
102✔
3203
  }
3204

3205
  STMT_ERR_RET(taosThreadMutexLock(&pStmt->asyncBindParam.mutex));
790,757✔
3206
  while (atomic_load_8((int8_t*)&pStmt->asyncBindParam.asyncBindNum) > 0) {
790,876✔
3207
    (void)taosThreadCondWait(&pStmt->asyncBindParam.waitCond, &pStmt->asyncBindParam.mutex);
×
3208
  }
3209
  STMT_ERR_RET(taosThreadMutexUnlock(&pStmt->asyncBindParam.mutex));
790,526✔
3210

3211
  if (pStmt->sql.stbInterlaceMode) {
790,520✔
3212
    STMT_ERR_RET(stmtAddBatch2(pStmt));
610,151✔
3213
  }
3214

3215
  code = stmtSwitchStatus(pStmt, STMT_EXECUTE);
790,369✔
3216
  if (code != TSDB_CODE_SUCCESS) goto _return;
790,316✔
3217

3218
  if (STMT_TYPE_QUERY != pStmt->sql.type) {
789,860✔
3219
    if (pStmt->sql.stbInterlaceMode) {
783,201✔
3220
      int64_t startTs = taosGetTimestampUs();
610,250✔
3221
      // wait for stmt bind thread to finish
3222
      while (atomic_load_64(&pStmt->sql.siInfo.tbRemainNum)) {
2,318,019✔
3223
        taosUsleep(1);
1,708,059✔
3224
      }
3225

3226
      if (pStmt->errCode != TSDB_CODE_SUCCESS) {
610,116✔
3227
        return pStmt->errCode;
102✔
3228
      }
3229

3230
      pStmt->stat.execWaitUs += taosGetTimestampUs() - startTs;
609,987✔
3231
      STMT_ERR_RET(qBuildStmtFinOutput(pStmt->sql.pQuery, pStmt->sql.pVgHash, pStmt->sql.siInfo.pVgroupList));
610,107✔
3232
      taosHashCleanup(pStmt->sql.siInfo.pVgroupHash);
609,974✔
3233
      pStmt->sql.siInfo.pVgroupHash = NULL;
610,148✔
3234
      pStmt->sql.siInfo.pVgroupList = NULL;
610,148✔
3235
    } else {
3236
      tDestroySubmitTbData(pStmt->exec.pCurrTbData, TSDB_MSG_FLG_ENCODE);
173,164✔
3237
      taosMemoryFreeClear(pStmt->exec.pCurrTbData);
173,130✔
3238

3239
      STMT_ERR_RET(qCloneCurrentTbData(pStmt->exec.pCurrBlock, &pStmt->exec.pCurrTbData));
173,130✔
3240

3241
      STMT_ERR_RET(qBuildStmtOutput(pStmt->sql.pQuery, pStmt->sql.pVgHash, pStmt->exec.pBlockHash));
173,012✔
3242
    }
3243
    // Save serialized data blocks for potential NEED_CLIENT_HANDLE_ERROR retry before the planner
3244
    // takes ownership of pDataBlocks during createQueryPlan.
3245
    STMT_ERR_RET(stmtSaveVgDataBlocksForRetry(pStmt));
782,948✔
3246
  }
3247

3248
  pStmt->asyncResultAvailable = false;
789,437✔
3249
  SRequestObj*      pRequest = pStmt->exec.pRequest;
789,630✔
3250
  __taos_async_fn_t fp = pStmt->options.asyncExecFn;
789,621✔
3251
  STMT2_DLOG("EXEC INFO :req:0x%" PRIx64 ", QID:0x%" PRIx64 ", exec sql:%s,  conn:%" PRId64, pRequest->self,
790,184✔
3252
             pRequest->requestId, pStmt->sql.sqlStr, pRequest->pTscObj->id);
3253

3254
  if (!fp) {
789,641✔
3255
    launchQueryImpl(pStmt->exec.pRequest, pStmt->sql.pQuery, true, NULL);
786,887✔
3256

3257
    if (pStmt->exec.pRequest->code && NEED_CLIENT_HANDLE_ERROR(pStmt->exec.pRequest->code)) {
787,237✔
3258
      int32_t origExecCode = pStmt->exec.pRequest->code;
204✔
3259
      STMT2_WLOG_E("exec failed errorcode:NEED_CLIENT_HANDLE_ERROR, refresh meta and retry internally");
204✔
3260
      code = refreshMeta(pStmt->exec.pRequest->pTscObj, pStmt->exec.pRequest);
204✔
3261
      if (code == TSDB_CODE_SUCCESS) {
204✔
3262
        stmtInvalidateStbInterlaceTableUidCache(pStmt);
204✔
3263
      }
3264
      if (code == TSDB_CODE_SUCCESS && pStmt->pVgDataBlocksForRetry != NULL) {
204✔
3265
        if (origExecCode == TSDB_CODE_TDB_TABLE_NOT_EXIST) {
204✔
3266
          code = stmtUpdateVgDataBlocksTbMetaFromCatalog(pStmt, pStmt->exec.pRequest);
102✔
3267
        } else if (stmtIsSchemaVersionRetryError(origExecCode)) {
102✔
3268
          code = stmtUpdateVgDataBlocksSchemaVer(pStmt, pStmt->exec.pRequest);
102✔
3269
        }
3270
      }
3271
      if (code == TSDB_CODE_SUCCESS && pStmt->pVgDataBlocksForRetry != NULL) {
204✔
3272
        // Restore saved serialized data blocks and re-execute with refreshed meta.
3273
        STMT_ERR_JRET(stmtRestoreVgDataBlocksForRetry(pStmt));
204✔
3274
        resetRequest(pStmt);
204✔
3275
        STMT_ERR_JRET(stmtCreateRequest(pStmt));
204✔
3276
        launchQueryImpl(pStmt->exec.pRequest, pStmt->sql.pQuery, true, NULL);
204✔
3277
        code = pStmt->exec.pRequest->code;
204✔
3278
      } else if (code == TSDB_CODE_SUCCESS) {
×
3279
        code = pStmt->exec.pRequest->code;
×
3280
      } else {
3281
        pStmt->exec.pRequest->code = code;
×
3282
      }
3283
    }
3284

3285
    STMT_ERR_JRET(pStmt->exec.pRequest->code);
787,395✔
3286

3287
    pStmt->exec.affectedRows = taos_affected_rows(pStmt->exec.pRequest);
787,160✔
3288
    if (affected_rows) {
787,208✔
3289
      *affected_rows = pStmt->exec.affectedRows;
783,158✔
3290
    }
3291
    pStmt->affectedRows += pStmt->exec.affectedRows;
786,845✔
3292

3293
    // wait for stmt bind thread to finish
3294
    while (0 == atomic_load_8((int8_t*)&pStmt->sql.siInfo.tableColsReady)) {
788,403✔
3295
      taosUsleep(1);
1,195✔
3296
    }
3297

3298
    STMT_ERR_RET(stmtCleanExecInfo(pStmt, (code ? false : true), false));
787,073✔
3299

3300
    ++pStmt->sql.runTimes;
787,053✔
3301
  } else {
3302
    SSqlCallbackWrapper* pWrapper = taosMemoryCalloc(1, sizeof(SSqlCallbackWrapper));
2,754✔
3303
    if (pWrapper == NULL) {
2,754✔
3304
      code = terrno;
×
3305
    } else {
3306
      pWrapper->pRequest = pRequest;
2,754✔
3307
      pRequest->pWrapper = pWrapper;
2,754✔
3308
    }
3309
    if (TSDB_CODE_SUCCESS == code) {
2,754✔
3310
      code = createParseContext(pRequest, &pWrapper->pParseCtx, pWrapper);
2,754✔
3311
    }
3312
    pRequest->syncQuery = false;
2,754✔
3313
    pRequest->body.queryFp = asyncQueryCb;
2,754✔
3314
    ((SSyncQueryParam*)(pRequest)->body.interParam)->userParam = pStmt;
2,754✔
3315

3316
    pStmt->execSemWaited = false;
2,754✔
3317
    launchAsyncQuery(pRequest, pStmt->sql.pQuery, NULL, pWrapper);
2,754✔
3318
  }
3319

3320
_return:
790,482✔
3321
  if (code) {
790,482✔
3322
    STMT2_ELOG("exec failed, error:%s", tstrerror(code));
660✔
3323
  }
3324
  pStmt->stat.execUseUs += taosGetTimestampUs() - startUs;
790,589✔
3325

3326
  STMT_RET(code);
790,529✔
3327
}
3328

3329
int stmtClose2(TAOS_STMT2* stmt) {
176,180✔
3330
  STscStmt2* pStmt = (STscStmt2*)stmt;
176,180✔
3331

3332
  STMT2_DLOG_E("start to close stmt");
176,180✔
3333
  taosMemoryFreeClear(pStmt->db);
176,180✔
3334

3335
  if (pStmt->bindThreadInUse) {
176,033✔
3336
    // wait for stmt bind thread to finish
3337
    while (0 == atomic_load_8((int8_t*)&pStmt->sql.siInfo.tableColsReady)) {
16,467✔
3338
      taosUsleep(1);
408✔
3339
    }
3340

3341
    (void)taosThreadMutexLock(&pStmt->queue.mutex);
16,059✔
3342
    pStmt->queue.stopQueue = true;
16,059✔
3343
    (void)taosThreadCondSignal(&(pStmt->queue.waitCond));
16,059✔
3344
    (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
16,059✔
3345

3346
    (void)taosThreadJoin(pStmt->bindThread, NULL);
16,059✔
3347
    pStmt->bindThreadInUse = false;
16,059✔
3348

3349
    (void)taosThreadCondDestroy(&pStmt->queue.waitCond);
16,059✔
3350
    (void)taosThreadMutexDestroy(&pStmt->queue.mutex);
16,059✔
3351
  }
3352

3353
  TSC_ERR_RET(taosThreadMutexLock(&pStmt->asyncBindParam.mutex));
176,060✔
3354
  while (atomic_load_8((int8_t*)&pStmt->asyncBindParam.asyncBindNum) > 0) {
176,116✔
3355
    (void)taosThreadCondWait(&pStmt->asyncBindParam.waitCond, &pStmt->asyncBindParam.mutex);
×
3356
  }
3357
  TSC_ERR_RET(taosThreadMutexUnlock(&pStmt->asyncBindParam.mutex));
176,180✔
3358

3359
  (void)taosThreadCondDestroy(&pStmt->asyncBindParam.waitCond);
176,180✔
3360
  (void)taosThreadMutexDestroy(&pStmt->asyncBindParam.mutex);
176,116✔
3361

3362
  if (pStmt->options.asyncExecFn && !pStmt->execSemWaited) {
176,180✔
3363
    if (tsem_wait(&pStmt->asyncExecSem) != 0) {
1,326✔
3364
      STMT2_ELOG_E("fail to wait asyncExecSem");
×
3365
    }
3366
  }
3367

3368
  /* On macOS dispatch_semaphore_dispose requires value >= orig (1). After tsem_wait above value is 0; post once before
3369
   * destroy. */
3370
  if (pStmt->options.asyncExecFn) {
176,180✔
3371
    if (tsem_post(&pStmt->asyncExecSem) != 0) {
1,326✔
3372
      STMT2_ELOG_E("fail to post asyncExecSem");
×
3373
    }
3374
  }
3375

3376
  STMT2_DLOG("stbInterlaceMode:%d, statInfo: ctgGetTbMetaNum=>%" PRId64 ", getCacheTbInfo=>%" PRId64
176,116✔
3377
             ", parseSqlNum=>%" PRId64 ", pStmt->stat.bindDataNum=>%" PRId64
3378
             ", settbnameAPI:%u, bindAPI:%u, addbatchAPI:%u, execAPI:%u"
3379
             ", setTbNameUs:%" PRId64 ", bindDataUs:%" PRId64 ",%" PRId64 ",%" PRId64 ",%" PRId64 " addBatchUs:%" PRId64
3380
             ", execWaitUs:%" PRId64 ", execUseUs:%" PRId64,
3381
             pStmt->sql.stbInterlaceMode, pStmt->stat.ctgGetTbMetaNum, pStmt->stat.getCacheTbInfo,
3382
             pStmt->stat.parseSqlNum, pStmt->stat.bindDataNum, pStmt->seqIds[STMT_SETTBNAME], pStmt->seqIds[STMT_BIND],
3383
             pStmt->seqIds[STMT_ADD_BATCH], pStmt->seqIds[STMT_EXECUTE], pStmt->stat.setTbNameUs,
3384
             pStmt->stat.bindDataUs1, pStmt->stat.bindDataUs2, pStmt->stat.bindDataUs3, pStmt->stat.bindDataUs4,
3385
             pStmt->stat.addBatchUs, pStmt->stat.execWaitUs, pStmt->stat.execUseUs);
3386
  if (pStmt->sql.stbInterlaceMode) {
176,116✔
3387
    pStmt->bInfo.tagsCached = false;
7,633✔
3388
  }
3389
  pStmt->bInfo.boundColsCached = false;
176,180✔
3390

3391
  STMT_ERR_RET(stmtCleanSQLInfo(pStmt));
176,120✔
3392

3393
  if (pStmt->options.asyncExecFn) {
176,035✔
3394
    if (tsem_destroy(&pStmt->asyncExecSem) != 0) {
1,326✔
3395
      STMT2_ELOG_E("fail to destroy asyncExecSem");
×
3396
    }
3397
  }
3398
  taosMemoryFree(stmt);
176,155✔
3399

3400
  return TSDB_CODE_SUCCESS;
176,155✔
3401
}
3402

3403
const char* stmt2Errstr(TAOS_STMT2* stmt) {
6,474✔
3404
  STscStmt2* pStmt = (STscStmt2*)stmt;
6,474✔
3405

3406
  if (stmt == NULL || NULL == pStmt->exec.pRequest) {
6,474✔
3407
    return (char*)tstrerror(terrno);
408✔
3408
  }
3409

3410
  // if stmt async exec ,error code is pStmt->exec.pRequest->code
3411
  if (!(pStmt->sql.status >= STMT_EXECUTE && pStmt->options.asyncExecFn != NULL && pStmt->asyncResultAvailable)) {
6,066✔
3412
    pStmt->exec.pRequest->code = terrno;
6,066✔
3413
  }
3414

3415
  SRequestObj* pRequest = pStmt->exec.pRequest;
6,066✔
3416
  if (NULL != pRequest->msgBuf && (strlen(pRequest->msgBuf) > 0 || pRequest->code == TSDB_CODE_RPC_FQDN_ERROR)) {
6,066✔
3417
    return pRequest->msgBuf;
3,986✔
3418
  }
3419
  return (const char*)tstrerror(pRequest->code);
2,080✔
3420
}
3421

3422
// Alias kept for compatibility with object files compiled against older headers.
3423
const char* stmtErrstr2(TAOS_STMT2* stmt) { return stmt2Errstr(stmt); }
×
3424
/*
3425
int stmtAffectedRows(TAOS_STMT* stmt) { return ((STscStmt2*)stmt)->affectedRows; }
3426

3427
int stmtAffectedRowsOnce(TAOS_STMT* stmt) { return ((STscStmt2*)stmt)->exec.affectedRows; }
3428
*/
3429

3430
int stmtParseColFields2(TAOS_STMT2* stmt) {
7,463✔
3431
  int32_t    code = 0;
7,463✔
3432
  STscStmt2* pStmt = (STscStmt2*)stmt;
7,463✔
3433
  int32_t    preCode = pStmt->errCode;
7,463✔
3434

3435
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
7,463✔
3436
    return pStmt->errCode;
×
3437
  }
3438

3439
  if (STMT_TYPE_QUERY == pStmt->sql.type) {
7,463✔
3440
    STMT2_ELOG_E("stmtParseColFields2 only for insert");
×
3441
    STMT_ERRI_JRET(TSDB_CODE_TSC_STMT_API_ERROR);
×
3442
  }
3443

3444
  STMT_ERRI_JRET(stmtSwitchStatus(pStmt, STMT_FETCH_FIELDS));
7,463✔
3445

3446
  if (pStmt->bInfo.needParse && pStmt->sql.runTimes && pStmt->sql.type > 0 &&
7,463✔
3447
      STMT_TYPE_MULTI_INSERT != pStmt->sql.type) {
306✔
3448
    pStmt->bInfo.needParse = false;
×
3449
  }
3450
  if (pStmt->sql.stbInterlaceMode && pStmt->sql.siInfo.pDataCtx != NULL) {
7,463✔
3451
    pStmt->bInfo.needParse = false;
612✔
3452
  }
3453

3454
  STMT_ERRI_JRET(stmtCreateRequest(pStmt));
7,463✔
3455

3456
  if (pStmt->bInfo.needParse) {
7,463✔
3457
    STMT_ERRI_JRET(stmtParseSql(pStmt));
6,749✔
3458
  }
3459

3460
_return:
5,533✔
3461
  // compatible with previous versions
3462
  if (code == TSDB_CODE_PAR_TABLE_NOT_EXIST && (pStmt->bInfo.tbNameFlag & NO_DATA_USING_CLAUSE) == 0x0) {
7,463✔
3463
    code = TSDB_CODE_TSC_STMT_TBNAME_ERROR;
408✔
3464
  }
3465

3466
  pStmt->errCode = preCode;
7,463✔
3467

3468
  return code;
7,463✔
3469
}
3470

3471
int stmtGetStbColFields2(TAOS_STMT2* stmt, int* nums, TAOS_FIELD_ALL** fields) {
7,463✔
3472
  int32_t code = stmtParseColFields2(stmt);
7,463✔
3473
  if (code != TSDB_CODE_SUCCESS) {
7,463✔
3474
    return code;
1,930✔
3475
  }
3476

3477
  return stmtFetchStbColFields2(stmt, nums, fields);
5,533✔
3478
}
3479

3480
/* When connection has no default DB (no USE), db may still appear as db.table in SQL. */
3481
static const char* stmtGetDbNameFromPrepareSelect(STscStmt2* pStmt) {
306✔
3482
  if (pStmt->sql.pQuery == NULL || pStmt->sql.pQuery->pPrepareRoot == NULL) {
306✔
3483
    return NULL;
×
3484
  }
3485
  SNode* pRoot = pStmt->sql.pQuery->pPrepareRoot;
306✔
3486
  if (QUERY_NODE_SELECT_STMT != nodeType(pRoot)) {
306✔
3487
    return NULL;
×
3488
  }
3489
  SSelectStmt* pSelect = (SSelectStmt*)pRoot;
306✔
3490
  SNode*       pFrom = pSelect->pFromTable;
306✔
3491
  if (pFrom == NULL) {
306✔
3492
    return NULL;
×
3493
  }
3494
  if (QUERY_NODE_REAL_TABLE == nodeType(pFrom)) {
306✔
3495
    SRealTableNode* pReal = (SRealTableNode*)pFrom;
306✔
3496
    if (pReal->table.dbName[0] != '\0') {
306✔
3497
      return pReal->table.dbName;
306✔
3498
    }
3499
  }
3500
  return NULL;
×
3501
}
3502

3503
static int32_t stmtFillDbPrecisionFieldForQuery(STscStmt2* pStmt, TAOS_FIELD_ALL** fields) {
2,142✔
3504
  if (pStmt->exec.pRequest == NULL) {
2,142✔
3505
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
3506
  }
3507
  const char* pDbName = pStmt->exec.pRequest->pDb;
2,142✔
3508
  if (pDbName == NULL || pDbName[0] == '\0') {
2,142✔
3509
    pDbName = pStmt->db;
306✔
3510
  }
3511
  if (pDbName == NULL || pDbName[0] == '\0') {
2,142✔
3512
    pDbName = stmtGetDbNameFromPrepareSelect(pStmt);
306✔
3513
  }
3514
  if (pDbName == NULL || pDbName[0] == '\0') {
2,142✔
3515
    return TSDB_CODE_PAR_DB_NOT_SPECIFIED;
×
3516
  }
3517

3518
  TAOS_FIELD_ALL* pField = taosMemoryCalloc(1, sizeof(TAOS_FIELD_ALL));
2,142✔
3519
  if (pField == NULL) {
2,142✔
3520
    return terrno;
×
3521
  }
3522

3523
  tstrncpy(pField->name, pDbName, sizeof(pField->name));
2,142✔
3524
  pField->field_type = TAOS_FIELD_DB;
2,142✔
3525
  pField->type = TSDB_DATA_TYPE_NULL;  // use null type to avoid unexpected behavior
2,142✔
3526
  pField->scale = 0;
2,142✔
3527
  pField->bytes = 0;
2,142✔
3528

3529
  SDbCfgInfo dbCfg = {0};
2,142✔
3530
  int32_t    code = TSDB_CODE_SUCCESS;
2,142✔
3531
  if (IS_SYS_DBNAME(pDbName)) {
2,142✔
3532
    dbCfg.precision = TSDB_TIME_PRECISION_MILLI;
×
3533
  } else {
3534
    if (NULL == pStmt->pCatalog) {
2,142✔
3535
      code = catalogGetHandle(pStmt->taos->pAppInfo->clusterId, &pStmt->pCatalog);
1,428✔
3536
      if (code != TSDB_CODE_SUCCESS) {
1,428✔
3537
        taosMemoryFree(pField);
×
3538
        return code;
×
3539
      }
3540
      pStmt->sql.siInfo.pCatalog = pStmt->pCatalog;
1,428✔
3541
    }
3542
    SName name = {0};
2,142✔
3543
    char  dbFname[TSDB_DB_FNAME_LEN] = {0};
2,142✔
3544
    code = tNameSetDbName(&name, pStmt->taos->acctId, pDbName, strlen(pDbName));
2,142✔
3545
    if (code != TSDB_CODE_SUCCESS) {
2,142✔
3546
      taosMemoryFree(pField);
×
3547
      return code;
×
3548
    }
3549
    (void)tNameGetFullDbName(&name, dbFname);
2,142✔
3550
    SRequestConnInfo conn = {.pTrans = pStmt->taos->pAppInfo->pTransporter,
2,142✔
3551
                             .requestId = pStmt->exec.pRequest->requestId,
2,142✔
3552
                             .requestObjRefId = pStmt->exec.pRequest->self,
2,142✔
3553
                             .mgmtEps = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp)};
2,142✔
3554
    code = catalogGetDBCfg(pStmt->pCatalog, &conn, dbFname, &dbCfg);
2,142✔
3555
    if (code != TSDB_CODE_SUCCESS) {
2,142✔
3556
      taosMemoryFree(pField);
×
3557
      return code;
×
3558
    }
3559
  }
3560

3561
  pField->precision = (uint8_t)dbCfg.precision;
2,142✔
3562
  *fields = pField;
2,142✔
3563
  return TSDB_CODE_SUCCESS;
2,142✔
3564
}
3565

3566
int stmtGetParamNum2(TAOS_STMT2* stmt, int* nums, TAOS_FIELD_ALL** fields) {
2,550✔
3567
  int32_t    code = 0;
2,550✔
3568
  STscStmt2* pStmt = (STscStmt2*)stmt;
2,550✔
3569
  int32_t    preCode = pStmt->errCode;
2,550✔
3570

3571
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
2,550✔
3572
    return pStmt->errCode;
×
3573
  }
3574

3575
  STMT_ERRI_JRET(stmtSwitchStatus(pStmt, STMT_FETCH_FIELDS));
2,550✔
3576

3577
  if (pStmt->bInfo.needParse && pStmt->sql.runTimes && pStmt->sql.type > 0 &&
2,550✔
3578
      STMT_TYPE_MULTI_INSERT != pStmt->sql.type) {
×
3579
    pStmt->bInfo.needParse = false;
×
3580
  }
3581

3582
  if (pStmt->exec.pRequest && STMT_TYPE_QUERY == pStmt->sql.type && pStmt->sql.runTimes) {
2,550✔
3583
    resetRequest(pStmt);
×
3584
  }
3585

3586
  STMT_ERRI_JRET(stmtCreateRequest(pStmt));
2,550✔
3587

3588
  if (pStmt->bInfo.needParse) {
2,550✔
3589
    STMT_ERRI_JRET(stmtParseSql(pStmt));
×
3590
  }
3591

3592
  if (STMT_TYPE_QUERY == pStmt->sql.type || (pStmt->sql.type == 0 && stmt2IsSelect(stmt))) {
2,550✔
3593
    *nums = taosArrayGetSize(pStmt->sql.pQuery->pPlaceholderValues);
2,550✔
3594
    if (fields != NULL) {
2,550✔
3595
      STMT_ERRI_JRET(stmtFillDbPrecisionFieldForQuery(pStmt, fields));
2,142✔
3596
    }
3597
  } else {
3598
    STMT_ERRI_JRET(stmtFetchColFields2(stmt, nums, NULL));
×
3599
  }
3600

3601
  STMT2_DLOG("get param num success, nums:%d", *nums);
2,550✔
3602

3603
_return:
2,550✔
3604

3605
  pStmt->errCode = preCode;
2,550✔
3606

3607
  return code;
2,550✔
3608
}
3609

3610
TAOS_RES* stmtUseResult2(TAOS_STMT2* stmt) {
6,669✔
3611
  STscStmt2* pStmt = (STscStmt2*)stmt;
6,669✔
3612

3613
  STMT2_TLOG_E("start to use result");
6,669✔
3614

3615
  if (STMT_TYPE_QUERY != pStmt->sql.type) {
6,669✔
3616
    STMT2_ELOG_E("useResult only for query statement");
×
3617
    return NULL;
×
3618
  }
3619

3620
  if (pStmt->options.asyncExecFn != NULL && !pStmt->asyncResultAvailable) {
6,669✔
3621
    STMT2_ELOG_E("use result after callBackFn return");
102✔
3622
    return NULL;
102✔
3623
  }
3624

3625
  if (tsUseAdapter) {
6,567✔
3626
    TAOS_RES* res = (TAOS_RES*)pStmt->exec.pRequest;
2,346✔
3627
    pStmt->exec.pRequest = NULL;
2,346✔
3628
    return res;
2,346✔
3629
  }
3630

3631
  return pStmt->exec.pRequest;
4,221✔
3632
}
3633

3634
int32_t stmtAsyncBindThreadFunc(void* args) {
×
3635
  qInfo("async stmt bind thread started");
×
3636

3637
  ThreadArgs* targs = (ThreadArgs*)args;
×
3638
  STscStmt2*  pStmt = (STscStmt2*)targs->stmt;
×
3639

3640
  int code = taos_stmt2_bind_param(targs->stmt, targs->bindv, targs->col_idx);
×
3641
  targs->fp(targs->param, NULL, code);
×
3642
  (void)taosThreadMutexLock(&(pStmt->asyncBindParam.mutex));
×
3643
  (void)atomic_sub_fetch_8(&pStmt->asyncBindParam.asyncBindNum, 1);
×
3644
  (void)taosThreadCondSignal(&(pStmt->asyncBindParam.waitCond));
×
3645
  (void)taosThreadMutexUnlock(&(pStmt->asyncBindParam.mutex));
×
3646
  taosMemoryFree(args);
×
3647

3648
  qInfo("async stmt bind thread stopped");
×
3649

3650
  return code;
×
3651
}
3652

3653
void stmtBuildErrorMsg(STscStmt2* pStmt, const char* msg) {
306✔
3654
  if (pStmt == NULL || msg == NULL) {
306✔
3655
    return;
×
3656
  }
3657

3658
  if (pStmt->exec.pRequest == NULL) {
306✔
3659
    return;
×
3660
  }
3661

3662
  if (pStmt->exec.pRequest->msgBuf == NULL) {
306✔
3663
    return;
×
3664
  }
3665

3666
  size_t msgLen = strlen(msg);
306✔
3667
  size_t bufLen = pStmt->exec.pRequest->msgBufLen;
306✔
3668

3669
  if (msgLen >= bufLen) {
306✔
3670
    tstrncpy(pStmt->exec.pRequest->msgBuf, msg, bufLen - 1);
×
3671
    pStmt->exec.pRequest->msgBuf[bufLen - 1] = '\0';
×
3672
    pStmt->exec.pRequest->msgBufLen = bufLen - 1;
×
3673
  } else {
3674
    tstrncpy(pStmt->exec.pRequest->msgBuf, msg, bufLen);
306✔
3675
    pStmt->exec.pRequest->msgBufLen = msgLen;
306✔
3676
  }
3677

3678
  return;
306✔
3679
}
3680

3681
int32_t stmtBuildErrorMsgWithCode(STscStmt2* pStmt, const char* msg, int32_t errorCode) {
306✔
3682
  stmtBuildErrorMsg(pStmt, msg);
306✔
3683
  pStmt->errCode = errorCode;
306✔
3684

3685
  return errorCode;
306✔
3686
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc