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

taosdata / TDengine / #5048

10 May 2026 03:11AM UTC coverage: 73.222% (+0.07%) from 73.152%
#5048

push

travis-ci

web-flow
merge: from main to 3.0 branch #35290

353 of 452 new or added lines in 9 files covered. (78.1%)

587 existing lines in 140 files now uncovered.

278189 of 379928 relevant lines covered (73.22%)

135206397.85 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,514,562✔
21
    *pBuf = (char*)pTblBuf->pCurBuff + pTblBuf->buffOffset;
1,514,640✔
22
    pTblBuf->buffOffset += pTblBuf->buffUnit;
1,514,656✔
23
  } else if (pTblBuf->buffIdx < taosArrayGetSize(pTblBuf->pBufList)) {
12✔
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,514,726✔
47
}
48

49
static bool stmtDequeue(STscStmt2* pStmt, SStmtQNode** param) {
1,514,637✔
50
  int i = 0;
1,514,637✔
51
  while (0 == atomic_load_64((int64_t*)&pStmt->queue.qRemainNum)) {
7,221,279✔
52
    if (pStmt->queue.stopQueue) {
5,853,577✔
53
      return false;
146,373✔
54
    }
55
    if (i < 10) {
5,707,265✔
56
      taosUsleep(1);
5,337,773✔
57
      i++;
5,337,315✔
58
    } else {
59
      (void)taosThreadMutexLock(&pStmt->queue.mutex);
369,492✔
60
      if (pStmt->queue.stopQueue) {
369,587✔
61
        (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
×
62
        return false;
×
63
      }
64
      if (0 == atomic_load_64((int64_t*)&pStmt->queue.qRemainNum)) {
369,562✔
65
        (void)taosThreadCondWait(&pStmt->queue.waitCond, &pStmt->queue.mutex);
369,467✔
66
      }
67
      (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
369,327✔
68
    }
69
  }
70

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

75
  (void)taosThreadMutexLock(&pStmt->queue.mutex);
1,367,256✔
76
  if (pStmt->queue.head == pStmt->queue.tail) {
1,368,167✔
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,368,039✔
84
  pStmt->queue.head->next = node->next;
1,368,089✔
85
  if (pStmt->queue.tail == node) {
1,368,142✔
86
    pStmt->queue.tail = pStmt->queue.head;
721,902✔
87
  }
88
  node->next = NULL;
1,368,192✔
89
  *param = node;
1,368,192✔
90

91
  (void)atomic_sub_fetch_64((int64_t*)&pStmt->queue.qRemainNum, 1);
1,368,167✔
92
  (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
1,368,213✔
93

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

96
  return true;
1,368,190✔
97
}
98

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

105
  param->next = NULL;
1,367,531✔
106

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

109
  pStmt->queue.tail->next = param;
1,368,043✔
110
  pStmt->queue.tail = param;
1,368,068✔
111
  pStmt->stat.bindDataNum++;
1,368,093✔
112

113
  (void)atomic_add_fetch_64(&pStmt->queue.qRemainNum, 1);
1,367,958✔
114
  (void)taosThreadCondSignal(&(pStmt->queue.waitCond));
1,368,115✔
115

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

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

122
static int32_t stmtCreateRequest(STscStmt2* pStmt) {
76,135,627✔
123
  int32_t code = 0;
76,135,627✔
124

125
  if (pStmt->exec.pRequest == NULL) {
76,135,627✔
126
    code = buildRequest(pStmt->taos->id, pStmt->sql.sqlStr, pStmt->sql.sqlLen, NULL, false, &pStmt->exec.pRequest,
179,675✔
127
                        pStmt->reqid);
128
    if (pStmt->reqid != 0) {
179,675✔
129
      pStmt->reqid++;
8✔
130
    }
131
    pStmt->exec.pRequest->type = RES_TYPE__QUERY;
179,675✔
132
    if (pStmt->db != NULL) {
179,675✔
133
      taosMemoryFreeClear(pStmt->exec.pRequest->pDb);
168,622✔
134
      pStmt->exec.pRequest->pDb = taosStrdup(pStmt->db);
168,578✔
135
    }
136
    if (TSDB_CODE_SUCCESS == code) {
179,653✔
137
      pStmt->exec.pRequest->syncQuery = true;
179,675✔
138
      pStmt->exec.pRequest->stmtBindVersion = 2;
179,675✔
139
    }
140
    STMT2_DLOG("create request:0x%" PRIx64 ", QID:0x%" PRIx64, pStmt->exec.pRequest->self,
179,653✔
141
               pStmt->exec.pRequest->requestId);
142
  }
143

144
  return code;
75,339,924✔
145
}
146

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

150
  if (newStatus >= STMT_INIT && newStatus < STMT_MAX) {
147,871,543✔
151
    STMT2_LOG_SEQ(newStatus);
149,596,871✔
152
  }
153

154
  if (pStmt->errCode && newStatus != STMT_PREPARE) {
148,796,468✔
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) {
148,143,091✔
160
    case STMT_PREPARE:
168,330✔
161
      pStmt->errCode = 0;
168,330✔
162
      break;
90,261✔
163
    case STMT_SETTBNAME:
968,653✔
164
      if (STMT_STATUS_EQ(INIT)) {
968,653✔
165
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
166
      }
167
      if (!pStmt->sql.stbInterlaceMode && (STMT_STATUS_EQ(BIND) || STMT_STATUS_EQ(BIND_COL))) {
968,742✔
168
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
169
      }
170
      break;
968,667✔
171
    case STMT_SETTAGS:
628,500✔
172
      if (STMT_STATUS_EQ(INIT)) {
628,500✔
173
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
174
      }
175
      break;
628,500✔
176
    case STMT_FETCH_FIELDS:
19,189✔
177
      if (STMT_STATUS_EQ(INIT)) {
19,189✔
178
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
179
      }
180
      break;
19,189✔
181
    case STMT_BIND:
72,875,467✔
182
      if (STMT_STATUS_EQ(INIT) || STMT_STATUS_EQ(BIND_COL)) {
72,875,467✔
183
        code = TSDB_CODE_TSC_STMT_API_ERROR;
198✔
184
      }
185
      /*
186
            if ((pStmt->sql.type == STMT_TYPE_MULTI_INSERT) && ()) {
187
              code = TSDB_CODE_TSC_STMT_API_ERROR;
188
            }
189
      */
190
      break;
74,117,973✔
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:
72,902,506✔
197
      if (STMT_STATUS_NE(BIND) && STMT_STATUS_NE(BIND_COL) && STMT_STATUS_NE(FETCH_FIELDS)) {
72,902,506✔
198
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
199
      }
200
      break;
73,283,172✔
201
    case STMT_EXECUTE:
580,446✔
202
      if (STMT_TYPE_QUERY == pStmt->sql.type) {
580,446✔
203
        if (STMT_STATUS_NE(ADD_BATCH) && STMT_STATUS_NE(FETCH_FIELDS) && STMT_STATUS_NE(BIND) &&
10,884✔
204
            STMT_STATUS_NE(BIND_COL)) {
419✔
205
          code = TSDB_CODE_TSC_STMT_API_ERROR;
419✔
206
        }
207
      } else {
208
        if (STMT_STATUS_NE(ADD_BATCH) && STMT_STATUS_NE(FETCH_FIELDS)) {
569,341✔
209
          code = TSDB_CODE_TSC_STMT_API_ERROR;
×
210
        }
211
      }
212
      break;
580,225✔
213
    default:
×
214
      code = TSDB_CODE_APP_ERROR;
×
215
      break;
×
216
  }
217

218
  STMT_ERR_RET(code);
148,932,215✔
219

220
  pStmt->sql.status = newStatus;
148,931,598✔
221

222
  return TSDB_CODE_SUCCESS;
148,527,296✔
223
}
224

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

228
  pStmt->sql.type = STMT_TYPE_MULTI_INSERT;
29,060✔
229

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

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

237
  return TSDB_CODE_SUCCESS;
20,330✔
238
}
239

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

249
  if ((tags != NULL && ((SBoundColInfo*)tags)->numOfCols == 0) || !autoCreateTbl) {
155,805✔
250
    pStmt->sql.autoCreateTbl = false;
133,783✔
251
  }
252

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

257
  pStmt->bInfo.tbUid = autoCreateTbl ? 0 : pTableMeta->uid;
155,272✔
258
  pStmt->bInfo.tbSuid = pTableMeta->suid;
155,506✔
259
  pStmt->bInfo.tbVgId = pTableMeta->vgId;
155,179✔
260
  pStmt->bInfo.tbType = pTableMeta->tableType;
155,027✔
261

262
  if (!pStmt->bInfo.tagsCached) {
155,024✔
263
    qDestroyBoundColInfo(pStmt->bInfo.boundTags);
153,802✔
264
    taosMemoryFreeClear(pStmt->bInfo.boundTags);
154,030✔
265
  }
266

267
  // transfer ownership of cols to stmt
268
  if (cols) {
155,241✔
269
    pStmt->bInfo.fixedValueCols = *cols;
154,914✔
270
    *cols = NULL;
154,904✔
271
  }
272

273
  pStmt->bInfo.boundTags = tags;
155,198✔
274
  pStmt->bInfo.tagsCached = false;
155,035✔
275
  pStmt->bInfo.tbNameFlag = tbNameFlag;
155,233✔
276
  tstrncpy(pStmt->bInfo.stbFName, sTableName, sizeof(pStmt->bInfo.stbFName));
155,147✔
277

278
  if (pTableMeta->tableType != TSDB_CHILD_TABLE && pTableMeta->tableType != TSDB_SUPER_TABLE) {
155,205✔
279
    pStmt->sql.stbInterlaceMode = false;
4,486✔
280
  }
281

282
  return TSDB_CODE_SUCCESS;
155,261✔
283
}
284

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

288
  pStmt->sql.pVgHash = pVgHash;
154,979✔
289
  pStmt->exec.pBlockHash = pBlockHash;
155,475✔
290

291
  return TSDB_CODE_SUCCESS;
155,464✔
292
}
293

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

299
  STMT_ERR_RET(stmtUpdateBindInfo(stmt, pTableMeta, tags, cols, tbName, sTableName, autoCreateTbl, tbNameFlag));
154,927✔
300
  STMT_ERR_RET(stmtUpdateExecInfo(stmt, pVgHash, pBlockHash));
154,998✔
301

302
  pStmt->sql.autoCreateTbl = autoCreateTbl;
155,397✔
303

304
  return TSDB_CODE_SUCCESS;
155,214✔
305
}
306

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

310
  *pVgHash = pStmt->sql.pVgHash;
3,582✔
311
  pStmt->sql.pVgHash = NULL;
3,582✔
312

313
  *pBlockHash = pStmt->exec.pBlockHash;
3,582✔
314
  pStmt->exec.pBlockHash = NULL;
3,582✔
315

316
  return TSDB_CODE_SUCCESS;
3,582✔
317
}
318

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

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

329
  STMT_ERR_RET(stmtCreateRequest(pStmt));
169,785✔
330
  pStmt->exec.pRequest->stmtBindVersion = 2;
169,785✔
331

332
  pStmt->stat.parseSqlNum++;
169,785✔
333

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

337
  pStmt->sql.siInfo.pQuery = pStmt->sql.pQuery;
165,743✔
338

339
  pStmt->bInfo.needParse = false;
165,754✔
340

341
  if (pStmt->sql.type == 0) {
165,715✔
342
    if (pStmt->sql.pQuery->pRoot && LEGAL_INSERT(nodeType(pStmt->sql.pQuery->pRoot))) {
137,942✔
343
      pStmt->sql.type = STMT_TYPE_INSERT;
127,657✔
344
      pStmt->sql.stbInterlaceMode = false;
127,657✔
345
    } else if (pStmt->sql.pQuery->pPrepareRoot && LEGAL_SELECT(nodeType(pStmt->sql.pQuery->pPrepareRoot))) {
10,265✔
346
      pStmt->sql.type = STMT_TYPE_QUERY;
9,871✔
347
      pStmt->sql.stbInterlaceMode = false;
9,871✔
348

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

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

371
  STableDataCxt* pTableCtx = *pSrc;
155,531✔
372
  if (pStmt->sql.stbInterlaceMode && pTableCtx->pData->pCreateTbReq && (pStmt->bInfo.tbNameFlag & USING_CLAUSE) == 0) {
155,506✔
373
    STMT2_TLOG("destroy pCreateTbReq for no-using insert, tbFName:%s", pStmt->bInfo.tbFName);
4,158✔
374
    tdDestroySVCreateTbReq(pTableCtx->pData->pCreateTbReq);
4,158✔
375
    taosMemoryFreeClear(pTableCtx->pData->pCreateTbReq);
4,158✔
376
    pTableCtx->pData->pCreateTbReq = NULL;
4,158✔
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) {
155,780✔
392
    pStmt->sql.pBindInfo = taosMemoryMalloc(pTableCtx->boundColsInfo.numOfBound * sizeof(*pStmt->sql.pBindInfo));
152,223✔
393
    if (NULL == pStmt->sql.pBindInfo) {
151,925✔
394
      STMT2_ELOG_E("fail to malloc pBindInfo");
×
395
      return terrno;
×
396
    }
397
  }
398

399
  return TSDB_CODE_SUCCESS;
155,492✔
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) {
309,718✔
526
  if (pStmt->exec.pRequest) {
309,718✔
527
    taos_free_result(pStmt->exec.pRequest);
174,725✔
528
    pStmt->exec.pRequest = NULL;
174,687✔
529
  }
530
  pStmt->asyncResultAvailable = false;
309,705✔
531
}
309,730✔
532

533
static int32_t stmtCleanBindInfo(STscStmt2* pStmt) {
774,495✔
534
  pStmt->bInfo.tbUid = 0;
774,495✔
535
  pStmt->bInfo.tbVgId = -1;
774,520✔
536
  pStmt->bInfo.tbType = 0;
774,484✔
537
  pStmt->bInfo.needParse = true;
774,490✔
538
  pStmt->bInfo.inExecCache = false;
774,583✔
539

540
  pStmt->bInfo.tbName[0] = 0;
774,509✔
541
  pStmt->bInfo.tbFName[0] = 0;
774,515✔
542
  if (!pStmt->bInfo.tagsCached) {
774,222✔
543
    qDestroyBoundColInfo(pStmt->bInfo.boundTags);
558,744✔
544
    taosMemoryFreeClear(pStmt->bInfo.boundTags);
558,812✔
545
    pStmt->bInfo.boundTags = NULL;
559,098✔
546
  }
547

548
  if (!pStmt->bInfo.boundColsCached) {
774,595✔
549
    tSimpleHashCleanup(pStmt->bInfo.fixedValueCols);
344,522✔
550
    pStmt->bInfo.fixedValueCols = NULL;
344,796✔
551
  }
552

553
  if (!pStmt->sql.autoCreateTbl) {
774,601✔
554
    pStmt->bInfo.stbFName[0] = 0;
541,221✔
555
    pStmt->bInfo.tbSuid = 0;
541,340✔
556
  }
557

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

561
  return TSDB_CODE_SUCCESS;
774,130✔
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) {
429,579✔
570
  pTblBuf->pCurBuff = taosArrayGetP(pTblBuf->pBufList, 0);
429,579✔
571
  if (NULL == pTblBuf->pCurBuff) {
429,871✔
572
    tscError("QInfo:%p, fail to get buffer from list", pTblBuf);
204✔
573
    return;
×
574
  }
575
  pTblBuf->buffIdx = 1;
429,667✔
576
  pTblBuf->buffOffset = sizeof(*pQueue->head);
429,667✔
577

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

583
static int32_t stmtCleanExecInfo(STscStmt2* pStmt, bool keepTable, bool deepClean) {
746,980✔
584
  if (pStmt->sql.stbInterlaceMode) {
746,980✔
585
    if (deepClean) {
443,662✔
586
      taosHashCleanup(pStmt->exec.pBlockHash);
14,084✔
587
      pStmt->exec.pBlockHash = NULL;
14,084✔
588

589
      if (NULL != pStmt->exec.pCurrBlock) {
14,084✔
590
        taosMemoryFreeClear(pStmt->exec.pCurrBlock->boundColsInfo.pColIndex);
12,390✔
591
        taosMemoryFreeClear(pStmt->exec.pCurrBlock->pData);
12,390✔
592
        qDestroyStmtDataBlock(pStmt->exec.pCurrBlock);
12,390✔
593
        pStmt->exec.pCurrBlock = NULL;
12,390✔
594
      }
595
      if (STMT_TYPE_QUERY != pStmt->sql.type) {
14,084✔
596
        resetRequest(pStmt);
14,084✔
597
      }
598
    } else {
599
      pStmt->sql.siInfo.pTableColsIdx = 0;
429,578✔
600
      stmtResetQueueTableBuf(&pStmt->sql.siInfo.tbBuf, &pStmt->queue);
429,603✔
601
      tSimpleHashClear(pStmt->sql.siInfo.pTableRowDataHash);
429,652✔
602
    }
603
    if (NULL != pStmt->exec.pRequest) {
443,991✔
604
      pStmt->exec.pRequest->body.resInfo.numOfRows = 0;
429,882✔
605
    }
606
  } else {
607
    if (STMT_TYPE_QUERY != pStmt->sql.type || deepClean) {
303,318✔
608
      resetRequest(pStmt);
292,828✔
609
    }
610

611
    size_t keyLen = 0;
303,354✔
612
    void*  pIter = taosHashIterate(pStmt->exec.pBlockHash, NULL);
303,354✔
613
    while (pIter) {
591,311✔
614
      STableDataCxt* pBlocks = *(STableDataCxt**)pIter;
287,944✔
615
      char*          key = taosHashGetKey(pIter, &keyLen);
287,944✔
616
      STableMeta*    pMeta = qGetTableMetaInDataBlock(pBlocks);
287,922✔
617

618
      if (keepTable && pBlocks == pStmt->exec.pCurrBlock) {
287,919✔
619
        TSWAP(pBlocks->pData, pStmt->exec.pCurrTbData);
138,832✔
620
        STMT_ERR_RET(qResetStmtDataBlock(pBlocks, false));
168,621✔
621

622
        pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter);
138,807✔
623
        continue;
138,854✔
624
      }
625

626
      qDestroyStmtDataBlock(pBlocks);
149,087✔
627
      STMT_ERR_RET(taosHashRemove(pStmt->exec.pBlockHash, key, keyLen));
149,065✔
628

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

632
    if (keepTable) {
303,367✔
633
      STMT2_TLOG("finish clean exec info, stbInterlaceMode:%d, keepTable:%d, deepClean:%d", pStmt->sql.stbInterlaceMode,
149,319✔
634
                 keepTable, deepClean);
635
      return TSDB_CODE_SUCCESS;
149,344✔
636
    }
637

638
    taosHashCleanup(pStmt->exec.pBlockHash);
154,048✔
639
    pStmt->exec.pBlockHash = NULL;
153,811✔
640

641
    tDestroySubmitTbData(pStmt->exec.pCurrTbData, TSDB_MSG_FLG_ENCODE);
153,811✔
642
    taosMemoryFreeClear(pStmt->exec.pCurrTbData);
154,048✔
643
  }
644

645
  STMT_ERR_RET(stmtCleanBindInfo(pStmt));
598,064✔
646
  STMT2_TLOG("finish clean exec info, stbInterlaceMode:%d, keepTable:%d, deepClean:%d", pStmt->sql.stbInterlaceMode,
597,466✔
647
             keepTable, deepClean);
648

649
  return TSDB_CODE_SUCCESS;
597,730✔
650
}
651

652
static void stmtFreeSingleVgDataBlock(void* p) {
618,017✔
653
  SVgDataBlocks* pVg = *(SVgDataBlocks**)p;
618,017✔
654
  if (pVg) {
618,083✔
655
    taosMemoryFree(pVg->pData);
618,167✔
656
    taosMemoryFree(pVg);
618,207✔
657
  }
658
}
618,088✔
659

660
static void stmtFreeVgDataBlocksForRetry(STscStmt2* pStmt) {
736,778✔
661
  if (pStmt->pVgDataBlocksForRetry) {
736,778✔
662
    taosArrayDestroyEx(pStmt->pVgDataBlocksForRetry, stmtFreeSingleVgDataBlock);
567,872✔
663
    pStmt->pVgDataBlocksForRetry = NULL;
567,944✔
664
  }
665
}
736,826✔
666

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

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

675
  int32_t num = taosArrayGetSize(pModif->pDataBlocks);
568,879✔
676
  pStmt->pVgDataBlocksForRetry = taosArrayInit(num, POINTER_BYTES);
568,707✔
677
  if (!pStmt->pVgDataBlocksForRetry) {
569,158✔
678
    return terrno;
×
679
  }
680

681
  for (int32_t i = 0; i < num; i++) {
1,188,160✔
682
    SVgDataBlocks* pSrc = taosArrayGetP(pModif->pDataBlocks, i);
619,229✔
683
    SVgDataBlocks* pDst = taosMemoryMalloc(sizeof(SVgDataBlocks));
619,385✔
684
    if (!pDst) {
618,979✔
685
      stmtFreeVgDataBlocksForRetry(pStmt);
×
686
      return terrno;
×
687
    }
688
    *pDst = *pSrc;
618,979✔
689
    pDst->pData = taosMemoryMalloc(pSrc->size);
618,979✔
690
    if (!pDst->pData) {
619,548✔
691
      taosMemoryFree(pDst);
×
692
      stmtFreeVgDataBlocksForRetry(pStmt);
×
693
      return terrno;
×
694
    }
695
    (void)memcpy(pDst->pData, pSrc->pData, pSrc->size);
619,286✔
696
    if (NULL == taosArrayPush(pStmt->pVgDataBlocksForRetry, &pDst)) {
1,238,591✔
697
      taosMemoryFree(pDst->pData);
×
698
      taosMemoryFree(pDst);
×
699
      stmtFreeVgDataBlocksForRetry(pStmt);
×
700
      return terrno;
×
701
    }
702
  }
703
  return TSDB_CODE_SUCCESS;
568,931✔
704
}
705

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1350
  return TSDB_CODE_SUCCESS;
396✔
1351
}
1352

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

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

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

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

1370
  taosMemoryFree(pStmt->sql.pBindInfo);
168,107✔
1371
  taosMemoryFree(pStmt->sql.queryRes.fields);
168,132✔
1372
  taosMemoryFree(pStmt->sql.queryRes.userFields);
168,132✔
1373
  taosMemoryFree(pStmt->sql.sqlStr);
168,132✔
1374
  qDestroyQuery(pStmt->sql.pQuery);
168,132✔
1375
  taosArrayDestroy(pStmt->sql.nodeList);
168,132✔
1376
  taosHashCleanup(pStmt->sql.pVgHash);
168,132✔
1377
  pStmt->sql.pVgHash = NULL;
168,132✔
1378
  if (pStmt->sql.fixValueTags) {
168,132✔
1379
    pStmt->sql.fixValueTags = false;
3,328✔
1380
    tdDestroySVCreateTbReq(pStmt->sql.fixValueTbReq);
3,328✔
1381
    taosMemoryFreeClear(pStmt->sql.fixValueTbReq);
3,328✔
1382
    pStmt->sql.fixValueTbReq = NULL;
3,328✔
1383
  }
1384

1385
  void* pIter = taosHashIterate(pStmt->sql.pTableCache, NULL);
168,132✔
1386
  while (pIter) {
174,686✔
1387
    SStmtTableCache* pCache = (SStmtTableCache*)pIter;
6,554✔
1388

1389
    qDestroyStmtDataBlock(pCache->pDataCtx);
6,554✔
1390
    qDestroyBoundColInfo(pCache->boundTags);
6,554✔
1391
    taosMemoryFreeClear(pCache->boundTags);
6,554✔
1392

1393
    pIter = taosHashIterate(pStmt->sql.pTableCache, pIter);
6,554✔
1394
  }
1395
  taosHashCleanup(pStmt->sql.pTableCache);
168,132✔
1396
  pStmt->sql.pTableCache = NULL;
168,132✔
1397

1398
  STMT_ERR_RET(stmtCleanExecInfo(pStmt, false, true));
168,132✔
1399
  STMT_ERR_RET(stmtCleanBindInfo(pStmt));
168,132✔
1400
  stmtFreeVgDataBlocksForRetry(pStmt);
168,132✔
1401

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

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

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

1417
  return TSDB_CODE_SUCCESS;
168,106✔
1418
}
1419

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

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

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

1444
  *vgId = vgInfo.vgId;
614,274✔
1445

1446
  return TSDB_CODE_SUCCESS;
614,274✔
1447
}
1448

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

1457
  pStmt->stat.ctgGetTbMetaNum++;
9,773✔
1458

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

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

1468
    STMT_ERR_RET(code);
×
1469
  }
1470

1471
  STMT_ERR_RET(code);
8,783✔
1472

1473
  *uid = pTableMeta->uid;
8,783✔
1474
  *suid = pTableMeta->suid;
8,783✔
1475
  *tableType = pTableMeta->tableType;
8,781✔
1476
  pStmt->bInfo.tbVgId = pTableMeta->vgId;
8,744✔
1477
  *vgId = pTableMeta->vgId;
8,744✔
1478

1479
  taosMemoryFree(pTableMeta);
8,744✔
1480

1481
  return TSDB_CODE_SUCCESS;
8,783✔
1482
}
1483

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

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

1491
  return TSDB_CODE_SUCCESS;
14,380✔
1492
}
1493

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

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

1504
  STableDataCxt** pCxtInExec = taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
41,721✔
1505
  if (pCxtInExec) {
41,799✔
1506
    pStmt->bInfo.needParse = false;
6,930✔
1507
    pStmt->bInfo.inExecCache = true;
6,930✔
1508

1509
    pStmt->exec.pCurrBlock = *pCxtInExec;
6,930✔
1510

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

1517
  if (NULL == pStmt->pCatalog) {
35,859✔
1518
    STMT_ERR_RET(catalogGetHandle(pStmt->taos->pAppInfo->clusterId, &pStmt->pCatalog));
15,413✔
1519
    pStmt->sql.siInfo.pCatalog = pStmt->pCatalog;
15,413✔
1520
  }
1521

1522
  if (NULL == pStmt->sql.pTableCache || taosHashGetSize(pStmt->sql.pTableCache) <= 0) {
35,898✔
1523
    if (pStmt->bInfo.inExecCache) {
20,291✔
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,330✔
1530

1531
    return TSDB_CODE_SUCCESS;
20,330✔
1532
  }
1533

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

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

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

1548
      pStmt->exec.pCurrBlock = pNewBlock;
12,004✔
1549

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

1552
      return TSDB_CODE_SUCCESS;
12,004✔
1553
    }
1554

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

1558
  uint64_t uid, suid;
×
1559
  int32_t  vgId;
×
1560
  int8_t   tableType;
×
1561

1562
  STMT_ERR_RET(stmtGetTableMetaAndValidate(pStmt, &uid, &suid, &vgId, &tableType));
3,564✔
1563

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

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

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

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

1593
    return TSDB_CODE_SUCCESS;
990✔
1594
  }
1595

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

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

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

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

1614
    pStmt->exec.pCurrBlock = pNewBlock;
2,376✔
1615

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

1618
    return TSDB_CODE_SUCCESS;
2,376✔
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,367,956✔
1641
  SStmtQNode* pParam = (SStmtQNode*)param;
1,367,956✔
1642

1643
  if (pParam->restoreTbCols) {
1,367,956✔
1644
    for (int32_t i = 0; i < pStmt->sql.siInfo.pTableColsIdx; ++i) {
1,367,488✔
1645
      SArray** p = (SArray**)TARRAY_GET_ELEM(pStmt->sql.siInfo.pTableCols, i);
937,407✔
1646
      *p = taosArrayInit(20, POINTER_BYTES);
937,407✔
1647
      if (*p == NULL) {
937,333✔
1648
        pStmt->errCode = terrno;
24✔
1649
      }
1650
    }
1651
    atomic_store_8((int8_t*)&pStmt->sql.siInfo.tableColsReady, true);
430,081✔
1652
    STMT2_TLOG_E("restore pTableCols finished");
430,141✔
1653
  } else {
1654
    int code = qAppendStmt2TableOutput(pStmt->sql.pQuery, pStmt->sql.pVgHash, &pParam->tblData, pStmt->exec.pCurrBlock,
937,877✔
1655
                                       &pStmt->sql.siInfo, pParam->pCreateTbReq);
1656
    // taosMemoryFree(pParam->pTbData);
1657
    if (code != TSDB_CODE_SUCCESS) {
937,796✔
1658
      STMT2_ELOG("async append stmt output failed, tbname:%s, err:%s", pParam->tblData.tbName, tstrerror(code));
198✔
1659
      pStmt->errCode = code;
198✔
1660
    }
1661
    (void)atomic_sub_fetch_64(&pStmt->sql.siInfo.tbRemainNum, 1);
937,796✔
1662
  }
1663
}
1,368,264✔
1664

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

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

1671
  while (true) {
1,368,166✔
1672
    SStmtQNode* asyncParam = NULL;
1,514,737✔
1673

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

1682
    stmtAsyncOutput(pStmt, asyncParam);
1,368,040✔
1683
  }
1684

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

1689
static int32_t stmtStartBindThread(STscStmt2* pStmt) {
146,536✔
1690
  TdThreadAttr thAttr;
118,115✔
1691
  if (taosThreadAttrInit(&thAttr) != 0) {
146,571✔
1692
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1693
  }
1694
  if (taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE) != 0) {
146,510✔
1695
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1696
  }
1697

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

1703
  pStmt->bindThreadInUse = true;
146,571✔
1704

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

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

1715
  return TSDB_CODE_SUCCESS;
146,571✔
1716
}
1717

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

1723
  return TSDB_CODE_SUCCESS;
167,340✔
1724
}
1725

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

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

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

1746
  return TSDB_CODE_SUCCESS;
146,571✔
1747
}
1748

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

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

1775
  if (NULL != pOptions) {
162,066✔
1776
    (void)memcpy(&pStmt->options, pOptions, sizeof(pStmt->options));
158,533✔
1777
    if (pOptions->singleStbInsert && pOptions->singleTableBindOnce) {
158,533✔
1778
      pStmt->stbInterlaceMode = true;
141,271✔
1779
    }
1780

1781
    pStmt->reqid = pOptions->reqid;
158,507✔
1782
  }
1783

1784
  if (pStmt->stbInterlaceMode) {
162,066✔
1785
    pStmt->sql.siInfo.transport = taos->pAppInfo->pTransporter;
141,297✔
1786
    pStmt->sql.siInfo.acctId = taos->acctId;
141,297✔
1787
    pStmt->sql.siInfo.dbname = taos->db;
141,060✔
1788
    pStmt->sql.siInfo.mgmtEpSet = getEpSet_s(&pStmt->taos->pAppInfo->mgmtEp);
141,060✔
1789

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

1851
  return pStmt;
162,066✔
1852
}
1853

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

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

1870
  // The SQL statement specifies a database name, overriding the previously specified database
1871
  taosMemoryFreeClear(pStmt->exec.pRequest->pDb);
146,224✔
1872
  pStmt->exec.pRequest->pDb = taosStrdup(dbName);
146,202✔
1873
  (void)strdequote(pStmt->exec.pRequest->pDb);
146,224✔
1874
  if (pStmt->exec.pRequest->pDb == NULL) {
146,202✔
1875
    return terrno;
×
1876
  }
1877
  if (pStmt->sql.stbInterlaceMode) {
146,202✔
1878
    pStmt->sql.siInfo.dbname = pStmt->exec.pRequest->pDb;
134,577✔
1879
  }
1880
  return TSDB_CODE_SUCCESS;
145,965✔
1881
}
1882
static int32_t stmtResetStbInterlaceCache(STscStmt2* pStmt) {
5,274✔
1883
  int32_t code = TSDB_CODE_SUCCESS;
5,274✔
1884

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

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

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

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

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

1913
  return TSDB_CODE_SUCCESS;
5,274✔
1914
}
1915

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

1923
  pStmt->errCode = 0;
6,858✔
1924

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

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

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

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

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

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

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

1972
    STMT_ERR_RET(stmtResetStbInterlaceCache(pStmt));
5,274✔
1973

1974
    int32_t code = stmtIniAsyncBind(pStmt);
5,274✔
1975
    if (TSDB_CODE_SUCCESS != code) {
5,274✔
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;
6,858✔
1983
  pStmt->options = options;
6,858✔
1984
  pStmt->reqid = reqid;
6,858✔
1985
  pStmt->stbInterlaceMode = stbInterlaceMode;
6,858✔
1986

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

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

1997
  return TSDB_CODE_SUCCESS;
6,858✔
1998
}
1999

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

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

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

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

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

2022
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_PREPARE));
168,330✔
2023

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

2035
  if (stmt2IsInsert(pStmt)) {
168,330✔
2036
    pStmt->sql.stbInterlaceMode = pStmt->stbInterlaceMode;
157,248✔
2037
    char* dbName = NULL;
157,248✔
2038
    if (qParseDbName(sql, length, &dbName)) {
157,248✔
2039
      STMT_ERR_RET(stmtSetDbName2(stmt, dbName));
146,224✔
2040
      taosMemoryFreeClear(dbName);
145,965✔
2041
    } else if (pStmt->db != NULL && pStmt->db[0] != '\0') {
10,987✔
2042
      taosMemoryFreeClear(pStmt->exec.pRequest->pDb);
10,789✔
2043
      pStmt->exec.pRequest->pDb = taosStrdup(pStmt->db);
10,752✔
2044
      if (pStmt->exec.pRequest->pDb == NULL) {
10,826✔
2045
        STMT_ERR_RET(terrno);
×
2046
      }
2047
      (void)strdequote(pStmt->exec.pRequest->pDb);
10,789✔
2048

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

2054
  } else if (stmt2IsSelect(pStmt)) {
11,082✔
2055
    pStmt->sql.stbInterlaceMode = false;
10,488✔
2056
    STMT_ERR_RET(stmtParseSql(pStmt));
10,488✔
2057
  } else {
2058
    return stmtBuildErrorMsgWithCode(pStmt, "stmt only support 'SELECT' or 'INSERT'", TSDB_CODE_PAR_SYNTAX_ERROR);
594✔
2059
  }
2060
  return TSDB_CODE_SUCCESS;
166,845✔
2061
}
2062

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

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

2073
  SArray* pTblCols = NULL;
12,353✔
2074
  for (int32_t i = 0; i < STMT_TABLE_COLS_NUM; i++) {
12,381,940✔
2075
    pTblCols = taosArrayInit(20, POINTER_BYTES);
12,369,490✔
2076
    if (NULL == pTblCols) {
12,362,728✔
2077
      return terrno;
×
2078
    }
2079

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

2085
  pStmt->sql.siInfo.boundTags = pStmt->bInfo.boundTags;
12,450✔
2086

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

2090
  return TSDB_CODE_SUCCESS;
12,390✔
2091
}
2092

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

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

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

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

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

2114
  int64_t startUs = taosGetTimestampUs();
968,759✔
2115

2116
  STMT2_TLOG("start to set tbName:%s", tbName);
968,759✔
2117

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

2122
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_SETTBNAME));
968,816✔
2123

2124
  int32_t insert = 0;
968,585✔
2125
  if (!stmt2IsInsert(stmt)) {
968,585✔
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));
968,827✔
2131

2132
  STMT_ERR_RET(qCreateSName2(&pStmt->bInfo.sname, tbName, pStmt->taos->acctId, pStmt->exec.pRequest->pDb,
968,632✔
2133
                             pStmt->exec.pRequest->msgBuf, pStmt->exec.pRequest->msgBufLen));
2134
  STMT_ERR_RET(tNameExtractFullName(&pStmt->bInfo.sname, pStmt->bInfo.tbFName));
967,215✔
2135
  tstrncpy(pStmt->bInfo.tbName, (char*)tNameGetTableName(&pStmt->bInfo.sname), TSDB_TABLE_NAME_LEN);
967,219✔
2136

2137
  if (!pStmt->sql.stbInterlaceMode || NULL == pStmt->sql.siInfo.pDataCtx) {
967,184✔
2138
    STMT_ERR_RET(stmtGetFromCache(pStmt));
42,030✔
2139

2140
    if (pStmt->bInfo.needParse) {
41,562✔
2141
      STMT_ERR_RET(stmtParseSql(pStmt));
20,291✔
2142
      if (!pStmt->sql.autoCreateTbl) {
20,254✔
2143
        uint64_t uid, suid;
2,023✔
2144
        int32_t  vgId;
2,023✔
2145
        int8_t   tableType;
2,023✔
2146

2147
        int32_t code = stmtGetTableMetaAndValidate(pStmt, &uid, &suid, &vgId, &tableType);
6,246✔
2148
        if (code != TSDB_CODE_SUCCESS) {
6,207✔
2149
          return code;
792✔
2150
        }
2151
      }
2152
    }
2153

2154
  } else {
2155
    pStmt->exec.pRequest->requestId++;
925,256✔
2156
    pStmt->bInfo.needParse = false;
925,318✔
2157
  }
2158

2159
  if (pStmt->sql.stbInterlaceMode && NULL == pStmt->sql.siInfo.pDataCtx) {
966,104✔
2160
    STMT_ERR_RET(stmtInitStbInterlaceTableInfo(pStmt));
12,351✔
2161
  }
2162

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

2166
  return TSDB_CODE_SUCCESS;
966,379✔
2167
}
2168

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

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

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

2181
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_SETTAGS));
526,808✔
2182

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

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

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

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

2218
  STMT2_TLOG_E("start to bind stmt tag values");
526,676✔
2219

2220
  void* boundTags = NULL;
526,592✔
2221
  if (pStmt->sql.stbInterlaceMode) {
526,592✔
2222
    boundTags = pStmt->sql.siInfo.boundTags;
502,886✔
2223
    *pCreateTbReq = taosMemoryCalloc(1, sizeof(SVCreateTbReq));
502,886✔
2224
    if (NULL == pCreateTbReq) {
503,018✔
2225
      return terrno;
×
2226
    }
2227
    int32_t vgId = -1;
503,018✔
2228
    STMT_ERR_RET(stmtTryAddTableVgroupInfo(pStmt, &vgId));
503,018✔
2229
    (*pCreateTbReq)->uid = vgId;
503,234✔
2230
  } else {
2231
    boundTags = pStmt->bInfo.boundTags;
23,706✔
2232
  }
2233

2234
  STMT_ERR_RET(qBindStmtTagsValue2(*pDataBlock, boundTags, pStmt->bInfo.tbSuid, pStmt->bInfo.stbFName,
526,940✔
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;
526,670✔
2239
}
2240

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

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

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

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

2254
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_SETTAGS));
101,848✔
2255

2256
  if (pStmt->sql.fixValueTags) {
101,836✔
2257
    STMT2_TLOG_E("tags are fixed, use one createTbReq");
98,508✔
2258
    STMT_ERR_RET(cloneSVreateTbReq(pStmt->sql.fixValueTbReq, pCreateTbReq));
98,508✔
2259
    if ((*pCreateTbReq)->name) {
98,496✔
2260
      taosMemoryFree((*pCreateTbReq)->name);
98,460✔
2261
    }
2262
    (*pCreateTbReq)->name = taosStrdup(pStmt->bInfo.tbName);
98,568✔
2263
    int32_t vgId = -1;
98,532✔
2264
    STMT_ERR_RET(stmtTryAddTableVgroupInfo(pStmt, &vgId));
98,532✔
2265
    (*pCreateTbReq)->uid = vgId;
98,652✔
2266
    return TSDB_CODE_SUCCESS;
98,652✔
2267
  }
2268

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

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

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

2312
  return TSDB_CODE_SUCCESS;
3,328✔
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) {
10,710✔
2344
  int32_t code = 0;
10,710✔
2345
  int32_t preCode = pStmt->errCode;
10,710✔
2346

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

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

2359
  if (pStmt->sql.stbInterlaceMode && pStmt->sql.siInfo.pDataCtx != NULL) {
10,710✔
2360
    pDataBlock = &pStmt->sql.siInfo.pDataCtx;
1,188✔
2361
  } else {
2362
    cleanStb = true;
9,522✔
2363
    pDataBlock =
2364
        (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
9,522✔
2365
  }
2366

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

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

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

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

2400
_return:
10,710✔
2401

2402
  pStmt->errCode = preCode;
10,710✔
2403

2404
  return code;
10,710✔
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) {
937,618✔
2424
  if (NULL == pStmt->sql.siInfo.pVgroupHash) {
937,618✔
2425
    pStmt->sql.siInfo.pVgroupHash =
430,601✔
2426
        taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_ENTRY_LOCK);
430,527✔
2427
  }
2428
  if (NULL == pStmt->sql.siInfo.pVgroupList) {
937,891✔
2429
    pStmt->sql.siInfo.pVgroupList = taosArrayInit(64, POINTER_BYTES);
430,589✔
2430
  }
2431

2432
  if (NULL == pStmt->sql.siInfo.pRequest) {
937,706✔
2433
    STMT_ERR_RET(buildRequest(pStmt->taos->id, pStmt->sql.sqlStr, pStmt->sql.sqlLen, NULL, false,
11,994✔
2434
                              (SRequestObj**)&pStmt->sql.siInfo.pRequest, pStmt->reqid));
2435

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

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

2445
  if (!pStmt->sql.siInfo.tbFromHash && pStmt->sql.siInfo.firstName[0] &&
937,669✔
2446
      0 == strcmp(pStmt->sql.siInfo.firstName, pStmt->bInfo.tbName)) {
26,344✔
2447
    pStmt->sql.siInfo.tbFromHash = true;
4,254✔
2448
  }
2449

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

2454
  param->tblData.getFromHash = pStmt->sql.siInfo.tbFromHash;
937,678✔
2455
  param->next = NULL;
937,575✔
2456

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

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

2465
  return TSDB_CODE_SUCCESS;
937,906✔
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)) {
937,999✔
2471
      *pTableCols = (SArray*)taosArrayGetP(pStmt->sql.siInfo.pTableCols, pStmt->sql.siInfo.pTableColsIdx++);
938,314✔
2472
      break;
938,041✔
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;
938,041✔
2489
}
2490

2491
static int32_t stmtCacheBlock(STscStmt2* pStmt) {
72,300,754✔
2492
  if (pStmt->sql.type != STMT_TYPE_MULTI_INSERT) {
72,300,754✔
2493
    return TSDB_CODE_SUCCESS;
72,786,414✔
2494
  }
2495

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

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

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

2511
  STMT_ERR_RET(qCloneStmtDataBlock(&pDst, *pSrc, true));
6,752✔
2512

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

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

2523
  if (pStmt->sql.autoCreateTbl) {
6,752✔
2524
    pStmt->bInfo.tagsCached = true;
5,168✔
2525
  } else {
2526
    pStmt->bInfo.boundTags = NULL;
1,584✔
2527
  }
2528

2529
  return TSDB_CODE_SUCCESS;
6,752✔
2530
}
2531

2532
static int stmtAddBatch2(TAOS_STMT2* stmt) {
72,790,366✔
2533
  STscStmt2* pStmt = (STscStmt2*)stmt;
72,790,366✔
2534

2535
  int64_t startUs = taosGetTimestampUs();
73,427,228✔
2536

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

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

2543
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_ADD_BATCH));
73,404,573✔
2544

2545
  if (pStmt->sql.stbInterlaceMode) {
73,407,534✔
2546
    int64_t startUs2 = taosGetTimestampUs();
430,105✔
2547
    pStmt->stat.addBatchUs += startUs2 - startUs;
430,105✔
2548

2549
    pStmt->sql.siInfo.tableColsReady = false;
430,031✔
2550

2551
    SStmtQNode* param = NULL;
430,006✔
2552
    STMT_ERR_RET(stmtAllocQNodeFromBuf(&pStmt->sql.siInfo.tbBuf, (void**)&param));
860,149✔
2553
    param->restoreTbCols = true;
430,069✔
2554
    param->next = NULL;
429,995✔
2555

2556
    if (pStmt->sql.autoCreateTbl) {
430,044✔
2557
      pStmt->bInfo.tagsCached = true;
204,198✔
2558
    }
2559
    pStmt->bInfo.boundColsCached = true;
429,970✔
2560

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

2568
    return TSDB_CODE_SUCCESS;
430,081✔
2569
  }
2570

2571
  STMT_ERR_RET(stmtCacheBlock(pStmt));
72,739,514✔
2572

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

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

2664
  TAOS_MEMSET(pMetaData, 0, sizeof(SMetaData));
10,663✔
2665

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

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

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

2704
  return code;
10,663✔
2705
}
2706

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

2711
  int64_t startUs = taosGetTimestampUs();
73,766,507✔
2712

2713
  if (qDebugFlag & DEBUG_TRACE) {
73,766,507✔
2714
    (void)stmtPrintBindv(stmt, bind, colIdx, false);
×
2715
  }
2716

2717
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
73,777,053✔
2718
    return pStmt->errCode;
198✔
2719
  }
2720

2721
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_BIND));
74,125,561✔
2722

2723
  if (pStmt->bInfo.needParse && pStmt->sql.runTimes && pStmt->sql.type > 0 &&
74,097,547✔
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) {
73,718,356✔
2729
    resetRequest(pStmt);
2,201✔
2730
  }
2731

2732
  STMT_ERR_RET(stmtCreateRequest(pStmt));
73,954,735✔
2733
  if (pStmt->bInfo.needParse) {
73,361,789✔
2734
    code = stmtParseSql(pStmt);
125,755✔
2735
    if (code != TSDB_CODE_SUCCESS) {
125,518✔
2736
      goto cleanup_root;
×
2737
    }
2738
  }
2739

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

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

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

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

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

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

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

2821
  STableDataCxt** pDataBlock = NULL;
73,171,681✔
2822

2823
  if (pStmt->exec.pCurrBlock) {
73,171,681✔
2824
    pDataBlock = &pStmt->exec.pCurrBlock;
72,991,060✔
2825
  } else {
2826
    pDataBlock =
2827
        (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
145,215✔
2828
    if (NULL == pDataBlock) {
145,491✔
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;
145,491✔
2833
    if (pStmt->sql.stbInterlaceMode) {
145,466✔
2834
      taosArrayDestroy(pStmt->exec.pCurrBlock->pData->aCol);
12,390✔
2835
      (*pDataBlock)->pData->aCol = NULL;
12,390✔
2836
    }
2837
    if (colIdx < -1) {
145,229✔
2838
      pStmt->sql.bindRowFormat = true;
198✔
2839
      taosArrayDestroy((*pDataBlock)->pData->aCol);
198✔
2840
      (*pDataBlock)->pData->aCol = taosArrayInit(20, POINTER_BYTES);
198✔
2841
    }
2842
  }
2843

2844
  int64_t startUs2 = taosGetTimestampUs();
73,875,740✔
2845
  pStmt->stat.bindDataUs1 += startUs2 - startUs;
73,875,740✔
2846

2847
  SStmtQNode* param = NULL;
73,695,593✔
2848
  if (pStmt->sql.stbInterlaceMode) {
73,945,379✔
2849
    STMT_ERR_RET(stmtAllocQNodeFromBuf(&pStmt->sql.siInfo.tbBuf, (void**)&param));
1,876,124✔
2850
    STMT_ERR_RET(stmtGetTableColsFromCache(pStmt, &param->tblData.aCol));
1,876,028✔
2851
    taosArrayClear(param->tblData.aCol);
938,041✔
2852

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

2855
    param->restoreTbCols = false;
937,356✔
2856
    param->tblData.isOrdered = true;
937,356✔
2857
    param->tblData.isDuplicateTs = false;
937,455✔
2858
    tstrncpy(param->tblData.tbName, pStmt->bInfo.tbName, TSDB_TABLE_NAME_LEN);
937,452✔
2859

2860
    param->pCreateTbReq = pCreateTbReq;
937,505✔
2861
  }
2862

2863
  int64_t startUs3 = taosGetTimestampUs();
73,678,131✔
2864
  pStmt->stat.bindDataUs2 += startUs3 - startUs2;
73,678,131✔
2865

2866
  SArray*   pCols = pStmt->sql.stbInterlaceMode ? param->tblData.aCol : (*pDataBlock)->pData->aCol;
73,669,376✔
2867
  SBlobSet* pBlob = NULL;
74,239,283✔
2868
  if (colIdx < 0) {
74,311,326✔
2869
    if (pStmt->sql.stbInterlaceMode) {
74,334,893✔
2870
      (*pDataBlock)->pData->flags &= ~SUBMIT_REQ_COLUMN_DATA_FORMAT;
937,574✔
2871
      code = qBindStmtStbColsValue2(*pDataBlock, pCols, pStmt->bInfo.fixedValueCols, bind, pStmt->exec.pRequest->msgBuf,
1,153,833✔
2872
                                    pStmt->exec.pRequest->msgBufLen, &pStmt->sql.siInfo.pTSchema, pStmt->sql.pBindInfo,
937,841✔
2873
                                    pStmt->taos->optionInfo.charsetCxt, &pBlob);
937,915✔
2874
      param->tblData.isOrdered = (*pDataBlock)->ordered;
938,124✔
2875
      param->tblData.isDuplicateTs = (*pDataBlock)->duplicateTs;
938,287✔
2876
    } else {
2877
      if (colIdx == -1) {
73,212,902✔
2878
        if (pStmt->sql.bindRowFormat) {
72,740,327✔
2879
          STMT2_ELOG_E("can't mix bind row format and bind column format");
198✔
2880
          STMT_ERR_RET(TSDB_CODE_TSC_STMT_API_ERROR);
198✔
2881
        }
2882
        code = qBindStmtColsValue2(*pDataBlock, pCols, pStmt->bInfo.fixedValueCols, bind, pStmt->exec.pRequest->msgBuf,
140,332,734✔
2883
                                   pStmt->exec.pRequest->msgBufLen, pStmt->taos->optionInfo.charsetCxt);
140,015,294✔
2884
      } else {
2885
        code =
2886
            qBindStmt2RowValue(*pDataBlock, (*pDataBlock)->pData->aRowP, pStmt->bInfo.fixedValueCols, bind,
396✔
2887
                               pStmt->exec.pRequest->msgBuf, pStmt->exec.pRequest->msgBufLen,
396✔
2888
                               &pStmt->sql.siInfo.pTSchema, pStmt->sql.pBindInfo, pStmt->taos->optionInfo.charsetCxt);
476,500✔
2889
      }
2890
    }
2891

2892
    if (code) {
73,119,150✔
2893
      STMT2_ELOG("bind cols or rows failed, error:%s", tstrerror(code));
396✔
2894
      STMT_ERR_RET(code);
396✔
2895
    }
2896
  } else {
2897
    if (pStmt->sql.stbInterlaceMode) {
10,969✔
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) {
1,188✔
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) {
1,188✔
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;
1,188✔
2913

2914
    if (0 == colIdx) {
1,188✔
2915
      pStmt->bInfo.sBindRowNum = bind->num;
594✔
2916
    }
2917

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

2927
  int64_t startUs4 = taosGetTimestampUs();
73,545,625✔
2928
  pStmt->stat.bindDataUs3 += startUs4 - startUs3;
73,545,625✔
2929

2930
  if (pStmt->stbInterlaceMode) {
73,980,933✔
2931
    if (param) param->tblData.pBlobSet = pBlob;
74,050,124✔
2932
  }
2933

2934
  if (pStmt->sql.stbInterlaceMode) {
74,007,014✔
2935
    STMT_ERR_RET(stmtAppendTablePostHandle(pStmt, param));
937,973✔
2936
  } else {
2937
    STMT_ERR_RET(stmtAddBatch2(pStmt));
73,124,067✔
2938
  }
2939

2940
  pStmt->stat.bindDataUs4 += taosGetTimestampUs() - startUs4;
73,654,138✔
2941
  return TSDB_CODE_SUCCESS;
73,969,090✔
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) {
5,544✔
3078
  const STscObj* pTscObj = pRequest->pTscObj;
5,544✔
3079

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

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

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

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

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

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

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

3199
  STMT2_DLOG_E("start to exec");
580,301✔
3200

3201
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
580,265✔
3202
    return pStmt->errCode;
198✔
3203
  }
3204

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

3211
  if (pStmt->sql.stbInterlaceMode) {
580,175✔
3212
    STMT_ERR_RET(stmtAddBatch2(pStmt));
430,081✔
3213
  }
3214

3215
  code = stmtSwitchStatus(pStmt, STMT_EXECUTE);
580,199✔
3216
  if (code != TSDB_CODE_SUCCESS) goto _return;
580,400✔
3217

3218
  if (STMT_TYPE_QUERY != pStmt->sql.type) {
579,981✔
3219
    if (pStmt->sql.stbInterlaceMode) {
569,216✔
3220
      int64_t startTs = taosGetTimestampUs();
430,093✔
3221
      // wait for stmt bind thread to finish
3222
      while (atomic_load_64(&pStmt->sql.siInfo.tbRemainNum)) {
3,903,739✔
3223
        taosUsleep(1);
3,473,603✔
3224
      }
3225

3226
      if (pStmt->errCode != TSDB_CODE_SUCCESS) {
430,105✔
3227
        return pStmt->errCode;
198✔
3228
      }
3229

3230
      pStmt->stat.execWaitUs += taosGetTimestampUs() - startTs;
429,907✔
3231
      STMT_ERR_RET(qBuildStmtFinOutput(pStmt->sql.pQuery, pStmt->sql.pVgHash, pStmt->sql.siInfo.pVgroupList));
429,907✔
3232
      taosHashCleanup(pStmt->sql.siInfo.pVgroupHash);
429,820✔
3233
      pStmt->sql.siInfo.pVgroupHash = NULL;
429,740✔
3234
      pStmt->sql.siInfo.pVgroupList = NULL;
429,765✔
3235
    } else {
3236
      tDestroySubmitTbData(pStmt->exec.pCurrTbData, TSDB_MSG_FLG_ENCODE);
139,212✔
3237
      taosMemoryFreeClear(pStmt->exec.pCurrTbData);
139,208✔
3238

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

3241
      STMT_ERR_RET(qBuildStmtOutput(pStmt->sql.pQuery, pStmt->sql.pVgHash, pStmt->exec.pBlockHash));
138,763✔
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));
569,022✔
3246
  }
3247

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

3254
  if (!fp) {
579,161✔
3255
    launchQueryImpl(pStmt->exec.pRequest, pStmt->sql.pQuery, true, NULL);
573,815✔
3256

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

3287
    pStmt->exec.affectedRows = taos_affected_rows(pStmt->exec.pRequest);
573,782✔
3288
    if (affected_rows) {
573,822✔
3289
      *affected_rows = pStmt->exec.affectedRows;
564,556✔
3290
    }
3291
    pStmt->affectedRows += pStmt->exec.affectedRows;
573,648✔
3292

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

3298
    STMT_ERR_RET(stmtCleanExecInfo(pStmt, (code ? false : true), false));
573,638✔
3299

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

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

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

3326
  STMT_RET(code);
579,525✔
3327
}
3328

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

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

3335
  if (pStmt->bindThreadInUse) {
161,235✔
3336
    // wait for stmt bind thread to finish
3337
    while (0 == atomic_load_8((int8_t*)&pStmt->sql.siInfo.tableColsReady)) {
141,060✔
3338
      taosUsleep(1);
198✔
3339
    }
3340

3341
    (void)taosThreadMutexLock(&pStmt->queue.mutex);
140,625✔
3342
    pStmt->queue.stopQueue = true;
141,099✔
3343
    (void)taosThreadCondSignal(&(pStmt->queue.waitCond));
141,099✔
3344
    (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
141,074✔
3345

3346
    (void)taosThreadJoin(pStmt->bindThread, NULL);
141,074✔
3347
    pStmt->bindThreadInUse = false;
141,099✔
3348

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

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

3359
  (void)taosThreadCondDestroy(&pStmt->asyncBindParam.waitCond);
161,274✔
3360
  (void)taosThreadMutexDestroy(&pStmt->asyncBindParam.mutex);
161,274✔
3361

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

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

3391
  STMT_ERR_RET(stmtCleanSQLInfo(pStmt));
161,274✔
3392

3393
  if (pStmt->options.asyncExecFn) {
161,248✔
3394
    if (tsem_destroy(&pStmt->asyncExecSem) != 0) {
2,574✔
3395
      STMT2_ELOG_E("fail to destroy asyncExecSem");
×
3396
    }
3397
  }
3398
  taosMemoryFree(stmt);
161,248✔
3399

3400
  return TSDB_CODE_SUCCESS;
161,252✔
3401
}
3402

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

3406
  if (stmt == NULL || NULL == pStmt->exec.pRequest) {
10,703✔
3407
    return (char*)tstrerror(terrno);
792✔
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)) {
9,911✔
3412
    pStmt->exec.pRequest->code = terrno;
9,911✔
3413
  }
3414

3415
  SRequestObj* pRequest = pStmt->exec.pRequest;
9,911✔
3416
  if (NULL != pRequest->msgBuf && (strlen(pRequest->msgBuf) > 0 || pRequest->code == TSDB_CODE_RPC_FQDN_ERROR)) {
9,911✔
3417
    return pRequest->msgBuf;
6,557✔
3418
  }
3419
  return (const char*)tstrerror(pRequest->code);
3,354✔
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) {
14,239✔
3431
  int32_t    code = 0;
14,239✔
3432
  STscStmt2* pStmt = (STscStmt2*)stmt;
14,239✔
3433
  int32_t    preCode = pStmt->errCode;
14,239✔
3434

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

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

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

3454
  STMT_ERRI_JRET(stmtCreateRequest(pStmt));
14,239✔
3455

3456
  if (pStmt->bInfo.needParse) {
14,239✔
3457
    STMT_ERRI_JRET(stmtParseSql(pStmt));
12,853✔
3458
  }
3459

3460
_return:
10,710✔
3461
  // compatible with previous versions
3462
  if (code == TSDB_CODE_PAR_TABLE_NOT_EXIST && (pStmt->bInfo.tbNameFlag & NO_DATA_USING_CLAUSE) == 0x0) {
14,239✔
3463
    code = TSDB_CODE_TSC_STMT_TBNAME_ERROR;
792✔
3464
  }
3465

3466
  pStmt->errCode = preCode;
14,239✔
3467

3468
  return code;
14,239✔
3469
}
3470

3471
int stmtGetStbColFields2(TAOS_STMT2* stmt, int* nums, TAOS_FIELD_ALL** fields) {
14,239✔
3472
  int32_t code = stmtParseColFields2(stmt);
14,239✔
3473
  if (code != TSDB_CODE_SUCCESS) {
14,239✔
3474
    return code;
3,529✔
3475
  }
3476

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

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

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

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

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

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

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

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

3575
  STMT_ERRI_JRET(stmtSwitchStatus(pStmt, STMT_FETCH_FIELDS));
4,950✔
3576

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

3586
  STMT_ERRI_JRET(stmtCreateRequest(pStmt));
4,950✔
3587

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

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

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

3603
_return:
4,950✔
3604

3605
  pStmt->errCode = preCode;
4,950✔
3606

3607
  return code;
4,950✔
3608
}
3609

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

3613
  STMT2_TLOG_E("start to use result");
9,673✔
3614

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

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

3625
  if (tsUseAdapter) {
9,475✔
3626
    TAOS_RES* res = (TAOS_RES*)pStmt->exec.pRequest;
4,554✔
3627
    pStmt->exec.pRequest = NULL;
4,554✔
3628
    return res;
4,554✔
3629
  }
3630

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

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

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

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

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

3678
  return;
594✔
3679
}
3680

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

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