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

taosdata / TDengine / #4897

25 Dec 2025 10:17AM UTC coverage: 65.717% (-0.2%) from 65.929%
#4897

push

travis-ci

web-flow
fix: [6622889291] Fix invalid rowSize. (#34043)

186011 of 283047 relevant lines covered (65.72%)

113853896.64 hits per line

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

69.25
/source/client/src/clientImpl.c
1
/*
2
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
3
 *
4
 * This program is free software: you can use, redistribute, and/or modify
5
 * it under the terms of the GNU Affero General Public License, version 3
6
 * or later ("AGPL"), as published by the Free Software Foundation.
7
 *
8
 * This program is distributed in the hope that it will be useful, but WITHOUT
9
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10
 * FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * You should have received a copy of the GNU Affero General Public License
13
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14
 */
15

16
#include "cJSON.h"
17
#include "clientInt.h"
18
#include "clientLog.h"
19
#include "clientMonitor.h"
20
#include "clientSession.h"
21
#include "command.h"
22
#include "decimal.h"
23
#include "scheduler.h"
24
#include "tdatablock.h"
25
#include "tdataformat.h"
26
#include "tdef.h"
27
#include "tglobal.h"
28
#include "tmisce.h"
29
#include "tmsg.h"
30
#include "tmsgtype.h"
31
#include "tpagedbuf.h"
32
#include "tref.h"
33
#include "tsched.h"
34
#include "tversion.h"
35

36
static int32_t initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet);
37
static int32_t buildConnectMsg(SRequestObj* pRequest, SMsgSendInfo** pMsgSendInfo, int32_t totpCode);
38

39
void setQueryRequest(int64_t rId) {
417,709,461✔
40
  SRequestObj* pReq = acquireRequest(rId);
417,709,461✔
41
  if (pReq != NULL) {
417,709,400✔
42
    pReq->isQuery = true;
417,697,564✔
43
    (void)releaseRequest(rId);
417,697,773✔
44
  }
45
}
417,709,188✔
46

47
static bool stringLengthCheck(const char* str, size_t maxsize) {
6,594,741✔
48
  if (str == NULL) {
6,594,741✔
49
    return false;
×
50
  }
51

52
  size_t len = strlen(str);
6,594,741✔
53
  if (len <= 0 || len > maxsize) {
6,594,741✔
54
    return false;
×
55
  }
56

57
  return true;
6,594,996✔
58
}
59

60
static bool validateUserName(const char* user) { return stringLengthCheck(user, TSDB_USER_LEN - 1); }
2,709,091✔
61

62
static bool validatePassword(const char* passwd) { return stringLengthCheck(passwd, TSDB_PASSWORD_MAX_LEN); }
2,708,909✔
63

64
static bool validateDbName(const char* db) { return stringLengthCheck(db, TSDB_DB_NAME_LEN - 1); }
1,177,006✔
65

66
static char* getClusterKey(const char* user, const char* auth, const char* ip, int32_t port) {
2,707,865✔
67
  char key[512] = {0};
2,707,865✔
68
  if (user == NULL) {
2,707,865✔
69
    (void)snprintf(key, sizeof(key), "%s:%s:%d", auth, ip, port);
×
70
  } else {
71
    (void)snprintf(key, sizeof(key), "%s:%s:%s:%d", user, auth, ip, port);
2,707,865✔
72
  }
73
  return taosStrdup(key);
2,707,865✔
74
}
75

76
static int32_t escapeToPrinted(char* dst, size_t maxDstLength, const char* src, size_t srcLength) {
652,392✔
77
  if (dst == NULL || src == NULL || srcLength == 0) {
652,392✔
78
    return 0;
542✔
79
  }
80

81
  size_t escapeLength = 0;
651,850✔
82
  for (size_t i = 0; i < srcLength; ++i) {
18,493,304✔
83
    if (src[i] == '\"' || src[i] == '\\' || src[i] == '\b' || src[i] == '\f' || src[i] == '\n' || src[i] == '\r' ||
17,841,454✔
84
        src[i] == '\t') {
17,841,454✔
85
      escapeLength += 1;
×
86
    }
87
  }
88

89
  size_t dstLength = srcLength;
651,850✔
90
  if (escapeLength == 0) {
651,850✔
91
    (void)memcpy(dst, src, srcLength);
651,850✔
92
  } else {
93
    dstLength = 0;
×
94
    for (size_t i = 0; i < srcLength && dstLength <= maxDstLength; i++) {
×
95
      switch (src[i]) {
×
96
        case '\"':
×
97
          dst[dstLength++] = '\\';
×
98
          dst[dstLength++] = '\"';
×
99
          break;
×
100
        case '\\':
×
101
          dst[dstLength++] = '\\';
×
102
          dst[dstLength++] = '\\';
×
103
          break;
×
104
        case '\b':
×
105
          dst[dstLength++] = '\\';
×
106
          dst[dstLength++] = 'b';
×
107
          break;
×
108
        case '\f':
×
109
          dst[dstLength++] = '\\';
×
110
          dst[dstLength++] = 'f';
×
111
          break;
×
112
        case '\n':
×
113
          dst[dstLength++] = '\\';
×
114
          dst[dstLength++] = 'n';
×
115
          break;
×
116
        case '\r':
×
117
          dst[dstLength++] = '\\';
×
118
          dst[dstLength++] = 'r';
×
119
          break;
×
120
        case '\t':
×
121
          dst[dstLength++] = '\\';
×
122
          dst[dstLength++] = 't';
×
123
          break;
×
124
        default:
×
125
          dst[dstLength++] = src[i];
×
126
      }
127
    }
128
  }
129

130
  return dstLength;
651,850✔
131
}
132

133
bool chkRequestKilled(void* param) {
2,147,483,647✔
134
  bool         killed = false;
2,147,483,647✔
135
  SRequestObj* pRequest = acquireRequest((int64_t)param);
2,147,483,647✔
136
  if (NULL == pRequest || pRequest->killed) {
2,147,483,647✔
137
    killed = true;
296✔
138
  }
139

140
  (void)releaseRequest((int64_t)param);
2,147,483,647✔
141

142
  return killed;
2,147,483,647✔
143
}
144

145
void cleanupAppInfo() {
1,195,667✔
146
  taosHashCleanup(appInfo.pInstMap);
1,195,667✔
147
  taosHashCleanup(appInfo.pInstMapByClusterId);
1,195,667✔
148
  tscInfo("cluster instance map cleaned");
1,195,667✔
149
}
1,195,667✔
150

151
static int32_t taosConnectImpl(const char* user, const char* auth, int32_t totpCode, const char* db,
152
                               __taos_async_fn_t fp, void* param, SAppInstInfo* pAppInfo, int connType,
153
                               STscObj** pTscObj);
154

155
static int32_t taos_connect_by_auth(const char* ip, const char* user, const char* auth, const char* totp,
2,708,976✔
156
                              const char* db, uint16_t port, int connType, STscObj** pObj) {
157
  TSC_ERR_RET(taos_init());
2,708,976✔
158

159
  if (user == NULL) {
2,708,586✔
160
    if (auth == NULL || strlen(auth) != (TSDB_TOKEN_LEN - 1)) {
×
161
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_TOKEN);
×
162
    }
163
  } else if (!validateUserName(user)) {
2,708,586✔
164
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
165
  }
166
  int32_t code = 0;
2,709,042✔
167

168
  char localDb[TSDB_DB_NAME_LEN] = {0};
2,709,042✔
169
  if (db != NULL && strlen(db) > 0) {
2,709,042✔
170
    if (!validateDbName(db)) {
1,176,555✔
171
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_DB_LENGTH);
×
172
    }
173

174
    tstrncpy(localDb, db, sizeof(localDb));
1,176,973✔
175
    (void)strdequote(localDb);
1,176,973✔
176
  }
177

178
  int32_t totpCode = -1;
2,709,205✔
179
  if (totp != NULL) {
2,709,205✔
180
    char* endptr = NULL;
35✔
181
    totpCode = taosStr2Int32(totp, &endptr, 10);
35✔
182
    if (endptr == totp || *endptr != '\0' || totpCode < 0 || totpCode > 999999) {
35✔
183
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_TOTP_CODE);
×
184
    }
185
  }
186

187
  SCorEpSet epSet = {0};
2,709,205✔
188
  if (ip) {
2,708,953✔
189
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
938,346✔
190
  } else {
191
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
1,770,607✔
192
  }
193

194
  if (port) {
2,707,613✔
195
    epSet.epSet.eps[0].port = port;
110,096✔
196
    epSet.epSet.eps[1].port = port;
110,096✔
197
  }
198

199
  char* key = getClusterKey(user, auth, ip, port);
2,707,613✔
200
  if (NULL == key) {
2,708,068✔
201
    TSC_ERR_RET(terrno);
×
202
  }
203
  tscInfo("connecting to server, numOfEps:%d inUse:%d user:%s db:%s key:%s", epSet.epSet.numOfEps, epSet.epSet.inUse,
2,708,068✔
204
          user ? user : "", db, key);
205
  for (int32_t i = 0; i < epSet.epSet.numOfEps; ++i) {
7,187,750✔
206
    tscInfo("ep:%d, %s:%u", i, epSet.epSet.eps[i].fqdn, epSet.epSet.eps[i].port);
4,479,135✔
207
  }
208

209
  SAppInstInfo** pInst = NULL;
2,708,615✔
210
  code = taosThreadMutexLock(&appInfo.mutex);
2,708,615✔
211
  if (TSDB_CODE_SUCCESS != code) {
2,708,615✔
212
    tscError("failed to lock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
213
    TSC_ERR_RET(code);
×
214
  }
215

216
  pInst = taosHashGet(appInfo.pInstMap, key, strlen(key));
2,708,615✔
217
  SAppInstInfo* p = NULL;
2,708,615✔
218
  if (pInst == NULL) {
2,708,615✔
219
    p = taosMemoryCalloc(1, sizeof(struct SAppInstInfo));
1,252,954✔
220
    if (NULL == p) {
1,252,954✔
221
      TSC_ERR_JRET(terrno);
×
222
    }
223
    p->mgmtEp = epSet;
1,252,954✔
224
    code = taosThreadMutexInit(&p->qnodeMutex, NULL);
1,252,954✔
225
    if (TSDB_CODE_SUCCESS != code) {
1,252,954✔
226
      taosMemoryFree(p);
×
227
      TSC_ERR_JRET(code);
×
228
    }
229
    code = openTransporter(user, auth, tsNumOfCores / 2, &p->pTransporter);
1,252,954✔
230
    if (TSDB_CODE_SUCCESS != code) {
1,252,954✔
231
      taosMemoryFree(p);
38✔
232
      TSC_ERR_JRET(code);
38✔
233
    }
234
    code = appHbMgrInit(p, key, &p->pAppHbMgr);
1,252,916✔
235
    if (TSDB_CODE_SUCCESS != code) {
1,252,916✔
236
      destroyAppInst(&p);
×
237
      TSC_ERR_JRET(code);
×
238
    }
239
    code = taosHashPut(appInfo.pInstMap, key, strlen(key), &p, POINTER_BYTES);
1,252,916✔
240
    if (TSDB_CODE_SUCCESS != code) {
1,252,916✔
241
      destroyAppInst(&p);
×
242
      TSC_ERR_JRET(code);
×
243
    }
244
    p->instKey = key;
1,252,916✔
245
    key = NULL;
1,252,916✔
246
    tscInfo("new app inst mgr:%p, user:%s, ip:%s, port:%d", p, user ? user : "", epSet.epSet.eps[0].fqdn, epSet.epSet.eps[0].port);
1,252,916✔
247

248
    pInst = &p;
1,252,916✔
249
  } else {
250
    if (NULL == *pInst || NULL == (*pInst)->pAppHbMgr) {
1,455,661✔
251
      tscError("*pInst:%p, pAppHgMgr:%p", *pInst, (*pInst) ? (*pInst)->pAppHbMgr : NULL);
×
252
      TSC_ERR_JRET(TSDB_CODE_TSC_INTERNAL_ERROR);
×
253
    }
254
    // reset to 0 in case of conn with duplicated user key but its user has ever been dropped.
255
    atomic_store_8(&(*pInst)->pAppHbMgr->connHbFlag, 0);
1,455,661✔
256
  }
257

258
_return:
2,708,615✔
259

260
  if (TSDB_CODE_SUCCESS != code) {
2,708,615✔
261
    (void)taosThreadMutexUnlock(&appInfo.mutex);
38✔
262
    taosMemoryFreeClear(key);
38✔
263
    return code;
38✔
264
  } else {
265
    code = taosThreadMutexUnlock(&appInfo.mutex);
2,708,577✔
266
    taosMemoryFreeClear(key);
2,708,577✔
267
    if (TSDB_CODE_SUCCESS != code) {
2,708,577✔
268
      tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
269
      return code;
×
270
    }
271
    
272
    // TODO: this block should not be here as user may be NULL in token auth mode
273
    // SSessParam pPara = {.type = SESSION_PER_USER, .value = 1};
274
    // code = sessMgtUpdateUserMetric((char*)user, &pPara);
275
    // if (TSDB_CODE_SUCCESS != code) {
276
    //  tscError("failed to connect with user:%s, code:%s", user ? user : "", tstrerror(code));
277
    //  return code;
278
    // }
279
    
280
    return taosConnectImpl(user, auth, totpCode, localDb, NULL, NULL, *pInst, connType, pObj);
2,708,577✔
281
  }
282
}
283

284
int32_t taos_connect_internal(const char* ip, const char* user, const char* pass, const char* totp,
2,708,965✔
285
                              const char* db, uint16_t port, int connType, STscObj** pObj) {
286
  char auth[TSDB_PASSWORD_LEN + 1] = {0};
2,708,965✔
287
  if (!validatePassword(pass)) {
2,708,965✔
288
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_PASS_LENGTH);
×
289
  }
290

291
  taosEncryptPass_c((uint8_t*)pass, strlen(pass), auth);
2,708,965✔
292
  return taos_connect_by_auth(ip, user, auth, totp, db, port, connType, pObj);
2,708,626✔
293
}
294

295
// SAppInstInfo* getAppInstInfo(const char* clusterKey) {
296
//   SAppInstInfo** ppAppInstInfo = taosHashGet(appInfo.pInstMap, clusterKey, strlen(clusterKey));
297
//   if (ppAppInstInfo != NULL && *ppAppInstInfo != NULL) {
298
//     return *ppAppInstInfo;
299
//   } else {
300
//     return NULL;
301
//   }
302
// }
303

304
void freeQueryParam(SSyncQueryParam* param) {
564,883✔
305
  if (param == NULL) return;
564,883✔
306
  if (TSDB_CODE_SUCCESS != tsem_destroy(&param->sem)) {
564,883✔
307
    tscError("failed to destroy semaphore in freeQueryParam");
×
308
  }
309
  taosMemoryFree(param);
564,883✔
310
}
311

312
int32_t buildRequest(uint64_t connId, const char* sql, int sqlLen, void* param, bool validateSql,
727,022,697✔
313
                     SRequestObj** pRequest, int64_t reqid) {
314
  int32_t code = createRequest(connId, TSDB_SQL_SELECT, reqid, pRequest);
727,022,697✔
315
  if (TSDB_CODE_SUCCESS != code) {
727,020,126✔
316
    tscError("failed to malloc sqlObj, %s", sql);
×
317
    return code;
×
318
  }
319

320
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
727,020,126✔
321
  if ((*pRequest)->sqlstr == NULL) {
727,022,116✔
322
    tscError("req:0x%" PRIx64 ", failed to prepare sql string buffer, %s", (*pRequest)->self, sql);
×
323
    destroyRequest(*pRequest);
×
324
    *pRequest = NULL;
×
325
    return terrno;
×
326
  }
327

328
  (void)strntolower((*pRequest)->sqlstr, sql, (int32_t)sqlLen);
727,023,713✔
329
  (*pRequest)->sqlstr[sqlLen] = 0;
727,027,844✔
330
  (*pRequest)->sqlLen = sqlLen;
727,031,217✔
331
  (*pRequest)->validateOnly = validateSql;
727,028,670✔
332
  (*pRequest)->stmtBindVersion = 0;
727,029,187✔
333

334
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
727,027,250✔
335

336
  STscObj* pTscObj = (*pRequest)->pTscObj;
727,029,639✔
337
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
727,027,747✔
338
                             sizeof((*pRequest)->self));
339
  if (err) {
727,024,475✔
340
    tscError("req:0x%" PRId64 ", failed to add to request container, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
341
             (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
342
    destroyRequest(*pRequest);
×
343
    *pRequest = NULL;
×
344
    return terrno;
×
345
  }
346

347
  (*pRequest)->allocatorRefId = -1;
727,024,475✔
348
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
727,023,666✔
349
    if (TSDB_CODE_SUCCESS !=
271,146,360✔
350
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
271,137,939✔
351
      tscError("req:0x%" PRId64 ", failed to create node allocator, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
352
               (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
353
      destroyRequest(*pRequest);
×
354
      *pRequest = NULL;
×
355
      return terrno;
×
356
    }
357
  }
358

359
  tscDebug("req:0x%" PRIx64 ", build request, QID:0x%" PRIx64, (*pRequest)->self, (*pRequest)->requestId);
727,030,662✔
360
  return TSDB_CODE_SUCCESS;
727,026,911✔
361
}
362

363
int32_t buildPreviousRequest(SRequestObj* pRequest, const char* sql, SRequestObj** pNewRequest) {
×
364
  int32_t code =
365
      buildRequest(pRequest->pTscObj->id, sql, strlen(sql), pRequest, pRequest->validateOnly, pNewRequest, 0);
×
366
  if (TSDB_CODE_SUCCESS == code) {
×
367
    pRequest->relation.prevRefId = (*pNewRequest)->self;
×
368
    (*pNewRequest)->relation.nextRefId = pRequest->self;
×
369
    (*pNewRequest)->relation.userRefId = pRequest->self;
×
370
    (*pNewRequest)->isSubReq = true;
×
371
  }
372
  return code;
×
373
}
374

375
int32_t parseSql(SRequestObj* pRequest, bool topicQuery, SQuery** pQuery, SStmtCallback* pStmtCb) {
642,391✔
376
  STscObj* pTscObj = pRequest->pTscObj;
642,391✔
377

378
  SParseContext cxt = {
642,793✔
379
      .requestId = pRequest->requestId,
641,475✔
380
      .requestRid = pRequest->self,
641,013✔
381
      .acctId = pTscObj->acctId,
642,883✔
382
      .db = pRequest->pDb,
642,793✔
383
      .topicQuery = topicQuery,
384
      .pSql = pRequest->sqlstr,
642,763✔
385
      .sqlLen = pRequest->sqlLen,
642,793✔
386
      .pMsg = pRequest->msgBuf,
642,089✔
387
      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
388
      .pTransporter = pTscObj->pAppInfo->pTransporter,
641,998✔
389
      .pStmtCb = pStmtCb,
390
      .pUser = pTscObj->user,
642,253✔
391
      .isSuperUser = (0 == strcmp(pTscObj->user, TSDB_DEFAULT_USER)),
641,861✔
392
      .enableSysInfo = pTscObj->sysInfo,
641,657✔
393
      .svrVer = pTscObj->sVer,
641,767✔
394
      .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes),
642,853✔
395
      .stmtBindVersion = pRequest->stmtBindVersion,
642,119✔
396
      .setQueryFp = setQueryRequest,
397
      .timezone = pTscObj->optionInfo.timezone,
641,677✔
398
      .charsetCxt = pTscObj->optionInfo.charsetCxt,
642,151✔
399
  };
400

401
  cxt.mgmtEpSet = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
642,181✔
402
  int32_t code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &cxt.pCatalog);
642,897✔
403
  if (code != TSDB_CODE_SUCCESS) {
642,597✔
404
    return code;
×
405
  }
406

407
  code = qParseSql(&cxt, pQuery);
642,597✔
408
  if (TSDB_CODE_SUCCESS == code) {
642,032✔
409
    if ((*pQuery)->haveResultSet) {
640,604✔
410
      code = setResSchemaInfo(&pRequest->body.resInfo, (*pQuery)->pResSchema, (*pQuery)->numOfResCols,
×
411
                              (*pQuery)->pResExtSchema, pRequest->stmtBindVersion > 0);
×
412
      setResPrecision(&pRequest->body.resInfo, (*pQuery)->precision);
×
413
    }
414
  }
415

416
  if (TSDB_CODE_SUCCESS == code || NEED_CLIENT_HANDLE_ERROR(code)) {
642,122✔
417
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
640,215✔
418
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
640,712✔
419
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
639,334✔
420
  }
421

422
  taosArrayDestroy(cxt.pTableMetaPos);
641,237✔
423
  taosArrayDestroy(cxt.pTableVgroupPos);
641,230✔
424

425
  return code;
641,457✔
426
}
427

428
int32_t execLocalCmd(SRequestObj* pRequest, SQuery* pQuery) {
×
429
  SRetrieveTableRsp* pRsp = NULL;
×
430
  int8_t             biMode = atomic_load_8(&pRequest->pTscObj->biMode);
×
431
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp, biMode,
×
432
                              pRequest->pTscObj->optionInfo.charsetCxt);
×
433
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
×
434
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4,
×
435
                                 pRequest->stmtBindVersion > 0);
×
436
  }
437

438
  return code;
×
439
}
440

441
int32_t execDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
351,294✔
442
  // drop table if exists not_exists_table
443
  if (NULL == pQuery->pCmdMsg) {
351,294✔
444
    return TSDB_CODE_SUCCESS;
×
445
  }
446

447
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
351,294✔
448
  pRequest->type = pMsgInfo->msgType;
351,294✔
449
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
351,294✔
450
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
351,294✔
451

452
  STscObj*      pTscObj = pRequest->pTscObj;
351,294✔
453
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
351,294✔
454

455
  // int64_t transporterId = 0;
456
  TSC_ERR_RET(asyncSendMsgToServer(pTscObj->pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg));
351,294✔
457
  TSC_ERR_RET(tsem_wait(&pRequest->body.rspSem));
351,294✔
458
  return TSDB_CODE_SUCCESS;
351,294✔
459
}
460

461
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
1,270,451,741✔
462

463
void asyncExecLocalCmd(SRequestObj* pRequest, SQuery* pQuery) {
5,226,952✔
464
  SRetrieveTableRsp* pRsp = NULL;
5,226,952✔
465
  if (pRequest->validateOnly) {
5,226,952✔
466
    doRequestCallback(pRequest, 0);
12,285✔
467
    return;
12,285✔
468
  }
469

470
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp,
10,414,552✔
471
                              atomic_load_8(&pRequest->pTscObj->biMode), pRequest->pTscObj->optionInfo.charsetCxt);
10,414,552✔
472
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
5,214,667✔
473
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4,
2,812,260✔
474
                                 pRequest->stmtBindVersion > 0);
2,812,260✔
475
  }
476

477
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
5,214,429✔
478
  pRequest->code = code;
5,214,429✔
479

480
  if (pRequest->code != TSDB_CODE_SUCCESS) {
5,214,429✔
481
    pResultInfo->numOfRows = 0;
3,810✔
482
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
3,810✔
483
             pRequest->requestId);
484
  } else {
485
    tscDebug(
5,210,857✔
486
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
487
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
488
  }
489

490
  doRequestCallback(pRequest, code);
5,214,667✔
491
}
492

493
int32_t asyncExecDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
16,862,352✔
494
  if (pRequest->validateOnly) {
16,862,352✔
495
    doRequestCallback(pRequest, 0);
×
496
    return TSDB_CODE_SUCCESS;
×
497
  }
498

499
  // drop table if exists not_exists_table
500
  if (NULL == pQuery->pCmdMsg) {
16,862,561✔
501
    doRequestCallback(pRequest, 0);
7,931✔
502
    return TSDB_CODE_SUCCESS;
7,931✔
503
  }
504

505
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
16,854,888✔
506
  pRequest->type = pMsgInfo->msgType;
16,854,630✔
507
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
16,854,628✔
508
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
16,854,370✔
509

510
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
16,854,370✔
511
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
16,854,161✔
512

513
  int32_t code = asyncSendMsgToServer(pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg);
16,854,544✔
514
  if (code) {
16,854,888✔
515
    doRequestCallback(pRequest, code);
×
516
  }
517
  return code;
16,854,888✔
518
}
519

520
int compareQueryNodeLoad(const void* elem1, const void* elem2) {
361,755✔
521
  SQueryNodeLoad* node1 = (SQueryNodeLoad*)elem1;
361,755✔
522
  SQueryNodeLoad* node2 = (SQueryNodeLoad*)elem2;
361,755✔
523

524
  if (node1->load < node2->load) {
361,755✔
525
    return -1;
×
526
  }
527

528
  return node1->load > node2->load;
361,755✔
529
}
530

531
int32_t updateQnodeList(SAppInstInfo* pInfo, SArray* pNodeList) {
55,483✔
532
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
55,483✔
533
  if (pInfo->pQnodeList) {
55,483✔
534
    taosArrayDestroy(pInfo->pQnodeList);
52,924✔
535
    pInfo->pQnodeList = NULL;
52,924✔
536
    tscDebug("QnodeList cleared in cluster 0x%" PRIx64, pInfo->clusterId);
52,924✔
537
  }
538

539
  if (pNodeList) {
55,483✔
540
    pInfo->pQnodeList = taosArrayDup(pNodeList, NULL);
55,483✔
541
    taosArraySort(pInfo->pQnodeList, compareQueryNodeLoad);
55,483✔
542
    tscDebug("QnodeList updated in cluster 0x%" PRIx64 ", num:%ld", pInfo->clusterId,
55,483✔
543
             taosArrayGetSize(pInfo->pQnodeList));
544
  }
545
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
55,483✔
546

547
  return TSDB_CODE_SUCCESS;
55,483✔
548
}
549

550
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
727,155,768✔
551
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
727,155,768✔
552
    *required = false;
727,006,060✔
553
    return TSDB_CODE_SUCCESS;
727,006,029✔
554
  }
555

556
  int32_t       code = TSDB_CODE_SUCCESS;
149,708✔
557
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
149,708✔
558
  *required = false;
149,708✔
559

560
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
149,708✔
561
  *required = (NULL == pInfo->pQnodeList);
149,708✔
562
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
149,708✔
563
  return TSDB_CODE_SUCCESS;
149,708✔
564
}
565

566
int32_t getQnodeList(SRequestObj* pRequest, SArray** pNodeList) {
×
567
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
×
568
  int32_t       code = 0;
×
569

570
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
×
571
  if (pInfo->pQnodeList) {
×
572
    *pNodeList = taosArrayDup(pInfo->pQnodeList, NULL);
×
573
  }
574
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
×
575
  if (NULL == *pNodeList) {
×
576
    SCatalog* pCatalog = NULL;
×
577
    code = catalogGetHandle(pRequest->pTscObj->pAppInfo->clusterId, &pCatalog);
×
578
    if (TSDB_CODE_SUCCESS == code) {
×
579
      *pNodeList = taosArrayInit(5, sizeof(SQueryNodeLoad));
×
580
      if (NULL == pNodeList) {
×
581
        TSC_ERR_RET(terrno);
×
582
      }
583
      SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
×
584
                               .requestId = pRequest->requestId,
×
585
                               .requestObjRefId = pRequest->self,
×
586
                               .mgmtEps = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp)};
×
587
      code = catalogGetQnodeList(pCatalog, &conn, *pNodeList);
×
588
    }
589

590
    if (TSDB_CODE_SUCCESS == code && *pNodeList) {
×
591
      code = updateQnodeList(pInfo, *pNodeList);
×
592
    }
593
  }
594

595
  return code;
×
596
}
597

598
int32_t getPlan(SRequestObj* pRequest, SQuery* pQuery, SQueryPlan** pPlan, SArray* pNodeList) {
6,204,228✔
599
  pRequest->type = pQuery->msgType;
6,204,228✔
600
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
6,204,168✔
601

602
  SPlanContext cxt = {.queryId = pRequest->requestId,
7,052,756✔
603
                      .acctId = pRequest->pTscObj->acctId,
6,205,274✔
604
                      .mgmtEpSet = getEpSet_s(&pAppInfo->mgmtEp),
6,205,334✔
605
                      .pAstRoot = pQuery->pRoot,
6,205,170✔
606
                      .showRewrite = pQuery->showRewrite,
6,205,144✔
607
                      .pMsg = pRequest->msgBuf,
6,205,144✔
608
                      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
609
                      .pUser = pRequest->pTscObj->user,
6,204,176✔
610
                      .timezone = pRequest->pTscObj->optionInfo.timezone,
6,203,822✔
611
                      .sysInfo = pRequest->pTscObj->sysInfo};
6,204,105✔
612

613
  return qCreateQueryPlan(&cxt, pPlan, pNodeList);
6,204,023✔
614
}
615

616
int32_t setResSchemaInfo(SReqResultInfo* pResInfo, const SSchema* pSchema, int32_t numOfCols,
142,287,657✔
617
                         const SExtSchema* pExtSchema, bool isStmt) {
618
  if (pResInfo == NULL || pSchema == NULL || numOfCols <= 0) {
142,287,657✔
619
    tscError("invalid paras, pResInfo == NULL || pSchema == NULL || numOfCols <= 0");
342✔
620
    return TSDB_CODE_INVALID_PARA;
×
621
  }
622

623
  pResInfo->numOfCols = numOfCols;
142,287,756✔
624
  if (pResInfo->fields != NULL) {
142,287,716✔
625
    taosMemoryFree(pResInfo->fields);
19,078✔
626
  }
627
  if (pResInfo->userFields != NULL) {
142,284,007✔
628
    taosMemoryFree(pResInfo->userFields);
19,078✔
629
  }
630
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD_E));
142,287,453✔
631
  if (NULL == pResInfo->fields) return terrno;
142,282,063✔
632
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
142,283,126✔
633
  if (NULL == pResInfo->userFields) {
142,283,270✔
634
    taosMemoryFree(pResInfo->fields);
×
635
    return terrno;
×
636
  }
637
  if (numOfCols != pResInfo->numOfCols) {
142,285,825✔
638
    tscError("numOfCols:%d != pResInfo->numOfCols:%d", numOfCols, pResInfo->numOfCols);
×
639
    return TSDB_CODE_FAILED;
×
640
  }
641

642
  for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
779,318,102✔
643
    pResInfo->fields[i].type = pSchema[i].type;
637,029,913✔
644

645
    pResInfo->userFields[i].type = pSchema[i].type;
637,029,562✔
646
    // userFields must convert to type bytes, no matter isStmt or not
647
    pResInfo->userFields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, false);
637,033,611✔
648
    pResInfo->fields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, isStmt);
637,032,630✔
649
    if (IS_DECIMAL_TYPE(pSchema[i].type) && pExtSchema) {
637,027,152✔
650
      decimalFromTypeMod(pExtSchema[i].typeMod, &pResInfo->fields[i].precision, &pResInfo->fields[i].scale);
1,426,881✔
651
    }
652

653
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
637,029,614✔
654
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
637,035,028✔
655
  }
656
  return TSDB_CODE_SUCCESS;
142,288,131✔
657
}
658

659
void setResPrecision(SReqResultInfo* pResInfo, int32_t precision) {
112,485,303✔
660
  if (precision != TSDB_TIME_PRECISION_MILLI && precision != TSDB_TIME_PRECISION_MICRO &&
112,485,303✔
661
      precision != TSDB_TIME_PRECISION_NANO) {
662
    return;
×
663
  }
664

665
  pResInfo->precision = precision;
112,485,303✔
666
}
667

668
int32_t buildVnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pDbVgList) {
116,464,731✔
669
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
116,464,731✔
670
  if (NULL == nodeList) {
116,470,699✔
671
    return terrno;
×
672
  }
673
  char* policy = (tsQueryPolicy == QUERY_POLICY_VNODE) ? "vnode" : "client";
116,471,203✔
674

675
  int32_t dbNum = taosArrayGetSize(pDbVgList);
116,471,203✔
676
  for (int32_t i = 0; i < dbNum; ++i) {
230,671,743✔
677
    SArray* pVg = taosArrayGetP(pDbVgList, i);
114,196,770✔
678
    if (NULL == pVg) {
114,197,879✔
679
      continue;
×
680
    }
681
    int32_t vgNum = taosArrayGetSize(pVg);
114,197,879✔
682
    if (vgNum <= 0) {
114,196,273✔
683
      continue;
706,974✔
684
    }
685

686
    for (int32_t j = 0; j < vgNum; ++j) {
362,132,562✔
687
      SVgroupInfo* pInfo = taosArrayGet(pVg, j);
248,639,998✔
688
      if (NULL == pInfo) {
248,640,970✔
689
        taosArrayDestroy(nodeList);
×
690
        return TSDB_CODE_OUT_OF_RANGE;
×
691
      }
692
      SQueryNodeLoad load = {0};
248,640,970✔
693
      load.addr.nodeId = pInfo->vgId;
248,641,742✔
694
      load.addr.epSet = pInfo->epSet;
248,642,083✔
695

696
      if (NULL == taosArrayPush(nodeList, &load)) {
248,639,424✔
697
        taosArrayDestroy(nodeList);
×
698
        return terrno;
×
699
      }
700
    }
701
  }
702

703
  int32_t vnodeNum = taosArrayGetSize(nodeList);
116,474,973✔
704
  if (vnodeNum > 0) {
116,473,047✔
705
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
113,204,827✔
706
    goto _return;
113,203,437✔
707
  }
708

709
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
3,268,220✔
710
  if (mnodeNum <= 0) {
3,267,935✔
711
    tscDebug("0x%" PRIx64 " %s policy, empty node list", pRequest->requestId, policy);
×
712
    goto _return;
×
713
  }
714

715
  void* pData = taosArrayGet(pMnodeList, 0);
3,267,935✔
716
  if (NULL == pData) {
3,267,935✔
717
    taosArrayDestroy(nodeList);
×
718
    return TSDB_CODE_OUT_OF_RANGE;
×
719
  }
720
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
3,267,935✔
721
    taosArrayDestroy(nodeList);
×
722
    return terrno;
×
723
  }
724

725
  tscDebug("0x%" PRIx64 " %s policy, use mnode list, num:%d", pRequest->requestId, policy, mnodeNum);
3,267,935✔
726

727
_return:
54,432✔
728

729
  *pNodeList = nodeList;
116,470,998✔
730

731
  return TSDB_CODE_SUCCESS;
116,470,788✔
732
}
733

734
int32_t buildQnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pQnodeList) {
82,456✔
735
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
82,456✔
736
  if (NULL == nodeList) {
82,456✔
737
    return terrno;
×
738
  }
739

740
  int32_t qNodeNum = taosArrayGetSize(pQnodeList);
82,456✔
741
  if (qNodeNum > 0) {
82,456✔
742
    void* pData = taosArrayGet(pQnodeList, 0);
322✔
743
    if (NULL == pData) {
322✔
744
      taosArrayDestroy(nodeList);
×
745
      return TSDB_CODE_OUT_OF_RANGE;
×
746
    }
747
    if (NULL == taosArrayAddBatch(nodeList, pData, qNodeNum)) {
322✔
748
      taosArrayDestroy(nodeList);
×
749
      return terrno;
×
750
    }
751
    tscDebug("0x%" PRIx64 " qnode policy, use qnode list, num:%d", pRequest->requestId, qNodeNum);
322✔
752
    goto _return;
322✔
753
  }
754

755
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
82,134✔
756
  if (mnodeNum <= 0) {
82,134✔
757
    tscDebug("0x%" PRIx64 " qnode policy, empty node list", pRequest->requestId);
56✔
758
    goto _return;
56✔
759
  }
760

761
  void* pData = taosArrayGet(pMnodeList, 0);
82,078✔
762
  if (NULL == pData) {
82,078✔
763
    taosArrayDestroy(nodeList);
×
764
    return TSDB_CODE_OUT_OF_RANGE;
×
765
  }
766
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
82,078✔
767
    taosArrayDestroy(nodeList);
×
768
    return terrno;
×
769
  }
770

771
  tscDebug("0x%" PRIx64 " qnode policy, use mnode list, num:%d", pRequest->requestId, mnodeNum);
82,078✔
772

773
_return:
×
774

775
  *pNodeList = nodeList;
82,456✔
776

777
  return TSDB_CODE_SUCCESS;
82,456✔
778
}
779

780
void freeVgList(void* list) {
6,159,690✔
781
  SArray* pList = *(SArray**)list;
6,159,690✔
782
  taosArrayDestroy(pList);
6,160,669✔
783
}
6,160,442✔
784

785
int32_t buildAsyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SMetaData* pResultMeta) {
110,349,001✔
786
  SArray* pDbVgList = NULL;
110,349,001✔
787
  SArray* pQnodeList = NULL;
110,349,001✔
788
  FDelete fp = NULL;
110,349,001✔
789
  int32_t code = 0;
110,349,001✔
790

791
  switch (tsQueryPolicy) {
110,349,001✔
792
    case QUERY_POLICY_VNODE:
110,265,413✔
793
    case QUERY_POLICY_CLIENT: {
794
      if (pResultMeta) {
110,265,413✔
795
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
110,266,408✔
796
        if (NULL == pDbVgList) {
110,266,319✔
797
          code = terrno;
×
798
          goto _return;
×
799
        }
800
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
110,266,319✔
801
        for (int32_t i = 0; i < dbNum; ++i) {
218,302,864✔
802
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
108,035,826✔
803
          if (pRes->code || NULL == pRes->pRes) {
108,036,077✔
804
            continue;
1,071✔
805
          }
806

807
          if (NULL == taosArrayPush(pDbVgList, &pRes->pRes)) {
216,069,586✔
808
            code = terrno;
×
809
            goto _return;
×
810
          }
811
        }
812
      } else {
813
        fp = freeVgList;
×
814

815
        int32_t dbNum = taosArrayGetSize(pRequest->dbList);
×
816
        if (dbNum > 0) {
×
817
          SCatalog*     pCtg = NULL;
×
818
          SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
×
819
          code = catalogGetHandle(pInst->clusterId, &pCtg);
×
820
          if (code != TSDB_CODE_SUCCESS) {
×
821
            goto _return;
×
822
          }
823

824
          pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
×
825
          if (NULL == pDbVgList) {
×
826
            code = terrno;
×
827
            goto _return;
×
828
          }
829
          SArray* pVgList = NULL;
×
830
          for (int32_t i = 0; i < dbNum; ++i) {
×
831
            char*            dbFName = taosArrayGet(pRequest->dbList, i);
×
832
            SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
×
833
                                     .requestId = pRequest->requestId,
×
834
                                     .requestObjRefId = pRequest->self,
×
835
                                     .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
×
836

837
            // catalogGetDBVgList will handle dbFName == null.
838
            code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
×
839
            if (code) {
×
840
              goto _return;
×
841
            }
842

843
            if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
×
844
              code = terrno;
×
845
              goto _return;
×
846
            }
847
          }
848
        }
849
      }
850

851
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
110,267,038✔
852
      break;
110,267,241✔
853
    }
854
    case QUERY_POLICY_HYBRID:
82,456✔
855
    case QUERY_POLICY_QNODE: {
856
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
164,702✔
857
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
82,246✔
858
        if (pRes->code) {
82,246✔
859
          pQnodeList = NULL;
×
860
        } else {
861
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
82,246✔
862
          if (NULL == pQnodeList) {
82,246✔
863
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
864
            goto _return;
×
865
          }
866
        }
867
      } else {
868
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
210✔
869
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
210✔
870
        if (pInst->pQnodeList) {
210✔
871
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
210✔
872
          if (NULL == pQnodeList) {
210✔
873
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
874
            goto _return;
×
875
          }
876
        }
877
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
210✔
878
      }
879

880
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
82,456✔
881
      break;
82,456✔
882
    }
883
    default:
1,132✔
884
      tscError("unknown query policy: %d", tsQueryPolicy);
1,132✔
885
      return TSDB_CODE_APP_ERROR;
×
886
  }
887

888
_return:
110,349,697✔
889
  taosArrayDestroyEx(pDbVgList, fp);
110,349,697✔
890
  taosArrayDestroy(pQnodeList);
110,349,895✔
891

892
  return code;
110,350,089✔
893
}
894

895
int32_t buildSyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList) {
6,202,834✔
896
  SArray* pDbVgList = NULL;
6,202,834✔
897
  SArray* pQnodeList = NULL;
6,202,834✔
898
  int32_t code = 0;
6,203,031✔
899

900
  switch (tsQueryPolicy) {
6,203,031✔
901
    case QUERY_POLICY_VNODE:
6,201,015✔
902
    case QUERY_POLICY_CLIENT: {
903
      int32_t dbNum = taosArrayGetSize(pRequest->dbList);
6,201,015✔
904
      if (dbNum > 0) {
6,203,197✔
905
        SCatalog*     pCtg = NULL;
6,161,111✔
906
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
6,160,602✔
907
        code = catalogGetHandle(pInst->clusterId, &pCtg);
6,160,695✔
908
        if (code != TSDB_CODE_SUCCESS) {
6,158,757✔
909
          goto _return;
×
910
        }
911

912
        pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
6,158,757✔
913
        if (NULL == pDbVgList) {
6,161,195✔
914
          code = terrno;
×
915
          goto _return;
×
916
        }
917
        SArray* pVgList = NULL;
6,161,195✔
918
        for (int32_t i = 0; i < dbNum; ++i) {
12,317,070✔
919
          char*            dbFName = taosArrayGet(pRequest->dbList, i);
6,158,409✔
920
          SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
6,161,863✔
921
                                   .requestId = pRequest->requestId,
6,159,985✔
922
                                   .requestObjRefId = pRequest->self,
6,160,484✔
923
                                   .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
6,160,060✔
924

925
          // catalogGetDBVgList will handle dbFName == null.
926
          code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
6,161,510✔
927
          if (code) {
6,157,734✔
928
            goto _return;
×
929
          }
930

931
          if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
6,162,007✔
932
            code = terrno;
×
933
            goto _return;
×
934
          }
935
        }
936
      }
937

938
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
6,202,478✔
939
      break;
6,203,225✔
940
    }
941
    case QUERY_POLICY_HYBRID:
×
942
    case QUERY_POLICY_QNODE: {
943
      TSC_ERR_JRET(getQnodeList(pRequest, &pQnodeList));
×
944

945
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
×
946
      break;
×
947
    }
948
    default:
2,016✔
949
      tscError("unknown query policy: %d", tsQueryPolicy);
2,016✔
950
      return TSDB_CODE_APP_ERROR;
×
951
  }
952

953
_return:
6,201,561✔
954

955
  taosArrayDestroyEx(pDbVgList, freeVgList);
6,202,464✔
956
  taosArrayDestroy(pQnodeList);
6,203,043✔
957

958
  return code;
6,203,539✔
959
}
960

961
int32_t scheduleQuery(SRequestObj* pRequest, SQueryPlan* pDag, SArray* pNodeList) {
6,198,022✔
962
  void* pTransporter = pRequest->pTscObj->pAppInfo->pTransporter;
6,198,022✔
963

964
  SExecResult      res = {0};
6,202,555✔
965
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
6,203,805✔
966
                           .requestId = pRequest->requestId,
6,203,888✔
967
                           .requestObjRefId = pRequest->self};
6,201,462✔
968
  SSchedulerReq    req = {
7,047,260✔
969
         .syncReq = true,
970
         .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
6,199,131✔
971
         .pConn = &conn,
972
         .pNodeList = pNodeList,
973
         .pDag = pDag,
974
         .sql = pRequest->sqlstr,
6,199,131✔
975
         .startTs = pRequest->metric.start,
6,202,292✔
976
         .execFp = NULL,
977
         .cbParam = NULL,
978
         .chkKillFp = chkRequestKilled,
979
         .chkKillParam = (void*)pRequest->self,
6,201,033✔
980
         .pExecRes = &res,
981
         .source = pRequest->source,
6,200,899✔
982
         .pWorkerCb = getTaskPoolWorkerCb(),
6,199,464✔
983
  };
984

985
  int32_t code = schedulerExecJob(&req, &pRequest->body.queryJob);
6,201,345✔
986

987
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
6,205,546✔
988
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
6,204,784✔
989

990
  if (code != TSDB_CODE_SUCCESS) {
6,204,784✔
991
    schedulerFreeJob(&pRequest->body.queryJob, 0);
×
992

993
    pRequest->code = code;
×
994
    terrno = code;
×
995
    return pRequest->code;
×
996
  }
997

998
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_DELETE == pRequest->type ||
6,204,784✔
999
      TDMT_VND_CREATE_TABLE == pRequest->type) {
15,882✔
1000
    pRequest->body.resInfo.numOfRows = res.numOfRows;
6,193,272✔
1001
    if (TDMT_VND_SUBMIT == pRequest->type) {
6,193,655✔
1002
      STscObj*            pTscObj = pRequest->pTscObj;
6,188,555✔
1003
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
6,188,555✔
1004
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
6,189,538✔
1005
    }
1006

1007
    schedulerFreeJob(&pRequest->body.queryJob, 0);
6,193,871✔
1008
  }
1009

1010
  pRequest->code = res.code;
6,203,901✔
1011
  terrno = res.code;
6,204,211✔
1012
  return pRequest->code;
6,201,486✔
1013
}
1014

1015
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
459,976,424✔
1016
  SArray*      pArray = NULL;
459,976,424✔
1017
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
459,976,424✔
1018
  if (NULL == pRsp->aCreateTbRsp) {
459,976,424✔
1019
    return TSDB_CODE_SUCCESS;
451,251,326✔
1020
  }
1021

1022
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
8,736,447✔
1023
  for (int32_t i = 0; i < tbNum; ++i) {
21,057,641✔
1024
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
12,320,979✔
1025
    if (pTbRsp->pMeta) {
12,320,799✔
1026
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
11,715,103✔
1027
    }
1028
  }
1029

1030
  return TSDB_CODE_SUCCESS;
8,736,662✔
1031
}
1032

1033
int32_t handleQueryExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
97,652,018✔
1034
  int32_t code = 0;
97,652,018✔
1035
  SArray* pArray = NULL;
97,652,018✔
1036
  SArray* pTbArray = (SArray*)res;
97,652,018✔
1037
  int32_t tbNum = taosArrayGetSize(pTbArray);
97,652,018✔
1038
  if (tbNum <= 0) {
97,651,819✔
1039
    return TSDB_CODE_SUCCESS;
×
1040
  }
1041

1042
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
97,651,819✔
1043
  if (NULL == pArray) {
97,651,378✔
1044
    return terrno;
×
1045
  }
1046

1047
  for (int32_t i = 0; i < tbNum; ++i) {
320,141,208✔
1048
    STbVerInfo* tbInfo = taosArrayGet(pTbArray, i);
222,490,044✔
1049
    if (NULL == tbInfo) {
222,490,071✔
1050
      code = terrno;
×
1051
      goto _return;
×
1052
    }
1053
    STbSVersion tbSver = {
222,490,071✔
1054
        .tbFName = tbInfo->tbFName, .sver = tbInfo->sversion, .tver = tbInfo->tversion, .rver = tbInfo->rversion};
222,489,372✔
1055
    if (NULL == taosArrayPush(pArray, &tbSver)) {
222,489,848✔
1056
      code = terrno;
×
1057
      goto _return;
×
1058
    }
1059
  }
1060

1061
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
97,651,164✔
1062
                           .requestId = pRequest->requestId,
97,651,572✔
1063
                           .requestObjRefId = pRequest->self,
97,651,792✔
1064
                           .mgmtEps = *epset};
1065

1066
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
97,651,596✔
1067

1068
_return:
97,651,592✔
1069

1070
  taosArrayDestroy(pArray);
97,650,872✔
1071
  return code;
97,651,346✔
1072
}
1073

1074
int32_t handleAlterTbExecRes(void* res, SCatalog* pCatalog) {
9,065,827✔
1075
  return catalogUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
9,065,827✔
1076
}
1077

1078
int32_t handleCreateTbExecRes(void* res, SCatalog* pCatalog) {
70,752,147✔
1079
  return catalogAsyncUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
70,752,147✔
1080
}
1081

1082
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
639,234,259✔
1083
  if (NULL == pRequest->body.resInfo.execRes.res) {
639,234,259✔
1084
    return pRequest->code;
24,533,105✔
1085
  }
1086

1087
  SCatalog*     pCatalog = NULL;
614,695,874✔
1088
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
614,696,930✔
1089

1090
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
614,710,481✔
1091
  if (code) {
614,697,724✔
1092
    return code;
×
1093
  }
1094

1095
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
614,697,724✔
1096
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
614,716,728✔
1097

1098
  switch (pRes->msgType) {
614,717,082✔
1099
    case TDMT_VND_ALTER_TABLE:
3,975,693✔
1100
    case TDMT_MND_ALTER_STB: {
1101
      code = handleAlterTbExecRes(pRes->res, pCatalog);
3,975,693✔
1102
      break;
3,975,693✔
1103
    }
1104
    case TDMT_VND_CREATE_TABLE: {
52,753,895✔
1105
      SArray* pList = (SArray*)pRes->res;
52,753,895✔
1106
      int32_t num = taosArrayGetSize(pList);
52,755,740✔
1107
      for (int32_t i = 0; i < num; ++i) {
109,876,781✔
1108
        void* res = taosArrayGetP(pList, i);
57,116,131✔
1109
        // handleCreateTbExecRes will handle res == null
1110
        code = handleCreateTbExecRes(res, pCatalog);
57,119,776✔
1111
      }
1112
      break;
52,760,650✔
1113
    }
1114
    case TDMT_MND_CREATE_STB: {
342,740✔
1115
      code = handleCreateTbExecRes(pRes->res, pCatalog);
342,740✔
1116
      break;
342,740✔
1117
    }
1118
    case TDMT_VND_SUBMIT: {
459,976,811✔
1119
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
459,976,811✔
1120

1121
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
459,989,029✔
1122
      break;
459,982,582✔
1123
    }
1124
    case TDMT_SCH_QUERY:
97,652,018✔
1125
    case TDMT_SCH_MERGE_QUERY: {
1126
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
97,652,018✔
1127
      break;
97,649,621✔
1128
    }
1129
    default:
172✔
1130
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self,
172✔
1131
               pRequest->type, pRequest->requestId);
1132
      code = TSDB_CODE_APP_ERROR;
×
1133
  }
1134

1135
  return code;
614,711,286✔
1136
}
1137

1138
static bool incompletaFileParsing(SNode* pStmt) {
619,711,305✔
1139
  return QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pStmt) ? false : ((SVnodeModifyOpStmt*)pStmt)->fileProcessing;
619,711,305✔
1140
}
1141

1142
void continuePostSubQuery(SRequestObj* pRequest, SSDataBlock* pBlock) {
×
1143
  SSqlCallbackWrapper* pWrapper = pRequest->pWrapper;
×
1144

1145
  int32_t code = nodesAcquireAllocator(pWrapper->pParseCtx->allocatorId);
×
1146
  if (TSDB_CODE_SUCCESS == code) {
×
1147
    int64_t analyseStart = taosGetTimestampUs();
×
1148
    code = qContinueParsePostQuery(pWrapper->pParseCtx, pRequest->pQuery, pBlock);
×
1149
    pRequest->metric.analyseCostUs += taosGetTimestampUs() - analyseStart;
×
1150
  }
1151

1152
  if (TSDB_CODE_SUCCESS == code) {
×
1153
    code = qContinuePlanPostQuery(pRequest->pPostPlan);
×
1154
  }
1155

1156
  code = nodesReleaseAllocator(pWrapper->pParseCtx->allocatorId);
×
1157
  handleQueryAnslyseRes(pWrapper, NULL, code);
×
1158
}
×
1159

1160
void returnToUser(SRequestObj* pRequest) {
57,394,115✔
1161
  if (pRequest->relation.userRefId == pRequest->self || 0 == pRequest->relation.userRefId) {
57,394,115✔
1162
    // return to client
1163
    doRequestCallback(pRequest, pRequest->code);
57,394,115✔
1164
    return;
57,394,115✔
1165
  }
1166

1167
  SRequestObj* pUserReq = acquireRequest(pRequest->relation.userRefId);
×
1168
  if (pUserReq) {
×
1169
    pUserReq->code = pRequest->code;
×
1170
    // return to client
1171
    doRequestCallback(pUserReq, pUserReq->code);
×
1172
    (void)releaseRequest(pRequest->relation.userRefId);
×
1173
    return;
×
1174
  } else {
1175
    tscError("req:0x%" PRIx64 ", user ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1176
             pRequest->relation.userRefId, pRequest->requestId);
1177
  }
1178
}
1179

1180
static int32_t createResultBlock(TAOS_RES* pRes, int32_t numOfRows, SSDataBlock** pBlock) {
×
1181
  int64_t     lastTs = 0;
×
1182
  TAOS_FIELD* pResFields = taos_fetch_fields(pRes);
×
1183
  int32_t     numOfFields = taos_num_fields(pRes);
×
1184

1185
  int32_t code = createDataBlock(pBlock);
×
1186
  if (code) {
×
1187
    return code;
×
1188
  }
1189

1190
  for (int32_t i = 0; i < numOfFields; ++i) {
×
1191
    SColumnInfoData colInfoData = createColumnInfoData(pResFields[i].type, pResFields[i].bytes, i + 1);
×
1192
    code = blockDataAppendColInfo(*pBlock, &colInfoData);
×
1193
    if (TSDB_CODE_SUCCESS != code) {
×
1194
      blockDataDestroy(*pBlock);
×
1195
      return code;
×
1196
    }
1197
  }
1198

1199
  code = blockDataEnsureCapacity(*pBlock, numOfRows);
×
1200
  if (TSDB_CODE_SUCCESS != code) {
×
1201
    blockDataDestroy(*pBlock);
×
1202
    return code;
×
1203
  }
1204

1205
  for (int32_t i = 0; i < numOfRows; ++i) {
×
1206
    TAOS_ROW pRow = taos_fetch_row(pRes);
×
1207
    if (NULL == pRow[0] || NULL == pRow[1] || NULL == pRow[2]) {
×
1208
      tscError("invalid data from vnode");
×
1209
      blockDataDestroy(*pBlock);
×
1210
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1211
    }
1212
    int64_t ts = *(int64_t*)pRow[0];
×
1213
    if (lastTs < ts) {
×
1214
      lastTs = ts;
×
1215
    }
1216

1217
    for (int32_t j = 0; j < numOfFields; ++j) {
×
1218
      SColumnInfoData* pColInfoData = taosArrayGet((*pBlock)->pDataBlock, j);
×
1219
      code = colDataSetVal(pColInfoData, i, pRow[j], false);
×
1220
      if (TSDB_CODE_SUCCESS != code) {
×
1221
        blockDataDestroy(*pBlock);
×
1222
        return code;
×
1223
      }
1224
    }
1225

1226
    tscInfo("[create stream with histroy] lastKey:%" PRId64 " vgId:%d, vgVer:%" PRId64, ts, *(int32_t*)pRow[1],
×
1227
            *(int64_t*)pRow[2]);
1228
  }
1229

1230
  (*pBlock)->info.window.ekey = lastTs;
×
1231
  (*pBlock)->info.rows = numOfRows;
×
1232

1233
  tscInfo("[create stream with histroy] lastKey:%" PRId64 " numOfRows:%d from all vgroups", lastTs, numOfRows);
×
1234
  return TSDB_CODE_SUCCESS;
×
1235
}
1236

1237
void postSubQueryFetchCb(void* param, TAOS_RES* res, int32_t rowNum) {
×
1238
  SRequestObj* pRequest = (SRequestObj*)res;
×
1239
  if (pRequest->code) {
×
1240
    returnToUser(pRequest);
×
1241
    return;
×
1242
  }
1243

1244
  SSDataBlock* pBlock = NULL;
×
1245
  pRequest->code = createResultBlock(res, rowNum, &pBlock);
×
1246
  if (TSDB_CODE_SUCCESS != pRequest->code) {
×
1247
    tscError("req:0x%" PRIx64 ", create result block failed, QID:0x%" PRIx64 " %s", pRequest->self, pRequest->requestId,
×
1248
             tstrerror(pRequest->code));
1249
    returnToUser(pRequest);
×
1250
    return;
×
1251
  }
1252

1253
  SRequestObj* pNextReq = acquireRequest(pRequest->relation.nextRefId);
×
1254
  if (pNextReq) {
×
1255
    continuePostSubQuery(pNextReq, pBlock);
×
1256
    (void)releaseRequest(pRequest->relation.nextRefId);
×
1257
  } else {
1258
    tscError("req:0x%" PRIx64 ", next req ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1259
             pRequest->relation.nextRefId, pRequest->requestId);
1260
  }
1261

1262
  blockDataDestroy(pBlock);
×
1263
}
1264

1265
void handlePostSubQuery(SSqlCallbackWrapper* pWrapper) {
×
1266
  SRequestObj* pRequest = pWrapper->pRequest;
×
1267
  if (TD_RES_QUERY(pRequest)) {
×
1268
    taosAsyncFetchImpl(pRequest, postSubQueryFetchCb, pWrapper);
×
1269
    return;
×
1270
  }
1271

1272
  SRequestObj* pNextReq = acquireRequest(pRequest->relation.nextRefId);
×
1273
  if (pNextReq) {
×
1274
    continuePostSubQuery(pNextReq, NULL);
×
1275
    (void)releaseRequest(pRequest->relation.nextRefId);
×
1276
  } else {
1277
    tscError("req:0x%" PRIx64 ", next req ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1278
             pRequest->relation.nextRefId, pRequest->requestId);
1279
  }
1280
}
1281

1282
// todo refacto the error code  mgmt
1283
void schedulerExecCb(SExecResult* pResult, void* param, int32_t code) {
632,727,859✔
1284
  SSqlCallbackWrapper* pWrapper = param;
632,727,859✔
1285
  SRequestObj*         pRequest = pWrapper->pRequest;
632,727,859✔
1286
  STscObj*             pTscObj = pRequest->pTscObj;
632,736,557✔
1287

1288
  pRequest->code = code;
632,740,520✔
1289
  if (pResult) {
632,741,262✔
1290
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
632,700,389✔
1291
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
632,704,183✔
1292
  }
1293

1294
  int32_t type = pRequest->type;
632,722,333✔
1295
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
632,712,666✔
1296
    if (pResult) {
510,134,507✔
1297
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
510,123,150✔
1298

1299
      // record the insert rows
1300
      if (TDMT_VND_SUBMIT == type) {
510,134,097✔
1301
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
453,974,260✔
1302
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
453,975,682✔
1303
      }
1304
    }
1305
    schedulerFreeJob(&pRequest->body.queryJob, 0);
510,144,976✔
1306
  }
1307

1308
  taosMemoryFree(pResult);
632,735,890✔
1309
  tscDebug("req:0x%" PRIx64 ", enter scheduler exec cb, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
632,726,464✔
1310
           pRequest->requestId);
1311

1312
  if (code != TSDB_CODE_SUCCESS && NEED_CLIENT_HANDLE_ERROR(code) && pRequest->sqlstr != NULL &&
632,726,274✔
1313
      pRequest->stmtBindVersion == 0) {
44,523✔
1314
    tscDebug("req:0x%" PRIx64 ", client retry to handle the error, code:%s, tryCount:%d, QID:0x%" PRIx64,
44,523✔
1315
             pRequest->self, tstrerror(code), pRequest->retry, pRequest->requestId);
1316
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
44,523✔
1317
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1318
    }
1319
    restartAsyncQuery(pRequest, code);
44,523✔
1320
    return;
44,523✔
1321
  }
1322

1323
  tscTrace("req:0x%" PRIx64 ", scheduler exec cb, request type:%s", pRequest->self, TMSG_INFO(pRequest->type));
632,681,751✔
1324
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
632,681,751✔
1325
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
2,888,786✔
1326
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1327
    }
1328
  }
1329

1330
  pRequest->metric.execCostUs = taosGetTimestampUs() - pRequest->metric.execStart;
632,683,007✔
1331
  int32_t code1 = handleQueryExecRsp(pRequest);
632,692,498✔
1332
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
632,696,437✔
1333
    pRequest->code = code1;
×
1334
  }
1335

1336
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
1,252,411,971✔
1337
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
619,708,515✔
1338
    continueInsertFromCsv(pWrapper, pRequest);
12,458✔
1339
    return;
12,458✔
1340
  }
1341

1342
  if (pRequest->relation.nextRefId) {
632,688,264✔
1343
    handlePostSubQuery(pWrapper);
×
1344
  } else {
1345
    destorySqlCallbackWrapper(pWrapper);
632,685,544✔
1346
    pRequest->pWrapper = NULL;
632,668,536✔
1347

1348
    // return to client
1349
    doRequestCallback(pRequest, code);
632,675,830✔
1350
  }
1351
}
1352

1353
void launchQueryImpl(SRequestObj* pRequest, SQuery* pQuery, bool keepQuery, void** res) {
6,553,775✔
1354
  int32_t code = 0;
6,553,775✔
1355
  int32_t subplanNum = 0;
6,553,775✔
1356

1357
  if (pQuery->pRoot) {
6,553,775✔
1358
    pRequest->stmtType = pQuery->pRoot->type;
6,203,928✔
1359
  }
1360

1361
  if (pQuery->pRoot && !pRequest->inRetry) {
6,554,084✔
1362
    STscObj*            pTscObj = pRequest->pTscObj;
6,204,831✔
1363
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
6,204,693✔
1364
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type) {
6,204,610✔
1365
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
6,193,554✔
1366
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
10,587✔
1367
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
10,585✔
1368
    }
1369
  }
1370

1371
  pRequest->body.execMode = pQuery->execMode;
6,554,769✔
1372
  switch (pQuery->execMode) {
6,556,468✔
1373
    case QUERY_EXEC_MODE_LOCAL:
×
1374
      if (!pRequest->validateOnly) {
×
1375
        if (NULL == pQuery->pRoot) {
×
1376
          terrno = TSDB_CODE_INVALID_PARA;
×
1377
          code = terrno;
×
1378
        } else {
1379
          code = execLocalCmd(pRequest, pQuery);
×
1380
        }
1381
      }
1382
      break;
×
1383
    case QUERY_EXEC_MODE_RPC:
351,294✔
1384
      if (!pRequest->validateOnly) {
351,294✔
1385
        code = execDdlQuery(pRequest, pQuery);
351,294✔
1386
      }
1387
      break;
351,294✔
1388
    case QUERY_EXEC_MODE_SCHEDULE: {
6,201,016✔
1389
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
6,201,016✔
1390
      if (NULL == pMnodeList) {
6,204,340✔
1391
        code = terrno;
×
1392
        break;
×
1393
      }
1394
      SQueryPlan* pDag = NULL;
6,204,340✔
1395
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
6,204,340✔
1396
      if (TSDB_CODE_SUCCESS == code) {
6,203,642✔
1397
        pRequest->body.subplanNum = pDag->numOfSubplans;
6,204,238✔
1398
        if (!pRequest->validateOnly) {
6,203,612✔
1399
          SArray* pNodeList = NULL;
6,202,050✔
1400
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
6,202,361✔
1401

1402
          if (TSDB_CODE_SUCCESS == code) {
6,203,704✔
1403
            SSessParam para = {.type = SESSION_MAX_CALL_VNODE_NUM, .value = taosArrayGetSize(pNodeList)};
6,204,328✔
1404
            code = tscUpdateSessMgtMetric(pRequest->pTscObj, &para);
6,202,333✔
1405
          }
1406

1407
          if (TSDB_CODE_SUCCESS == code) {
6,203,040✔
1408
            code = scheduleQuery(pRequest, pDag, pNodeList);
6,203,133✔
1409
          }
1410
          taosArrayDestroy(pNodeList);
6,202,011✔
1411
        }
1412
      }
1413
      taosArrayDestroy(pMnodeList);
6,200,047✔
1414
      break;
6,203,345✔
1415
    }
1416
    case QUERY_EXEC_MODE_EMPTY_RESULT:
×
1417
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
1418
      break;
×
1419
    default:
×
1420
      break;
×
1421
  }
1422

1423
  if (!keepQuery) {
6,555,292✔
1424
    qDestroyQuery(pQuery);
×
1425
  }
1426

1427
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
6,555,292✔
1428
    int ret = removeMeta(pRequest->pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type));
8,682✔
1429
    if (TSDB_CODE_SUCCESS != ret) {
8,682✔
1430
      tscError("req:0x%" PRIx64 ", remove meta failed,code:%d, QID:0x%" PRIx64, pRequest->self, ret,
×
1431
               pRequest->requestId);
1432
    }
1433
  }
1434

1435
  if (TSDB_CODE_SUCCESS == code) {
6,553,887✔
1436
    code = handleQueryExecRsp(pRequest);
6,553,190✔
1437
  }
1438

1439
  if (TSDB_CODE_SUCCESS != code) {
6,555,827✔
1440
    pRequest->code = code;
6,479✔
1441
  }
1442

1443
  if (res) {
6,555,827✔
1444
    *res = pRequest->body.resInfo.execRes.res;
×
1445
    pRequest->body.resInfo.execRes.res = NULL;
×
1446
  }
1447
}
6,555,827✔
1448

1449
static int32_t asyncExecSchQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta,
633,197,529✔
1450
                                 SSqlCallbackWrapper* pWrapper) {
1451
  int32_t code = TSDB_CODE_SUCCESS;
633,197,529✔
1452
  pRequest->type = pQuery->msgType;
633,197,529✔
1453
  SArray*     pMnodeList = NULL;
633,195,064✔
1454
  SQueryPlan* pDag = NULL;
633,195,064✔
1455
  int64_t     st = taosGetTimestampUs();
633,170,284✔
1456

1457
  if (!pRequest->parseOnly) {
633,170,284✔
1458
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
633,170,057✔
1459
    if (NULL == pMnodeList) {
633,181,907✔
1460
      code = terrno;
×
1461
    }
1462
    SPlanContext cxt = {.queryId = pRequest->requestId,
638,832,635✔
1463
                        .acctId = pRequest->pTscObj->acctId,
633,221,620✔
1464
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
633,234,454✔
1465
                        .pAstRoot = pQuery->pRoot,
633,235,316✔
1466
                        .showRewrite = pQuery->showRewrite,
633,238,854✔
1467
                        .isView = pWrapper->pParseCtx->isView,
633,221,534✔
1468
                        .isAudit = pWrapper->pParseCtx->isAudit,
633,209,604✔
1469
                        .pMsg = pRequest->msgBuf,
633,228,317✔
1470
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1471
                        .pUser = pRequest->pTscObj->user,
633,205,647✔
1472
                        .sysInfo = pRequest->pTscObj->sysInfo,
633,213,167✔
1473
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
633,210,323✔
1474
                        .allocatorId = pRequest->stmtBindVersion > 0 ? 0 : pRequest->allocatorRefId};
633,206,099✔
1475
    if (TSDB_CODE_SUCCESS == code) {
633,213,959✔
1476
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
633,211,868✔
1477
    }
1478
    if (code) {
633,189,895✔
1479
      tscError("req:0x%" PRIx64 ", failed to create query plan, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
271,209✔
1480
               pRequest->requestId);
1481
    } else {
1482
      pRequest->body.subplanNum = pDag->numOfSubplans;
632,918,686✔
1483
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
632,946,040✔
1484
    }
1485
  }
1486

1487
  pRequest->metric.execStart = taosGetTimestampUs();
633,212,720✔
1488
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
633,206,213✔
1489

1490
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
636,011,145✔
1491
    SArray* pNodeList = NULL;
632,681,256✔
1492
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
632,687,538✔
1493
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
110,348,765✔
1494
    }
1495

1496
    SRequestConnInfo conn = {.pTrans = getAppInfo(pRequest)->pTransporter,
632,697,898✔
1497
                             .requestId = pRequest->requestId,
632,705,245✔
1498
                             .requestObjRefId = pRequest->self};
632,715,396✔
1499
    SSchedulerReq    req = {
635,530,645✔
1500
           .syncReq = false,
1501
           .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
632,689,639✔
1502
           .pConn = &conn,
1503
           .pNodeList = pNodeList,
1504
           .pDag = pDag,
1505
           .allocatorRefId = pRequest->allocatorRefId,
632,689,639✔
1506
           .sql = pRequest->sqlstr,
632,679,096✔
1507
           .startTs = pRequest->metric.start,
632,703,201✔
1508
           .execFp = schedulerExecCb,
1509
           .cbParam = pWrapper,
1510
           .chkKillFp = chkRequestKilled,
1511
           .chkKillParam = (void*)pRequest->self,
632,688,325✔
1512
           .pExecRes = NULL,
1513
           .source = pRequest->source,
632,670,408✔
1514
           .pWorkerCb = getTaskPoolWorkerCb(),
632,648,968✔
1515
    };
1516
    if (TSDB_CODE_SUCCESS == code) {
632,696,871✔
1517
      code = schedulerExecJob(&req, &pRequest->body.queryJob);
632,729,695✔
1518
    }
1519

1520
    taosArrayDestroy(pNodeList);
632,699,448✔
1521
  } else {
1522
    qDestroyQueryPlan(pDag);
518,580✔
1523
    tscDebug("req:0x%" PRIx64 ", plan not executed, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
497,279✔
1524
             pRequest->requestId);
1525
    destorySqlCallbackWrapper(pWrapper);
497,279✔
1526
    pRequest->pWrapper = NULL;
497,279✔
1527
    if (TSDB_CODE_SUCCESS != code) {
497,279✔
1528
      pRequest->code = terrno;
271,209✔
1529
    }
1530

1531
    doRequestCallback(pRequest, code);
497,279✔
1532
  }
1533

1534
  // todo not to be released here
1535
  taosArrayDestroy(pMnodeList);
633,236,008✔
1536

1537
  return code;
633,218,534✔
1538
}
1539

1540
void launchAsyncQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta, SSqlCallbackWrapper* pWrapper) {
655,954,990✔
1541
  int32_t code = 0;
655,954,990✔
1542

1543
  if (pRequest->parseOnly) {
655,954,990✔
1544
    doRequestCallback(pRequest, 0);
294,748✔
1545
    return;
294,748✔
1546
  }
1547

1548
  pRequest->body.execMode = pQuery->execMode;
655,679,426✔
1549
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
655,663,592✔
1550
    destorySqlCallbackWrapper(pWrapper);
22,457,994✔
1551
    pRequest->pWrapper = NULL;
22,457,527✔
1552
  }
1553

1554
  if (pQuery->pRoot && !pRequest->inRetry) {
655,637,522✔
1555
    STscObj*            pTscObj = pRequest->pTscObj;
655,644,427✔
1556
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
655,609,194✔
1557
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
655,665,487✔
1558
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
522,330,889✔
1559
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
453,899,107✔
1560
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
201,808,239✔
1561
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
104,598,347✔
1562
    }
1563
  }
1564

1565
  switch (pQuery->execMode) {
655,671,878✔
1566
    case QUERY_EXEC_MODE_LOCAL:
5,226,952✔
1567
      asyncExecLocalCmd(pRequest, pQuery);
5,226,952✔
1568
      break;
5,226,952✔
1569
    case QUERY_EXEC_MODE_RPC:
16,862,561✔
1570
      code = asyncExecDdlQuery(pRequest, pQuery);
16,862,561✔
1571
      break;
16,862,819✔
1572
    case QUERY_EXEC_MODE_SCHEDULE: {
633,204,792✔
1573
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
633,204,792✔
1574
      break;
633,221,842✔
1575
    }
1576
    case QUERY_EXEC_MODE_EMPTY_RESULT:
368,223✔
1577
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
368,223✔
1578
      doRequestCallback(pRequest, 0);
368,223✔
1579
      break;
368,223✔
1580
    default:
×
1581
      tscError("req:0x%" PRIx64 ", invalid execMode %d", pRequest->self, pQuery->execMode);
×
1582
      doRequestCallback(pRequest, -1);
×
1583
      break;
×
1584
  }
1585
}
1586

1587
int32_t refreshMeta(STscObj* pTscObj, SRequestObj* pRequest) {
11,515✔
1588
  SCatalog* pCatalog = NULL;
11,515✔
1589
  int32_t   code = 0;
11,515✔
1590
  int32_t   dbNum = taosArrayGetSize(pRequest->dbList);
11,515✔
1591
  int32_t   tblNum = taosArrayGetSize(pRequest->tableList);
11,515✔
1592

1593
  if (dbNum <= 0 && tblNum <= 0) {
11,515✔
1594
    return TSDB_CODE_APP_ERROR;
11,515✔
1595
  }
1596

1597
  code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
×
1598
  if (code != TSDB_CODE_SUCCESS) {
×
1599
    return code;
×
1600
  }
1601

1602
  SRequestConnInfo conn = {.pTrans = pTscObj->pAppInfo->pTransporter,
×
1603
                           .requestId = pRequest->requestId,
×
1604
                           .requestObjRefId = pRequest->self,
×
1605
                           .mgmtEps = getEpSet_s(&pTscObj->pAppInfo->mgmtEp)};
×
1606

1607
  for (int32_t i = 0; i < dbNum; ++i) {
×
1608
    char* dbFName = taosArrayGet(pRequest->dbList, i);
×
1609

1610
    // catalogRefreshDBVgInfo will handle dbFName == null.
1611
    code = catalogRefreshDBVgInfo(pCatalog, &conn, dbFName);
×
1612
    if (code != TSDB_CODE_SUCCESS) {
×
1613
      return code;
×
1614
    }
1615
  }
1616

1617
  for (int32_t i = 0; i < tblNum; ++i) {
×
1618
    SName* tableName = taosArrayGet(pRequest->tableList, i);
×
1619

1620
    // catalogRefreshTableMeta will handle tableName == null.
1621
    code = catalogRefreshTableMeta(pCatalog, &conn, tableName, -1);
×
1622
    if (code != TSDB_CODE_SUCCESS) {
×
1623
      return code;
×
1624
    }
1625
  }
1626

1627
  return code;
×
1628
}
1629

1630
int32_t removeMeta(STscObj* pTscObj, SArray* tbList, bool isView) {
4,203,183✔
1631
  SCatalog* pCatalog = NULL;
4,203,183✔
1632
  int32_t   tbNum = taosArrayGetSize(tbList);
4,203,183✔
1633
  int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
4,203,183✔
1634
  if (code != TSDB_CODE_SUCCESS) {
4,203,183✔
1635
    return code;
×
1636
  }
1637

1638
  if (isView) {
4,203,183✔
1639
    for (int32_t i = 0; i < tbNum; ++i) {
824,876✔
1640
      SName* pViewName = taosArrayGet(tbList, i);
412,438✔
1641
      char   dbFName[TSDB_DB_FNAME_LEN];
409,858✔
1642
      if (NULL == pViewName) {
412,438✔
1643
        continue;
×
1644
      }
1645
      (void)tNameGetFullDbName(pViewName, dbFName);
412,438✔
1646
      TSC_ERR_RET(catalogRemoveViewMeta(pCatalog, dbFName, 0, pViewName->tname, 0));
412,438✔
1647
    }
1648
  } else {
1649
    for (int32_t i = 0; i < tbNum; ++i) {
5,648,817✔
1650
      SName* pTbName = taosArrayGet(tbList, i);
1,858,072✔
1651
      TSC_ERR_RET(catalogRemoveTableMeta(pCatalog, pTbName));
1,858,072✔
1652
    }
1653
  }
1654

1655
  return TSDB_CODE_SUCCESS;
4,203,183✔
1656
}
1657

1658
int32_t initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet) {
2,708,953✔
1659
  pEpSet->version = 0;
2,708,953✔
1660

1661
  // init mnode ip set
1662
  SEpSet* mgmtEpSet = &(pEpSet->epSet);
2,708,953✔
1663
  mgmtEpSet->numOfEps = 0;
2,708,725✔
1664
  mgmtEpSet->inUse = 0;
2,708,464✔
1665

1666
  if (firstEp && firstEp[0] != 0) {
2,708,231✔
1667
    if (strlen(firstEp) >= TSDB_EP_LEN) {
2,709,009✔
1668
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1669
      return -1;
×
1670
    }
1671

1672
    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
2,709,009✔
1673
    if (code != TSDB_CODE_SUCCESS) {
2,708,712✔
1674
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1675
      return terrno;
×
1676
    }
1677
    // uint32_t addr = 0;
1678
    SIpAddr addr = {0};
2,708,712✔
1679
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
2,708,940✔
1680
    if (code) {
2,707,990✔
1681
      tscError("failed to resolve firstEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
595✔
1682
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1683
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
539✔
1684
    } else {
1685
      mgmtEpSet->numOfEps++;
2,707,395✔
1686
    }
1687
  }
1688

1689
  if (secondEp && secondEp[0] != 0) {
2,707,511✔
1690
    if (strlen(secondEp) >= TSDB_EP_LEN) {
1,768,564✔
1691
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1692
      return terrno;
×
1693
    }
1694

1695
    int32_t code = taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
1,768,564✔
1696
    if (code != TSDB_CODE_SUCCESS) {
1,770,311✔
1697
      return code;
×
1698
    }
1699
    SIpAddr addr = {0};
1,770,311✔
1700
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
1,769,303✔
1701
    if (code) {
1,770,239✔
1702
      tscError("failed to resolve secondEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
×
1703
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1704
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
×
1705
    } else {
1706
      mgmtEpSet->numOfEps++;
1,770,270✔
1707
    }
1708
  }
1709

1710
  if (mgmtEpSet->numOfEps == 0) {
2,709,229✔
1711
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
539✔
1712
    return TSDB_CODE_RPC_NETWORK_UNAVAIL;
539✔
1713
  }
1714

1715
  return 0;
2,708,288✔
1716
}
1717

1718
int32_t taosConnectImpl(const char* user, const char* auth, int32_t totpCode, const char* db,
2,708,577✔
1719
                        __taos_async_fn_t fp, void* param, SAppInstInfo* pAppInfo, int connType, STscObj** pTscObj) {
1720
  *pTscObj = NULL;
2,708,577✔
1721
  int32_t code = createTscObj(user, auth, db, connType, pAppInfo, pTscObj);
2,708,577✔
1722
  if (TSDB_CODE_SUCCESS != code) {
2,708,577✔
1723
    return code;
×
1724
  }
1725

1726
  SRequestObj* pRequest = NULL;
2,708,577✔
1727
  code = createRequest((*pTscObj)->id, TDMT_MND_CONNECT, 0, &pRequest);
2,708,577✔
1728
  if (TSDB_CODE_SUCCESS != code) {
2,708,533✔
1729
    destroyTscObj(*pTscObj);
×
1730
    return code;
×
1731
  }
1732

1733
  pRequest->sqlstr = taosStrdup("taos_connect");
2,708,533✔
1734
  if (pRequest->sqlstr) {
2,708,521✔
1735
    pRequest->sqlLen = strlen(pRequest->sqlstr);
2,708,521✔
1736
  } else {
1737
    return terrno;
×
1738
  }
1739

1740
  SMsgSendInfo* body = NULL;
2,708,521✔
1741
  code = buildConnectMsg(pRequest, &body, totpCode);
2,708,521✔
1742
  if (TSDB_CODE_SUCCESS != code) {
2,707,586✔
1743
    destroyTscObj(*pTscObj);
×
1744
    return code;
×
1745
  }
1746

1747
  // int64_t transporterId = 0;
1748
  SEpSet epset = getEpSet_s(&(*pTscObj)->pAppInfo->mgmtEp);
2,707,586✔
1749
  code = asyncSendMsgToServer((*pTscObj)->pAppInfo->pTransporter, &epset, NULL, body);
2,707,819✔
1750
  if (TSDB_CODE_SUCCESS != code) {
2,708,106✔
1751
    destroyTscObj(*pTscObj);
×
1752
    tscError("failed to send connect msg to server, code:%s", tstrerror(code));
×
1753
    return code;
×
1754
  }
1755
  if (TSDB_CODE_SUCCESS != tsem_wait(&pRequest->body.rspSem)) {
2,708,106✔
1756
    destroyTscObj(*pTscObj);
×
1757
    tscError("failed to wait sem, code:%s", terrstr());
×
1758
    return terrno;
×
1759
  }
1760
  if (pRequest->code != TSDB_CODE_SUCCESS) {
2,708,577✔
1761
    const char* errorMsg = (code == TSDB_CODE_RPC_FQDN_ERROR) ? taos_errstr(pRequest) : tstrerror(pRequest->code);
13,672✔
1762
    tscError("failed to connect to server, reason: %s", errorMsg);
13,672✔
1763

1764
    terrno = pRequest->code;
13,672✔
1765
    destroyRequest(pRequest);
13,672✔
1766
    taos_close_internal(*pTscObj);
13,672✔
1767
    *pTscObj = NULL;
13,672✔
1768
    return terrno;
13,672✔
1769
  }
1770
  if (connType == CONN_TYPE__AUTH_TEST) {
2,694,905✔
1771
    terrno = TSDB_CODE_SUCCESS;
×
1772
    destroyRequest(pRequest);
×
1773
    taos_close_internal(*pTscObj);
×
1774
    *pTscObj = NULL;
×
1775
    return TSDB_CODE_SUCCESS;
×
1776
  }
1777

1778
  tscInfo("conn:0x%" PRIx64 ", connection is opening, connId:%u, dnodeConn:%p, QID:0x%" PRIx64, (*pTscObj)->id,
2,694,905✔
1779
          (*pTscObj)->connId, (*pTscObj)->pAppInfo->pTransporter, pRequest->requestId);
1780
  destroyRequest(pRequest);
2,694,905✔
1781
  return code;
2,694,872✔
1782
}
1783

1784
static int32_t buildConnectMsg(SRequestObj* pRequest, SMsgSendInfo** pMsgSendInfo, int32_t totpCode) {
2,708,533✔
1785
  *pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
2,708,533✔
1786
  if (*pMsgSendInfo == NULL) {
2,708,533✔
1787
    return terrno;
×
1788
  }
1789

1790
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
2,708,533✔
1791

1792
  (*pMsgSendInfo)->requestObjRefId = pRequest->self;
2,708,533✔
1793
  (*pMsgSendInfo)->requestId = pRequest->requestId;
2,708,533✔
1794
  (*pMsgSendInfo)->fp = getMsgRspHandle((*pMsgSendInfo)->msgType);
2,708,533✔
1795
  (*pMsgSendInfo)->param = taosMemoryCalloc(1, sizeof(pRequest->self));
2,708,513✔
1796
  if (NULL == (*pMsgSendInfo)->param) {
2,708,500✔
1797
    taosMemoryFree(*pMsgSendInfo);
×
1798
    return terrno;
×
1799
  }
1800

1801
  *(int64_t*)(*pMsgSendInfo)->param = pRequest->self;
2,707,993✔
1802

1803
  SConnectReq connectReq = {0};
2,708,500✔
1804
  STscObj*    pObj = pRequest->pTscObj;
2,707,993✔
1805

1806
  char* db = getDbOfConnection(pObj);
2,708,500✔
1807
  if (db != NULL) {
2,708,544✔
1808
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
1,177,062✔
1809
  } else if (terrno) {
1,531,482✔
1810
    taosMemoryFree(*pMsgSendInfo);
×
1811
    return terrno;
×
1812
  }
1813
  taosMemoryFreeClear(db);
2,708,577✔
1814

1815
  connectReq.connType = pObj->connType;
2,708,608✔
1816
  connectReq.pid = appInfo.pid;
2,708,608✔
1817
  connectReq.startTime = appInfo.startTime;
2,708,608✔
1818
  connectReq.totpCode = totpCode;
2,708,608✔
1819

1820
  tstrncpy(connectReq.app, appInfo.appName, sizeof(connectReq.app));
2,708,608✔
1821
  tstrncpy(connectReq.user, pObj->user, sizeof(connectReq.user));
2,708,608✔
1822
  tstrncpy(connectReq.passwd, pObj->pass, sizeof(connectReq.passwd));
2,708,101✔
1823
  tstrncpy(connectReq.token, pObj->token, sizeof(connectReq.token));
2,708,608✔
1824
  tstrncpy(connectReq.sVer, td_version, sizeof(connectReq.sVer));
2,708,608✔
1825

1826
  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connectReq);
2,708,608✔
1827
  void*   pReq = taosMemoryMalloc(contLen);
2,707,875✔
1828
  if (NULL == pReq) {
2,708,378✔
1829
    taosMemoryFree(*pMsgSendInfo);
×
1830
    return terrno;
×
1831
  }
1832

1833
  if (-1 == tSerializeSConnectReq(pReq, contLen, &connectReq)) {
2,708,378✔
1834
    taosMemoryFree(*pMsgSendInfo);
69✔
1835
    taosMemoryFree(pReq);
×
1836
    return terrno;
×
1837
  }
1838

1839
  (*pMsgSendInfo)->msgInfo.len = contLen;
2,708,475✔
1840
  (*pMsgSendInfo)->msgInfo.pData = pReq;
2,708,475✔
1841
  return TSDB_CODE_SUCCESS;
2,708,475✔
1842
}
1843

1844
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,244,697,245✔
1845
  if (NULL == pEpSet) {
1,244,697,245✔
1846
    return;
1,239,521,208✔
1847
  }
1848

1849
  switch (pSendInfo->target.type) {
5,176,037✔
1850
    case TARGET_TYPE_MNODE:
945✔
1851
      if (NULL == pTscObj) {
945✔
1852
        tscError("mnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1853
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1854
        return;
×
1855
      }
1856

1857
      SEpSet  originEpset = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
945✔
1858
      SEpSet* pOrig = &originEpset;
945✔
1859
      SEp*    pOrigEp = &pOrig->eps[pOrig->inUse];
945✔
1860
      SEp*    pNewEp = &pEpSet->eps[pEpSet->inUse];
945✔
1861
      tscDebug("mnode epset updated from %d/%d=>%s:%d to %d/%d=>%s:%d in client", pOrig->inUse, pOrig->numOfEps,
945✔
1862
               pOrigEp->fqdn, pOrigEp->port, pEpSet->inUse, pEpSet->numOfEps, pNewEp->fqdn, pNewEp->port);
1863
      updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
945✔
1864
      break;
995,034✔
1865
    case TARGET_TYPE_VNODE: {
4,969,595✔
1866
      if (NULL == pTscObj) {
4,969,595✔
1867
        tscError("vnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1868
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1869
        return;
×
1870
      }
1871

1872
      SCatalog* pCatalog = NULL;
4,969,595✔
1873
      int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
4,969,595✔
1874
      if (code != TSDB_CODE_SUCCESS) {
4,969,668✔
1875
        tscError("fail to get catalog handle, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1876
                 tstrerror(code));
1877
        return;
×
1878
      }
1879

1880
      code = catalogUpdateVgEpSet(pCatalog, pSendInfo->target.dbFName, pSendInfo->target.vgId, pEpSet);
4,969,668✔
1881
      if (code != TSDB_CODE_SUCCESS) {
4,969,885✔
1882
        tscError("fail to update catalog vg epset, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1883
                 tstrerror(code));
1884
        return;
×
1885
      }
1886
      taosMemoryFreeClear(pSendInfo->target.dbFName);
4,969,885✔
1887
      break;
4,969,823✔
1888
    }
1889
    default:
209,604✔
1890
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
209,604✔
1891
      break;
209,843✔
1892
  }
1893
}
1894

1895
int32_t doProcessMsgFromServerImpl(SRpcMsg* pMsg, SEpSet* pEpSet) {
1,245,434,007✔
1896
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
1,245,434,007✔
1897
  if (pMsg->info.ahandle == NULL) {
1,245,438,285✔
1898
    tscError("doProcessMsgFromServer pMsg->info.ahandle == NULL");
712,800✔
1899
    rpcFreeCont(pMsg->pCont);
712,800✔
1900
    taosMemoryFree(pEpSet);
712,800✔
1901
    return TSDB_CODE_TSC_INTERNAL_ERROR;
712,800✔
1902
  }
1903

1904
  STscObj* pTscObj = NULL;
1,244,726,726✔
1905

1906
  STraceId* trace = &pMsg->info.traceId;
1,244,726,726✔
1907
  char      tbuf[40] = {0};
1,244,729,118✔
1908
  TRACE_TO_STR(trace, tbuf);
1,244,728,208✔
1909

1910
  tscDebug("QID:%s, process message from server, handle:%p, message:%s, size:%d, code:%s", tbuf, pMsg->info.handle,
1,244,729,022✔
1911
           TMSG_INFO(pMsg->msgType), pMsg->contLen, tstrerror(pMsg->code));
1912

1913
  if (pSendInfo->requestObjRefId != 0) {
1,244,730,098✔
1914
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
1,068,454,810✔
1915
    if (pRequest) {
1,068,459,021✔
1916
      if (pRequest->self != pSendInfo->requestObjRefId) {
1,058,320,830✔
1917
        tscError("doProcessMsgFromServer req:0x%" PRId64 " != pSendInfo->requestObjRefId:0x%" PRId64, pRequest->self,
×
1918
                 pSendInfo->requestObjRefId);
1919

1920
        if (TSDB_CODE_SUCCESS != taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId)) {
×
1921
          tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1922
        }
1923
        rpcFreeCont(pMsg->pCont);
×
1924
        taosMemoryFree(pEpSet);
×
1925
        destroySendMsgInfo(pSendInfo);
×
1926
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1927
      }
1928
      pTscObj = pRequest->pTscObj;
1,058,315,660✔
1929
    }
1930
  }
1931

1932
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
1,244,725,497✔
1933

1934
  SDataBuf buf = {.msgType = pMsg->msgType,
1,244,700,472✔
1935
                  .len = pMsg->contLen,
1,244,706,163✔
1936
                  .pData = NULL,
1937
                  .handle = pMsg->info.handle,
1,244,711,611✔
1938
                  .handleRefId = pMsg->info.refId,
1,244,713,586✔
1939
                  .pEpSet = pEpSet};
1940

1941
  if (pMsg->contLen > 0) {
1,244,716,946✔
1942
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
1,204,398,769✔
1943
    if (buf.pData == NULL) {
1,204,371,333✔
1944
      pMsg->code = terrno;
×
1945
    } else {
1946
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
1,204,371,333✔
1947
    }
1948
  }
1949

1950
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
1,244,722,053✔
1951

1952
  if (pTscObj) {
1,244,695,359✔
1953
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
1,058,300,770✔
1954
    if (TSDB_CODE_SUCCESS != code) {
1,058,321,960✔
1955
      tscError("doProcessMsgFromServer taosReleaseRef failed");
786✔
1956
      terrno = code;
786✔
1957
      pMsg->code = code;
786✔
1958
    }
1959
  }
1960

1961
  rpcFreeCont(pMsg->pCont);
1,244,716,549✔
1962
  destroySendMsgInfo(pSendInfo);
1,244,685,416✔
1963
  return TSDB_CODE_SUCCESS;
1,244,638,248✔
1964
}
1965

1966
int32_t doProcessMsgFromServer(void* param) {
1,245,443,904✔
1967
  AsyncArg* arg = (AsyncArg*)param;
1,245,443,904✔
1968
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
1,245,443,904✔
1969
  taosMemoryFree(arg);
1,245,364,213✔
1970
  return code;
1,245,392,244✔
1971
}
1972

1973
void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,245,343,428✔
1974
  int32_t code = 0;
1,245,343,428✔
1975
  SEpSet* tEpSet = NULL;
1,245,343,428✔
1976

1977
  tscDebug("msg callback, ahandle %p", pMsg->info.ahandle);
1,245,343,428✔
1978

1979
  if (pEpSet != NULL) {
1,245,321,266✔
1980
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
5,180,392✔
1981
    if (NULL == tEpSet) {
5,180,352✔
1982
      code = terrno;
×
1983
      pMsg->code = terrno;
×
1984
      goto _exit;
×
1985
    }
1986
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
5,180,352✔
1987
  }
1988

1989
  // pMsg is response msg
1990
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
1,245,321,226✔
1991
    // restore origin code
1992
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
2,708,577✔
1993
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1994
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
2,708,577✔
1995
      pMsg->code = TSDB_CODE_RPC_BROKEN_LINK;
×
1996
    }
1997
  } else {
1998
    // uniform to one error code: TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED
1999
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
1,242,635,309✔
2000
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
2001
    }
2002
  }
2003

2004
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
1,245,374,267✔
2005
  if (NULL == arg) {
1,245,233,705✔
2006
    code = terrno;
×
2007
    pMsg->code = code;
×
2008
    goto _exit;
×
2009
  }
2010

2011
  arg->msg = *pMsg;
1,245,233,705✔
2012
  arg->pEpset = tEpSet;
1,245,272,356✔
2013

2014
  if ((code = taosAsyncExec(doProcessMsgFromServer, arg, NULL)) != 0) {
1,245,370,067✔
2015
    pMsg->code = code;
×
2016
    taosMemoryFree(arg);
×
2017
    goto _exit;
×
2018
  }
2019
  return;
1,245,413,017✔
2020

2021
_exit:
×
2022
  tscError("failed to sched msg to tsc since %s", tstrerror(code));
×
2023
  code = doProcessMsgFromServerImpl(pMsg, tEpSet);
×
2024
  if (code != 0) {
×
2025
    tscError("failed to sched msg to tsc, tsc ready quit");
×
2026
  }
2027
}
2028

2029
TAOS* taos_connect_totp(const char* ip, const char* user, const char* pass, const char* totp, const char* db,
35✔
2030
                        uint16_t port) {
2031
  tscInfo("try to connect to %s:%u by totp, user:%s db:%s", ip, port, user, db);
35✔
2032
  if (user == NULL) {
35✔
2033
    user = TSDB_DEFAULT_USER;
×
2034
  }
2035

2036
  if (pass == NULL) {
35✔
2037
    pass = TSDB_DEFAULT_PASS;
×
2038
  }
2039

2040
  STscObj *pObj = NULL;
35✔
2041
  int32_t  code = taos_connect_internal(ip, user, pass, totp, db, port, CONN_TYPE__QUERY, &pObj);
35✔
2042
  if (TSDB_CODE_SUCCESS == code) {
35✔
2043
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
35✔
2044
    if (NULL == rid) {
35✔
2045
      tscError("out of memory when taos_connect_totp to %s:%u, user:%s db:%s", ip, port, user, db);
×
2046
      return NULL;
×
2047
    }
2048
    *rid = pObj->id;
35✔
2049
    return (TAOS*)rid;
35✔
2050
  } else {
2051
    terrno = code;
×
2052
  }
2053

2054
  return NULL;
×
2055
}
2056

2057

2058
int taos_connect_test(const char *ip, const char *user, const char *pass, const char* totp, const char *db, uint16_t port) {
×
2059
  tscInfo("try to test connect to %s:%u by totp, user:%s db:%s", ip, port, user, db);
×
2060
  if (user == NULL) {
×
2061
    user = TSDB_DEFAULT_USER;
×
2062
  }
2063

2064
  if (pass == NULL) {
×
2065
    pass = TSDB_DEFAULT_PASS;
×
2066
  }
2067

2068
  STscObj *pObj = NULL;
×
2069
  return taos_connect_internal(ip, user, pass, totp, db, port, CONN_TYPE__AUTH_TEST, &pObj);
×
2070
}
2071

2072

2073
TAOS *taos_connect_token(const char *ip, const char *token, const char *db, uint16_t port) {
×
2074
  tscInfo("try to connect to %s:%u by token, db:%s", ip, port, db);
×
2075

2076
  STscObj *pObj = NULL;
×
2077
  int32_t code = taos_connect_by_auth(ip, NULL, token, NULL, db, port, CONN_TYPE__QUERY, &pObj);
×
2078
  if (TSDB_CODE_SUCCESS == code) {
×
2079
    int64_t *rid = taosMemoryCalloc(1, sizeof(int64_t));
×
2080
    if (NULL == rid) {
×
2081
      tscError("out of memory when taos_connect_token to %s:%u db:%s", ip, port, db);
×
2082
      return NULL;
×
2083
    }
2084
    *rid = pObj->id;
×
2085
    return (TAOS *)rid;
×
2086
  } else {
2087
    terrno = code;
×
2088
  }
2089

2090
  return NULL;
×
2091
}
2092

2093

2094
TAOS* taos_connect_auth(const char* ip, const char* user, const char* auth, const char* db, uint16_t port) {
189✔
2095
  tscInfo("try to connect to %s:%u by auth, user:%s db:%s", ip, port, user, db);
189✔
2096
  if (user == NULL) {
189✔
2097
    user = TSDB_DEFAULT_USER;
×
2098
  }
2099

2100
  if (auth == NULL) {
189✔
2101
    tscError("No auth info is given, failed to connect to server");
×
2102
    return NULL;
×
2103
  }
2104

2105
  STscObj* pObj = NULL;
189✔
2106
  int32_t  code = taos_connect_by_auth(ip, user, auth, NULL, db, port, CONN_TYPE__QUERY, &pObj);
189✔
2107
  if (TSDB_CODE_SUCCESS == code) {
189✔
2108
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
×
2109
    if (NULL == rid) {
×
2110
      tscError("out of memory when taos connect to %s:%u, user:%s db:%s", ip, port, user, db);
×
2111
    }
2112
    *rid = pObj->id;
×
2113
    return (TAOS*)rid;
×
2114
  }
2115

2116
  return NULL;
189✔
2117
}
2118

2119
// TAOS* taos_connect_l(const char* ip, int ipLen, const char* user, int userLen, const char* pass, int passLen,
2120
//                      const char* db, int dbLen, uint16_t port) {
2121
//   char ipStr[TSDB_EP_LEN] = {0};
2122
//   char dbStr[TSDB_DB_NAME_LEN] = {0};
2123
//   char userStr[TSDB_USER_LEN] = {0};
2124
//   char passStr[TSDB_PASSWORD_LEN] = {0};
2125
//
2126
//   tstrncpy(ipStr, ip, TMIN(TSDB_EP_LEN - 1, ipLen));
2127
//   tstrncpy(userStr, user, TMIN(TSDB_USER_LEN - 1, userLen));
2128
//   tstrncpy(passStr, pass, TMIN(TSDB_PASSWORD_LEN - 1, passLen));
2129
//   tstrncpy(dbStr, db, TMIN(TSDB_DB_NAME_LEN - 1, dbLen));
2130
//   return taos_connect(ipStr, userStr, passStr, dbStr, port);
2131
// }
2132

2133
void doSetOneRowPtr(SReqResultInfo* pResultInfo) {
2,040,658,937✔
2134
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
2,147,483,647✔
2135
    SResultColumn* pCol = &pResultInfo->pCol[i];
2,147,483,647✔
2136

2137
    int32_t type = pResultInfo->fields[i].type;
2,147,483,647✔
2138
    int32_t schemaBytes = calcSchemaBytesFromTypeBytes(type, pResultInfo->userFields[i].bytes, false);
2,147,483,647✔
2139

2140
    if (IS_VAR_DATA_TYPE(type)) {
2,147,483,647✔
2141
      if (!IS_VAR_NULL_TYPE(type, schemaBytes) && pCol->offset[pResultInfo->current] != -1) {
2,147,483,647✔
2142
        char* pStart = pResultInfo->pCol[i].offset[pResultInfo->current] + pResultInfo->pCol[i].pData;
1,906,099,952✔
2143

2144
        if (IS_STR_DATA_BLOB(type)) {
1,906,094,283✔
2145
          pResultInfo->length[i] = blobDataLen(pStart);
×
2146
          pResultInfo->row[i] = blobDataVal(pStart);
×
2147
        } else {
2148
          pResultInfo->length[i] = varDataLen(pStart);
1,906,165,320✔
2149
          pResultInfo->row[i] = varDataVal(pStart);
1,906,124,769✔
2150
        }
2151
      } else {
2152
        pResultInfo->row[i] = NULL;
60,501,055✔
2153
        pResultInfo->length[i] = 0;
60,518,400✔
2154
      }
2155
    } else {
2156
      if (!colDataIsNull_f(pCol, pResultInfo->current)) {
2,147,483,647✔
2157
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + schemaBytes * pResultInfo->current;
2,147,483,647✔
2158
        pResultInfo->length[i] = schemaBytes;
2,147,483,647✔
2159
      } else {
2160
        pResultInfo->row[i] = NULL;
251,545,700✔
2161
        pResultInfo->length[i] = 0;
252,152,581✔
2162
      }
2163
    }
2164
  }
2165
}
2,041,097,084✔
2166

2167
void* doFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
×
2168
  if (pRequest == NULL) {
×
2169
    return NULL;
×
2170
  }
2171

2172
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
×
2173
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
×
2174
    // All data has returned to App already, no need to try again
2175
    if (pResultInfo->completed) {
×
2176
      pResultInfo->numOfRows = 0;
×
2177
      return NULL;
×
2178
    }
2179

2180
    SReqResultInfo* pResInfo = &pRequest->body.resInfo;
×
2181
    SSchedulerReq   req = {.syncReq = true, .pFetchRes = (void**)&pResInfo->pData};
×
2182

2183
    pRequest->code = schedulerFetchRows(pRequest->body.queryJob, &req);
×
2184
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2185
      pResultInfo->numOfRows = 0;
×
2186
      return NULL;
×
2187
    }
2188

2189
    pRequest->code = setQueryResultFromRsp(&pRequest->body.resInfo, (const SRetrieveTableRsp*)pResInfo->pData,
×
2190
                                           convertUcs4, pRequest->stmtBindVersion > 0);
×
2191
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2192
      pResultInfo->numOfRows = 0;
×
2193
      return NULL;
×
2194
    }
2195

2196
    tscDebug("req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64
×
2197
             ", complete:%d, QID:0x%" PRIx64,
2198
             pRequest->self, pResInfo->numOfRows, pResInfo->totalRows, pResInfo->completed, pRequest->requestId);
2199

2200
    STscObj*            pTscObj = pRequest->pTscObj;
×
2201
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
×
2202
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
×
2203

2204
    if (pResultInfo->numOfRows == 0) {
×
2205
      return NULL;
×
2206
    }
2207
  }
2208

2209
  if (setupOneRowPtr) {
×
2210
    doSetOneRowPtr(pResultInfo);
×
2211
    pResultInfo->current += 1;
×
2212
  }
2213

2214
  return pResultInfo->row;
×
2215
}
2216

2217
static void syncFetchFn(void* param, TAOS_RES* res, int32_t numOfRows) {
89,532,791✔
2218
  tsem_t* sem = param;
89,532,791✔
2219
  if (TSDB_CODE_SUCCESS != tsem_post(sem)) {
89,532,791✔
2220
    tscError("failed to post sem, code:%s", terrstr());
×
2221
  }
2222
}
89,532,978✔
2223

2224
void* doAsyncFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
1,110,507,976✔
2225
  if (pRequest == NULL) {
1,110,507,976✔
2226
    return NULL;
×
2227
  }
2228

2229
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
1,110,507,976✔
2230
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
1,110,547,379✔
2231
    // All data has returned to App already, no need to try again
2232
    if (pResultInfo->completed) {
159,839,331✔
2233
      pResultInfo->numOfRows = 0;
70,366,302✔
2234
      return NULL;
70,366,528✔
2235
    }
2236

2237
    // convert ucs4 to native multi-bytes string
2238
    pResultInfo->convertUcs4 = convertUcs4;
89,532,055✔
2239
    tsem_t sem;
88,786,047✔
2240
    if (TSDB_CODE_SUCCESS != tsem_init(&sem, 0, 0)) {
89,532,758✔
2241
      tscError("failed to init sem, code:%s", terrstr());
×
2242
    }
2243
    taos_fetch_rows_a(pRequest, syncFetchFn, &sem);
89,532,118✔
2244
    if (TSDB_CODE_SUCCESS != tsem_wait(&sem)) {
89,533,034✔
2245
      tscError("failed to wait sem, code:%s", terrstr());
×
2246
    }
2247
    if (TSDB_CODE_SUCCESS != tsem_destroy(&sem)) {
89,533,228✔
2248
      tscError("failed to destroy sem, code:%s", terrstr());
×
2249
    }
2250
    pRequest->inCallback = false;
89,533,228✔
2251
  }
2252

2253
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
1,040,322,246✔
2254
    return NULL;
6,762,658✔
2255
  } else {
2256
    if (setupOneRowPtr) {
1,033,522,206✔
2257
      doSetOneRowPtr(pResultInfo);
952,386,981✔
2258
      pResultInfo->current += 1;
952,440,215✔
2259
    }
2260

2261
    return pResultInfo->row;
1,033,576,108✔
2262
  }
2263
}
2264

2265
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
125,749,036✔
2266
  if (pResInfo->row == NULL) {
125,749,036✔
2267
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
111,379,408✔
2268
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
111,379,246✔
2269
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
111,377,972✔
2270
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
111,378,164✔
2271

2272
    if (pResInfo->row == NULL || pResInfo->pCol == NULL || pResInfo->length == NULL || pResInfo->convertBuf == NULL) {
111,378,195✔
2273
      taosMemoryFree(pResInfo->row);
265✔
2274
      taosMemoryFree(pResInfo->pCol);
×
2275
      taosMemoryFree(pResInfo->length);
×
2276
      taosMemoryFree(pResInfo->convertBuf);
×
2277
      return terrno;
×
2278
    }
2279
  }
2280

2281
  return TSDB_CODE_SUCCESS;
125,750,043✔
2282
}
2283

2284
static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength, bool isStmt) {
125,520,311✔
2285
  int32_t idx = -1;
125,520,311✔
2286
  iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt);
125,521,563✔
2287
  if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR;
125,519,158✔
2288

2289
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
706,454,854✔
2290
    int32_t type = pResultInfo->fields[i].type;
580,940,137✔
2291
    int32_t schemaBytes =
2292
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
580,939,776✔
2293

2294
    if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) {
580,938,358✔
2295
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
19,867,055✔
2296
      if (p == NULL) {
19,867,055✔
2297
        taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
×
2298
        return terrno;
×
2299
      }
2300

2301
      pResultInfo->convertBuf[i] = p;
19,867,055✔
2302

2303
      SResultColumn* pCol = &pResultInfo->pCol[i];
19,867,055✔
2304
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
2,147,483,647✔
2305
        if (pCol->offset[j] != -1) {
2,147,483,647✔
2306
          char* pStart = pCol->offset[j] + pCol->pData;
2,147,483,647✔
2307

2308
          int32_t len = taosUcs4ToMbsEx((TdUcs4*)varDataVal(pStart), varDataLen(pStart), varDataVal(p), conv);
2,147,483,647✔
2309
          if (len < 0 || len > schemaBytes || (p + len) >= (pResultInfo->convertBuf[i] + colLength[i])) {
2,147,483,647✔
2310
            tscError(
74✔
2311
                "doConvertUCS4 error, invalid data. len:%d, bytes:%d, (p + len):%p, (pResultInfo->convertBuf[i] + "
2312
                "colLength[i]):%p",
2313
                len, schemaBytes, (p + len), (pResultInfo->convertBuf[i] + colLength[i]));
2314
            taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
74✔
2315
            return TSDB_CODE_TSC_INTERNAL_ERROR;
74✔
2316
          }
2317

2318
          varDataSetLen(p, len);
2,147,483,647✔
2319
          pCol->offset[j] = (p - pResultInfo->convertBuf[i]);
2,147,483,647✔
2320
          p += (len + VARSTR_HEADER_SIZE);
2,147,483,647✔
2321
        }
2322
      }
2323

2324
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
19,866,981✔
2325
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
19,866,981✔
2326
    }
2327
  }
2328
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
125,519,854✔
2329
  return TSDB_CODE_SUCCESS;
125,521,447✔
2330
}
2331

2332
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
125,520,464✔
2333
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
706,452,053✔
2334
    TAOS_FIELD_E* pFieldE = pResultInfo->fields + i;
580,936,321✔
2335
    TAOS_FIELD*   pField = pResultInfo->userFields + i;
580,925,950✔
2336
    int32_t       type = pFieldE->type;
580,934,505✔
2337
    int32_t       bufLen = 0;
580,934,434✔
2338
    char*         p = NULL;
580,934,434✔
2339
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
580,934,434✔
2340
      continue;
579,311,975✔
2341
    } else {
2342
      bufLen = 64;
1,621,879✔
2343
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
1,621,879✔
2344
      pFieldE->bytes = bufLen;
1,621,879✔
2345
      pField->bytes = bufLen;
1,621,879✔
2346
    }
2347
    if (!p) return terrno;
1,621,879✔
2348
    pResultInfo->convertBuf[i] = p;
1,621,879✔
2349

2350
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
1,006,709,289✔
2351
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
1,005,087,410✔
2352
                                  pFieldE->precision, pFieldE->scale, p, bufLen);
1,005,087,410✔
2353
      p += bufLen;
1,005,087,410✔
2354
      if (TSDB_CODE_SUCCESS != code) {
1,005,087,410✔
2355
        return code;
×
2356
      }
2357
    }
2358
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
1,621,879✔
2359
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
1,621,879✔
2360
  }
2361
  return 0;
125,518,890✔
2362
}
2363

2364
int32_t getVersion1BlockMetaSize(const char* p, int32_t numOfCols) {
392,398✔
2365
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) * 3 + sizeof(uint64_t) +
784,796✔
2366
         numOfCols * (sizeof(int8_t) + sizeof(int32_t));
392,398✔
2367
}
2368

2369
static int32_t estimateJsonLen(SReqResultInfo* pResultInfo) {
196,199✔
2370
  char*   p = (char*)pResultInfo->pData;
196,199✔
2371
  int32_t blockVersion = *(int32_t*)p;
196,199✔
2372

2373
  int32_t numOfRows = pResultInfo->numOfRows;
196,199✔
2374
  int32_t numOfCols = pResultInfo->numOfCols;
196,199✔
2375

2376
  // | version | total length | total rows | total columns | flag seg| block group id | column schema | each column
2377
  // length |
2378
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
196,199✔
2379
  if (numOfCols != cols) {
196,199✔
2380
    tscError("estimateJsonLen error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2381
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2382
  }
2383

2384
  int32_t  len = getVersion1BlockMetaSize(p, numOfCols);
196,199✔
2385
  int32_t* colLength = (int32_t*)(p + len);
196,199✔
2386
  len += sizeof(int32_t) * numOfCols;
196,199✔
2387

2388
  char* pStart = p + len;
196,199✔
2389
  for (int32_t i = 0; i < numOfCols; ++i) {
852,575✔
2390
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
656,376✔
2391

2392
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
656,376✔
2393
      int32_t* offset = (int32_t*)pStart;
232,348✔
2394
      int32_t  lenTmp = numOfRows * sizeof(int32_t);
232,348✔
2395
      len += lenTmp;
232,348✔
2396
      pStart += lenTmp;
232,348✔
2397

2398
      int32_t estimateColLen = 0;
232,348✔
2399
      for (int32_t j = 0; j < numOfRows; ++j) {
1,211,824✔
2400
        if (offset[j] == -1) {
979,476✔
2401
          continue;
49,208✔
2402
        }
2403
        char* data = offset[j] + pStart;
930,268✔
2404

2405
        int32_t jsonInnerType = *data;
930,268✔
2406
        char*   jsonInnerData = data + CHAR_BYTES;
930,268✔
2407
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
930,268✔
2408
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
13,008✔
2409
        } else if (tTagIsJson(data)) {
917,260✔
2410
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
216,088✔
2411
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
701,172✔
2412
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
652,392✔
2413
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
48,780✔
2414
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
35,772✔
2415
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
13,008✔
2416
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
13,008✔
2417
        } else if (IS_STR_DATA_BLOB(jsonInnerType)) {
×
2418
          estimateColLen += (BLOBSTR_HEADER_SIZE + 32);
×
2419
        } else {
2420
          tscError("estimateJsonLen error: invalid type:%d", jsonInnerType);
×
2421
          return -1;
×
2422
        }
2423
      }
2424
      len += TMAX(colLen, estimateColLen);
232,348✔
2425
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
424,028✔
2426
      int32_t lenTmp = numOfRows * sizeof(int32_t);
54,200✔
2427
      len += (lenTmp + colLen);
54,200✔
2428
      pStart += lenTmp;
54,200✔
2429
    } else {
2430
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
369,828✔
2431
      len += (lenTmp + colLen);
369,828✔
2432
      pStart += lenTmp;
369,828✔
2433
    }
2434
    pStart += colLen;
656,376✔
2435
  }
2436

2437
  // Ensure the complete structure of the block, including the blankfill field,
2438
  // even though it is not used on the client side.
2439
  len += sizeof(bool);
196,199✔
2440
  return len;
196,199✔
2441
}
2442

2443
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
125,750,437✔
2444
  int32_t numOfRows = pResultInfo->numOfRows;
125,750,437✔
2445
  int32_t numOfCols = pResultInfo->numOfCols;
125,750,596✔
2446
  bool    needConvert = false;
125,752,683✔
2447
  for (int32_t i = 0; i < numOfCols; ++i) {
707,783,439✔
2448
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
582,229,477✔
2449
      needConvert = true;
196,199✔
2450
      break;
196,199✔
2451
    }
2452
  }
2453

2454
  if (!needConvert) {
125,750,161✔
2455
    return TSDB_CODE_SUCCESS;
125,553,962✔
2456
  }
2457

2458
  tscDebug("start to convert form json format string");
196,199✔
2459

2460
  char*   p = (char*)pResultInfo->pData;
196,199✔
2461
  int32_t blockVersion = *(int32_t*)p;
196,199✔
2462
  int32_t dataLen = estimateJsonLen(pResultInfo);
196,199✔
2463
  if (dataLen <= 0) {
196,199✔
2464
    tscError("doConvertJson error: estimateJsonLen failed");
×
2465
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2466
  }
2467

2468
  taosMemoryFreeClear(pResultInfo->convertJson);
196,199✔
2469
  pResultInfo->convertJson = taosMemoryCalloc(1, dataLen);
196,199✔
2470
  if (pResultInfo->convertJson == NULL) return terrno;
196,199✔
2471
  char* p1 = pResultInfo->convertJson;
196,199✔
2472

2473
  int32_t totalLen = 0;
196,199✔
2474
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
196,199✔
2475
  if (numOfCols != cols) {
196,199✔
2476
    tscError("doConvertJson error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2477
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2478
  }
2479

2480
  int32_t len = getVersion1BlockMetaSize(p, numOfCols);
196,199✔
2481
  (void)memcpy(p1, p, len);
196,199✔
2482

2483
  p += len;
196,199✔
2484
  p1 += len;
196,199✔
2485
  totalLen += len;
196,199✔
2486

2487
  len = sizeof(int32_t) * numOfCols;
196,199✔
2488
  int32_t* colLength = (int32_t*)p;
196,199✔
2489
  int32_t* colLength1 = (int32_t*)p1;
196,199✔
2490
  (void)memcpy(p1, p, len);
196,199✔
2491
  p += len;
196,199✔
2492
  p1 += len;
196,199✔
2493
  totalLen += len;
196,199✔
2494

2495
  char* pStart = p;
196,199✔
2496
  char* pStart1 = p1;
196,199✔
2497
  for (int32_t i = 0; i < numOfCols; ++i) {
852,575✔
2498
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
656,376✔
2499
    int32_t colLen1 = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength1[i]) : colLength1[i];
656,376✔
2500
    if (colLen >= dataLen) {
656,376✔
2501
      tscError("doConvertJson error: colLen:%d >= dataLen:%d", colLen, dataLen);
×
2502
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2503
    }
2504
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
656,376✔
2505
      int32_t* offset = (int32_t*)pStart;
232,348✔
2506
      int32_t* offset1 = (int32_t*)pStart1;
232,348✔
2507
      len = numOfRows * sizeof(int32_t);
232,348✔
2508
      (void)memcpy(pStart1, pStart, len);
232,348✔
2509
      pStart += len;
232,348✔
2510
      pStart1 += len;
232,348✔
2511
      totalLen += len;
232,348✔
2512

2513
      len = 0;
232,348✔
2514
      for (int32_t j = 0; j < numOfRows; ++j) {
1,211,824✔
2515
        if (offset[j] == -1) {
979,476✔
2516
          continue;
49,208✔
2517
        }
2518
        char* data = offset[j] + pStart;
930,268✔
2519

2520
        int32_t jsonInnerType = *data;
930,268✔
2521
        char*   jsonInnerData = data + CHAR_BYTES;
930,268✔
2522
        char    dst[TSDB_MAX_JSON_TAG_LEN] = {0};
930,268✔
2523
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
930,268✔
2524
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s", TSDB_DATA_NULL_STR_L);
13,008✔
2525
          varDataSetLen(dst, strlen(varDataVal(dst)));
13,008✔
2526
        } else if (tTagIsJson(data)) {
917,260✔
2527
          char* jsonString = NULL;
216,088✔
2528
          parseTagDatatoJson(data, &jsonString, pResultInfo->charsetCxt);
216,088✔
2529
          if (jsonString == NULL) {
216,088✔
2530
            tscError("doConvertJson error: parseTagDatatoJson failed");
×
2531
            return terrno;
×
2532
          }
2533
          STR_TO_VARSTR(dst, jsonString);
216,088✔
2534
          taosMemoryFree(jsonString);
216,088✔
2535
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
701,172✔
2536
          *(char*)varDataVal(dst) = '\"';
652,392✔
2537
          char    tmp[TSDB_MAX_JSON_TAG_LEN] = {0};
652,392✔
2538
          int32_t length = taosUcs4ToMbs((TdUcs4*)varDataVal(jsonInnerData), varDataLen(jsonInnerData), varDataVal(tmp),
652,392✔
2539
                                         pResultInfo->charsetCxt);
2540
          if (length <= 0) {
652,392✔
2541
            tscError("charset:%s to %s. convert failed.", DEFAULT_UNICODE_ENCODEC,
542✔
2542
                     pResultInfo->charsetCxt != NULL ? ((SConvInfo*)(pResultInfo->charsetCxt))->charset : tsCharset);
2543
            length = 0;
542✔
2544
          }
2545
          int32_t escapeLength = escapeToPrinted(varDataVal(dst) + CHAR_BYTES, TSDB_MAX_JSON_TAG_LEN - CHAR_BYTES * 2,
652,392✔
2546
                                                 varDataVal(tmp), length);
2547
          varDataSetLen(dst, escapeLength + CHAR_BYTES * 2);
652,392✔
2548
          *(char*)POINTER_SHIFT(varDataVal(dst), escapeLength + CHAR_BYTES) = '\"';
652,392✔
2549
          tscError("value:%s.", varDataVal(dst));
652,392✔
2550
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
48,780✔
2551
          double jsonVd = *(double*)(jsonInnerData);
35,772✔
2552
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%.9lf", jsonVd);
35,772✔
2553
          varDataSetLen(dst, strlen(varDataVal(dst)));
35,772✔
2554
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
13,008✔
2555
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s",
13,008✔
2556
                         (*((char*)jsonInnerData) == 1) ? "true" : "false");
13,008✔
2557
          varDataSetLen(dst, strlen(varDataVal(dst)));
13,008✔
2558
        } else {
2559
          tscError("doConvertJson error: invalid type:%d", jsonInnerType);
×
2560
          return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2561
        }
2562

2563
        offset1[j] = len;
930,268✔
2564
        (void)memcpy(pStart1 + len, dst, varDataTLen(dst));
930,268✔
2565
        len += varDataTLen(dst);
930,268✔
2566
      }
2567
      colLen1 = len;
232,348✔
2568
      totalLen += colLen1;
232,348✔
2569
      colLength1[i] = (blockVersion == BLOCK_VERSION_1) ? htonl(len) : len;
232,348✔
2570
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
424,028✔
2571
      len = numOfRows * sizeof(int32_t);
54,200✔
2572
      (void)memcpy(pStart1, pStart, len);
54,200✔
2573
      pStart += len;
54,200✔
2574
      pStart1 += len;
54,200✔
2575
      totalLen += len;
54,200✔
2576
      totalLen += colLen;
54,200✔
2577
      (void)memcpy(pStart1, pStart, colLen);
54,200✔
2578
    } else {
2579
      len = BitmapLen(pResultInfo->numOfRows);
369,828✔
2580
      (void)memcpy(pStart1, pStart, len);
369,828✔
2581
      pStart += len;
369,828✔
2582
      pStart1 += len;
369,828✔
2583
      totalLen += len;
369,828✔
2584
      totalLen += colLen;
369,828✔
2585
      (void)memcpy(pStart1, pStart, colLen);
369,828✔
2586
    }
2587
    pStart += colLen;
656,376✔
2588
    pStart1 += colLen1;
656,376✔
2589
  }
2590

2591
  // Ensure the complete structure of the block, including the blankfill field,
2592
  // even though it is not used on the client side.
2593
  // (void)memcpy(pStart1, pStart, sizeof(bool));
2594
  totalLen += sizeof(bool);
196,199✔
2595

2596
  *(int32_t*)(pResultInfo->convertJson + 4) = totalLen;
196,199✔
2597
  pResultInfo->pData = pResultInfo->convertJson;
196,199✔
2598
  return TSDB_CODE_SUCCESS;
196,199✔
2599
}
2600

2601
int32_t setResultDataPtr(SReqResultInfo* pResultInfo, bool convertUcs4, bool isStmt) {
140,902,278✔
2602
  bool convertForDecimal = convertUcs4;
140,902,278✔
2603
  if (pResultInfo == NULL || pResultInfo->numOfCols <= 0 || pResultInfo->fields == NULL) {
140,902,278✔
2604
    tscError("setResultDataPtr paras error");
159✔
2605
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2606
  }
2607

2608
  if (pResultInfo->numOfRows == 0) {
140,902,551✔
2609
    return TSDB_CODE_SUCCESS;
15,152,960✔
2610
  }
2611

2612
  if (pResultInfo->pData == NULL) {
125,750,705✔
2613
    tscError("setResultDataPtr error: pData is NULL");
×
2614
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2615
  }
2616

2617
  int32_t code = doPrepareResPtr(pResultInfo);
125,749,317✔
2618
  if (code != TSDB_CODE_SUCCESS) {
125,750,437✔
2619
    return code;
×
2620
  }
2621
  code = doConvertJson(pResultInfo);
125,750,437✔
2622
  if (code != TSDB_CODE_SUCCESS) {
125,749,200✔
2623
    return code;
×
2624
  }
2625

2626
  char* p = (char*)pResultInfo->pData;
125,749,200✔
2627

2628
  // version:
2629
  int32_t blockVersion = *(int32_t*)p;
125,749,288✔
2630
  p += sizeof(int32_t);
125,750,326✔
2631

2632
  int32_t dataLen = *(int32_t*)p;
125,750,397✔
2633
  p += sizeof(int32_t);
125,750,397✔
2634

2635
  int32_t rows = *(int32_t*)p;
125,750,573✔
2636
  p += sizeof(int32_t);
125,750,435✔
2637

2638
  int32_t cols = *(int32_t*)p;
125,749,279✔
2639
  p += sizeof(int32_t);
125,750,091✔
2640

2641
  if (rows != pResultInfo->numOfRows || cols != pResultInfo->numOfCols) {
125,749,408✔
2642
    tscError("setResultDataPtr paras error:rows;%d numOfRows:%" PRId64 " cols:%d numOfCols:%d", rows,
3,855✔
2643
             pResultInfo->numOfRows, cols, pResultInfo->numOfCols);
2644
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2645
  }
2646

2647
  int32_t hasColumnSeg = *(int32_t*)p;
125,746,277✔
2648
  p += sizeof(int32_t);
125,750,044✔
2649

2650
  uint64_t groupId = taosGetUInt64Aligned((uint64_t*)p);
125,749,920✔
2651
  p += sizeof(uint64_t);
125,749,920✔
2652

2653
  // check fields
2654
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
708,025,237✔
2655
    int8_t type = *(int8_t*)p;
582,279,633✔
2656
    p += sizeof(int8_t);
582,275,242✔
2657

2658
    int32_t bytes = *(int32_t*)p;
582,277,337✔
2659
    p += sizeof(int32_t);
582,277,763✔
2660

2661
    if (IS_DECIMAL_TYPE(type) && pResultInfo->fields[i].precision == 0) {
582,277,921✔
2662
      extractDecimalTypeInfoFromBytes(&bytes, &pResultInfo->fields[i].precision, &pResultInfo->fields[i].scale);
316,024✔
2663
    }
2664
  }
2665

2666
  int32_t* colLength = (int32_t*)p;
125,749,587✔
2667
  p += sizeof(int32_t) * pResultInfo->numOfCols;
125,749,587✔
2668

2669
  char* pStart = p;
125,749,388✔
2670
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
708,033,358✔
2671
    if ((pStart - pResultInfo->pData) >= dataLen) {
582,283,314✔
2672
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2673
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2674
    }
2675
    if (blockVersion == BLOCK_VERSION_1) {
582,281,359✔
2676
      colLength[i] = htonl(colLength[i]);
448,779,606✔
2677
    }
2678
    if (colLength[i] >= dataLen) {
582,281,580✔
2679
      tscError("invalid colLength %d, dataLen %d", colLength[i], dataLen);
×
2680
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2681
    }
2682
    if (IS_INVALID_TYPE(pResultInfo->fields[i].type)) {
582,281,611✔
2683
      tscError("invalid type %d", pResultInfo->fields[i].type);
5,067✔
2684
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2685
    }
2686
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
582,279,153✔
2687
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
141,282,688✔
2688
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
141,287,944✔
2689
    } else {
2690
      pResultInfo->pCol[i].nullbitmap = pStart;
440,997,608✔
2691
      pStart += BitmapLen(pResultInfo->numOfRows);
440,998,773✔
2692
    }
2693

2694
    pResultInfo->pCol[i].pData = pStart;
582,286,092✔
2695
    pResultInfo->length[i] =
1,164,569,344✔
2696
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
1,158,879,602✔
2697
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
582,284,123✔
2698

2699
    pStart += colLength[i];
582,284,030✔
2700
  }
2701

2702
  p = pStart;
125,751,115✔
2703
  // bool blankFill = *(bool*)p;
2704
  p += sizeof(bool);
125,751,115✔
2705
  int32_t offset = p - pResultInfo->pData;
125,750,889✔
2706
  if (offset > dataLen) {
125,750,698✔
2707
    tscError("invalid offset %d, dataLen %d", offset, dataLen);
×
2708
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2709
  }
2710

2711
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
2712
  if (convertUcs4) {
125,750,698✔
2713
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
125,521,619✔
2714
  }
2715
#endif
2716
  if (TSDB_CODE_SUCCESS == code && convertForDecimal) {
125,750,512✔
2717
    code = convertDecimalType(pResultInfo);
125,521,447✔
2718
  }
2719
  return code;
125,748,689✔
2720
}
2721

2722
char* getDbOfConnection(STscObj* pObj) {
732,437,404✔
2723
  terrno = TSDB_CODE_SUCCESS;
732,437,404✔
2724
  char* p = NULL;
732,441,641✔
2725
  (void)taosThreadMutexLock(&pObj->mutex);
732,441,641✔
2726
  size_t len = strlen(pObj->db);
732,444,344✔
2727
  if (len > 0) {
732,445,628✔
2728
    p = taosStrndup(pObj->db, tListLen(pObj->db));
664,181,308✔
2729
    if (p == NULL) {
664,182,667✔
2730
      tscError("failed to taosStrndup db name");
×
2731
    }
2732
  }
2733

2734
  (void)taosThreadMutexUnlock(&pObj->mutex);
732,446,987✔
2735
  return p;
732,437,132✔
2736
}
2737

2738
void setConnectionDB(STscObj* pTscObj, const char* db) {
2,512,476✔
2739
  if (db == NULL || pTscObj == NULL) {
2,512,476✔
2740
    tscError("setConnectionDB para is NULL");
×
2741
    return;
×
2742
  }
2743

2744
  (void)taosThreadMutexLock(&pTscObj->mutex);
2,512,685✔
2745
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
2,512,286✔
2746
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
2,512,445✔
2747
}
2748

2749
void resetConnectDB(STscObj* pTscObj) {
×
2750
  if (pTscObj == NULL) {
×
2751
    return;
×
2752
  }
2753

2754
  (void)taosThreadMutexLock(&pTscObj->mutex);
×
2755
  pTscObj->db[0] = 0;
×
2756
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
×
2757
}
2758

2759
int32_t setQueryResultFromRsp(SReqResultInfo* pResultInfo, const SRetrieveTableRsp* pRsp, bool convertUcs4,
111,101,397✔
2760
                              bool isStmt) {
2761
  if (pResultInfo == NULL || pRsp == NULL) {
111,101,397✔
2762
    tscError("setQueryResultFromRsp paras is null");
×
2763
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2764
  }
2765

2766
  taosMemoryFreeClear(pResultInfo->pRspMsg);
111,101,397✔
2767
  pResultInfo->pRspMsg = (const char*)pRsp;
111,100,478✔
2768
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
111,101,814✔
2769
  pResultInfo->current = 0;
111,101,397✔
2770
  pResultInfo->completed = (pRsp->completed == 1);
111,101,147✔
2771
  pResultInfo->precision = pRsp->precision;
111,101,119✔
2772

2773
  // decompress data if needed
2774
  int32_t payloadLen = htonl(pRsp->payloadLen);
111,100,948✔
2775

2776
  if (pRsp->compressed) {
111,100,698✔
2777
    if (pResultInfo->decompBuf == NULL) {
×
2778
      pResultInfo->decompBuf = taosMemoryMalloc(payloadLen);
×
2779
      if (pResultInfo->decompBuf == NULL) {
×
2780
        tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2781
        return terrno;
×
2782
      }
2783
      pResultInfo->decompBufSize = payloadLen;
×
2784
    } else {
2785
      if (pResultInfo->decompBufSize < payloadLen) {
×
2786
        char* p = taosMemoryRealloc(pResultInfo->decompBuf, payloadLen);
×
2787
        if (p == NULL) {
×
2788
          tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2789
          return terrno;
×
2790
        }
2791

2792
        pResultInfo->decompBuf = p;
×
2793
        pResultInfo->decompBufSize = payloadLen;
×
2794
      }
2795
    }
2796
  }
2797

2798
  if (payloadLen > 0) {
111,100,921✔
2799
    int32_t compLen = *(int32_t*)pRsp->data;
95,948,823✔
2800
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
95,948,545✔
2801

2802
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
95,948,823✔
2803

2804
    if (pRsp->compressed && compLen < rawLen) {
95,948,573✔
2805
      int32_t len = tsDecompressString(pStart, compLen, 1, pResultInfo->decompBuf, rawLen, ONE_STAGE_COMP, NULL, 0);
×
2806
      if (len < 0) {
×
2807
        tscError("tsDecompressString failed");
×
2808
        return terrno ? terrno : TSDB_CODE_FAILED;
×
2809
      }
2810
      if (len != rawLen) {
×
2811
        tscError("tsDecompressString failed, len:%d != rawLen:%d", len, rawLen);
×
2812
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2813
      }
2814
      pResultInfo->pData = pResultInfo->decompBuf;
×
2815
      pResultInfo->payloadLen = rawLen;
×
2816
    } else {
2817
      pResultInfo->pData = pStart;
95,948,791✔
2818
      pResultInfo->payloadLen = htonl(pRsp->compLen);
95,948,572✔
2819
      if (pRsp->compLen != pRsp->payloadLen) {
95,948,823✔
2820
        tscError("pRsp->compLen:%d != pRsp->payloadLen:%d", pRsp->compLen, pRsp->payloadLen);
×
2821
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2822
      }
2823
    }
2824
  }
2825

2826
  // TODO handle the compressed case
2827
  pResultInfo->totalRows += pResultInfo->numOfRows;
111,099,751✔
2828

2829
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
111,100,869✔
2830
  return code;
111,099,950✔
2831
}
2832

2833
TSDB_SERVER_STATUS taos_check_server_status(const char* fqdn, int port, char* details, int maxlen) {
461✔
2834
  TSDB_SERVER_STATUS code = TSDB_SRV_STATUS_UNAVAILABLE;
461✔
2835
  void*              clientRpc = NULL;
461✔
2836
  SServerStatusRsp   statusRsp = {0};
461✔
2837
  SEpSet             epSet = {.inUse = 0, .numOfEps = 1};
461✔
2838
  SRpcMsg  rpcMsg = {.info.ahandle = (void*)0x9527, .info.notFreeAhandle = 1, .msgType = TDMT_DND_SERVER_STATUS};
461✔
2839
  SRpcMsg  rpcRsp = {0};
461✔
2840
  SRpcInit rpcInit = {0};
461✔
2841
  char     pass[TSDB_PASSWORD_LEN + 1] = {0};
461✔
2842

2843
  rpcInit.label = "CHK";
461✔
2844
  rpcInit.numOfThreads = 1;
461✔
2845
  rpcInit.cfp = NULL;
461✔
2846
  rpcInit.sessions = 16;
461✔
2847
  rpcInit.connType = TAOS_CONN_CLIENT;
461✔
2848
  rpcInit.idleTime = tsShellActivityTimer * 1000;
461✔
2849
  rpcInit.compressSize = tsCompressMsgSize;
461✔
2850
  rpcInit.user = "_dnd";
461✔
2851

2852
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
461✔
2853
  connLimitNum = TMAX(connLimitNum, 10);
461✔
2854
  connLimitNum = TMIN(connLimitNum, 500);
461✔
2855
  rpcInit.connLimitNum = connLimitNum;
461✔
2856
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
461✔
2857
  rpcInit.readTimeout = tsReadTimeout;
461✔
2858
  rpcInit.ipv6 = tsEnableIpv6;
461✔
2859
  rpcInit.enableSSL = tsEnableTLS;
461✔
2860

2861
  memcpy(rpcInit.caPath, tsTLSCaPath, strlen(tsTLSCaPath));
461✔
2862
  memcpy(rpcInit.certPath, tsTLSSvrCertPath, strlen(tsTLSSvrCertPath));
461✔
2863
  memcpy(rpcInit.keyPath, tsTLSSvrKeyPath, strlen(tsTLSSvrKeyPath));
461✔
2864
  memcpy(rpcInit.cliCertPath, tsTLSCliCertPath, strlen(tsTLSCliCertPath));
461✔
2865
  memcpy(rpcInit.cliKeyPath, tsTLSCliKeyPath, strlen(tsTLSCliKeyPath));
461✔
2866

2867
  if (TSDB_CODE_SUCCESS != taosVersionStrToInt(td_version, &rpcInit.compatibilityVer)) {
461✔
2868
    tscError("faild to convert taos version from str to int, errcode:%s", terrstr());
×
2869
    goto _OVER;
×
2870
  }
2871

2872
  clientRpc = rpcOpen(&rpcInit);
461✔
2873
  if (clientRpc == NULL) {
461✔
2874
    code = terrno;
×
2875
    tscError("failed to init server status client since %s", tstrerror(code));
×
2876
    goto _OVER;
×
2877
  }
2878

2879
  if (fqdn == NULL) {
461✔
2880
    fqdn = tsLocalFqdn;
461✔
2881
  }
2882

2883
  if (port == 0) {
461✔
2884
    port = tsServerPort;
461✔
2885
  }
2886

2887
  tstrncpy(epSet.eps[0].fqdn, fqdn, TSDB_FQDN_LEN);
461✔
2888
  epSet.eps[0].port = (uint16_t)port;
461✔
2889
  int32_t ret = rpcSendRecv(clientRpc, &epSet, &rpcMsg, &rpcRsp);
461✔
2890
  if (TSDB_CODE_SUCCESS != ret) {
461✔
2891
    tscError("failed to send recv since %s", tstrerror(ret));
×
2892
    goto _OVER;
×
2893
  }
2894

2895
  if (rpcRsp.code != 0 || rpcRsp.contLen <= 0 || rpcRsp.pCont == NULL) {
461✔
2896
    tscError("failed to send server status req since %s", terrstr());
130✔
2897
    goto _OVER;
130✔
2898
  }
2899

2900
  if (tDeserializeSServerStatusRsp(rpcRsp.pCont, rpcRsp.contLen, &statusRsp) != 0) {
331✔
2901
    tscError("failed to parse server status rsp since %s", terrstr());
×
2902
    goto _OVER;
×
2903
  }
2904

2905
  code = statusRsp.statusCode;
331✔
2906
  if (details != NULL) {
331✔
2907
    tstrncpy(details, statusRsp.details, maxlen);
331✔
2908
  }
2909

2910
_OVER:
391✔
2911
  if (clientRpc != NULL) {
461✔
2912
    rpcClose(clientRpc);
461✔
2913
  }
2914
  if (rpcRsp.pCont != NULL) {
461✔
2915
    rpcFreeCont(rpcRsp.pCont);
331✔
2916
  }
2917
  return code;
461✔
2918
}
2919

2920
int32_t appendTbToReq(SHashObj* pHash, int32_t pos1, int32_t len1, int32_t pos2, int32_t len2, const char* str,
1,276✔
2921
                      int32_t acctId, char* db) {
2922
  SName name = {0};
1,276✔
2923

2924
  if (len1 <= 0) {
1,276✔
2925
    return -1;
×
2926
  }
2927

2928
  const char* dbName = db;
1,276✔
2929
  const char* tbName = NULL;
1,276✔
2930
  int32_t     dbLen = 0;
1,276✔
2931
  int32_t     tbLen = 0;
1,276✔
2932
  if (len2 > 0) {
1,276✔
2933
    dbName = str + pos1;
×
2934
    dbLen = len1;
×
2935
    tbName = str + pos2;
×
2936
    tbLen = len2;
×
2937
  } else {
2938
    dbLen = strlen(db);
1,276✔
2939
    tbName = str + pos1;
1,276✔
2940
    tbLen = len1;
1,276✔
2941
  }
2942

2943
  if (dbLen <= 0 || tbLen <= 0) {
1,276✔
2944
    return -1;
×
2945
  }
2946

2947
  if (tNameSetDbName(&name, acctId, dbName, dbLen)) {
1,276✔
2948
    return -1;
×
2949
  }
2950

2951
  if (tNameAddTbName(&name, tbName, tbLen)) {
1,276✔
2952
    return -1;
×
2953
  }
2954

2955
  char dbFName[TSDB_DB_FNAME_LEN] = {0};
1,276✔
2956
  (void)snprintf(dbFName, TSDB_DB_FNAME_LEN, "%d.%.*s", acctId, dbLen, dbName);
1,276✔
2957

2958
  STablesReq* pDb = taosHashGet(pHash, dbFName, strlen(dbFName));
1,276✔
2959
  if (pDb) {
1,276✔
2960
    if (NULL == taosArrayPush(pDb->pTables, &name)) {
×
2961
      return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
2962
    }
2963
  } else {
2964
    STablesReq db;
1,276✔
2965
    db.pTables = taosArrayInit(20, sizeof(SName));
1,276✔
2966
    if (NULL == db.pTables) {
1,276✔
2967
      return terrno;
×
2968
    }
2969
    tstrncpy(db.dbFName, dbFName, TSDB_DB_FNAME_LEN);
1,276✔
2970
    if (NULL == taosArrayPush(db.pTables, &name)) {
2,552✔
2971
      return terrno;
×
2972
    }
2973
    TSC_ERR_RET(taosHashPut(pHash, dbFName, strlen(dbFName), &db, sizeof(db)));
1,276✔
2974
  }
2975

2976
  return TSDB_CODE_SUCCESS;
1,276✔
2977
}
2978

2979
int32_t transferTableNameList(const char* tbList, int32_t acctId, char* dbName, SArray** pReq) {
1,276✔
2980
  SHashObj* pHash = taosHashInit(3, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
1,276✔
2981
  if (NULL == pHash) {
1,276✔
2982
    return terrno;
×
2983
  }
2984

2985
  bool    inEscape = false;
1,276✔
2986
  int32_t code = 0;
1,276✔
2987
  void*   pIter = NULL;
1,276✔
2988

2989
  int32_t vIdx = 0;
1,276✔
2990
  int32_t vPos[2];
1,276✔
2991
  int32_t vLen[2];
1,276✔
2992

2993
  (void)memset(vPos, -1, sizeof(vPos));
1,276✔
2994
  (void)memset(vLen, 0, sizeof(vLen));
1,276✔
2995

2996
  for (int32_t i = 0;; ++i) {
6,380✔
2997
    if (0 == *(tbList + i)) {
6,380✔
2998
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
1,276✔
2999
        vLen[vIdx] = i - vPos[vIdx];
1,276✔
3000
      }
3001

3002
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
1,276✔
3003
      if (code) {
1,276✔
3004
        goto _return;
×
3005
      }
3006

3007
      break;
1,276✔
3008
    }
3009

3010
    if ('`' == *(tbList + i)) {
5,104✔
3011
      inEscape = !inEscape;
×
3012
      if (!inEscape) {
×
3013
        if (vPos[vIdx] >= 0) {
×
3014
          vLen[vIdx] = i - vPos[vIdx];
×
3015
        } else {
3016
          goto _return;
×
3017
        }
3018
      }
3019

3020
      continue;
×
3021
    }
3022

3023
    if (inEscape) {
5,104✔
3024
      if (vPos[vIdx] < 0) {
×
3025
        vPos[vIdx] = i;
×
3026
      }
3027
      continue;
×
3028
    }
3029

3030
    if ('.' == *(tbList + i)) {
5,104✔
3031
      if (vPos[vIdx] < 0) {
×
3032
        goto _return;
×
3033
      }
3034
      if (vLen[vIdx] <= 0) {
×
3035
        vLen[vIdx] = i - vPos[vIdx];
×
3036
      }
3037
      vIdx++;
×
3038
      if (vIdx >= 2) {
×
3039
        goto _return;
×
3040
      }
3041
      continue;
×
3042
    }
3043

3044
    if (',' == *(tbList + i)) {
5,104✔
3045
      if (vPos[vIdx] < 0) {
×
3046
        goto _return;
×
3047
      }
3048
      if (vLen[vIdx] <= 0) {
×
3049
        vLen[vIdx] = i - vPos[vIdx];
×
3050
      }
3051

3052
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
×
3053
      if (code) {
×
3054
        goto _return;
×
3055
      }
3056

3057
      (void)memset(vPos, -1, sizeof(vPos));
×
3058
      (void)memset(vLen, 0, sizeof(vLen));
×
3059
      vIdx = 0;
×
3060
      continue;
×
3061
    }
3062

3063
    if (' ' == *(tbList + i) || '\r' == *(tbList + i) || '\t' == *(tbList + i) || '\n' == *(tbList + i)) {
5,104✔
3064
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
×
3065
        vLen[vIdx] = i - vPos[vIdx];
×
3066
      }
3067
      continue;
×
3068
    }
3069

3070
    if (('a' <= *(tbList + i) && 'z' >= *(tbList + i)) || ('A' <= *(tbList + i) && 'Z' >= *(tbList + i)) ||
5,104✔
3071
        ('0' <= *(tbList + i) && '9' >= *(tbList + i)) || ('_' == *(tbList + i))) {
638✔
3072
      if (vLen[vIdx] > 0) {
5,104✔
3073
        goto _return;
×
3074
      }
3075
      if (vPos[vIdx] < 0) {
5,104✔
3076
        vPos[vIdx] = i;
1,276✔
3077
      }
3078
      continue;
5,104✔
3079
    }
3080

3081
    goto _return;
×
3082
  }
3083

3084
  int32_t dbNum = taosHashGetSize(pHash);
1,276✔
3085
  *pReq = taosArrayInit(dbNum, sizeof(STablesReq));
1,276✔
3086
  if (NULL == pReq) {
1,276✔
3087
    TSC_ERR_JRET(terrno);
×
3088
  }
3089
  pIter = taosHashIterate(pHash, NULL);
1,276✔
3090
  while (pIter) {
2,552✔
3091
    STablesReq* pDb = (STablesReq*)pIter;
1,276✔
3092
    if (NULL == taosArrayPush(*pReq, pDb)) {
2,552✔
3093
      TSC_ERR_JRET(terrno);
×
3094
    }
3095
    pIter = taosHashIterate(pHash, pIter);
1,276✔
3096
  }
3097

3098
  taosHashCleanup(pHash);
1,276✔
3099

3100
  return TSDB_CODE_SUCCESS;
1,276✔
3101

3102
_return:
×
3103

3104
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
3105

3106
  pIter = taosHashIterate(pHash, NULL);
×
3107
  while (pIter) {
×
3108
    STablesReq* pDb = (STablesReq*)pIter;
×
3109
    taosArrayDestroy(pDb->pTables);
×
3110
    pIter = taosHashIterate(pHash, pIter);
×
3111
  }
3112

3113
  taosHashCleanup(pHash);
×
3114

3115
  return terrno;
×
3116
}
3117

3118
void syncCatalogFn(SMetaData* pResult, void* param, int32_t code) {
1,276✔
3119
  SSyncQueryParam* pParam = param;
1,276✔
3120
  pParam->pRequest->code = code;
1,276✔
3121

3122
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
1,276✔
3123
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3124
  }
3125
}
1,276✔
3126

3127
void syncQueryFn(void* param, void* res, int32_t code) {
725,322,091✔
3128
  SSyncQueryParam* pParam = param;
725,322,091✔
3129
  pParam->pRequest = res;
725,322,091✔
3130

3131
  if (pParam->pRequest) {
725,328,812✔
3132
    pParam->pRequest->code = code;
725,313,586✔
3133
    clientOperateReport(pParam->pRequest);
725,319,351✔
3134
  }
3135

3136
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
725,307,750✔
3137
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3138
  }
3139
}
725,331,152✔
3140

3141
void taosAsyncQueryImpl(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
724,797,582✔
3142
                        int8_t source) {
3143
  if (sql == NULL || NULL == fp) {
724,797,582✔
3144
    terrno = TSDB_CODE_INVALID_PARA;
975✔
3145
    if (fp) {
×
3146
      fp(param, NULL, terrno);
×
3147
    }
3148

3149
    return;
×
3150
  }
3151

3152
  size_t sqlLen = strlen(sql);
724,796,842✔
3153
  if (sqlLen > (size_t)tsMaxSQLLength) {
724,796,842✔
3154
    tscError("conn:0x%" PRIx64 ", sql string exceeds max length:%d", connId, tsMaxSQLLength);
1,264✔
3155
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
1,264✔
3156
    fp(param, NULL, terrno);
1,264✔
3157
    return;
1,264✔
3158
  }
3159

3160
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, sql:%s", connId, sql);
724,795,578✔
3161

3162
  SRequestObj* pRequest = NULL;
724,796,060✔
3163
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
724,793,891✔
3164
  if (code != TSDB_CODE_SUCCESS) {
724,795,812✔
3165
    terrno = code;
×
3166
    fp(param, NULL, terrno);
×
3167
    return;
×
3168
  }
3169

3170
  code = connCheckAndUpateMetric(connId);
724,795,812✔
3171
  if (code != TSDB_CODE_SUCCESS) {
724,793,443✔
3172
    terrno = code;
×
3173
    fp(param, NULL, terrno);
×
3174
    return;
×
3175
  }
3176

3177
  pRequest->source = source;
724,793,443✔
3178
  pRequest->body.queryFp = fp;
724,794,784✔
3179
  doAsyncQuery(pRequest, false);
724,792,850✔
3180
}
3181

3182
void taosAsyncQueryImplWithReqid(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
795✔
3183
                                 int64_t reqid) {
3184
  if (sql == NULL || NULL == fp) {
795✔
3185
    terrno = TSDB_CODE_INVALID_PARA;
×
3186
    if (fp) {
×
3187
      fp(param, NULL, terrno);
×
3188
    }
3189

3190
    return;
×
3191
  }
3192

3193
  size_t sqlLen = strlen(sql);
795✔
3194
  if (sqlLen > (size_t)tsMaxSQLLength) {
795✔
3195
    tscError("conn:0x%" PRIx64 ", QID:0x%" PRIx64 ", sql string exceeds max length:%d", connId, reqid, tsMaxSQLLength);
×
3196
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
3197
    fp(param, NULL, terrno);
×
3198
    return;
×
3199
  }
3200

3201
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, QID:0x%" PRIx64 ", sql:%s", connId, reqid, sql);
795✔
3202

3203
  SRequestObj* pRequest = NULL;
795✔
3204
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, reqid);
795✔
3205
  if (code != TSDB_CODE_SUCCESS) {
795✔
3206
    terrno = code;
×
3207
    fp(param, NULL, terrno);
×
3208
    return;
×
3209
  }
3210

3211
  code = connCheckAndUpateMetric(connId);
795✔
3212

3213
  if (code != TSDB_CODE_SUCCESS) {
795✔
3214
    terrno = code;
×
3215
    fp(param, NULL, terrno);
×
3216
    return;
×
3217
  }
3218

3219
  pRequest->body.queryFp = fp;
795✔
3220

3221
  doAsyncQuery(pRequest, false);
795✔
3222
}
3223

3224
TAOS_RES* taosQueryImpl(TAOS* taos, const char* sql, bool validateOnly, int8_t source) {
724,757,830✔
3225
  if (NULL == taos) {
724,757,830✔
3226
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3227
    return NULL;
×
3228
  }
3229

3230
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
724,757,830✔
3231
  if (NULL == param) {
724,762,500✔
3232
    return NULL;
×
3233
  }
3234

3235
  int32_t code = tsem_init(&param->sem, 0, 0);
724,762,500✔
3236
  if (TSDB_CODE_SUCCESS != code) {
724,758,164✔
3237
    taosMemoryFree(param);
×
3238
    return NULL;
×
3239
  }
3240

3241
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
724,758,164✔
3242
  code = tsem_wait(&param->sem);
724,754,653✔
3243
  if (TSDB_CODE_SUCCESS != code) {
724,766,354✔
3244
    taosMemoryFree(param);
×
3245
    return NULL;
×
3246
  }
3247
  code = tsem_destroy(&param->sem);
724,766,354✔
3248
  if (TSDB_CODE_SUCCESS != code) {
724,767,575✔
3249
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3250
  }
3251

3252
  SRequestObj* pRequest = NULL;
724,767,575✔
3253
  if (param->pRequest != NULL) {
724,767,575✔
3254
    param->pRequest->syncQuery = true;
724,764,510✔
3255
    pRequest = param->pRequest;
724,765,804✔
3256
    param->pRequest->inCallback = false;
724,765,096✔
3257
  }
3258
  taosMemoryFree(param);
724,765,338✔
3259

3260
  // tscDebug("QID:0x%" PRIx64 ", taos_query end, conn:0x%" PRIx64 ", res:%p", pRequest ? pRequest->requestId : 0,
3261
  //          *(int64_t*)taos, pRequest);
3262

3263
  return pRequest;
724,765,052✔
3264
}
3265

3266
TAOS_RES* taosQueryImplWithReqid(TAOS* taos, const char* sql, bool validateOnly, int64_t reqid) {
795✔
3267
  if (NULL == taos) {
795✔
3268
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3269
    return NULL;
×
3270
  }
3271

3272
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
795✔
3273
  if (param == NULL) {
795✔
3274
    return NULL;
×
3275
  }
3276
  int32_t code = tsem_init(&param->sem, 0, 0);
795✔
3277
  if (TSDB_CODE_SUCCESS != code) {
795✔
3278
    taosMemoryFree(param);
×
3279
    return NULL;
×
3280
  }
3281

3282
  taosAsyncQueryImplWithReqid(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, reqid);
795✔
3283
  code = tsem_wait(&param->sem);
795✔
3284
  if (TSDB_CODE_SUCCESS != code) {
795✔
3285
    taosMemoryFree(param);
×
3286
    return NULL;
×
3287
  }
3288
  SRequestObj* pRequest = NULL;
795✔
3289
  if (param->pRequest != NULL) {
795✔
3290
    param->pRequest->syncQuery = true;
795✔
3291
    pRequest = param->pRequest;
795✔
3292
  }
3293
  taosMemoryFree(param);
795✔
3294

3295
  // tscDebug("QID:0x%" PRIx64 ", taos_query end, conn:0x%" PRIx64 ", res:%p", pRequest ? pRequest->requestId : 0,
3296
  //   *(int64_t*)taos, pRequest);
3297

3298
  return pRequest;
795✔
3299
}
3300

3301
static void fetchCallback(void* pResult, void* param, int32_t code) {
108,194,293✔
3302
  SRequestObj* pRequest = (SRequestObj*)param;
108,194,293✔
3303

3304
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
108,194,293✔
3305

3306
  tscDebug("req:0x%" PRIx64 ", enter scheduler fetch cb, code:%d - %s, QID:0x%" PRIx64, pRequest->self, code,
108,193,792✔
3307
           tstrerror(code), pRequest->requestId);
3308

3309
  pResultInfo->pData = pResult;
108,193,792✔
3310
  pResultInfo->numOfRows = 0;
108,194,293✔
3311

3312
  if (code != TSDB_CODE_SUCCESS) {
108,192,368✔
3313
    pRequest->code = code;
×
3314
    taosMemoryFreeClear(pResultInfo->pData);
×
3315
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
×
3316
    return;
×
3317
  }
3318

3319
  if (pRequest->code != TSDB_CODE_SUCCESS) {
108,192,368✔
3320
    taosMemoryFreeClear(pResultInfo->pData);
×
3321
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pRequest->code);
×
3322
    return;
×
3323
  }
3324

3325
  pRequest->code = setQueryResultFromRsp(pResultInfo, (const SRetrieveTableRsp*)pResultInfo->pData,
108,944,227✔
3326
                                         pResultInfo->convertUcs4, pRequest->stmtBindVersion > 0);
108,193,541✔
3327
  if (pRequest->code != TSDB_CODE_SUCCESS) {
108,192,870✔
3328
    pResultInfo->numOfRows = 0;
74✔
3329
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self,
74✔
3330
             tstrerror(pRequest->code), pRequest->requestId);
3331
  } else {
3332
    tscDebug(
108,192,149✔
3333
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
3334
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
3335

3336
    STscObj*            pTscObj = pRequest->pTscObj;
108,192,149✔
3337
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
108,193,811✔
3338
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
108,194,422✔
3339
  }
3340

3341
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
108,194,261✔
3342
}
3343

3344
void taosAsyncFetchImpl(SRequestObj* pRequest, __taos_async_fn_t fp, void* param) {
119,854,246✔
3345
  pRequest->body.fetchFp = fp;
119,854,246✔
3346
  ((SSyncQueryParam*)pRequest->body.interParam)->userParam = param;
119,854,246✔
3347

3348
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
119,854,246✔
3349

3350
  // this query has no results or error exists, return directly
3351
  if (taos_num_fields(pRequest) == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
119,854,246✔
3352
    pResultInfo->numOfRows = 0;
×
3353
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
×
3354
    return;
1,780✔
3355
  }
3356

3357
  // all data has returned to App already, no need to try again
3358
  if (pResultInfo->completed) {
119,854,246✔
3359
    // it is a local executed query, no need to do async fetch
3360
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
11,659,536✔
3361
      if (pResultInfo->localResultFetched) {
1,554,070✔
3362
        pResultInfo->numOfRows = 0;
777,035✔
3363
        pResultInfo->current = 0;
777,035✔
3364
      } else {
3365
        pResultInfo->localResultFetched = true;
777,035✔
3366
      }
3367
    } else {
3368
      pResultInfo->numOfRows = 0;
10,105,466✔
3369
    }
3370

3371
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
11,659,536✔
3372
    return;
11,659,536✔
3373
  }
3374

3375
  SSchedulerReq req = {
108,194,710✔
3376
      .syncReq = false,
3377
      .fetchFp = fetchCallback,
3378
      .cbParam = pRequest,
3379
  };
3380

3381
  int32_t code = schedulerFetchRows(pRequest->body.queryJob, &req);
108,194,710✔
3382
  if (TSDB_CODE_SUCCESS != code) {
108,193,529✔
3383
    tscError("0x%" PRIx64 " failed to schedule fetch rows", pRequest->requestId);
×
3384
    // pRequest->body.fetchFp(param, pRequest, code);
3385
  }
3386
}
3387

3388
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
725,289,397✔
3389
  pRequest->inCallback = true;
725,289,397✔
3390
  int64_t this = pRequest->self;
725,301,515✔
3391
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
725,276,755✔
3392
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
82,050✔
3393
    code = TSDB_CODE_SUCCESS;
×
3394
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3395
  }
3396

3397
  tscDebug("QID:0x%" PRIx64 ", taos_query end, req:0x%" PRIx64 ", res:%p", pRequest->requestId, pRequest->self,
725,276,755✔
3398
           pRequest);
3399

3400
  if (pRequest->body.queryFp != NULL) {
725,277,859✔
3401
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
725,293,657✔
3402
  }
3403

3404
  SRequestObj* pReq = acquireRequest(this);
725,306,010✔
3405
  if (pReq != NULL) {
725,301,473✔
3406
    pReq->inCallback = false;
724,469,029✔
3407
    (void)releaseRequest(this);
724,473,236✔
3408
  }
3409
}
725,304,740✔
3410

3411
int32_t clientParseSql(void* param, const char* dbName, const char* sql, bool parseOnly, const char* effectiveUser,
564,883✔
3412
                       SParseSqlRes* pRes) {
3413
#ifndef TD_ENTERPRISE
3414
  return TSDB_CODE_SUCCESS;
3415
#else
3416
  return clientParseSqlImpl(param, dbName, sql, parseOnly, effectiveUser, pRes);
564,883✔
3417
#endif
3418
}
3419

3420
void updateConnAccessInfo(SConnAccessInfo *pInfo) {
2,708,564✔
3421
  if (pInfo == NULL) {
2,708,564✔
3422
    return;
×
3423
  }
3424
  int64_t ts = taosGetTimestampMs();
2,708,544✔
3425
  if (pInfo->startTime == 0) {
2,708,544✔
3426
    pInfo->startTime = ts;
2,708,544✔
3427
  }
3428
  pInfo->lastAccessTime = ts;
2,708,544✔
3429
}
3430
 
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc