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

taosdata / TDengine / #5060

17 May 2026 01:15AM UTC coverage: 73.425% (-0.02%) from 73.443%
#5060

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)

281800 of 383795 relevant lines covered (73.42%)

134332207.97 hits per line

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

73.66
/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,653,675✔
21
    *pBuf = (char*)pTblBuf->pCurBuff + pTblBuf->buffOffset;
1,653,572✔
22
    pTblBuf->buffOffset += pTblBuf->buffUnit;
1,653,708✔
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,652,185✔
47
}
48

49
static bool stmtDequeue(STscStmt2* pStmt, SStmtQNode** param) {
1,653,660✔
50
  int i = 0;
1,653,660✔
51
  while (0 == atomic_load_64((int64_t*)&pStmt->queue.qRemainNum)) {
7,261,352✔
52
    if (pStmt->queue.stopQueue) {
5,625,646✔
53
      return false;
17,188✔
54
    }
55
    if (i < 10) {
5,608,658✔
56
      taosUsleep(1);
5,259,695✔
57
      i++;
5,258,499✔
58
    } else {
59
      (void)taosThreadMutexLock(&pStmt->queue.mutex);
348,963✔
60
      if (pStmt->queue.stopQueue) {
349,293✔
61
        (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
×
62
        return false;
×
63
      }
64
      if (0 == atomic_load_64((int64_t*)&pStmt->queue.qRemainNum)) {
349,243✔
65
        (void)taosThreadCondWait(&pStmt->queue.waitCond, &pStmt->queue.mutex);
349,050✔
66
      }
67
      (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
349,120✔
68
    }
69
  }
70

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

75
  (void)taosThreadMutexLock(&pStmt->queue.mutex);
1,635,950✔
76
  if (pStmt->queue.head == pStmt->queue.tail) {
1,636,902✔
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,636,852✔
84
  pStmt->queue.head->next = node->next;
1,636,852✔
85
  if (pStmt->queue.tail == node) {
1,636,791✔
86
    pStmt->queue.tail = pStmt->queue.head;
894,157✔
87
  }
88
  node->next = NULL;
1,636,791✔
89
  *param = node;
1,636,741✔
90

91
  (void)atomic_sub_fetch_64((int64_t*)&pStmt->queue.qRemainNum, 1);
1,636,691✔
92
  (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
1,636,890✔
93

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

96
  return true;
1,636,802✔
97
}
98

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

105
  param->next = NULL;
1,635,904✔
106

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

109
  pStmt->queue.tail->next = param;
1,636,694✔
110
  pStmt->queue.tail = param;
1,636,756✔
111
  pStmt->stat.bindDataNum++;
1,636,570✔
112

113
  (void)atomic_add_fetch_64(&pStmt->queue.qRemainNum, 1);
1,636,164✔
114
  (void)taosThreadCondSignal(&(pStmt->queue.waitCond));
1,636,718✔
115

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

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

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

125
  if (pStmt->exec.pRequest == NULL) {
3,443,951✔
126
    code = buildRequest(pStmt->taos->id, pStmt->sql.sqlStr, pStmt->sql.sqlLen, NULL, false, &pStmt->exec.pRequest,
184,016✔
127
                        pStmt->reqid);
128
    if (pStmt->reqid != 0) {
184,055✔
129
      pStmt->reqid++;
8✔
130
    }
131
    pStmt->exec.pRequest->type = RES_TYPE__QUERY;
184,055✔
132
    if (pStmt->db != NULL) {
183,991✔
133
      taosMemoryFreeClear(pStmt->exec.pRequest->pDb);
176,263✔
134
      pStmt->exec.pRequest->pDb = taosStrdup(pStmt->db);
176,234✔
135
    }
136
    if (TSDB_CODE_SUCCESS == code) {
183,778✔
137
      pStmt->exec.pRequest->syncQuery = true;
183,721✔
138
      pStmt->exec.pRequest->stmtBindVersion = 2;
183,657✔
139
    }
140
    STMT2_DLOG("create request:0x%" PRIx64 ", QID:0x%" PRIx64, pStmt->exec.pRequest->self,
184,033✔
141
               pStmt->exec.pRequest->requestId);
142
  }
143

144
  return code;
3,444,077✔
145
}
146

147
static int32_t stmtSwitchStatus(STscStmt2* pStmt, STMT_STATUS newStatus) {
4,650,595✔
148
  int32_t code = 0;
4,650,595✔
149

150
  if (newStatus >= STMT_INIT && newStatus < STMT_MAX) {
4,650,595✔
151
    STMT2_LOG_SEQ(newStatus);
4,651,957✔
152
  }
153

154
  if (pStmt->errCode && newStatus != STMT_PREPARE) {
4,651,921✔
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) {
4,652,264✔
160
    case STMT_PREPARE:
167,789✔
161
      pStmt->errCode = 0;
167,789✔
162
      break;
166,710✔
163
    case STMT_SETTBNAME:
1,147,192✔
164
      if (STMT_STATUS_EQ(INIT)) {
1,147,192✔
165
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
166
      }
167
      if (!pStmt->sql.stbInterlaceMode && (STMT_STATUS_EQ(BIND) || STMT_STATUS_EQ(BIND_COL))) {
1,147,602✔
168
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
169
      }
170
      break;
1,147,520✔
171
    case STMT_SETTAGS:
605,035✔
172
      if (STMT_STATUS_EQ(INIT)) {
605,035✔
173
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
174
      }
175
      break;
605,035✔
176
    case STMT_FETCH_FIELDS:
9,801✔
177
      if (STMT_STATUS_EQ(INIT)) {
9,801✔
178
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
179
      }
180
      break;
9,801✔
181
    case STMT_BIND:
1,299,276✔
182
      if (STMT_STATUS_EQ(INIT) || STMT_STATUS_EQ(BIND_COL)) {
1,299,276✔
183
        code = TSDB_CODE_TSC_STMT_API_ERROR;
100✔
184
      }
185
      /*
186
            if ((pStmt->sql.type == STMT_TYPE_MULTI_INSERT) && ()) {
187
              code = TSDB_CODE_TSC_STMT_API_ERROR;
188
            }
189
      */
190
      break;
1,299,252✔
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:
722,861✔
197
      if (STMT_STATUS_NE(BIND) && STMT_STATUS_NE(BIND_COL) && STMT_STATUS_NE(FETCH_FIELDS)) {
722,861✔
198
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
199
      }
200
      break;
722,861✔
201
    case STMT_EXECUTE:
700,310✔
202
      if (STMT_TYPE_QUERY == pStmt->sql.type) {
700,310✔
203
        if (STMT_STATUS_NE(ADD_BATCH) && STMT_STATUS_NE(FETCH_FIELDS) && STMT_STATUS_NE(BIND) &&
7,343✔
204
            STMT_STATUS_NE(BIND_COL)) {
442✔
205
          code = TSDB_CODE_TSC_STMT_API_ERROR;
442✔
206
        }
207
      } else {
208
        if (STMT_STATUS_NE(ADD_BATCH) && STMT_STATUS_NE(FETCH_FIELDS)) {
692,489✔
209
          code = TSDB_CODE_TSC_STMT_API_ERROR;
×
210
        }
211
      }
212
      break;
699,924✔
213
    default:
×
214
      code = TSDB_CODE_APP_ERROR;
×
215
      break;
×
216
  }
217

218
  STMT_ERR_RET(code);
4,651,103✔
219

220
  pStmt->sql.status = newStatus;
4,650,561✔
221

222
  return TSDB_CODE_SUCCESS;
4,651,475✔
223
}
224

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

228
  pStmt->sql.type = STMT_TYPE_MULTI_INSERT;
24,854✔
229

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

235
  *tbName = pStmt->bInfo.tbName;
20,424✔
236

237
  return TSDB_CODE_SUCCESS;
20,445✔
238
}
239

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

249
  if ((tags != NULL && ((SBoundColInfo*)tags)->numOfCols == 0) || !autoCreateTbl) {
159,865✔
250
    pStmt->sql.autoCreateTbl = false;
148,664✔
251
  }
252

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

257
  pStmt->bInfo.tbUid = autoCreateTbl ? 0 : pTableMeta->uid;
159,763✔
258
  pStmt->bInfo.tbSuid = pTableMeta->suid;
159,752✔
259
  pStmt->bInfo.tbVgId = pTableMeta->vgId;
159,676✔
260
  pStmt->bInfo.tbType = pTableMeta->tableType;
159,747✔
261

262
  if (!pStmt->bInfo.tagsCached) {
159,647✔
263
    qDestroyBoundColInfo(pStmt->bInfo.boundTags);
159,116✔
264
    taosMemoryFreeClear(pStmt->bInfo.boundTags);
159,284✔
265
  }
266

267
  // transfer ownership of cols to stmt
268
  if (cols) {
160,048✔
269
    pStmt->bInfo.fixedValueCols = *cols;
159,727✔
270
    *cols = NULL;
159,829✔
271
  }
272

273
  pStmt->bInfo.boundTags = tags;
159,841✔
274
  pStmt->bInfo.tagsCached = false;
159,717✔
275
  pStmt->bInfo.tbNameFlag = tbNameFlag;
159,302✔
276
  tstrncpy(pStmt->bInfo.stbFName, sTableName, sizeof(pStmt->bInfo.stbFName));
159,415✔
277

278
  if (pTableMeta->tableType != TSDB_CHILD_TABLE && pTableMeta->tableType != TSDB_SUPER_TABLE) {
159,715✔
279
    pStmt->sql.stbInterlaceMode = false;
6,012✔
280
  }
281

282
  return TSDB_CODE_SUCCESS;
159,338✔
283
}
284

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

288
  pStmt->sql.pVgHash = pVgHash;
159,752✔
289
  pStmt->exec.pBlockHash = pBlockHash;
159,722✔
290

291
  return TSDB_CODE_SUCCESS;
159,412✔
292
}
293

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

299
  STMT_ERR_RET(stmtUpdateBindInfo(stmt, pTableMeta, tags, cols, tbName, sTableName, autoCreateTbl, tbNameFlag));
159,879✔
300
  STMT_ERR_RET(stmtUpdateExecInfo(stmt, pVgHash, pBlockHash));
159,574✔
301

302
  pStmt->sql.autoCreateTbl = autoCreateTbl;
159,424✔
303

304
  return TSDB_CODE_SUCCESS;
159,697✔
305
}
306

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

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

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

316
  return TSDB_CODE_SUCCESS;
1,817✔
317
}
318

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

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

329
  STMT_ERR_RET(stmtCreateRequest(pStmt));
168,824✔
330
  pStmt->exec.pRequest->stmtBindVersion = 2;
168,712✔
331

332
  pStmt->stat.parseSqlNum++;
168,807✔
333

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

337
  pStmt->sql.siInfo.pQuery = pStmt->sql.pQuery;
167,004✔
338

339
  pStmt->bInfo.needParse = false;
166,970✔
340

341
  if (pStmt->sql.type == 0) {
166,786✔
342
    if (pStmt->sql.pQuery->pRoot && LEGAL_INSERT(nodeType(pStmt->sql.pQuery->pRoot))) {
142,773✔
343
      pStmt->sql.type = STMT_TYPE_INSERT;
135,783✔
344
      pStmt->sql.stbInterlaceMode = false;
135,782✔
345
    } else if (pStmt->sql.pQuery->pPrepareRoot && LEGAL_SELECT(nodeType(pStmt->sql.pQuery->pPrepareRoot))) {
7,147✔
346
      pStmt->sql.type = STMT_TYPE_QUERY;
6,601✔
347
      pStmt->sql.stbInterlaceMode = false;
6,601✔
348

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

364
  STableDataCxt** pSrc =
365
      (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
159,856✔
366
  if (NULL == pSrc || NULL == *pSrc) {
159,891✔
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;
159,891✔
372
  if (pStmt->sql.stbInterlaceMode && pTableCtx->pData->pCreateTbReq && (pStmt->bInfo.tbNameFlag & USING_CLAUSE) == 0) {
159,851✔
373
    STMT2_TLOG("destroy pCreateTbReq for no-using insert, tbFName:%s", pStmt->bInfo.tbFName);
2,100✔
374
    tdDestroySVCreateTbReq(pTableCtx->pData->pCreateTbReq);
2,100✔
375
    taosMemoryFreeClear(pTableCtx->pData->pCreateTbReq);
2,100✔
376
    pTableCtx->pData->pCreateTbReq = NULL;
2,100✔
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) {
159,809✔
392
    pStmt->sql.pBindInfo = taosMemoryMalloc(pTableCtx->boundColsInfo.numOfBound * sizeof(*pStmt->sql.pBindInfo));
158,123✔
393
    if (NULL == pStmt->sql.pBindInfo) {
158,030✔
394
      STMT2_ELOG_E("fail to malloc pBindInfo");
×
395
      return terrno;
×
396
    }
397
  }
398

399
  return TSDB_CODE_SUCCESS;
159,817✔
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) {
328,362✔
526
  if (pStmt->exec.pRequest) {
328,362✔
527
    taos_free_result(pStmt->exec.pRequest);
181,555✔
528
    pStmt->exec.pRequest = NULL;
181,555✔
529
  }
530
  pStmt->asyncResultAvailable = false;
328,383✔
531
}
328,384✔
532

533
static int32_t stmtCleanBindInfo(STscStmt2* pStmt) {
872,986✔
534
  pStmt->bInfo.tbUid = 0;
872,986✔
535
  pStmt->bInfo.tbVgId = -1;
873,112✔
536
  pStmt->bInfo.tbType = 0;
873,082✔
537
  pStmt->bInfo.needParse = true;
872,957✔
538
  pStmt->bInfo.inExecCache = false;
873,009✔
539

540
  pStmt->bInfo.tbName[0] = 0;
873,065✔
541
  pStmt->bInfo.tbFName[0] = 0;
873,109✔
542
  if (!pStmt->bInfo.tagsCached) {
872,963✔
543
    qDestroyBoundColInfo(pStmt->bInfo.boundTags);
663,112✔
544
    taosMemoryFreeClear(pStmt->bInfo.boundTags);
663,328✔
545
    pStmt->bInfo.boundTags = NULL;
663,266✔
546
  }
547

548
  if (!pStmt->bInfo.boundColsCached) {
873,114✔
549
    tSimpleHashCleanup(pStmt->bInfo.fixedValueCols);
339,595✔
550
    pStmt->bInfo.fixedValueCols = NULL;
339,575✔
551
  }
552

553
  if (!pStmt->sql.autoCreateTbl) {
873,184✔
554
    pStmt->bInfo.stbFName[0] = 0;
659,379✔
555
    pStmt->bInfo.tbSuid = 0;
659,452✔
556
  }
557

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

561
  return TSDB_CODE_SUCCESS;
872,303✔
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) {
533,239✔
570
  pTblBuf->pCurBuff = taosArrayGetP(pTblBuf->pBufList, 0);
533,239✔
571
  if (NULL == pTblBuf->pCurBuff) {
533,493✔
572
    tscError("QInfo:%p, fail to get buffer from list", pTblBuf);
132✔
573
    return;
×
574
  }
575
  pTblBuf->buffIdx = 1;
533,361✔
576
  pTblBuf->buffOffset = sizeof(*pQueue->head);
533,361✔
577

578
  pQueue->head = pQueue->tail = pTblBuf->pCurBuff;
533,361✔
579
  pQueue->qRemainNum = 0;
533,261✔
580
  pQueue->head->next = NULL;
533,161✔
581
}
582

583
static int32_t stmtCleanExecInfo(STscStmt2* pStmt, bool keepTable, bool deepClean) {
866,894✔
584
  if (pStmt->sql.stbInterlaceMode) {
866,894✔
585
    if (deepClean) {
542,483✔
586
      taosHashCleanup(pStmt->exec.pBlockHash);
9,236✔
587
      pStmt->exec.pBlockHash = NULL;
9,236✔
588

589
      if (NULL != pStmt->exec.pCurrBlock) {
9,236✔
590
        taosMemoryFreeClear(pStmt->exec.pCurrBlock->boundColsInfo.pColIndex);
8,915✔
591
        taosMemoryFreeClear(pStmt->exec.pCurrBlock->pData);
8,915✔
592
        qDestroyStmtDataBlock(pStmt->exec.pCurrBlock);
8,915✔
593
        pStmt->exec.pCurrBlock = NULL;
8,915✔
594
      }
595
      if (STMT_TYPE_QUERY != pStmt->sql.type) {
9,236✔
596
        resetRequest(pStmt);
9,236✔
597
      }
598
    } else {
599
      pStmt->sql.siInfo.pTableColsIdx = 0;
533,247✔
600
      stmtResetQueueTableBuf(&pStmt->sql.siInfo.tbBuf, &pStmt->queue);
533,347✔
601
      tSimpleHashClear(pStmt->sql.siInfo.pTableRowDataHash);
533,197✔
602
    }
603
    if (NULL != pStmt->exec.pRequest) {
542,777✔
604
      pStmt->exec.pRequest->body.resInfo.numOfRows = 0;
533,541✔
605
    }
606
  } else {
607
    if (STMT_TYPE_QUERY != pStmt->sql.type || deepClean) {
324,461✔
608
      resetRequest(pStmt);
317,389✔
609
    }
610

611
    size_t keyLen = 0;
324,363✔
612
    void*  pIter = taosHashIterate(pStmt->exec.pBlockHash, NULL);
324,363✔
613
    while (pIter) {
659,319✔
614
      STableDataCxt* pBlocks = *(STableDataCxt**)pIter;
334,913✔
615
      char*          key = taosHashGetKey(pIter, &keyLen);
334,913✔
616
      STableMeta*    pMeta = qGetTableMetaInDataBlock(pBlocks);
334,892✔
617

618
      if (keepTable && pBlocks == pStmt->exec.pCurrBlock) {
334,913✔
619
        TSWAP(pBlocks->pData, pStmt->exec.pCurrTbData);
159,014✔
620
        STMT_ERR_RET(qResetStmtDataBlock(pBlocks, false));
178,462✔
621

622
        pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter);
158,822✔
623
        continue;
159,014✔
624
      }
625

626
      qDestroyStmtDataBlock(pBlocks);
175,899✔
627
      STMT_ERR_RET(taosHashRemove(pStmt->exec.pBlockHash, key, keyLen));
175,797✔
628

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

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

638
    taosHashCleanup(pStmt->exec.pBlockHash);
158,491✔
639
    pStmt->exec.pBlockHash = NULL;
158,469✔
640

641
    tDestroySubmitTbData(pStmt->exec.pCurrTbData, TSDB_MSG_FLG_ENCODE);
158,416✔
642
    taosMemoryFreeClear(pStmt->exec.pCurrTbData);
158,492✔
643
  }
644

645
  STMT_ERR_RET(stmtCleanBindInfo(pStmt));
701,219✔
646
  STMT2_TLOG("finish clean exec info, stbInterlaceMode:%d, keepTable:%d, deepClean:%d", pStmt->sql.stbInterlaceMode,
700,721✔
647
             keepTable, deepClean);
648

649
  return TSDB_CODE_SUCCESS;
700,729✔
650
}
651

652
static void stmtFreeSingleVgDataBlock(void* p) {
767,276✔
653
  SVgDataBlocks* pVg = *(SVgDataBlocks**)p;
767,276✔
654
  if (pVg) {
767,299✔
655
    taosMemoryFree(pVg->pData);
767,250✔
656
    taosMemoryFree(pVg);
767,267✔
657
  }
658
}
767,364✔
659

660
static void stmtFreeVgDataBlocksForRetry(STscStmt2* pStmt) {
859,795✔
661
  if (pStmt->pVgDataBlocksForRetry) {
859,795✔
662
    taosArrayDestroyEx(pStmt->pVgDataBlocksForRetry, stmtFreeSingleVgDataBlock);
691,936✔
663
    pStmt->pVgDataBlocksForRetry = NULL;
692,106✔
664
  }
665
}
859,944✔
666

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

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

675
  int32_t num = taosArrayGetSize(pModif->pDataBlocks);
692,379✔
676
  pStmt->pVgDataBlocksForRetry = taosArrayInit(num, POINTER_BYTES);
691,865✔
677
  if (!pStmt->pVgDataBlocksForRetry) {
692,667✔
678
    return terrno;
×
679
  }
680

681
  for (int32_t i = 0; i < num; i++) {
1,459,888✔
682
    SVgDataBlocks* pSrc = taosArrayGetP(pModif->pDataBlocks, i);
767,694✔
683
    SVgDataBlocks* pDst = taosMemoryMalloc(sizeof(SVgDataBlocks));
767,675✔
684
    if (!pDst) {
767,162✔
685
      stmtFreeVgDataBlocksForRetry(pStmt);
×
686
      return terrno;
×
687
    }
688
    *pDst = *pSrc;
767,162✔
689
    pDst->pData = taosMemoryMalloc(pSrc->size);
767,148✔
690
    if (!pDst->pData) {
767,210✔
691
      taosMemoryFree(pDst);
×
692
      stmtFreeVgDataBlocksForRetry(pStmt);
×
693
      return terrno;
×
694
    }
695
    (void)memcpy(pDst->pData, pSrc->pData, pSrc->size);
767,117✔
696
    if (NULL == taosArrayPush(pStmt->pVgDataBlocksForRetry, &pDst)) {
1,535,374✔
697
      taosMemoryFree(pDst->pData);
×
698
      taosMemoryFree(pDst);
×
699
      stmtFreeVgDataBlocksForRetry(pStmt);
×
700
      return terrno;
×
701
    }
702
  }
703
  return TSDB_CODE_SUCCESS;
692,194✔
704
}
705

706
static int32_t stmtRestoreVgDataBlocksForRetry(STscStmt2* pStmt) {
300✔
707
  SVnodeModifyOpStmt* pModif = (SVnodeModifyOpStmt*)pStmt->sql.pQuery->pRoot;
300✔
708
  if (!pModif || !pStmt->pVgDataBlocksForRetry) {
300✔
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;
300✔
714
  pStmt->pVgDataBlocksForRetry = NULL;
300✔
715
  return TSDB_CODE_SUCCESS;
300✔
716
}
717

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

732
static void stmtFreeUidTableMetaHash(SHashObj* pHash) {
100✔
733
  if (pHash == NULL) {
100✔
734
    return;
×
735
  }
736
  void* pIter = NULL;
100✔
737
  while ((pIter = taosHashIterate(pHash, pIter)) != NULL) {
300✔
738
    STableMeta* pMeta = *(STableMeta**)pIter;
200✔
739
    taosMemoryFree(pMeta);
200✔
740
  }
741
  taosHashCleanup(pHash);
100✔
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) {
800✔
747
  if (!COL_VAL_IS_VALUE(pCv) || !IS_VAR_DATA_TYPE(colType)) {
800✔
748
    return true;
400✔
749
  }
750
  if (pCv->value.nData == 0) {
400✔
751
    return true;
×
752
  }
753
  if (pCv->value.pData == NULL) {
400✔
754
    return false;
×
755
  }
756
  const uint8_t* rbeg = (const uint8_t*)pRow;
400✔
757
  const uint8_t* rend = rbeg + pRow->len;
400✔
758
  const uint8_t* p = (const uint8_t*)pCv->value.pData;
400✔
759
  return (p >= rbeg) && (p + pCv->value.nData <= rend);
400✔
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) {
200✔
764
  uint16_t oldSver = pRow->sver;
200✔
765
  int32_t  nMax = pMeta->tableInfo.numOfColumns;
200✔
766
  SSchema* base = (SSchema*)&pMeta->schema[0];
200✔
767

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

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

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

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

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

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

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

882
static void stmtFreeHeapPatchRowsArray(SArray* aHeapRows) {
100✔
883
  if (aHeapRows == NULL) {
100✔
884
    return;
×
885
  }
886
  int32_t n = (int32_t)taosArrayGetSize(aHeapRows);
100✔
887
  for (int32_t i = 0; i < n; ++i) {
300✔
888
    SRow* p = taosArrayGetP(aHeapRows, i);
200✔
889
    tRowDestroy(p);
200✔
890
  }
891
  taosArrayDestroy(aHeapRows);
100✔
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) {
100✔
898
  if (pTb->uid == 0) {
100✔
899
    return;
×
900
  }
901
  void* pMv = taosHashGet(pUidMetaHash, &pTb->uid, sizeof(uint64_t));
100✔
902
  if (pMv == NULL) {
100✔
903
    return;
×
904
  }
905
  STableMeta* pMeta = *(STableMeta**)pMv;
100✔
906
  pTb->sver = pMeta->sversion;
100✔
907
  if (pTb->flags & SUBMIT_REQ_COLUMN_DATA_FORMAT) {
100✔
908
    return;
×
909
  }
910
  if (pTb->aRowP == NULL) {
100✔
911
    return;
×
912
  }
913
  if (pTb->pBlobSet != NULL) {
100✔
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);
100✔
925
  for (int32_t i = 0; i < nRow; ++i) {
300✔
926
    SRow* pRow = taosArrayGetP(pTb->aRowP, i);
200✔
927
    if (pRow == NULL) {
200✔
928
      continue;
×
929
    }
930
    if ((uint16_t)pMeta->sversion == pRow->sver) {
200✔
931
      continue;
×
932
    }
933
    if (pRow->flag & HAS_BLOB) {
200✔
934
      pRow->sver = (uint16_t)pMeta->sversion;
×
935
      continue;
×
936
    }
937
    SRow* pNew = NULL;
200✔
938
    if (stmtRebuildOneRowToLatestSchema(pRow, pMeta, &pNew) == TSDB_CODE_SUCCESS && pNew != NULL) {
200✔
939
      // pRow points into the decoded submit payload (tDecodeBinaryWithSize); do not tRowDestroy it.
940
      if (aHeapRows != NULL && taosArrayPush(aHeapRows, &pNew) == NULL) {
400✔
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);
200✔
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) {
100✔
954
  int32_t code = TSDB_CODE_SUCCESS;
100✔
955
  *ppHash = NULL;
100✔
956

957
  if (NULL == pStmt->pCatalog) {
100✔
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);
100✔
965
  if (pHash == NULL) {
100✔
966
    return terrno;
×
967
  }
968

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

974
  int32_t tblNum = pRequest->tableList ? (int32_t)taosArrayGetSize(pRequest->tableList) : 0;
100✔
975
  for (int32_t i = 0; i < tblNum; ++i) {
300✔
976
    SName*      pName = taosArrayGet(pRequest->tableList, i);
200✔
977
    STableMeta* pMeta = NULL;
200✔
978
    int32_t     c = catalogGetTableMeta(pStmt->pCatalog, &conn, pName, &pMeta);
200✔
979
    if (c != TSDB_CODE_SUCCESS) {
200✔
980
      if (pMeta != NULL) {
×
981
        taosMemoryFree(pMeta);
×
982
      }
983
      taosHashCleanup(pHash);
×
984
      return c;
×
985
    }
986
    if (pMeta != NULL) {
200✔
987
      STableMeta* pDup = stmtCloneTableMetaForRetry(pMeta);
200✔
988
      taosMemoryFree(pMeta);
200✔
989
      pMeta = NULL;
200✔
990
      if (pDup != NULL) {
200✔
991
        int32_t putCode = taosHashPut(pHash, &pDup->uid, sizeof(uint64_t), &pDup, POINTER_BYTES);
200✔
992
        if (putCode != TSDB_CODE_SUCCESS) {
200✔
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) {
100✔
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;
100✔
1026
  return TSDB_CODE_SUCCESS;
100✔
1027
}
1028

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

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

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

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

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

1059
    tDecoderInit(&decoder, (uint8_t*)pVg->pData + headSz, bodyLen);
100✔
1060
    code = tDecodeSubmitReq(&decoder, &req, NULL);
100✔
1061
    tDecoderClear(&decoder);
100✔
1062
    if (code != TSDB_CODE_SUCCESS) {
100✔
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) {
100✔
1068
      tDestroySubmitReq(&req, TSDB_MSG_FLG_DECODE);
×
1069
      continue;
×
1070
    }
1071

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

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

1084
    int32_t encCap = 0;
100✔
1085
    int32_t szRet = 0;
100✔
1086
    tEncodeSize(tEncodeSubmitReq, &req, encCap, szRet);
100✔
1087
    if (szRet != 0) {
100✔
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;
100✔
1095
    void*   pNew = taosMemoryMalloc(allocLen);
100✔
1096
    if (pNew == NULL) {
100✔
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);
100✔
1104
    ((SSubmitReq2Msg*)pNew)->header.vgId = htonl(pVg->vg.vgId);
100✔
1105
    ((SSubmitReq2Msg*)pNew)->version = htobe64(1);
100✔
1106

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

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

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

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

1129
  stmtFreeUidTableMetaHash(pUidMetaHash);
100✔
1130
  return TSDB_CODE_SUCCESS;
100✔
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) {
300✔
1141
  if (pStmt->sql.stbInterlaceMode && pStmt->sql.siInfo.pTableHash != NULL) {
300✔
1142
    tSimpleHashClear(pStmt->sql.siInfo.pTableHash);
300✔
1143
  }
1144
}
300✔
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) {
400✔
1149
  return (pMeta != NULL && pMeta->tableType == TSDB_SUPER_TABLE);
400✔
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,
200✔
1154
                                            int32_t nSubmitTb, SStmtRetryTbPatch* pPatch) {
1155
  if (NULL == pStmt->pCatalog) {
200✔
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,
200✔
1163
                           .requestId = pRequest->requestId,
200✔
1164
                           .requestObjRefId = pRequest->self,
200✔
1165
                           .mgmtEps = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp)};
200✔
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) {
200✔
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) {
200✔
1208
    int32_t nList = (int32_t)taosArrayGetSize(pRequest->tableList);
200✔
1209
    int32_t nonStbOrd = 0;
200✔
1210
    for (int32_t li = 0; li < nList; ++li) {
400✔
1211
      SName*      pName = taosArrayGet(pRequest->tableList, li);
400✔
1212
      STableMeta* pMeta = NULL;
400✔
1213
      int32_t     c = catalogGetTableMeta(pStmt->pCatalog, &conn, pName, &pMeta);
400✔
1214
      if (c != TSDB_CODE_SUCCESS) {
400✔
1215
        taosMemoryFreeClear(pMeta);
×
1216
        return c;
200✔
1217
      }
1218
      if (pMeta == NULL) {
400✔
1219
        return TSDB_CODE_INTERNAL_ERROR;
×
1220
      }
1221
      if (stmtRetryTbMetaIsSuperTable(pMeta)) {
400✔
1222
        taosMemoryFree(pMeta);
200✔
1223
        continue;
200✔
1224
      }
1225
      if (nonStbOrd == tbIdx) {
200✔
1226
        pPatch->uid = pMeta->uid;
200✔
1227
        pPatch->suid = pMeta->suid;
200✔
1228
        pPatch->sver = pMeta->sversion;
200✔
1229
        taosMemoryFree(pMeta);
200✔
1230
        return TSDB_CODE_SUCCESS;
200✔
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) {
200✔
1267
  if (pStmt->pVgDataBlocksForRetry == NULL || taosArrayGetSize(pStmt->pVgDataBlocksForRetry) == 0) {
200✔
1268
    return TSDB_CODE_SUCCESS;
×
1269
  }
1270

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

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

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

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

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

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

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

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

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

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

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

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

1350
  return TSDB_CODE_SUCCESS;
200✔
1351
}
1352

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

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

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

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

1370
  taosMemoryFree(pStmt->sql.pBindInfo);
167,697✔
1371
  taosMemoryFree(pStmt->sql.queryRes.fields);
167,419✔
1372
  taosMemoryFree(pStmt->sql.queryRes.userFields);
167,602✔
1373
  taosMemoryFree(pStmt->sql.sqlStr);
167,667✔
1374
  qDestroyQuery(pStmt->sql.pQuery);
167,307✔
1375
  taosArrayDestroy(pStmt->sql.nodeList);
167,633✔
1376
  taosHashCleanup(pStmt->sql.pVgHash);
167,705✔
1377
  pStmt->sql.pVgHash = NULL;
167,728✔
1378
  if (pStmt->sql.fixValueTags) {
167,728✔
1379
    pStmt->sql.fixValueTags = false;
1,760✔
1380
    tdDestroySVCreateTbReq(pStmt->sql.fixValueTbReq);
1,760✔
1381
    taosMemoryFreeClear(pStmt->sql.fixValueTbReq);
1,760✔
1382
    pStmt->sql.fixValueTbReq = NULL;
1,760✔
1383
  }
1384

1385
  void* pIter = taosHashIterate(pStmt->sql.pTableCache, NULL);
167,728✔
1386
  while (pIter) {
178,422✔
1387
    SStmtTableCache* pCache = (SStmtTableCache*)pIter;
10,694✔
1388

1389
    qDestroyStmtDataBlock(pCache->pDataCtx);
10,694✔
1390
    qDestroyBoundColInfo(pCache->boundTags);
10,649✔
1391
    taosMemoryFreeClear(pCache->boundTags);
10,672✔
1392

1393
    pIter = taosHashIterate(pStmt->sql.pTableCache, pIter);
10,649✔
1394
  }
1395
  taosHashCleanup(pStmt->sql.pTableCache);
167,728✔
1396
  pStmt->sql.pTableCache = NULL;
167,728✔
1397

1398
  STMT_ERR_RET(stmtCleanExecInfo(pStmt, false, true));
167,728✔
1399
  STMT_ERR_RET(stmtCleanBindInfo(pStmt));
167,571✔
1400
  stmtFreeVgDataBlocksForRetry(pStmt);
167,675✔
1401

1402
  taos_free_result(pStmt->sql.siInfo.pRequest);
167,705✔
1403
  taosHashCleanup(pStmt->sql.siInfo.pVgroupHash);
167,728✔
1404
  tSimpleHashCleanup(pStmt->sql.siInfo.pTableHash);
167,675✔
1405
  tSimpleHashCleanup(pStmt->sql.siInfo.pTableRowDataHash);
167,720✔
1406
  taosArrayDestroyEx(pStmt->sql.siInfo.tbBuf.pBufList, stmtFreeTbBuf);
167,667✔
1407
  taosMemoryFree(pStmt->sql.siInfo.pTSchema);
167,720✔
1408
  qDestroyStmtDataBlock(pStmt->sql.siInfo.pDataCtx);
167,728✔
1409
  taosArrayDestroyEx(pStmt->sql.siInfo.pTableCols, stmtFreeTbCols);
167,697✔
1410
  pStmt->sql.siInfo.pTableCols = NULL;
167,615✔
1411

1412
  (void)memset(&pStmt->sql, 0, sizeof(pStmt->sql));
167,629✔
1413
  pStmt->sql.siInfo.tableColsReady = true;
167,569✔
1414

1415
  STMT2_TLOG_E("end to free SQL info");
167,538✔
1416

1417
  return TSDB_CODE_SUCCESS;
167,591✔
1418
}
1419

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

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

1431
  int32_t code = catalogGetTableHashVgroup(pStmt->pCatalog, &conn, &pStmt->bInfo.sname, &vgInfo);
599,499✔
1432
  if (TSDB_CODE_SUCCESS != code) {
599,463✔
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));
599,463✔
1439
  if (TSDB_CODE_SUCCESS != code) {
599,439✔
1440
    STMT2_ELOG("fail to put vgroup info, code:%d", code);
×
1441
    return code;
×
1442
  }
1443

1444
  *vgId = vgInfo.vgId;
599,439✔
1445

1446
  return TSDB_CODE_SUCCESS;
599,439✔
1447
}
1448

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

1457
  pStmt->stat.ctgGetTbMetaNum++;
36,844✔
1458

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

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

1468
    STMT_ERR_RET(code);
×
1469
  }
1470

1471
  STMT_ERR_RET(code);
36,286✔
1472

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

1479
  taosMemoryFree(pTableMeta);
36,286✔
1480

1481
  return TSDB_CODE_SUCCESS;
36,344✔
1482
}
1483

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

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

1491
  return TSDB_CODE_SUCCESS;
29,270✔
1492
}
1493

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

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

1504
  STableDataCxt** pCxtInExec = taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
53,293✔
1505
  if (pCxtInExec) {
53,209✔
1506
    pStmt->bInfo.needParse = false;
3,500✔
1507
    pStmt->bInfo.inExecCache = true;
3,500✔
1508

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

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

1517
  if (NULL == pStmt->pCatalog) {
50,209✔
1518
    STMT_ERR_RET(catalogGetHandle(pStmt->taos->pAppInfo->clusterId, &pStmt->pCatalog));
17,857✔
1519
    pStmt->sql.siInfo.pCatalog = pStmt->pCatalog;
17,875✔
1520
  }
1521

1522
  if (NULL == pStmt->sql.pTableCache || taosHashGetSize(pStmt->sql.pTableCache) <= 0) {
50,263✔
1523
    if (pStmt->bInfo.inExecCache) {
20,423✔
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);
20,445✔
1530

1531
    return TSDB_CODE_SUCCESS;
20,437✔
1532
  }
1533

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

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

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

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

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

1552
      return TSDB_CODE_SUCCESS;
6,113✔
1553
    }
1554

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

1558
  uint64_t uid, suid;
21,957✔
1559
  int32_t  vgId;
21,957✔
1560
  int8_t   tableType;
21,957✔
1561

1562
  STMT_ERR_RET(stmtGetTableMetaAndValidate(pStmt, &uid, &suid, &vgId, &tableType));
23,757✔
1563

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

1566
  if (uid == pStmt->bInfo.tbUid) {
23,657✔
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) {
23,657✔
1575
    SStmtTableCache* pCache = taosHashGet(pStmt->sql.pTableCache, &cacheUid, sizeof(cacheUid));
500✔
1576
    if (NULL == pCache) {
500✔
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;
500✔
1584

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

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

1593
    return TSDB_CODE_SUCCESS;
500✔
1594
  }
1595

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

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

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

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

1614
    pStmt->exec.pCurrBlock = pNewBlock;
23,157✔
1615

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

1618
    return TSDB_CODE_SUCCESS;
23,157✔
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,636,794✔
1641
  SStmtQNode* pParam = (SStmtQNode*)param;
1,636,794✔
1642

1643
  if (pParam->restoreTbCols) {
1,636,794✔
1644
    for (int32_t i = 0; i < pStmt->sql.siInfo.pTableColsIdx; ++i) {
1,636,258✔
1645
      SArray** p = (SArray**)TARRAY_GET_ELEM(pStmt->sql.siInfo.pTableCols, i);
1,102,703✔
1646
      *p = taosArrayInit(20, POINTER_BYTES);
1,102,703✔
1647
      if (*p == NULL) {
1,102,517✔
1648
        pStmt->errCode = terrno;
24✔
1649
      }
1650
    }
1651
    atomic_store_8((int8_t*)&pStmt->sql.siInfo.tableColsReady, true);
533,605✔
1652
    STMT2_TLOG_E("restore pTableCols finished");
533,653✔
1653
  } else {
1654
    int code = qAppendStmt2TableOutput(pStmt->sql.pQuery, pStmt->sql.pVgHash, &pParam->tblData, pStmt->exec.pCurrBlock,
1,103,141✔
1655
                                       &pStmt->sql.siInfo, pParam->pCreateTbReq);
1656
    // taosMemoryFree(pParam->pTbData);
1657
    if (code != TSDB_CODE_SUCCESS) {
1,102,971✔
1658
      STMT2_ELOG("async append stmt output failed, tbname:%s, err:%s", pParam->tblData.tbName, tstrerror(code));
100✔
1659
      pStmt->errCode = code;
100✔
1660
    }
1661
    (void)atomic_sub_fetch_64(&pStmt->sql.siInfo.tbRemainNum, 1);
1,102,971✔
1662
  }
1663
}
1,636,754✔
1664

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

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

1671
  while (true) {
1,636,632✔
1672
    SStmtQNode* asyncParam = NULL;
1,653,920✔
1673

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

1682
    stmtAsyncOutput(pStmt, asyncParam);
1,636,780✔
1683
  }
1684

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

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

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

1703
  pStmt->bindThreadInUse = true;
17,288✔
1704

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

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

1715
  return TSDB_CODE_SUCCESS;
17,288✔
1716
}
1717

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

1723
  return TSDB_CODE_SUCCESS;
167,328✔
1724
}
1725

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

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

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

1746
  return TSDB_CODE_SUCCESS;
17,288✔
1747
}
1748

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

1754
  pStmt = taosMemoryCalloc(1, sizeof(STscStmt2));
164,356✔
1755
  if (NULL == pStmt) {
164,475✔
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);
164,475✔
1761
  if (NULL == pStmt->sql.pTableCache) {
164,475✔
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;
164,475✔
1768
  if (taos->db[0] != '\0') {
164,475✔
1769
    pStmt->db = taosStrdup(taos->db);
156,448✔
1770
  }
1771
  pStmt->bInfo.needParse = true;
164,475✔
1772
  pStmt->sql.status = STMT_INIT;
164,475✔
1773
  pStmt->errCode = TSDB_CODE_SUCCESS;
164,475✔
1774

1775
  if (NULL != pOptions) {
164,475✔
1776
    (void)memcpy(&pStmt->options, pOptions, sizeof(pStmt->options));
160,739✔
1777
    if (pOptions->singleStbInsert && pOptions->singleTableBindOnce) {
160,739✔
1778
      pStmt->stbInterlaceMode = true;
14,435✔
1779
    }
1780

1781
    pStmt->reqid = pOptions->reqid;
160,739✔
1782
  }
1783

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

1790
    pStmt->sql.siInfo.pTableHash = tSimpleHashInit(100, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY));
14,435✔
1791
    if (NULL == pStmt->sql.siInfo.pTableHash) {
14,435✔
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));
14,435✔
1798
    if (NULL == pStmt->sql.siInfo.pTableRowDataHash) {
14,435✔
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);
14,435✔
1805
    if (NULL == pStmt->sql.siInfo.pTableCols) {
14,435✔
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);
14,435✔
1812
    if (TSDB_CODE_SUCCESS == code) {
14,435✔
1813
      code = stmtInitQueue(pStmt);
14,435✔
1814
    }
1815
    if (TSDB_CODE_SUCCESS == code) {
14,435✔
1816
      code = stmtStartBindThread(pStmt);
14,435✔
1817
    }
1818
    if (TSDB_CODE_SUCCESS != code) {
14,435✔
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;
164,475✔
1827
  if (pStmt->options.asyncExecFn) {
164,475✔
1828
    if (tsem_init(&pStmt->asyncExecSem, 0, 1) != 0) {
1,300✔
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);
164,475✔
1836
  if (TSDB_CODE_SUCCESS != code) {
164,475✔
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;
164,475✔
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,
164,475✔
1849
             pStmt->stbInterlaceMode, pStmt->options.asyncExecFn != NULL);
1850

1851
  return pStmt;
164,436✔
1852
}
1853

1854
static int stmtSetDbName2(TAOS_STMT2* stmt, const char* dbName) {
144,383✔
1855
  STscStmt2* pStmt = (STscStmt2*)stmt;
144,383✔
1856
  if (dbName == NULL || dbName[0] == '\0') {
144,383✔
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);
144,640✔
1862
  if (pStmt->db == NULL || pStmt->db[0] == '\0') {
144,640✔
1863
    taosMemoryFreeClear(pStmt->db);
7,461✔
1864
    STMT2_DLOG("dbname:%s is by sql, not by taosconnect", dbName);
7,204✔
1865
    pStmt->db = taosStrdup(dbName);
7,204✔
1866
    (void)strdequote(pStmt->db);
7,127✔
1867
  }
1868
  STMT_ERR_RET(stmtCreateRequest(pStmt));
144,563✔
1869

1870
  // The SQL statement specifies a database name, overriding the previously specified database
1871
  taosMemoryFreeClear(pStmt->exec.pRequest->pDb);
144,383✔
1872
  pStmt->exec.pRequest->pDb = taosStrdup(dbName);
144,344✔
1873
  (void)strdequote(pStmt->exec.pRequest->pDb);
144,601✔
1874
  if (pStmt->exec.pRequest->pDb == NULL) {
144,338✔
1875
    return terrno;
×
1876
  }
1877
  if (pStmt->sql.stbInterlaceMode) {
144,546✔
1878
    pStmt->sql.siInfo.dbname = pStmt->exec.pRequest->pDb;
8,573✔
1879
  }
1880
  return TSDB_CODE_SUCCESS;
144,289✔
1881
}
1882
static int32_t stmtResetStbInterlaceCache(STscStmt2* pStmt) {
2,853✔
1883
  int32_t code = TSDB_CODE_SUCCESS;
2,853✔
1884

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

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

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

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

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

1913
  return TSDB_CODE_SUCCESS;
2,853✔
1914
}
1915

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

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

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

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

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

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

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

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

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

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

1974
    int32_t code = stmtIniAsyncBind(pStmt);
2,853✔
1975
    if (TSDB_CODE_SUCCESS != code) {
2,853✔
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,653✔
1983
  pStmt->options = options;
3,653✔
1984
  pStmt->reqid = reqid;
3,653✔
1985
  pStmt->stbInterlaceMode = stbInterlaceMode;
3,653✔
1986

1987
  pStmt->sql.pTableCache = taosHashInit(100, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
3,653✔
1988
  if (NULL == pStmt->sql.pTableCache) {
3,653✔
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,653✔
1994
  pStmt->sql.status = STMT_INIT;
3,653✔
1995
  pStmt->sql.siInfo.tableColsReady = true;
3,653✔
1996

1997
  return TSDB_CODE_SUCCESS;
3,653✔
1998
}
1999

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

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

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

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

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

2022
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_PREPARE));
167,789✔
2023

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

2035
  if (stmt2IsInsert(pStmt)) {
167,685✔
2036
    pStmt->sql.stbInterlaceMode = pStmt->stbInterlaceMode;
160,385✔
2037
    char* dbName = NULL;
160,385✔
2038
    if (qParseDbName(sql, length, &dbName)) {
160,385✔
2039
      STMT_ERR_RET(stmtSetDbName2(stmt, dbName));
144,345✔
2040
      taosMemoryFreeClear(dbName);
144,211✔
2041
    } else if (pStmt->db != NULL && pStmt->db[0] != '\0') {
15,728✔
2042
      taosMemoryFreeClear(pStmt->exec.pRequest->pDb);
15,629✔
2043
      pStmt->exec.pRequest->pDb = taosStrdup(pStmt->db);
15,653✔
2044
      if (pStmt->exec.pRequest->pDb == NULL) {
15,645✔
2045
        STMT_ERR_RET(terrno);
×
2046
      }
2047
      (void)strdequote(pStmt->exec.pRequest->pDb);
15,645✔
2048

2049
      if (pStmt->sql.stbInterlaceMode) {
15,612✔
2050
        pStmt->sql.siInfo.dbname = pStmt->exec.pRequest->pDb;
5,615✔
2051
      }
2052
    }
2053

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

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

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

2073
  SArray* pTblCols = NULL;
8,915✔
2074
  for (int32_t i = 0; i < STMT_TABLE_COLS_NUM; i++) {
8,861,135✔
2075
    pTblCols = taosArrayInit(20, POINTER_BYTES);
8,852,228✔
2076
    if (NULL == pTblCols) {
8,845,427✔
2077
      return terrno;
×
2078
    }
2079

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

2085
  pStmt->sql.siInfo.boundTags = pStmt->bInfo.boundTags;
8,907✔
2086

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

2090
  return TSDB_CODE_SUCCESS;
8,915✔
2091
}
2092

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

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

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

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

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

2114
  int64_t startUs = taosGetTimestampUs();
1,147,551✔
2115

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

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

2122
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_SETTBNAME));
1,148,095✔
2123

2124
  int32_t insert = 0;
1,147,423✔
2125
  if (!stmt2IsInsert(stmt)) {
1,147,423✔
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,147,266✔
2131

2132
  STMT_ERR_RET(qCreateSName2(&pStmt->bInfo.sname, tbName, pStmt->taos->acctId, pStmt->exec.pRequest->pDb,
1,147,368✔
2133
                             pStmt->exec.pRequest->msgBuf, pStmt->exec.pRequest->msgBufLen));
2134
  STMT_ERR_RET(tNameExtractFullName(&pStmt->bInfo.sname, pStmt->bInfo.tbFName));
1,146,685✔
2135
  tstrncpy(pStmt->bInfo.tbName, (char*)tNameGetTableName(&pStmt->bInfo.sname), TSDB_TABLE_NAME_LEN);
1,146,680✔
2136

2137
  if (!pStmt->sql.stbInterlaceMode || NULL == pStmt->sql.siInfo.pDataCtx) {
1,147,004✔
2138
    STMT_ERR_RET(stmtGetFromCache(pStmt));
53,124✔
2139

2140
    if (pStmt->bInfo.needParse) {
53,171✔
2141
      STMT_ERR_RET(stmtParseSql(pStmt));
20,445✔
2142
      if (!pStmt->sql.autoCreateTbl) {
20,309✔
2143
        uint64_t uid, suid;
10,795✔
2144
        int32_t  vgId;
10,664✔
2145
        int8_t   tableType;
10,694✔
2146

2147
        int32_t code = stmtGetTableMetaAndValidate(pStmt, &uid, &suid, &vgId, &tableType);
12,879✔
2148
        if (code != TSDB_CODE_SUCCESS) {
13,029✔
2149
          return code;
400✔
2150
        }
2151
      }
2152
    }
2153

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

2159
  if (pStmt->sql.stbInterlaceMode && NULL == pStmt->sql.siInfo.pDataCtx) {
1,145,866✔
2160
    STMT_ERR_RET(stmtInitStbInterlaceTableInfo(pStmt));
8,915✔
2161
  }
2162

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

2166
  return TSDB_CODE_SUCCESS;
1,146,617✔
2167
}
2168

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

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

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

2181
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_SETTAGS));
506,067✔
2182

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

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

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

2198
  STableDataCxt** pDataBlock = NULL;
505,803✔
2199
  if (pStmt->exec.pCurrBlock) {
505,803✔
2200
    pDataBlock = &pStmt->exec.pCurrBlock;
500,141✔
2201
  } else {
2202
    pDataBlock =
2203
        (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
5,662✔
2204
    if (NULL == pDataBlock) {
5,662✔
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,662✔
2209
      tdDestroySVCreateTbReq((*pDataBlock)->pData->pCreateTbReq);
200✔
2210
      taosMemoryFreeClear((*pDataBlock)->pData->pCreateTbReq);
200✔
2211
      (*pDataBlock)->pData->pCreateTbReq = NULL;
200✔
2212
    }
2213
  }
2214
  if (pStmt->bInfo.inExecCache && !pStmt->sql.autoCreateTbl) {
505,803✔
2215
    return TSDB_CODE_SUCCESS;
×
2216
  }
2217

2218
  STMT2_TLOG_E("start to bind stmt tag values");
505,803✔
2219

2220
  void* boundTags = NULL;
505,911✔
2221
  if (pStmt->sql.stbInterlaceMode) {
505,911✔
2222
    boundTags = pStmt->sql.siInfo.boundTags;
493,880✔
2223
    *pCreateTbReq = taosMemoryCalloc(1, sizeof(SVCreateTbReq));
493,880✔
2224
    if (NULL == pCreateTbReq) {
494,012✔
2225
      return terrno;
×
2226
    }
2227
    int32_t vgId = -1;
494,012✔
2228
    STMT_ERR_RET(stmtTryAddTableVgroupInfo(pStmt, &vgId));
494,012✔
2229
    (*pCreateTbReq)->uid = vgId;
494,108✔
2230
  } else {
2231
    boundTags = pStmt->bInfo.boundTags;
12,031✔
2232
  }
2233

2234
  STMT_ERR_RET(qBindStmtTagsValue2(*pDataBlock, boundTags, pStmt->bInfo.tbSuid, pStmt->bInfo.stbFName,
506,139✔
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;
505,967✔
2239
}
2240

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

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

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

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

2254
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_SETTAGS));
98,992✔
2255

2256
  if (pStmt->sql.fixValueTags) {
99,004✔
2257
    STMT2_TLOG_E("tags are fixed, use one createTbReq");
97,244✔
2258
    STMT_ERR_RET(cloneSVreateTbReq(pStmt->sql.fixValueTbReq, pCreateTbReq));
97,244✔
2259
    if ((*pCreateTbReq)->name) {
97,184✔
2260
      taosMemoryFree((*pCreateTbReq)->name);
97,184✔
2261
    }
2262
    (*pCreateTbReq)->name = taosStrdup(pStmt->bInfo.tbName);
97,244✔
2263
    int32_t vgId = -1;
97,232✔
2264
    STMT_ERR_RET(stmtTryAddTableVgroupInfo(pStmt, &vgId));
97,232✔
2265
    (*pCreateTbReq)->uid = vgId;
97,268✔
2266
    return TSDB_CODE_SUCCESS;
97,268✔
2267
  }
2268

2269
  STMT_ERR_RET(stmtCreateRequest(pStmt));
1,760✔
2270
  if (pStmt->bInfo.needParse) {
1,760✔
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,760✔
2279
    STMT_ERR_RET(stmtInitStbInterlaceTableInfo(pStmt));
×
2280
  }
2281

2282
  STableDataCxt** pDataBlock = NULL;
1,760✔
2283
  if (pStmt->exec.pCurrBlock) {
1,760✔
2284
    pDataBlock = &pStmt->exec.pCurrBlock;
×
2285
  } else {
2286
    pDataBlock =
2287
        (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
1,760✔
2288
    if (NULL == pDataBlock) {
1,760✔
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,760✔
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,760✔
2300
    STMT2_TLOG_E("tags are fixed, set createTbReq first time");
1,760✔
2301
    pStmt->sql.fixValueTags = true;
1,760✔
2302
    STMT_ERR_RET(cloneSVreateTbReq((*pDataBlock)->pData->pCreateTbReq, &pStmt->sql.fixValueTbReq));
1,760✔
2303
    STMT_ERR_RET(cloneSVreateTbReq(pStmt->sql.fixValueTbReq, pCreateTbReq));
1,760✔
2304
    (*pCreateTbReq)->uid = (*pDataBlock)->pMeta->vgId;
1,760✔
2305

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

2312
  return TSDB_CODE_SUCCESS;
1,760✔
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,417✔
2344
  int32_t code = 0;
5,417✔
2345
  int32_t preCode = pStmt->errCode;
5,417✔
2346

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

2351
  if (STMT_TYPE_QUERY == pStmt->sql.type) {
5,417✔
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,417✔
2357
  bool            cleanStb = false;
5,417✔
2358

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

2367
  if (NULL == pDataBlock || NULL == *pDataBlock) {
5,417✔
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,417✔
2373
  pStmt->sql.placeholderOfCols = 0;
5,417✔
2374
  int32_t totalNum = 0;
5,417✔
2375
  STMT_ERRI_JRET(qBuildStmtStbColFields(*pDataBlock, pStmt->bInfo.boundTags, pStmt->bInfo.fixedValueCols,
5,417✔
2376
                                        pStmt->bInfo.tbNameFlag, &totalNum, fields, &pStmt->sql.placeholderOfTags,
2377
                                        &pStmt->sql.placeholderOfCols));
2378

2379
  if (pStmt->bInfo.tbType == TSDB_SUPER_TABLE && cleanStb) {
5,417✔
2380
    taosMemoryFreeClear((*pDataBlock)->boundColsInfo.pColIndex);
3,817✔
2381
    qDestroyStmtDataBlock(*pDataBlock);
3,817✔
2382
    *pDataBlock = NULL;
3,817✔
2383
    if (taosHashRemove(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName)) != 0) {
3,817✔
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,817✔
2388
    pStmt->bInfo.tagsCached = false;
3,817✔
2389
    pStmt->bInfo.sname = (SName){0};
3,817✔
2390
    STMT_ERR_RET(stmtCleanBindInfo(pStmt));
3,817✔
2391
  }
2392

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

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

2400
_return:
5,417✔
2401

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

2404
  return code;
5,417✔
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,101,928✔
2424
  if (NULL == pStmt->sql.siInfo.pVgroupHash) {
1,101,928✔
2425
    pStmt->sql.siInfo.pVgroupHash =
533,867✔
2426
        taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_ENTRY_LOCK);
533,631✔
2427
  }
2428
  if (NULL == pStmt->sql.siInfo.pVgroupList) {
1,102,648✔
2429
    pStmt->sql.siInfo.pVgroupList = taosArrayInit(64, POINTER_BYTES);
533,879✔
2430
  }
2431

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

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

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

2445
  if (!pStmt->sql.siInfo.tbFromHash && pStmt->sql.siInfo.firstName[0] &&
1,102,665✔
2446
      0 == strcmp(pStmt->sql.siInfo.firstName, pStmt->bInfo.tbName)) {
31,608✔
2447
    pStmt->sql.siInfo.tbFromHash = true;
3,697✔
2448
  }
2449

2450
  if (0 == pStmt->sql.siInfo.firstName[0]) {
1,102,355✔
2451
    tstrncpy(pStmt->sql.siInfo.firstName, pStmt->bInfo.tbName, TSDB_TABLE_NAME_LEN);
8,657✔
2452
  }
2453

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

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

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

2465
  return TSDB_CODE_SUCCESS;
1,102,519✔
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,101,736✔
2471
      *pTableCols = (SArray*)taosArrayGetP(pStmt->sql.siInfo.pTableCols, pStmt->sql.siInfo.pTableColsIdx++);
1,102,439✔
2472
      break;
1,102,458✔
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,102,458✔
2489
}
2490

2491
static int32_t stmtCacheBlock(STscStmt2* pStmt) {
189,433✔
2492
  if (pStmt->sql.type != STMT_TYPE_MULTI_INSERT) {
189,433✔
2493
    return TSDB_CODE_SUCCESS;
145,993✔
2494
  }
2495

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

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

2504
  STableDataCxt** pSrc = taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
10,794✔
2505
  if (!pSrc) {
10,770✔
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;
10,770✔
2510

2511
  STMT_ERR_RET(qCloneStmtDataBlock(&pDst, *pSrc, true));
10,794✔
2512

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

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

2523
  if (pStmt->sql.autoCreateTbl) {
10,794✔
2524
    pStmt->bInfo.tagsCached = true;
2,618✔
2525
  } else {
2526
    pStmt->bInfo.boundTags = NULL;
8,176✔
2527
  }
2528

2529
  return TSDB_CODE_SUCCESS;
10,794✔
2530
}
2531

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

2535
  int64_t startUs = taosGetTimestampUs();
723,040✔
2536

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

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

2543
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_ADD_BATCH));
722,966✔
2544

2545
  if (pStmt->sql.stbInterlaceMode) {
722,976✔
2546
    int64_t startUs2 = taosGetTimestampUs();
533,395✔
2547
    pStmt->stat.addBatchUs += startUs2 - startUs;
533,395✔
2548

2549
    pStmt->sql.siInfo.tableColsReady = false;
533,545✔
2550

2551
    SStmtQNode* param = NULL;
533,545✔
2552
    STMT_ERR_RET(stmtAllocQNodeFromBuf(&pStmt->sql.siInfo.tbBuf, (void**)&param));
1,067,160✔
2553
    param->restoreTbCols = true;
533,507✔
2554
    param->next = NULL;
533,507✔
2555

2556
    if (pStmt->sql.autoCreateTbl) {
533,615✔
2557
      pStmt->bInfo.tagsCached = true;
198,672✔
2558
    }
2559
    pStmt->bInfo.boundColsCached = true;
533,507✔
2560

2561
    if (pStmt->queue.stopQueue) {
533,507✔
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);
533,407✔
2567

2568
    return TSDB_CODE_SUCCESS;
533,497✔
2569
  }
2570

2571
  STMT_ERR_RET(stmtCacheBlock(pStmt));
189,457✔
2572

2573
  return TSDB_CODE_SUCCESS;
189,428✔
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,001✔
2644
  SCatalogSyncCbParam* pCbParam = (SCatalogSyncCbParam*)param;
7,001✔
2645
  if (TSDB_CODE_SUCCESS == code && pResultMeta) {
7,001✔
2646
    *pCbParam->pRsp = *pResultMeta;
7,001✔
2647
    TAOS_MEMSET(pResultMeta, 0, sizeof(SMetaData));  // Clear to avoid double free
7,001✔
2648
  }
2649
  pCbParam->code = code;
7,001✔
2650
  if (tsem_post(&pCbParam->sem) != 0) {
7,001✔
2651
    tscError("failed to post semaphore");
×
2652
  }
2653
}
7,001✔
2654

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

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

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

2686
      if (tsem_destroy(&cbParam.sem) != 0) {
7,001✔
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,001✔
2698
  destoryCatalogReq(&catalogReq);
7,001✔
2699

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

2704
  return code;
7,001✔
2705
}
2706

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

2711
  int64_t startUs = taosGetTimestampUs();
1,299,471✔
2712

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

2717
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
1,299,459✔
2718
    return pStmt->errCode;
100✔
2719
  }
2720

2721
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_BIND));
1,299,308✔
2722

2723
  if (pStmt->bInfo.needParse && pStmt->sql.runTimes && pStmt->sql.type > 0 &&
1,298,927✔
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,298,755✔
2729
    resetRequest(pStmt);
1,342✔
2730
  }
2731

2732
  STMT_ERR_RET(stmtCreateRequest(pStmt));
1,298,950✔
2733
  if (pStmt->bInfo.needParse) {
1,298,824✔
2734
    code = stmtParseSql(pStmt);
134,676✔
2735
    if (code != TSDB_CODE_SUCCESS) {
134,735✔
2736
      goto cleanup_root;
×
2737
    }
2738
  }
2739

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

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

2772
    code = qStmtParseQuerySql(&ctx, pStmt->sql.pQuery, &metaData);
7,001✔
2773
    if (TSDB_CODE_SUCCESS == code) {
7,001✔
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));
6,901✔
2777
      (void)memset(&metaData, 0, sizeof(SMetaData));  // Clear to avoid double free
6,901✔
2778
    } else {
2779
      // Clean up metaData on failure - free all arrays
2780
      if (metaData.pVStbRefDbs) {
100✔
2781
        taosArrayDestroy(metaData.pVStbRefDbs);
100✔
2782
        metaData.pVStbRefDbs = NULL;
100✔
2783
      }
2784
      // Note: Other fields in metaData are managed by catalog module if ctgFree is true
2785
      goto cleanup_root;
100✔
2786
    }
2787

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

2796
    TSWAP(pStmt->exec.pRequest->dbList, pStmt->sql.pQuery->pDbList);
6,901✔
2797
    TSWAP(pStmt->exec.pRequest->tableList, pStmt->sql.pQuery->pTableList);
6,901✔
2798
    TSWAP(pStmt->exec.pRequest->targetTableList, pStmt->sql.pQuery->pTargetTableList);
6,901✔
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;
6,901✔
2807

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

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

2821
  STableDataCxt** pDataBlock = NULL;
1,291,193✔
2822

2823
  if (pStmt->exec.pCurrBlock) {
1,291,193✔
2824
    pDataBlock = &pStmt->exec.pCurrBlock;
1,136,727✔
2825
  } else {
2826
    pDataBlock =
2827
        (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
154,744✔
2828
    if (NULL == pDataBlock) {
154,744✔
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;
154,744✔
2833
    if (pStmt->sql.stbInterlaceMode) {
154,723✔
2834
      taosArrayDestroy(pStmt->exec.pCurrBlock->pData->aCol);
8,915✔
2835
      (*pDataBlock)->pData->aCol = NULL;
8,915✔
2836
    }
2837
    if (colIdx < -1) {
154,678✔
2838
      pStmt->sql.bindRowFormat = true;
100✔
2839
      taosArrayDestroy((*pDataBlock)->pData->aCol);
100✔
2840
      (*pDataBlock)->pData->aCol = taosArrayInit(20, POINTER_BYTES);
100✔
2841
    }
2842
  }
2843

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

2847
  SStmtQNode* param = NULL;
1,292,020✔
2848
  if (pStmt->sql.stbInterlaceMode) {
1,291,972✔
2849
    STMT_ERR_RET(stmtAllocQNodeFromBuf(&pStmt->sql.siInfo.tbBuf, (void**)&param));
2,204,759✔
2850
    STMT_ERR_RET(stmtGetTableColsFromCache(pStmt, &param->tblData.aCol));
2,204,464✔
2851
    taosArrayClear(param->tblData.aCol);
1,102,458✔
2852

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

2855
    param->restoreTbCols = false;
1,101,911✔
2856
    param->tblData.isOrdered = true;
1,101,911✔
2857
    param->tblData.isDuplicateTs = false;
1,101,961✔
2858
    tstrncpy(param->tblData.tbName, pStmt->bInfo.tbName, TSDB_TABLE_NAME_LEN);
1,101,833✔
2859

2860
    param->pCreateTbReq = pCreateTbReq;
1,102,008✔
2861
  }
2862

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

2866
  SArray*   pCols = pStmt->sql.stbInterlaceMode ? param->tblData.aCol : (*pDataBlock)->pData->aCol;
1,292,036✔
2867
  SBlobSet* pBlob = NULL;
1,291,211✔
2868
  if (colIdx < 0) {
1,291,116✔
2869
    if (pStmt->sql.stbInterlaceMode) {
1,290,958✔
2870
      (*pDataBlock)->pData->flags &= ~SUBMIT_REQ_COLUMN_DATA_FORMAT;
1,102,371✔
2871
      code = qBindStmtStbColsValue2(*pDataBlock, pCols, pStmt->bInfo.fixedValueCols, bind, pStmt->exec.pRequest->msgBuf,
1,498,181✔
2872
                                    pStmt->exec.pRequest->msgBufLen, &pStmt->sql.siInfo.pTSchema, pStmt->sql.pBindInfo,
1,102,823✔
2873
                                    pStmt->taos->optionInfo.charsetCxt, &pBlob);
1,102,731✔
2874
      param->tblData.isOrdered = (*pDataBlock)->ordered;
1,102,549✔
2875
      param->tblData.isDuplicateTs = (*pDataBlock)->duplicateTs;
1,103,133✔
2876
    } else {
2877
      if (colIdx == -1) {
188,555✔
2878
        if (pStmt->sql.bindRowFormat) {
188,315✔
2879
          STMT2_ELOG_E("can't mix bind row format and bind column format");
100✔
2880
          STMT_ERR_RET(TSDB_CODE_TSC_STMT_API_ERROR);
100✔
2881
        }
2882
        code = qBindStmtColsValue2(*pDataBlock, pCols, pStmt->bInfo.fixedValueCols, bind, pStmt->exec.pRequest->msgBuf,
352,649✔
2883
                                   pStmt->exec.pRequest->msgBufLen, pStmt->taos->optionInfo.charsetCxt);
352,322✔
2884
      } else {
2885
        code =
2886
            qBindStmt2RowValue(*pDataBlock, (*pDataBlock)->pData->aRowP, pStmt->bInfo.fixedValueCols, bind,
272✔
2887
                               pStmt->exec.pRequest->msgBuf, pStmt->exec.pRequest->msgBufLen,
272✔
2888
                               &pStmt->sql.siInfo.pTSchema, pStmt->sql.pBindInfo, pStmt->taos->optionInfo.charsetCxt);
281✔
2889
      }
2890
    }
2891

2892
    if (code) {
1,291,252✔
2893
      STMT2_ELOG("bind cols or rows failed, error:%s", tstrerror(code));
200✔
2894
      STMT_ERR_RET(code);
200✔
2895
    }
2896
  } else {
2897
    if (pStmt->sql.stbInterlaceMode) {
600✔
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) {
600✔
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) {
600✔
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;
600✔
2913

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

2918
    code = qBindStmtSingleColValue2(*pDataBlock, pCols, bind, pStmt->exec.pRequest->msgBuf,
600✔
2919
                                    pStmt->exec.pRequest->msgBufLen, colIdx, pStmt->bInfo.sBindRowNum,
600✔
2920
                                    pStmt->taos->optionInfo.charsetCxt);
600✔
2921
    if (code) {
600✔
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,291,964✔
2928
  pStmt->stat.bindDataUs3 += startUs4 - startUs3;
1,291,964✔
2929

2930
  if (pStmt->stbInterlaceMode) {
1,292,105✔
2931
    if (param) param->tblData.pBlobSet = pBlob;
1,118,712✔
2932
  }
2933

2934
  if (pStmt->sql.stbInterlaceMode) {
1,292,204✔
2935
    STMT_ERR_RET(stmtAppendTablePostHandle(pStmt, param));
1,102,903✔
2936
  } else {
2937
    STMT_ERR_RET(stmtAddBatch2(pStmt));
189,587✔
2938
  }
2939

2940
  pStmt->stat.bindDataUs4 += taosGetTimestampUs() - startUs4;
1,292,361✔
2941
  return TSDB_CODE_SUCCESS;
1,292,294✔
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,800✔
3078
  const STscObj* pTscObj = pRequest->pTscObj;
2,800✔
3079

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

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

3114
static void asyncQueryCb(void* userdata, TAOS_RES* res, int code) {
2,800✔
3115
  STscStmt2*        pStmt = userdata;
2,800✔
3116
  __taos_async_fn_t fp = pStmt->options.asyncExecFn;
2,800✔
3117
  pStmt->asyncResultAvailable = true;
2,800✔
3118
  pStmt->exec.pRequest->inCallback = true;
2,800✔
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,900✔
3122
    int32_t origExecCode = code;
200✔
3123
    STMT2_ELOG("async exec got NEED_CLIENT_HANDLE_ERROR (code:%s), retrying internally", tstrerror(code));
200✔
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);
200✔
3127
    if (retryCode == TSDB_CODE_SUCCESS) {
200✔
3128
      stmtInvalidateStbInterlaceTableUidCache(pStmt);
100✔
3129
      if (origExecCode == TSDB_CODE_TDB_TABLE_NOT_EXIST) {
100✔
3130
        retryCode = stmtUpdateVgDataBlocksTbMetaFromCatalog(pStmt, pStmt->exec.pRequest);
100✔
3131
      } else if (stmtIsSchemaVersionRetryError(origExecCode)) {
×
3132
        retryCode = stmtUpdateVgDataBlocksSchemaVer(pStmt, pStmt->exec.pRequest);
×
3133
      }
3134
    }
3135
    if (retryCode == TSDB_CODE_SUCCESS) {
200✔
3136
      (void)stmtRestoreVgDataBlocksForRetry(pStmt);
100✔
3137
      resetRequest(pStmt);
100✔
3138
      pStmt->asyncResultAvailable = false;
100✔
3139
      retryCode = stmtCreateRequest(pStmt);
100✔
3140
      if (retryCode == TSDB_CODE_SUCCESS) {
100✔
3141
        SRequestObj*         pNewReq = pStmt->exec.pRequest;
100✔
3142
        SSqlCallbackWrapper* pWrapper = taosMemoryCalloc(1, sizeof(SSqlCallbackWrapper));
100✔
3143
        if (pWrapper == NULL) {
100✔
3144
          retryCode = terrno;
×
3145
          resetRequest(pStmt);
×
3146
        } else {
3147
          pWrapper->pRequest = pNewReq;
100✔
3148
          pNewReq->pWrapper = pWrapper;
100✔
3149
          retryCode = createParseContext(pNewReq, &pWrapper->pParseCtx, pWrapper);
100✔
3150
          if (retryCode == TSDB_CODE_SUCCESS) {
100✔
3151
            pNewReq->syncQuery = false;
100✔
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;
100✔
3155
            ((SSyncQueryParam*)(pNewReq)->body.interParam)->userParam = pStmt;
100✔
3156
            launchAsyncQuery(pNewReq, pStmt->sql.pQuery, NULL, pWrapper);
100✔
3157
            // Retry asyncQueryCb will call fp, stmtCleanExecInfo, and tsem_post(asyncExecSem).
3158
            return;
100✔
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) {
100✔
3167
      fp(pStmt->options.userdata, res, code);
100✔
3168
    }
3169
  } else {
3170
    if (code == TSDB_CODE_SUCCESS) {
2,600✔
3171
      pStmt->exec.affectedRows = taos_affected_rows(res);
2,600✔
3172
      pStmt->affectedRows += pStmt->exec.affectedRows;
2,600✔
3173
    }
3174

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

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

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

3194
int stmtExec2(TAOS_STMT2* stmt, int* affected_rows) {
699,484✔
3195
  STscStmt2* pStmt = (STscStmt2*)stmt;
699,484✔
3196
  int32_t    code = 0;
699,484✔
3197
  int64_t    startUs = taosGetTimestampUs();
700,336✔
3198

3199
  STMT2_DLOG_E("start to exec");
700,336✔
3200

3201
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
700,300✔
3202
    return pStmt->errCode;
100✔
3203
  }
3204

3205
  STMT_ERR_RET(taosThreadMutexLock(&pStmt->asyncBindParam.mutex));
699,922✔
3206
  while (atomic_load_8((int8_t*)&pStmt->asyncBindParam.asyncBindNum) > 0) {
700,015✔
3207
    (void)taosThreadCondWait(&pStmt->asyncBindParam.waitCond, &pStmt->asyncBindParam.mutex);
×
3208
  }
3209
  STMT_ERR_RET(taosThreadMutexUnlock(&pStmt->asyncBindParam.mutex));
699,896✔
3210

3211
  if (pStmt->sql.stbInterlaceMode) {
699,927✔
3212
    STMT_ERR_RET(stmtAddBatch2(pStmt));
533,665✔
3213
  }
3214

3215
  code = stmtSwitchStatus(pStmt, STMT_EXECUTE);
699,867✔
3216
  if (code != TSDB_CODE_SUCCESS) goto _return;
700,113✔
3217

3218
  if (STMT_TYPE_QUERY != pStmt->sql.type) {
699,671✔
3219
    if (pStmt->sql.stbInterlaceMode) {
692,724✔
3220
      int64_t startTs = taosGetTimestampUs();
533,565✔
3221
      // wait for stmt bind thread to finish
3222
      while (atomic_load_64(&pStmt->sql.siInfo.tbRemainNum)) {
1,968,088✔
3223
        taosUsleep(1);
1,434,565✔
3224
      }
3225

3226
      if (pStmt->errCode != TSDB_CODE_SUCCESS) {
533,641✔
3227
        return pStmt->errCode;
100✔
3228
      }
3229

3230
      pStmt->stat.execWaitUs += taosGetTimestampUs() - startTs;
533,553✔
3231
      STMT_ERR_RET(qBuildStmtFinOutput(pStmt->sql.pQuery, pStmt->sql.pVgHash, pStmt->sql.siInfo.pVgroupList));
533,553✔
3232
      taosHashCleanup(pStmt->sql.siInfo.pVgroupHash);
533,479✔
3233
      pStmt->sql.siInfo.pVgroupHash = NULL;
533,503✔
3234
      pStmt->sql.siInfo.pVgroupList = NULL;
533,503✔
3235
    } else {
3236
      tDestroySubmitTbData(pStmt->exec.pCurrTbData, TSDB_MSG_FLG_ENCODE);
158,960✔
3237
      taosMemoryFreeClear(pStmt->exec.pCurrTbData);
159,262✔
3238

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

3241
      STMT_ERR_RET(qBuildStmtOutput(pStmt->sql.pQuery, pStmt->sql.pVgHash, pStmt->exec.pBlockHash));
158,856✔
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));
692,460✔
3246
  }
3247

3248
  pStmt->asyncResultAvailable = false;
698,907✔
3249
  SRequestObj*      pRequest = pStmt->exec.pRequest;
698,805✔
3250
  __taos_async_fn_t fp = pStmt->options.asyncExecFn;
698,875✔
3251
  STMT2_DLOG("EXEC INFO :req:0x%" PRIx64 ", QID:0x%" PRIx64 ", exec sql:%s,  conn:%" PRId64, pRequest->self,
699,147✔
3252
             pRequest->requestId, pStmt->sql.sqlStr, pRequest->pTscObj->id);
3253

3254
  if (!fp) {
699,052✔
3255
    launchQueryImpl(pStmt->exec.pRequest, pStmt->sql.pQuery, true, NULL);
696,352✔
3256

3257
    if (pStmt->exec.pRequest->code && NEED_CLIENT_HANDLE_ERROR(pStmt->exec.pRequest->code)) {
696,700✔
3258
      int32_t origExecCode = pStmt->exec.pRequest->code;
226✔
3259
      STMT2_WLOG_E("exec failed errorcode:NEED_CLIENT_HANDLE_ERROR, refresh meta and retry internally");
226✔
3260
      code = refreshMeta(pStmt->exec.pRequest->pTscObj, pStmt->exec.pRequest);
226✔
3261
      if (code == TSDB_CODE_SUCCESS) {
200✔
3262
        stmtInvalidateStbInterlaceTableUidCache(pStmt);
200✔
3263
      }
3264
      if (code == TSDB_CODE_SUCCESS && pStmt->pVgDataBlocksForRetry != NULL) {
200✔
3265
        if (origExecCode == TSDB_CODE_TDB_TABLE_NOT_EXIST) {
200✔
3266
          code = stmtUpdateVgDataBlocksTbMetaFromCatalog(pStmt, pStmt->exec.pRequest);
100✔
3267
        } else if (stmtIsSchemaVersionRetryError(origExecCode)) {
100✔
3268
          code = stmtUpdateVgDataBlocksSchemaVer(pStmt, pStmt->exec.pRequest);
100✔
3269
        }
3270
      }
3271
      if (code == TSDB_CODE_SUCCESS && pStmt->pVgDataBlocksForRetry != NULL) {
200✔
3272
        // Restore saved serialized data blocks and re-execute with refreshed meta.
3273
        STMT_ERR_JRET(stmtRestoreVgDataBlocksForRetry(pStmt));
200✔
3274
        resetRequest(pStmt);
200✔
3275
        STMT_ERR_JRET(stmtCreateRequest(pStmt));
200✔
3276
        launchQueryImpl(pStmt->exec.pRequest, pStmt->sql.pQuery, true, NULL);
200✔
3277
        code = pStmt->exec.pRequest->code;
200✔
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);
696,818✔
3286

3287
    pStmt->exec.affectedRows = taos_affected_rows(pStmt->exec.pRequest);
696,447✔
3288
    if (affected_rows) {
696,586✔
3289
      *affected_rows = pStmt->exec.affectedRows;
692,630✔
3290
    }
3291
    pStmt->affectedRows += pStmt->exec.affectedRows;
696,345✔
3292

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

3298
    STMT_ERR_RET(stmtCleanExecInfo(pStmt, (code ? false : true), false));
696,439✔
3299

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

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

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

3326
  STMT_RET(code);
699,838✔
3327
}
3328

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

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

3335
  if (pStmt->bindThreadInUse) {
163,991✔
3336
    // wait for stmt bind thread to finish
3337
    while (0 == atomic_load_8((int8_t*)&pStmt->sql.siInfo.tableColsReady)) {
14,435✔
3338
      taosUsleep(1);
100✔
3339
    }
3340

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

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

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

3353
  TSC_ERR_RET(taosThreadMutexLock(&pStmt->asyncBindParam.mutex));
163,940✔
3354
  while (atomic_load_8((int8_t*)&pStmt->asyncBindParam.asyncBindNum) > 0) {
164,023✔
3355
    (void)taosThreadCondWait(&pStmt->asyncBindParam.waitCond, &pStmt->asyncBindParam.mutex);
×
3356
  }
3357
  TSC_ERR_RET(taosThreadMutexUnlock(&pStmt->asyncBindParam.mutex));
164,052✔
3358

3359
  (void)taosThreadCondDestroy(&pStmt->asyncBindParam.waitCond);
163,955✔
3360
  (void)taosThreadMutexDestroy(&pStmt->asyncBindParam.mutex);
164,000✔
3361

3362
  if (pStmt->options.asyncExecFn && !pStmt->execSemWaited) {
164,052✔
3363
    if (tsem_wait(&pStmt->asyncExecSem) != 0) {
1,300✔
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) {
164,052✔
3371
    if (tsem_post(&pStmt->asyncExecSem) != 0) {
1,300✔
3372
      STMT2_ELOG_E("fail to post asyncExecSem");
×
3373
    }
3374
  }
3375

3376
  STMT2_DLOG("stbInterlaceMode:%d, statInfo: ctgGetTbMetaNum=>%" PRId64 ", getCacheTbInfo=>%" PRId64
164,075✔
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) {
164,075✔
3387
    pStmt->bInfo.tagsCached = false;
7,110✔
3388
  }
3389
  pStmt->bInfo.boundColsCached = false;
164,000✔
3390

3391
  STMT_ERR_RET(stmtCleanSQLInfo(pStmt));
164,052✔
3392

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

3400
  return TSDB_CODE_SUCCESS;
163,973✔
3401
}
3402

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

3406
  if (stmt == NULL || NULL == pStmt->exec.pRequest) {
6,240✔
3407
    return (char*)tstrerror(terrno);
400✔
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)) {
5,840✔
3412
    pStmt->exec.pRequest->code = terrno;
5,840✔
3413
  }
3414

3415
  SRequestObj* pRequest = pStmt->exec.pRequest;
5,840✔
3416
  if (NULL != pRequest->msgBuf && (strlen(pRequest->msgBuf) > 0 || pRequest->code == TSDB_CODE_RPC_FQDN_ERROR)) {
5,840✔
3417
    return pRequest->msgBuf;
3,814✔
3418
  }
3419
  return (const char*)tstrerror(pRequest->code);
2,026✔
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,301✔
3431
  int32_t    code = 0;
7,301✔
3432
  STscStmt2* pStmt = (STscStmt2*)stmt;
7,301✔
3433
  int32_t    preCode = pStmt->errCode;
7,301✔
3434

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

3439
  if (STMT_TYPE_QUERY == pStmt->sql.type) {
7,301✔
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,301✔
3445

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

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

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

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

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

3468
  return code;
7,301✔
3469
}
3470

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

3477
  return stmtFetchStbColFields2(stmt, nums, fields);
5,417✔
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) {
300✔
3482
  if (pStmt->sql.pQuery == NULL || pStmt->sql.pQuery->pPrepareRoot == NULL) {
300✔
3483
    return NULL;
×
3484
  }
3485
  SNode* pRoot = pStmt->sql.pQuery->pPrepareRoot;
300✔
3486
  if (QUERY_NODE_SELECT_STMT != nodeType(pRoot)) {
300✔
3487
    return NULL;
×
3488
  }
3489
  SSelectStmt* pSelect = (SSelectStmt*)pRoot;
300✔
3490
  SNode*       pFrom = pSelect->pFromTable;
300✔
3491
  if (pFrom == NULL) {
300✔
3492
    return NULL;
×
3493
  }
3494
  if (QUERY_NODE_REAL_TABLE == nodeType(pFrom)) {
300✔
3495
    SRealTableNode* pReal = (SRealTableNode*)pFrom;
300✔
3496
    if (pReal->table.dbName[0] != '\0') {
300✔
3497
      return pReal->table.dbName;
300✔
3498
    }
3499
  }
3500
  return NULL;
×
3501
}
3502

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

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

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

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

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

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

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

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

3577
  if (pStmt->bInfo.needParse && pStmt->sql.runTimes && pStmt->sql.type > 0 &&
2,500✔
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,500✔
3583
    resetRequest(pStmt);
×
3584
  }
3585

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

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

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

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

3603
_return:
2,500✔
3604

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

3607
  return code;
2,500✔
3608
}
3609

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

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

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

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

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

3631
  return pStmt->exec.pRequest;
4,101✔
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) {
300✔
3654
  if (pStmt == NULL || msg == NULL) {
300✔
3655
    return;
×
3656
  }
3657

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

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

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

3669
  if (msgLen >= bufLen) {
300✔
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);
300✔
3675
    pStmt->exec.pRequest->msgBufLen = msgLen;
300✔
3676
  }
3677

3678
  return;
300✔
3679
}
3680

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

3685
  return errorCode;
300✔
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