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

taosdata / TDengine / #5053

13 May 2026 12:00PM UTC coverage: 73.397% (+0.06%) from 73.338%
#5053

push

travis-ci

web-flow
feat: taosdump support stream backup/restore (#35326)

139 of 170 new or added lines in 3 files covered. (81.76%)

627 existing lines in 131 files now uncovered.

281694 of 383795 relevant lines covered (73.4%)

132505311.38 hits per line

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

73.75
/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,888,947✔
21
    *pBuf = (char*)pTblBuf->pCurBuff + pTblBuf->buffOffset;
1,889,305✔
22
    pTblBuf->buffOffset += pTblBuf->buffUnit;
1,889,114✔
23
  } else if (pTblBuf->buffIdx < taosArrayGetSize(pTblBuf->pBufList)) {
×
24
    pTblBuf->pCurBuff = taosArrayGetP(pTblBuf->pBufList, pTblBuf->buffIdx++);
×
25
    if (NULL == pTblBuf->pCurBuff) {
×
26
      return TAOS_GET_TERRNO(TSDB_CODE_OUT_OF_MEMORY);
×
27
    }
28
    *pBuf = pTblBuf->pCurBuff;
×
29
    pTblBuf->buffOffset = pTblBuf->buffUnit;
×
30
  } else {
31
    void* buff = taosMemoryMalloc(pTblBuf->buffSize);
×
32
    if (NULL == buff) {
×
33
      return terrno;
×
34
    }
35

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

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

46
  return TSDB_CODE_SUCCESS;
1,889,061✔
47
}
48

49
static bool stmtDequeue(STscStmt2* pStmt, SStmtQNode** param) {
1,889,458✔
50
  int i = 0;
1,889,458✔
51
  while (0 == atomic_load_64((int64_t*)&pStmt->queue.qRemainNum)) {
8,571,401✔
52
    if (pStmt->queue.stopQueue) {
6,710,384✔
53
      return false;
27,712✔
54
    }
55
    if (i < 10) {
6,682,492✔
56
      taosUsleep(1);
6,261,538✔
57
      i++;
6,260,431✔
58
    } else {
59
      (void)taosThreadMutexLock(&pStmt->queue.mutex);
420,954✔
60
      if (pStmt->queue.stopQueue) {
421,650✔
61
        (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
×
62
        return false;
×
63
      }
64
      if (0 == atomic_load_64((int64_t*)&pStmt->queue.qRemainNum)) {
421,650✔
65
        (void)taosThreadCondWait(&pStmt->queue.waitCond, &pStmt->queue.mutex);
421,463✔
66
      }
67
      (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
421,498✔
68
    }
69
  }
70

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

75
  (void)taosThreadMutexLock(&pStmt->queue.mutex);
1,860,584✔
76
  if (pStmt->queue.head == pStmt->queue.tail) {
1,861,466✔
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,861,459✔
84
  pStmt->queue.head->next = node->next;
1,861,459✔
85
  if (pStmt->queue.tail == node) {
1,861,586✔
86
    pStmt->queue.tail = pStmt->queue.head;
1,081,758✔
87
  }
88
  node->next = NULL;
1,861,639✔
89
  *param = node;
1,861,579✔
90

91
  (void)atomic_sub_fetch_64((int64_t*)&pStmt->queue.qRemainNum, 1);
1,861,579✔
92
  (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
1,861,605✔
93

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

96
  return true;
1,861,584✔
97
}
98

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

105
  param->next = NULL;
1,861,034✔
106

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

109
  pStmt->queue.tail->next = param;
1,861,552✔
110
  pStmt->queue.tail = param;
1,861,552✔
111
  pStmt->stat.bindDataNum++;
1,861,428✔
112

113
  (void)atomic_add_fetch_64(&pStmt->queue.qRemainNum, 1);
1,861,241✔
114
  (void)taosThreadCondSignal(&(pStmt->queue.waitCond));
1,861,657✔
115

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

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

122
static int32_t stmtCreateRequest(STscStmt2* pStmt) {
4,004,058✔
123
  int32_t code = 0;
4,004,058✔
124

125
  if (pStmt->exec.pRequest == NULL) {
4,004,058✔
126
    code = buildRequest(pStmt->taos->id, pStmt->sql.sqlStr, pStmt->sql.sqlLen, NULL, false, &pStmt->exec.pRequest,
233,093✔
127
                        pStmt->reqid);
128
    if (pStmt->reqid != 0) {
232,966✔
129
      pStmt->reqid++;
9✔
130
    }
131
    pStmt->exec.pRequest->type = RES_TYPE__QUERY;
233,029✔
132
    if (pStmt->db != NULL) {
233,093✔
133
      taosMemoryFreeClear(pStmt->exec.pRequest->pDb);
219,384✔
134
      pStmt->exec.pRequest->pDb = taosStrdup(pStmt->db);
219,552✔
135
    }
136
    if (TSDB_CODE_SUCCESS == code) {
232,902✔
137
      pStmt->exec.pRequest->syncQuery = true;
233,029✔
138
      pStmt->exec.pRequest->stmtBindVersion = 2;
233,029✔
139
    }
140
    STMT2_DLOG("create request:0x%" PRIx64 ", QID:0x%" PRIx64, pStmt->exec.pRequest->self,
232,903✔
141
               pStmt->exec.pRequest->requestId);
142
  }
143

144
  return code;
4,004,319✔
145
}
146

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

150
  if (newStatus >= STMT_INIT && newStatus < STMT_MAX) {
5,402,245✔
151
    STMT2_LOG_SEQ(newStatus);
5,403,422✔
152
  }
153

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

159
  switch (newStatus) {
5,403,577✔
160
    case STMT_PREPARE:
210,822✔
161
      pStmt->errCode = 0;
210,822✔
162
      break;
210,666✔
163
    case STMT_SETTBNAME:
1,317,687✔
164
      if (STMT_STATUS_EQ(INIT)) {
1,317,687✔
165
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
166
      }
167
      if (!pStmt->sql.stbInterlaceMode && (STMT_STATUS_EQ(BIND) || STMT_STATUS_EQ(BIND_COL))) {
1,317,932✔
168
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
169
      }
170
      break;
1,317,657✔
171
    case STMT_SETTAGS:
685,189✔
172
      if (STMT_STATUS_EQ(INIT)) {
685,189✔
173
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
174
      }
175
      break;
685,189✔
176
    case STMT_FETCH_FIELDS:
19,231✔
177
      if (STMT_STATUS_EQ(INIT)) {
19,231✔
178
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
179
      }
180
      break;
19,231✔
181
    case STMT_BIND:
1,496,453✔
182
      if (STMT_STATUS_EQ(INIT) || STMT_STATUS_EQ(BIND_COL)) {
1,496,453✔
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;
1,496,326✔
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:
855,840✔
197
      if (STMT_STATUS_NE(BIND) && STMT_STATUS_NE(BIND_COL) && STMT_STATUS_NE(FETCH_FIELDS)) {
855,840✔
198
        code = TSDB_CODE_TSC_STMT_API_ERROR;
×
199
      }
200
      break;
855,812✔
201
    case STMT_EXECUTE:
818,355✔
202
      if (STMT_TYPE_QUERY == pStmt->sql.type) {
818,355✔
203
        if (STMT_STATUS_NE(ADD_BATCH) && STMT_STATUS_NE(FETCH_FIELDS) && STMT_STATUS_NE(BIND) &&
11,173✔
204
            STMT_STATUS_NE(BIND_COL)) {
455✔
205
          code = TSDB_CODE_TSC_STMT_API_ERROR;
455✔
206
        }
207
      } else {
208
        if (STMT_STATUS_NE(ADD_BATCH) && STMT_STATUS_NE(FETCH_FIELDS)) {
806,990✔
209
          code = TSDB_CODE_TSC_STMT_API_ERROR;
×
210
        }
211
      }
212
      break;
818,541✔
213
    default:
×
214
      code = TSDB_CODE_APP_ERROR;
×
215
      break;
×
216
  }
217

218
  STMT_ERR_RET(code);
5,403,422✔
219

220
  pStmt->sql.status = newStatus;
5,402,769✔
221

222
  return TSDB_CODE_SUCCESS;
5,403,586✔
223
}
224

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

228
  pStmt->sql.type = STMT_TYPE_MULTI_INSERT;
40,491✔
229

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

235
  *tbName = pStmt->bInfo.tbName;
31,755✔
236

237
  return TSDB_CODE_SUCCESS;
31,837✔
238
}
239

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

249
  if ((tags != NULL && ((SBoundColInfo*)tags)->numOfCols == 0) || !autoCreateTbl) {
198,779✔
250
    pStmt->sql.autoCreateTbl = false;
176,674✔
251
  }
252

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

257
  pStmt->bInfo.tbUid = autoCreateTbl ? 0 : pTableMeta->uid;
198,362✔
258
  pStmt->bInfo.tbSuid = pTableMeta->suid;
198,677✔
259
  pStmt->bInfo.tbVgId = pTableMeta->vgId;
198,666✔
260
  pStmt->bInfo.tbType = pTableMeta->tableType;
198,447✔
261

262
  if (!pStmt->bInfo.tagsCached) {
198,023✔
263
    qDestroyBoundColInfo(pStmt->bInfo.boundTags);
196,957✔
264
    taosMemoryFreeClear(pStmt->bInfo.boundTags);
197,504✔
265
  }
266

267
  // transfer ownership of cols to stmt
268
  if (cols) {
198,896✔
269
    pStmt->bInfo.fixedValueCols = *cols;
198,734✔
270
    *cols = NULL;
198,641✔
271
  }
272

273
  pStmt->bInfo.boundTags = tags;
198,817✔
274
  pStmt->bInfo.tagsCached = false;
198,564✔
275
  pStmt->bInfo.tbNameFlag = tbNameFlag;
198,506✔
276
  tstrncpy(pStmt->bInfo.stbFName, sTableName, sizeof(pStmt->bInfo.stbFName));
198,125✔
277

278
  if (pTableMeta->tableType != TSDB_CHILD_TABLE && pTableMeta->tableType != TSDB_SUPER_TABLE) {
198,107✔
279
    pStmt->sql.stbInterlaceMode = false;
8,626✔
280
  }
281

282
  return TSDB_CODE_SUCCESS;
198,418✔
283
}
284

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

288
  pStmt->sql.pVgHash = pVgHash;
198,415✔
289
  pStmt->exec.pBlockHash = pBlockHash;
198,500✔
290

291
  return TSDB_CODE_SUCCESS;
198,081✔
292
}
293

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

299
  STMT_ERR_RET(stmtUpdateBindInfo(stmt, pTableMeta, tags, cols, tbName, sTableName, autoCreateTbl, tbNameFlag));
198,547✔
300
  STMT_ERR_RET(stmtUpdateExecInfo(stmt, pVgHash, pBlockHash));
197,655✔
301

302
  pStmt->sql.autoCreateTbl = autoCreateTbl;
198,131✔
303

304
  return TSDB_CODE_SUCCESS;
198,371✔
305
}
306

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

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

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

316
  return TSDB_CODE_SUCCESS;
3,588✔
317
}
318

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

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

329
  STMT_ERR_RET(stmtCreateRequest(pStmt));
213,421✔
330
  pStmt->exec.pRequest->stmtBindVersion = 2;
213,082✔
331

332
  pStmt->stat.parseSqlNum++;
213,353✔
333

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

337
  pStmt->sql.siInfo.pQuery = pStmt->sql.pQuery;
209,381✔
338

339
  pStmt->bInfo.needParse = false;
209,272✔
340

341
  if (pStmt->sql.type == 0) {
208,773✔
342
    if (pStmt->sql.pQuery->pRoot && LEGAL_INSERT(nodeType(pStmt->sql.pQuery->pRoot))) {
170,178✔
343
      pStmt->sql.type = STMT_TYPE_INSERT;
159,244✔
344
      pStmt->sql.stbInterlaceMode = false;
159,391✔
345
    } else if (pStmt->sql.pQuery->pPrepareRoot && LEGAL_SELECT(nodeType(pStmt->sql.pQuery->pPrepareRoot))) {
10,953✔
346
      pStmt->sql.type = STMT_TYPE_QUERY;
10,124✔
347
      pStmt->sql.stbInterlaceMode = false;
10,124✔
348

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

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

371
  STableDataCxt* pTableCtx = *pSrc;
198,404✔
372
  if (pStmt->sql.stbInterlaceMode && pTableCtx->pData->pCreateTbReq && (pStmt->bInfo.tbNameFlag & USING_CLAUSE) == 0) {
198,672✔
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) {
198,738✔
392
    pStmt->sql.pBindInfo = taosMemoryMalloc(pTableCtx->boundColsInfo.numOfBound * sizeof(*pStmt->sql.pBindInfo));
195,009✔
393
    if (NULL == pStmt->sql.pBindInfo) {
195,055✔
394
      STMT2_ELOG_E("fail to malloc pBindInfo");
×
395
      return terrno;
×
396
    }
397
  }
398

399
  return TSDB_CODE_SUCCESS;
198,578✔
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) {
403,901✔
526
  if (pStmt->exec.pRequest) {
403,901✔
527
    taos_free_result(pStmt->exec.pRequest);
227,929✔
528
    pStmt->exec.pRequest = NULL;
228,084✔
529
  }
530
  pStmt->asyncResultAvailable = false;
403,909✔
531
}
404,180✔
532

533
static int32_t stmtCleanBindInfo(STscStmt2* pStmt) {
1,044,683✔
534
  pStmt->bInfo.tbUid = 0;
1,044,683✔
535
  pStmt->bInfo.tbVgId = -1;
1,044,743✔
536
  pStmt->bInfo.tbType = 0;
1,044,683✔
537
  pStmt->bInfo.needParse = true;
1,044,990✔
538
  pStmt->bInfo.inExecCache = false;
1,044,930✔
539

540
  pStmt->bInfo.tbName[0] = 0;
1,044,743✔
541
  pStmt->bInfo.tbFName[0] = 0;
1,044,679✔
542
  if (!pStmt->bInfo.tagsCached) {
1,044,926✔
543
    qDestroyBoundColInfo(pStmt->bInfo.boundTags);
798,587✔
544
    taosMemoryFreeClear(pStmt->bInfo.boundTags);
798,267✔
545
    pStmt->bInfo.boundTags = NULL;
798,912✔
546
  }
547

548
  if (!pStmt->bInfo.boundColsCached) {
1,045,708✔
549
    tSimpleHashCleanup(pStmt->bInfo.fixedValueCols);
429,597✔
550
    pStmt->bInfo.fixedValueCols = NULL;
429,290✔
551
  }
552

553
  if (!pStmt->sql.autoCreateTbl) {
1,045,437✔
554
    pStmt->bInfo.stbFName[0] = 0;
787,687✔
555
    pStmt->bInfo.tbSuid = 0;
788,165✔
556
  }
557

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

561
  return TSDB_CODE_SUCCESS;
1,045,464✔
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) {
615,537✔
570
  pTblBuf->pCurBuff = taosArrayGetP(pTblBuf->pBufList, 0);
615,537✔
571
  if (NULL == pTblBuf->pCurBuff) {
615,801✔
572
    tscError("QInfo:%p, fail to get buffer from list", pTblBuf);
120✔
573
    return;
×
574
  }
575
  pTblBuf->buffIdx = 1;
615,681✔
576
  pTblBuf->buffOffset = sizeof(*pQueue->head);
615,681✔
577

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

583
static int32_t stmtCleanExecInfo(STscStmt2* pStmt, bool keepTable, bool deepClean) {
1,027,540✔
584
  if (pStmt->sql.stbInterlaceMode) {
1,027,540✔
585
    if (deepClean) {
630,458✔
586
      taosHashCleanup(pStmt->exec.pBlockHash);
14,837✔
587
      pStmt->exec.pBlockHash = NULL;
14,837✔
588

589
      if (NULL != pStmt->exec.pCurrBlock) {
14,837✔
590
        taosMemoryFreeClear(pStmt->exec.pCurrBlock->boundColsInfo.pColIndex);
14,243✔
591
        taosMemoryFreeClear(pStmt->exec.pCurrBlock->pData);
14,243✔
592
        qDestroyStmtDataBlock(pStmt->exec.pCurrBlock);
14,243✔
593
        pStmt->exec.pCurrBlock = NULL;
14,243✔
594
      }
595
      if (STMT_TYPE_QUERY != pStmt->sql.type) {
14,837✔
596
        resetRequest(pStmt);
14,837✔
597
      }
598
    } else {
599
      pStmt->sql.siInfo.pTableColsIdx = 0;
615,621✔
600
      stmtResetQueueTableBuf(&pStmt->sql.siInfo.tbBuf, &pStmt->queue);
615,625✔
601
      tSimpleHashClear(pStmt->sql.siInfo.pTableRowDataHash);
615,648✔
602
    }
603
    if (NULL != pStmt->exec.pRequest) {
630,754✔
604
      pStmt->exec.pRequest->body.resInfo.numOfRows = 0;
615,917✔
605
    }
606
  } else {
607
    if (STMT_TYPE_QUERY != pStmt->sql.type || deepClean) {
397,202✔
608
      resetRequest(pStmt);
386,213✔
609
    }
610

611
    size_t keyLen = 0;
397,012✔
612
    void*  pIter = taosHashIterate(pStmt->exec.pBlockHash, NULL);
396,741✔
613
    while (pIter) {
810,715✔
614
      STableDataCxt* pBlocks = *(STableDataCxt**)pIter;
413,058✔
615
      char*          key = taosHashGetKey(pIter, &keyLen);
413,058✔
616
      STableMeta*    pMeta = qGetTableMetaInDataBlock(pBlocks);
413,329✔
617

618
      if (keepTable && pBlocks == pStmt->exec.pCurrBlock) {
413,329✔
619
        TSWAP(pBlocks->pData, pStmt->exec.pCurrTbData);
191,111✔
620
        STMT_ERR_RET(qResetStmtDataBlock(pBlocks, false));
221,196✔
621

622
        pIter = taosHashIterate(pStmt->exec.pBlockHash, pIter);
190,869✔
623
        continue;
191,111✔
624
      }
625

626
      qDestroyStmtDataBlock(pBlocks);
222,218✔
627
      STMT_ERR_RET(taosHashRemove(pStmt->exec.pBlockHash, key, keyLen));
221,987✔
628

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

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

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

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

645
  STMT_ERR_RET(stmtCleanBindInfo(pStmt));
826,311✔
646
  STMT2_TLOG("finish clean exec info, stbInterlaceMode:%d, keepTable:%d, deepClean:%d", pStmt->sql.stbInterlaceMode,
825,954✔
647
             keepTable, deepClean);
648

649
  return TSDB_CODE_SUCCESS;
826,238✔
650
}
651

652
static void stmtFreeSingleVgDataBlock(void* p) {
895,600✔
653
  SVgDataBlocks* pVg = *(SVgDataBlocks**)p;
895,600✔
654
  if (pVg) {
895,600✔
655
    taosMemoryFree(pVg->pData);
895,382✔
656
    taosMemoryFree(pVg);
895,439✔
657
  }
658
}
895,968✔
659

660
static void stmtFreeVgDataBlocksForRetry(STscStmt2* pStmt) {
1,017,723✔
661
  if (pStmt->pVgDataBlocksForRetry) {
1,017,723✔
662
    taosArrayDestroyEx(pStmt->pVgDataBlocksForRetry, stmtFreeSingleVgDataBlock);
806,045✔
663
    pStmt->pVgDataBlocksForRetry = NULL;
805,708✔
664
  }
665
}
1,017,594✔
666

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

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

675
  int32_t num = taosArrayGetSize(pModif->pDataBlocks);
807,278✔
676
  pStmt->pVgDataBlocksForRetry = taosArrayInit(num, POINTER_BYTES);
806,983✔
677
  if (!pStmt->pVgDataBlocksForRetry) {
807,098✔
678
    return terrno;
×
679
  }
680

681
  for (int32_t i = 0; i < num; i++) {
1,704,238✔
682
    SVgDataBlocks* pSrc = taosArrayGetP(pModif->pDataBlocks, i);
896,872✔
683
    SVgDataBlocks* pDst = taosMemoryMalloc(sizeof(SVgDataBlocks));
896,350✔
684
    if (!pDst) {
896,661✔
685
      stmtFreeVgDataBlocksForRetry(pStmt);
×
686
      return terrno;
×
687
    }
688
    *pDst = *pSrc;
896,661✔
689
    pDst->pData = taosMemoryMalloc(pSrc->size);
896,721✔
690
    if (!pDst->pData) {
896,691✔
691
      taosMemoryFree(pDst);
×
692
      stmtFreeVgDataBlocksForRetry(pStmt);
×
693
      return terrno;
×
694
    }
695
    (void)memcpy(pDst->pData, pSrc->pData, pSrc->size);
896,691✔
696
    if (NULL == taosArrayPush(pStmt->pVgDataBlocksForRetry, &pDst)) {
1,793,935✔
697
      taosMemoryFree(pDst->pData);
×
698
      taosMemoryFree(pDst);
×
699
      stmtFreeVgDataBlocksForRetry(pStmt);
×
700
      return terrno;
×
701
    }
702
  }
703
  return TSDB_CODE_SUCCESS;
807,366✔
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✔
1169
    SName       nm = {0};
×
1170
    int32_t     nc = TSDB_CODE_SUCCESS;
×
1171
    STableMeta* pMeta = NULL;
×
1172
    if (pStmt->bInfo.sname.type != 0) {
×
1173
      tNameAssign(&nm, &pStmt->bInfo.sname);
×
1174
      nc = tNameAddTbName(&nm, pTb->pCreateTbReq->name, strlen(pTb->pCreateTbReq->name));
×
1175
    } else if (pRequest->tableList != NULL && taosArrayGetSize(pRequest->tableList) > 0) {
×
1176
      SName* p0 = taosArrayGet(pRequest->tableList, 0);
×
1177
      tNameAssign(&nm, p0);
×
1178
      nc = tNameAddTbName(&nm, pTb->pCreateTbReq->name, strlen(pTb->pCreateTbReq->name));
×
1179
    } else {
1180
      STMT2_ELOG_E("retry patch: no db/sname context for createTbReq name");
×
1181
      return TSDB_CODE_TDB_TABLE_NOT_EXIST;
×
1182
    }
1183
    if (nc != TSDB_CODE_SUCCESS) {
×
1184
      return nc;
×
1185
    }
1186
    nc = catalogGetTableMeta(pStmt->pCatalog, &conn, &nm, &pMeta);
×
1187
    if (nc != TSDB_CODE_SUCCESS) {
×
1188
      taosMemoryFreeClear(pMeta);
×
1189
      return nc;
×
1190
    }
1191
    if (pMeta == NULL) {
×
1192
      return TSDB_CODE_INTERNAL_ERROR;
×
1193
    }
1194
    if (stmtRetryTbMetaIsSuperTable(pMeta)) {
×
1195
      taosMemoryFree(pMeta);
×
1196
      STMT2_ELOG_E("retry patch: createTbReq resolved to super table meta (unexpected)");
×
1197
      return TSDB_CODE_TDB_TABLE_NOT_EXIST;
×
1198
    }
1199
    pPatch->uid = pMeta->uid;
×
1200
    pPatch->suid = pMeta->suid;
×
1201
    pPatch->sver = pMeta->sversion;
×
1202
    taosMemoryFree(pMeta);
×
1203
    return TSDB_CODE_SUCCESS;
×
1204
  }
1205

1206
  // 2) request->tableList: align tbIdx with the tbIdx-th non-super-table entry (skip super table names).
1207
  if (pRequest->tableList != NULL) {
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) {
27,712✔
1358
  void* pBuf = *(void**)buf;
27,712✔
1359
  taosMemoryFree(pBuf);
27,712✔
1360
}
27,712✔
1361

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

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

1370
  taosMemoryFree(pStmt->sql.pBindInfo);
210,100✔
1371
  taosMemoryFree(pStmt->sql.queryRes.fields);
210,354✔
1372
  taosMemoryFree(pStmt->sql.queryRes.userFields);
210,211✔
1373
  taosMemoryFree(pStmt->sql.sqlStr);
210,020✔
1374
  qDestroyQuery(pStmt->sql.pQuery);
210,246✔
1375
  taosArrayDestroy(pStmt->sql.nodeList);
210,123✔
1376
  taosHashCleanup(pStmt->sql.pVgHash);
210,665✔
1377
  pStmt->sql.pVgHash = NULL;
209,852✔
1378
  if (pStmt->sql.fixValueTags) {
209,852✔
1379
    pStmt->sql.fixValueTags = false;
3,356✔
1380
    tdDestroySVCreateTbReq(pStmt->sql.fixValueTbReq);
3,356✔
1381
    taosMemoryFreeClear(pStmt->sql.fixValueTbReq);
3,356✔
1382
    pStmt->sql.fixValueTbReq = NULL;
3,356✔
1383
  }
1384

1385
  void* pIter = taosHashIterate(pStmt->sql.pTableCache, NULL);
209,852✔
1386
  while (pIter) {
226,366✔
1387
    SStmtTableCache* pCache = (SStmtTableCache*)pIter;
16,048✔
1388

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

1393
    pIter = taosHashIterate(pStmt->sql.pTableCache, pIter);
16,048✔
1394
  }
1395
  taosHashCleanup(pStmt->sql.pTableCache);
210,318✔
1396
  pStmt->sql.pTableCache = NULL;
210,394✔
1397

1398
  STMT_ERR_RET(stmtCleanExecInfo(pStmt, false, true));
210,394✔
1399
  STMT_ERR_RET(stmtCleanBindInfo(pStmt));
209,984✔
1400
  stmtFreeVgDataBlocksForRetry(pStmt);
210,665✔
1401

1402
  taos_free_result(pStmt->sql.siInfo.pRequest);
210,331✔
1403
  taosHashCleanup(pStmt->sql.siInfo.pVgroupHash);
210,625✔
1404
  tSimpleHashCleanup(pStmt->sql.siInfo.pTableHash);
210,665✔
1405
  tSimpleHashCleanup(pStmt->sql.siInfo.pTableRowDataHash);
210,625✔
1406
  taosArrayDestroyEx(pStmt->sql.siInfo.tbBuf.pBufList, stmtFreeTbBuf);
210,291✔
1407
  taosMemoryFree(pStmt->sql.siInfo.pTSchema);
210,295✔
1408
  qDestroyStmtDataBlock(pStmt->sql.siInfo.pDataCtx);
210,589✔
1409
  taosArrayDestroyEx(pStmt->sql.siInfo.pTableCols, stmtFreeTbCols);
210,625✔
1410
  pStmt->sql.siInfo.pTableCols = NULL;
210,589✔
1411

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

1415
  STMT2_TLOG_E("end to free SQL info");
209,812✔
1416

1417
  return TSDB_CODE_SUCCESS;
210,083✔
1418
}
1419

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

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

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

1444
  *vgId = vgInfo.vgId;
672,978✔
1445

1446
  return TSDB_CODE_SUCCESS;
672,978✔
1447
}
1448

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

1457
  pStmt->stat.ctgGetTbMetaNum++;
52,963✔
1458

1459
  if (TSDB_CODE_PAR_TABLE_NOT_EXIST == code) {
52,991✔
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);
52,001✔
1472

1473
  *uid = pTableMeta->uid;
52,001✔
1474
  *suid = pTableMeta->suid;
51,973✔
1475
  *tableType = pTableMeta->tableType;
52,001✔
1476
  pStmt->bInfo.tbVgId = pTableMeta->vgId;
52,001✔
1477
  *vgId = pTableMeta->vgId;
51,934✔
1478

1479
  taosMemoryFree(pTableMeta);
51,934✔
1480

1481
  return TSDB_CODE_SUCCESS;
51,966✔
1482
}
1483

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

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

1491
  return TSDB_CODE_SUCCESS;
46,254✔
1492
}
1493

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

1501
  pStmt->bInfo.needParse = true;
85,190✔
1502
  pStmt->bInfo.inExecCache = false;
85,223✔
1503

1504
  STableDataCxt** pCxtInExec = taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
85,156✔
1505
  if (pCxtInExec) {
85,307✔
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) {
79,367✔
1518
    STMT_ERR_RET(catalogGetHandle(pStmt->taos->pAppInfo->clusterId, &pStmt->pCatalog));
26,902✔
1519
    pStmt->sql.siInfo.pCatalog = pStmt->pCatalog;
26,953✔
1520
  }
1521

1522
  if (NULL == pStmt->sql.pTableCache || taosHashGetSize(pStmt->sql.pTableCache) <= 0) {
79,334✔
1523
    if (pStmt->bInfo.inExecCache) {
31,641✔
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);
31,741✔
1530

1531
    return TSDB_CODE_SUCCESS;
31,741✔
1532
  }
1533

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

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

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

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

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

1552
      return TSDB_CODE_SUCCESS;
12,042✔
1553
    }
1554

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

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

1562
  STMT_ERR_RET(stmtGetTableMetaAndValidate(pStmt, &uid, &suid, &vgId, &tableType));
35,456✔
1563

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

1566
  if (uid == pStmt->bInfo.tbUid) {
35,230✔
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) {
35,174✔
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));
34,184✔
1597
  if (pCache) {
34,240✔
1598
    pStmt->bInfo.needParse = false;
34,240✔
1599

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

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

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

1614
    pStmt->exec.pCurrBlock = pNewBlock;
34,268✔
1615

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

1618
    return TSDB_CODE_SUCCESS;
34,156✔
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,861,435✔
1641
  SStmtQNode* pParam = (SStmtQNode*)param;
1,861,435✔
1642

1643
  if (pParam->restoreTbCols) {
1,861,435✔
1644
    for (int32_t i = 0; i < pStmt->sql.siInfo.pTableColsIdx; ++i) {
1,860,730✔
1645
      SArray** p = (SArray**)TARRAY_GET_ELEM(pStmt->sql.siInfo.pTableCols, i);
1,244,859✔
1646
      *p = taosArrayInit(20, POINTER_BYTES);
1,244,792✔
1647
      if (*p == NULL) {
1,244,650✔
1648
        pStmt->errCode = terrno;
36✔
1649
      }
1650
    }
1651
    atomic_store_8((int8_t*)&pStmt->sql.siInfo.tableColsReady, true);
615,938✔
1652
    STMT2_TLOG_E("restore pTableCols finished");
616,055✔
1653
  } else {
1654
    int code = qAppendStmt2TableOutput(pStmt->sql.pQuery, pStmt->sql.pVgHash, &pParam->tblData, pStmt->exec.pCurrBlock,
1,245,379✔
1655
                                       &pStmt->sql.siInfo, pParam->pCreateTbReq);
1656
    // taosMemoryFree(pParam->pTbData);
1657
    if (code != TSDB_CODE_SUCCESS) {
1,245,325✔
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);
1,245,325✔
1662
  }
1663
}
1,861,664✔
1664

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

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

1671
  while (true) {
1,861,641✔
1672
    SStmtQNode* asyncParam = NULL;
1,889,551✔
1673

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

1682
    stmtAsyncOutput(pStmt, asyncParam);
1,861,557✔
1683
  }
1684

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

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

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

1703
  pStmt->bindThreadInUse = true;
27,910✔
1704

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

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

1715
  return TSDB_CODE_SUCCESS;
27,882✔
1716
}
1717

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

1723
  return TSDB_CODE_SUCCESS;
209,753✔
1724
}
1725

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

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

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

1746
  return TSDB_CODE_SUCCESS;
27,910✔
1747
}
1748

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

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

1775
  if (NULL != pOptions) {
204,358✔
1776
    (void)memcpy(&pStmt->options, pOptions, sizeof(pStmt->options));
200,548✔
1777
    if (pOptions->singleStbInsert && pOptions->singleTableBindOnce) {
200,548✔
1778
      pStmt->stbInterlaceMode = true;
22,488✔
1779
    }
1780

1781
    pStmt->reqid = pOptions->reqid;
200,548✔
1782
  }
1783

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

1790
    pStmt->sql.siInfo.pTableHash = tSimpleHashInit(100, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY));
22,488✔
1791
    if (NULL == pStmt->sql.siInfo.pTableHash) {
22,488✔
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));
22,488✔
1798
    if (NULL == pStmt->sql.siInfo.pTableRowDataHash) {
22,475✔
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);
22,475✔
1805
    if (NULL == pStmt->sql.siInfo.pTableCols) {
22,488✔
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);
22,488✔
1812
    if (TSDB_CODE_SUCCESS == code) {
22,488✔
1813
      code = stmtInitQueue(pStmt);
22,488✔
1814
    }
1815
    if (TSDB_CODE_SUCCESS == code) {
22,460✔
1816
      code = stmtStartBindThread(pStmt);
22,460✔
1817
    }
1818
    if (TSDB_CODE_SUCCESS != code) {
22,488✔
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;
204,358✔
1827
  if (pStmt->options.asyncExecFn) {
204,358✔
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);
204,358✔
1836
  if (TSDB_CODE_SUCCESS != code) {
204,331✔
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;
204,331✔
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,
204,331✔
1849
             pStmt->stbInterlaceMode, pStmt->options.asyncExecFn != NULL);
1850

1851
  return pStmt;
204,331✔
1852
}
1853

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

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

1870
  // The SQL statement specifies a database name, overriding the previously specified database
1871
  taosMemoryFreeClear(pStmt->exec.pRequest->pDb);
176,746✔
1872
  pStmt->exec.pRequest->pDb = taosStrdup(dbName);
176,728✔
1873
  (void)strdequote(pStmt->exec.pRequest->pDb);
176,866✔
1874
  if (pStmt->exec.pRequest->pDb == NULL) {
176,531✔
1875
    return terrno;
80✔
1876
  }
1877
  if (pStmt->sql.stbInterlaceMode) {
176,722✔
1878
    pStmt->sql.siInfo.dbname = pStmt->exec.pRequest->pDb;
14,063✔
1879
  }
1880
  return TSDB_CODE_SUCCESS;
176,785✔
1881
}
1882
static int32_t stmtResetStbInterlaceCache(STscStmt2* pStmt) {
5,422✔
1883
  int32_t code = TSDB_CODE_SUCCESS;
5,422✔
1884

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

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

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

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

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

1913
  return TSDB_CODE_SUCCESS;
5,422✔
1914
}
1915

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

1923
  pStmt->errCode = 0;
7,006✔
1924

1925
  // Wait for async execution to complete
1926
  if (pStmt->options.asyncExecFn && !pStmt->execSemWaited) {
7,006✔
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) {
7,006✔
1935
    while (0 == atomic_load_8((int8_t*)&pStmt->sql.siInfo.tableColsReady)) {
5,422✔
1936
      taosUsleep(1);
×
1937
    }
1938
    (void)taosThreadMutexLock(&pStmt->queue.mutex);
5,422✔
1939
    pStmt->queue.stopQueue = true;
5,422✔
1940
    (void)taosThreadCondSignal(&(pStmt->queue.waitCond));
5,422✔
1941
    (void)taosThreadMutexUnlock(&pStmt->queue.mutex);
5,422✔
1942

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

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

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

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

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

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

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

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

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

1997
  return TSDB_CODE_SUCCESS;
7,006✔
1998
}
1999

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

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

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

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

2016
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
210,836✔
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));
210,702✔
2023

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

2035
  if (stmt2IsInsert(pStmt)) {
210,719✔
2036
    pStmt->sql.stbInterlaceMode = pStmt->stbInterlaceMode;
199,389✔
2037
    char* dbName = NULL;
199,389✔
2038
    if (qParseDbName(sql, length, &dbName)) {
199,389✔
2039
      STMT_ERR_RET(stmtSetDbName2(stmt, dbName));
176,826✔
2040
      taosMemoryFreeClear(dbName);
176,745✔
2041
    } else if (pStmt->db != NULL && pStmt->db[0] != '\0') {
22,528✔
2042
      taosMemoryFreeClear(pStmt->exec.pRequest->pDb);
22,301✔
2043
      pStmt->exec.pRequest->pDb = taosStrdup(pStmt->db);
22,237✔
2044
      if (pStmt->exec.pRequest->pDb == NULL) {
22,365✔
2045
        STMT_ERR_RET(terrno);
×
2046
      }
2047
      (void)strdequote(pStmt->exec.pRequest->pDb);
22,301✔
2048

2049
      if (pStmt->sql.stbInterlaceMode) {
22,278✔
2050
        pStmt->sql.siInfo.dbname = pStmt->exec.pRequest->pDb;
7,645✔
2051
      }
2052
    }
2053

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

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

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

2073
  SArray* pTblCols = NULL;
14,243✔
2074
  for (int32_t i = 0; i < STMT_TABLE_COLS_NUM; i++) {
14,227,255✔
2075
    pTblCols = taosArrayInit(20, POINTER_BYTES);
14,212,999✔
2076
    if (NULL == pTblCols) {
14,210,304✔
2077
      return terrno;
×
2078
    }
2079

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

2085
  pStmt->sql.siInfo.boundTags = pStmt->bInfo.boundTags;
14,256✔
2086

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

2090
  return TSDB_CODE_SUCCESS;
14,243✔
2091
}
2092

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

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

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

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

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

2114
  int64_t startUs = taosGetTimestampUs();
1,317,488✔
2115

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

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

2122
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_SETTBNAME));
1,317,608✔
2123

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

2132
  STMT_ERR_RET(qCreateSName2(&pStmt->bInfo.sname, tbName, pStmt->taos->acctId, pStmt->exec.pRequest->pDb,
1,317,724✔
2133
                             pStmt->exec.pRequest->msgBuf, pStmt->exec.pRequest->msgBufLen));
2134
  STMT_ERR_RET(tNameExtractFullName(&pStmt->bInfo.sname, pStmt->bInfo.tbFName));
1,316,049✔
2135
  tstrncpy(pStmt->bInfo.tbName, (char*)tNameGetTableName(&pStmt->bInfo.sname), TSDB_TABLE_NAME_LEN);
1,316,460✔
2136

2137
  if (!pStmt->sql.stbInterlaceMode || NULL == pStmt->sql.siInfo.pDataCtx) {
1,316,658✔
2138
    STMT_ERR_RET(stmtGetFromCache(pStmt));
85,574✔
2139

2140
    if (pStmt->bInfo.needParse) {
84,798✔
2141
      STMT_ERR_RET(stmtParseSql(pStmt));
31,631✔
2142
      if (!pStmt->sql.autoCreateTbl) {
31,649✔
2143
        uint64_t uid, suid;
13,208✔
2144
        int32_t  vgId;
13,141✔
2145
        int8_t   tableType;
13,140✔
2146

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

2154
  } else {
2155
    pStmt->exec.pRequest->requestId++;
1,230,967✔
2156
    pStmt->bInfo.needParse = false;
1,231,352✔
2157
  }
2158

2159
  if (pStmt->sql.stbInterlaceMode && NULL == pStmt->sql.siInfo.pDataCtx) {
1,314,828✔
2160
    STMT_ERR_RET(stmtInitStbInterlaceTableInfo(pStmt));
14,243✔
2161
  }
2162

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

2166
  return TSDB_CODE_SUCCESS;
1,315,415✔
2167
}
2168

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

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

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

2181
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_SETTAGS));
567,310✔
2182

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

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

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

2198
  STableDataCxt** pDataBlock = NULL;
567,271✔
2199
  if (pStmt->exec.pCurrBlock) {
567,271✔
2200
    pDataBlock = &pStmt->exec.pCurrBlock;
556,110✔
2201
  } else {
2202
    pDataBlock =
2203
        (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
11,161✔
2204
    if (NULL == pDataBlock) {
11,161✔
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,161✔
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) {
567,271✔
2215
    return TSDB_CODE_SUCCESS;
×
2216
  }
2217

2218
  STMT2_TLOG_E("start to bind stmt tag values");
567,271✔
2219

2220
  void* boundTags = NULL;
567,271✔
2221
  if (pStmt->sql.stbInterlaceMode) {
567,271✔
2222
    boundTags = pStmt->sql.siInfo.boundTags;
543,522✔
2223
    *pCreateTbReq = taosMemoryCalloc(1, sizeof(SVCreateTbReq));
543,522✔
2224
    if (NULL == pCreateTbReq) {
543,522✔
2225
      return terrno;
×
2226
    }
2227
    int32_t vgId = -1;
543,522✔
2228
    STMT_ERR_RET(stmtTryAddTableVgroupInfo(pStmt, &vgId));
543,522✔
2229
    (*pCreateTbReq)->uid = vgId;
543,665✔
2230
  } else {
2231
    boundTags = pStmt->bInfo.boundTags;
23,749✔
2232
  }
2233

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

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

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

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

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

2254
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_SETTAGS));
117,946✔
2255

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

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

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

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

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

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

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

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

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

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

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

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

2400
_return:
10,716✔
2401

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

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

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

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

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

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

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

2445
  if (!pStmt->sql.siInfo.tbFromHash && pStmt->sql.siInfo.firstName[0] &&
1,245,245✔
2446
      0 == strcmp(pStmt->sql.siInfo.firstName, pStmt->bInfo.tbName)) {
38,292✔
2447
    pStmt->sql.siInfo.tbFromHash = true;
5,334✔
2448
  }
2449

2450
  if (0 == pStmt->sql.siInfo.firstName[0]) {
1,245,366✔
2451
    tstrncpy(pStmt->sql.siInfo.firstName, pStmt->bInfo.tbName, TSDB_TABLE_NAME_LEN);
13,783✔
2452
  }
2453

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

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

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

2465
  return TSDB_CODE_SUCCESS;
1,245,314✔
2466
}
2467

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

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

2488
  return TSDB_CODE_SUCCESS;
1,245,353✔
2489
}
2490

2491
static int32_t stmtCacheBlock(STscStmt2* pStmt) {
239,803✔
2492
  if (pStmt->sql.type != STMT_TYPE_MULTI_INSERT) {
239,803✔
2493
    return TSDB_CODE_SUCCESS;
170,655✔
2494
  }
2495

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

2499
  if (taosHashGet(pStmt->sql.pTableCache, &cacheUid, sizeof(cacheUid))) {
69,176✔
2500
    STMT2_TLOG("table %s already cached, no need to cache again", pStmt->bInfo.tbFName);
53,042✔
2501
    return TSDB_CODE_SUCCESS;
52,986✔
2502
  }
2503

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

2511
  STMT_ERR_RET(qCloneStmtDataBlock(&pDst, *pSrc, true));
16,246✔
2512

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

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

2523
  if (pStmt->sql.autoCreateTbl) {
16,246✔
2524
    pStmt->bInfo.tagsCached = true;
5,173✔
2525
  } else {
2526
    pStmt->bInfo.boundTags = NULL;
11,057✔
2527
  }
2528

2529
  return TSDB_CODE_SUCCESS;
16,246✔
2530
}
2531

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

2535
  int64_t startUs = taosGetTimestampUs();
856,119✔
2536

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

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

2543
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_ADD_BATCH));
855,967✔
2544

2545
  if (pStmt->sql.stbInterlaceMode) {
855,961✔
2546
    int64_t startUs2 = taosGetTimestampUs();
615,877✔
2547
    pStmt->stat.addBatchUs += startUs2 - startUs;
615,877✔
2548

2549
    pStmt->sql.siInfo.tableColsReady = false;
615,933✔
2550

2551
    SStmtQNode* param = NULL;
615,933✔
2552
    STMT_ERR_RET(stmtAllocQNodeFromBuf(&pStmt->sql.siInfo.tbBuf, (void**)&param));
1,231,894✔
2553
    param->restoreTbCols = true;
615,961✔
2554
    param->next = NULL;
615,961✔
2555

2556
    if (pStmt->sql.autoCreateTbl) {
616,089✔
2557
      pStmt->bInfo.tagsCached = true;
228,353✔
2558
    }
2559
    pStmt->bInfo.boundColsCached = true;
615,961✔
2560

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

2568
    return TSDB_CODE_SUCCESS;
616,028✔
2569
  }
2570

2571
  STMT_ERR_RET(stmtCacheBlock(pStmt));
239,915✔
2572

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

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

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

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

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

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

2704
  return code;
10,916✔
2705
}
2706

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

2711
  int64_t startUs = taosGetTimestampUs();
1,496,910✔
2712

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

2717
  if (pStmt->errCode != TSDB_CODE_SUCCESS) {
1,496,923✔
2718
    return pStmt->errCode;
198✔
2719
  }
2720

2721
  STMT_ERR_RET(stmtSwitchStatus(pStmt, STMT_BIND));
1,496,341✔
2722

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

2728
  if (pStmt->exec.pRequest && STMT_TYPE_QUERY == pStmt->sql.type && pStmt->sql.runTimes) {
1,495,882✔
2729
    resetRequest(pStmt);
2,237✔
2730
  }
2731

2732
  STMT_ERR_RET(stmtCreateRequest(pStmt));
1,495,953✔
2733
  if (pStmt->bInfo.needParse) {
1,496,263✔
2734
    code = stmtParseSql(pStmt);
157,150✔
2735
    if (code != TSDB_CODE_SUCCESS) {
157,297✔
2736
      goto cleanup_root;
×
2737
    }
2738
  }
2739

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

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

2772
    code = qStmtParseQuerySql(&ctx, pStmt->sql.pQuery, &metaData);
10,916✔
2773
    if (TSDB_CODE_SUCCESS == code) {
10,916✔
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,718✔
2777
      (void)memset(&metaData, 0, sizeof(SMetaData));  // Clear to avoid double free
10,718✔
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,718✔
2789
      STMT_ERR_RET(setResSchemaInfo(&pStmt->exec.pRequest->body.resInfo, pStmt->sql.pQuery->pResSchema,
18,449✔
2790
                                    pStmt->sql.pQuery->numOfResCols, pStmt->sql.pQuery->pResExtSchema, true));
2791
      taosMemoryFreeClear(pStmt->sql.pQuery->pResSchema);
10,718✔
2792
      taosMemoryFreeClear(pStmt->sql.pQuery->pResExtSchema);
10,718✔
2793
      setResPrecision(&pStmt->exec.pRequest->body.resInfo, pStmt->sql.pQuery->precision);
10,718✔
2794
    }
2795

2796
    TSWAP(pStmt->exec.pRequest->dbList, pStmt->sql.pQuery->pDbList);
10,718✔
2797
    TSWAP(pStmt->exec.pRequest->tableList, pStmt->sql.pQuery->pTableList);
10,718✔
2798
    TSWAP(pStmt->exec.pRequest->targetTableList, pStmt->sql.pQuery->pTargetTableList);
10,718✔
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,718✔
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) {
1,485,338✔
2818
    STMT_ERR_RET(stmtInitStbInterlaceTableInfo(pStmt));
×
2819
  }
2820

2821
  STableDataCxt** pDataBlock = NULL;
1,484,672✔
2822

2823
  if (pStmt->exec.pCurrBlock) {
1,484,672✔
2824
    pDataBlock = &pStmt->exec.pCurrBlock;
1,296,598✔
2825
  } else {
2826
    pDataBlock =
2827
        (STableDataCxt**)taosHashGet(pStmt->exec.pBlockHash, pStmt->bInfo.tbFName, strlen(pStmt->bInfo.tbFName));
188,132✔
2828
    if (NULL == pDataBlock) {
188,607✔
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;
188,607✔
2833
    if (pStmt->sql.stbInterlaceMode) {
188,495✔
2834
      taosArrayDestroy(pStmt->exec.pCurrBlock->pData->aCol);
14,243✔
2835
      (*pDataBlock)->pData->aCol = NULL;
14,243✔
2836
    }
2837
    if (colIdx < -1) {
188,446✔
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();
1,485,452✔
2845
  pStmt->stat.bindDataUs1 += startUs2 - startUs;
1,485,452✔
2846

2847
  SStmtQNode* param = NULL;
1,485,345✔
2848
  if (pStmt->sql.stbInterlaceMode) {
1,485,433✔
2849
    STMT_ERR_RET(stmtAllocQNodeFromBuf(&pStmt->sql.siInfo.tbBuf, (void**)&param));
2,490,175✔
2850
    STMT_ERR_RET(stmtGetTableColsFromCache(pStmt, &param->tblData.aCol));
2,490,298✔
2851
    taosArrayClear(param->tblData.aCol);
1,245,353✔
2852

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

2855
    param->restoreTbCols = false;
1,244,917✔
2856
    param->tblData.isOrdered = true;
1,244,977✔
2857
    param->tblData.isDuplicateTs = false;
1,244,977✔
2858
    tstrncpy(param->tblData.tbName, pStmt->bInfo.tbName, TSDB_TABLE_NAME_LEN);
1,244,904✔
2859

2860
    param->pCreateTbReq = pCreateTbReq;
1,244,703✔
2861
  }
2862

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

2866
  SArray*   pCols = pStmt->sql.stbInterlaceMode ? param->tblData.aCol : (*pDataBlock)->pData->aCol;
1,484,705✔
2867
  SBlobSet* pBlob = NULL;
1,484,519✔
2868
  if (colIdx < 0) {
1,484,275✔
2869
    if (pStmt->sql.stbInterlaceMode) {
1,483,761✔
2870
      (*pDataBlock)->pData->flags &= ~SUBMIT_REQ_COLUMN_DATA_FORMAT;
1,245,303✔
2871
      code = qBindStmtStbColsValue2(*pDataBlock, pCols, pStmt->bInfo.fixedValueCols, bind, pStmt->exec.pRequest->msgBuf,
1,702,534✔
2872
                                    pStmt->exec.pRequest->msgBufLen, &pStmt->sql.siInfo.pTSchema, pStmt->sql.pBindInfo,
1,245,561✔
2873
                                    pStmt->taos->optionInfo.charsetCxt, &pBlob);
1,245,561✔
2874
      param->tblData.isOrdered = (*pDataBlock)->ordered;
1,245,585✔
2875
      param->tblData.isDuplicateTs = (*pDataBlock)->duplicateTs;
1,245,638✔
2876
    } else {
2877
      if (colIdx == -1) {
238,413✔
2878
        if (pStmt->sql.bindRowFormat) {
238,236✔
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,
437,623✔
2883
                                   pStmt->exec.pRequest->msgBufLen, pStmt->taos->optionInfo.charsetCxt);
437,520✔
2884
      } else {
2885
        code =
2886
            qBindStmt2RowValue(*pDataBlock, (*pDataBlock)->pData->aRowP, pStmt->bInfo.fixedValueCols, bind,
397✔
2887
                               pStmt->exec.pRequest->msgBuf, pStmt->exec.pRequest->msgBufLen,
397✔
2888
                               &pStmt->sql.siInfo.pTSchema, pStmt->sql.pBindInfo, pStmt->taos->optionInfo.charsetCxt);
397✔
2889
      }
2890
    }
2891

2892
    if (code) {
1,484,161✔
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) {
1,188✔
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();
1,485,297✔
2928
  pStmt->stat.bindDataUs3 += startUs4 - startUs3;
1,485,297✔
2929

2930
  if (pStmt->stbInterlaceMode) {
1,485,340✔
2931
    if (param) param->tblData.pBlobSet = pBlob;
1,264,711✔
2932
  }
2933

2934
  if (pStmt->sql.stbInterlaceMode) {
1,485,344✔
2935
    STMT_ERR_RET(stmtAppendTablePostHandle(pStmt, param));
1,245,317✔
2936
  } else {
2937
    STMT_ERR_RET(stmtAddBatch2(pStmt));
239,868✔
2938
  }
2939

2940
  pStmt->stat.bindDataUs4 += taosGetTimestampUs() - startUs4;
1,485,472✔
2941
  return TSDB_CODE_SUCCESS;
1,485,151✔
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) {
818,610✔
3195
  STscStmt2* pStmt = (STscStmt2*)stmt;
818,610✔
3196
  int32_t    code = 0;
818,610✔
3197
  int64_t    startUs = taosGetTimestampUs();
818,993✔
3198

3199
  STMT2_DLOG_E("start to exec");
818,993✔
3200

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

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

3211
  if (pStmt->sql.stbInterlaceMode) {
818,153✔
3212
    STMT_ERR_RET(stmtAddBatch2(pStmt));
616,101✔
3213
  }
3214

3215
  code = stmtSwitchStatus(pStmt, STMT_EXECUTE);
818,722✔
3216
  if (code != TSDB_CODE_SUCCESS) goto _return;
818,820✔
3217

3218
  if (STMT_TYPE_QUERY != pStmt->sql.type) {
818,365✔
3219
    if (pStmt->sql.stbInterlaceMode) {
807,465✔
3220
      int64_t startTs = taosGetTimestampUs();
616,088✔
3221
      // wait for stmt bind thread to finish
3222
      while (atomic_load_64(&pStmt->sql.siInfo.tbRemainNum)) {
2,535,313✔
3223
        taosUsleep(1);
1,919,101✔
3224
      }
3225

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

3230
      pStmt->stat.execWaitUs += taosGetTimestampUs() - startTs;
615,890✔
3231
      STMT_ERR_RET(qBuildStmtFinOutput(pStmt->sql.pQuery, pStmt->sql.pVgHash, pStmt->sql.siInfo.pVgroupList));
615,890✔
3232
      taosHashCleanup(pStmt->sql.siInfo.pVgroupHash);
615,840✔
3233
      pStmt->sql.siInfo.pVgroupHash = NULL;
615,797✔
3234
      pStmt->sql.siInfo.pVgroupList = NULL;
615,857✔
3235
    } else {
3236
      tDestroySubmitTbData(pStmt->exec.pCurrTbData, TSDB_MSG_FLG_ENCODE);
191,529✔
3237
      taosMemoryFreeClear(pStmt->exec.pCurrTbData);
191,212✔
3238

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

3241
      STMT_ERR_RET(qBuildStmtOutput(pStmt->sql.pQuery, pStmt->sql.pVgHash, pStmt->exec.pBlockHash));
191,215✔
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));
807,227✔
3246
  }
3247

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

3254
  if (!fp) {
817,825✔
3255
    launchQueryImpl(pStmt->exec.pRequest, pStmt->sql.pQuery, true, NULL);
812,479✔
3256

3257
    if (pStmt->exec.pRequest->code && NEED_CLIENT_HANDLE_ERROR(pStmt->exec.pRequest->code)) {
812,296✔
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);
812,651✔
3286

3287
    pStmt->exec.affectedRows = taos_affected_rows(pStmt->exec.pRequest);
811,801✔
3288
    if (affected_rows) {
812,058✔
3289
      *affected_rows = pStmt->exec.affectedRows;
803,819✔
3290
    }
3291
    pStmt->affectedRows += pStmt->exec.affectedRows;
811,902✔
3292

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

3298
    STMT_ERR_RET(stmtCleanExecInfo(pStmt, (code ? false : true), false));
811,663✔
3299

3300
    ++pStmt->sql.runTimes;
811,881✔
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:
818,016✔
3321
  if (code) {
818,016✔
3322
    STMT2_ELOG("exec failed, error:%s", tstrerror(code));
851✔
3323
  }
3324
  pStmt->stat.execUseUs += taosGetTimestampUs() - startUs;
818,327✔
3325

3326
  STMT_RET(code);
818,387✔
3327
}
3328

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

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

3335
  if (pStmt->bindThreadInUse) {
203,236✔
3336
    // wait for stmt bind thread to finish
3337
    while (0 == atomic_load_8((int8_t*)&pStmt->sql.siInfo.tableColsReady)) {
22,688✔
3338
      taosUsleep(1);
398✔
3339
    }
3340

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

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

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

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

3359
  (void)taosThreadCondDestroy(&pStmt->asyncBindParam.waitCond);
203,182✔
3360
  (void)taosThreadMutexDestroy(&pStmt->asyncBindParam.mutex);
203,162✔
3361

3362
  if (pStmt->options.asyncExecFn && !pStmt->execSemWaited) {
203,284✔
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) {
203,284✔
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
203,245✔
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) {
203,245✔
3387
    pStmt->bInfo.tagsCached = false;
10,729✔
3388
  }
3389
  pStmt->bInfo.boundColsCached = false;
203,245✔
3390

3391
  STMT_ERR_RET(stmtCleanSQLInfo(pStmt));
203,516✔
3392

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

3400
  return TSDB_CODE_SUCCESS;
202,991✔
3401
}
3402

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

3406
  if (stmt == NULL || NULL == pStmt->exec.pRequest) {
11,195✔
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)) {
10,403✔
3412
    pStmt->exec.pRequest->code = terrno;
10,403✔
3413
  }
3414

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

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

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

3446
  if (pStmt->bInfo.needParse && pStmt->sql.runTimes && pStmt->sql.type > 0 &&
14,281✔
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,281✔
3451
    pStmt->bInfo.needParse = false;
1,188✔
3452
  }
3453

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

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

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

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

3468
  return code;
14,281✔
3469
}
3470

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

3477
  return stmtFetchStbColFields2(stmt, nums, fields);
10,716✔
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✔
3483
    return NULL;
×
3484
  }
3485
  SNode* pRoot = pStmt->sql.pQuery->pPrepareRoot;
594✔
3486
  if (QUERY_NODE_SELECT_STMT != nodeType(pRoot)) {
594✔
3487
    return NULL;
×
3488
  }
3489
  SSelectStmt* pSelect = (SSelectStmt*)pRoot;
594✔
3490
  SNode*       pFrom = pSelect->pFromTable;
594✔
3491
  if (pFrom == NULL) {
594✔
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
  }
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✔
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✔
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✔
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✔
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✔
3537
        taosMemoryFree(pField);
×
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✔
3546
      taosMemoryFree(pField);
×
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✔
3556
      taosMemoryFree(pField);
×
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,926✔
3611
  STscStmt2* pStmt = (STscStmt2*)stmt;
9,926✔
3612

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

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

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

3625
  if (tsUseAdapter) {
9,728✔
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;
5,174✔
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