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

taosdata / TDengine / #4887

16 Dec 2025 08:27AM UTC coverage: 65.289% (-0.003%) from 65.292%
#4887

push

travis-ci

web-flow
feat[TS-7233]: audit (#33850)

377 of 536 new or added lines in 28 files covered. (70.34%)

1025 existing lines in 111 files now uncovered.

178977 of 274129 relevant lines covered (65.29%)

102580217.43 hits per line

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

70.06
/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 "command.h"
21
#include "decimal.h"
22
#include "scheduler.h"
23
#include "tdatablock.h"
24
#include "tdataformat.h"
25
#include "tdef.h"
26
#include "tglobal.h"
27
#include "tmisce.h"
28
#include "tmsg.h"
29
#include "tmsgtype.h"
30
#include "tpagedbuf.h"
31
#include "tref.h"
32
#include "tsched.h"
33
#include "tversion.h"
34

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

38
int32_t connUpdateSessMgtMetric(int64_t connId, SSessParam* pParam);
39
//int32_t tscUpdateSessMgtMetric(STscObj* pTscObj, SSessParam* pParam);
40

41
void setQueryRequest(int64_t rId) {
113,746,531✔
42
  SRequestObj* pReq = acquireRequest(rId);
113,746,531✔
43
  if (pReq != NULL) {
113,746,755✔
44
    pReq->isQuery = true;
113,736,395✔
45
    (void)releaseRequest(rId);
113,736,395✔
46
  }
47
}
113,746,127✔
48

49
static bool stringLengthCheck(const char* str, size_t maxsize) {
7,426,030✔
50
  if (str == NULL) {
7,426,030✔
51
    return false;
×
52
  }
53

54
  size_t len = strlen(str);
7,426,030✔
55
  if (len <= 0 || len > maxsize) {
7,426,030✔
56
    return false;
×
57
  }
58

59
  return true;
7,426,126✔
60
}
61

62
static bool validateUserName(const char* user) { return stringLengthCheck(user, TSDB_USER_LEN - 1); }
3,120,920✔
63

64
static bool validatePassword(const char* passwd) { return stringLengthCheck(passwd, TSDB_PASSWORD_MAX_LEN); }
3,120,368✔
65

66
static bool validateDbName(const char* db) { return stringLengthCheck(db, TSDB_DB_NAME_LEN - 1); }
1,184,582✔
67

68
static char* getClusterKey(const char* user, const char* auth, const char* ip, int32_t port) {
3,120,426✔
69
  char key[512] = {0};
3,120,426✔
70
  (void)snprintf(key, sizeof(key), "%s:%s:%s:%d", user, auth, ip, port);
3,120,426✔
71
  return taosStrdup(key);
3,120,426✔
72
}
73

74
static int32_t escapeToPrinted(char* dst, size_t maxDstLength, const char* src, size_t srcLength) {
650,109✔
75
  if (dst == NULL || src == NULL || srcLength == 0) {
650,109✔
76
    return 0;
545✔
77
  }
78

79
  size_t escapeLength = 0;
649,564✔
80
  for (size_t i = 0; i < srcLength; ++i) {
18,423,698✔
81
    if (src[i] == '\"' || src[i] == '\\' || src[i] == '\b' || src[i] == '\f' || src[i] == '\n' || src[i] == '\r' ||
17,774,134✔
82
        src[i] == '\t') {
17,774,134✔
83
      escapeLength += 1;
×
84
    }
85
  }
86

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

128
  return dstLength;
649,564✔
129
}
130

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

138
  (void)releaseRequest((int64_t)param);
2,147,483,647✔
139

140
  return killed;
2,147,483,647✔
141
}
142

143
void cleanupAppInfo() {
1,598,744✔
144
  taosHashCleanup(appInfo.pInstMap);
1,598,744✔
145
  taosHashCleanup(appInfo.pInstMapByClusterId);
1,598,744✔
146
  tscInfo("cluster instance map cleaned");
1,598,744✔
147
}
1,598,744✔
148

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

153
int32_t taos_connect_internal(const char* ip, const char* user, const char* pass, const char* auth, const char* totp,
3,120,920✔
154
                              const char* db, uint16_t port, int connType, STscObj** pObj) {
155
  TSC_ERR_RET(taos_init());
3,120,920✔
156
  if (!validateUserName(user)) {
3,121,143✔
157
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
158
  }
159
  int32_t code = 0;
3,120,980✔
160

161
  char localDb[TSDB_DB_NAME_LEN] = {0};
3,120,980✔
162
  if (db != NULL && strlen(db) > 0) {
3,120,980✔
163
    if (!validateDbName(db)) {
1,184,550✔
164
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_DB_LENGTH);
×
165
    }
166

167
    tstrncpy(localDb, db, sizeof(localDb));
1,184,837✔
168
    (void)strdequote(localDb);
1,184,837✔
169
  }
170

171
  char secretEncrypt[TSDB_PASSWORD_LEN + 1] = {0};
3,120,626✔
172
  if (auth == NULL) {
3,120,626✔
173
    if (!validatePassword(pass)) {
3,120,074✔
174
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_PASS_LENGTH);
×
175
    }
176

177
    taosEncryptPass_c((uint8_t*)pass, strlen(pass), secretEncrypt);
3,120,375✔
178
  } else {
179
    tstrncpy(secretEncrypt, auth, tListLen(secretEncrypt));
552✔
180
  }
181

182
  int32_t totpCode = -1;
3,121,147✔
183
  if (totp != NULL) {
3,121,147✔
184
    char* endptr = NULL;
×
185
    totpCode = taosStr2Int32(totp, &endptr, 10);
×
186
    if (endptr == totp || *endptr != '\0' || totpCode < 0 || totpCode > 999999) {
×
187
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_TOTP_CODE);
×
188
    }
189
  }
190

191
  SCorEpSet epSet = {0};
3,121,147✔
192
  if (ip) {
3,120,139✔
193
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
925,505✔
194
  } else {
195
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
2,194,634✔
196
  }
197

198
  if (port) {
3,120,171✔
199
    epSet.epSet.eps[0].port = port;
112,300✔
200
    epSet.epSet.eps[1].port = port;
112,300✔
201
  }
202

203
  char* key = getClusterKey(user, secretEncrypt, ip, port);
3,120,171✔
204
  if (NULL == key) {
3,120,426✔
205
    TSC_ERR_RET(terrno);
×
206
  }
207
  tscInfo("connecting to server, numOfEps:%d inUse:%d user:%s db:%s key:%s", epSet.epSet.numOfEps, epSet.epSet.inUse,
3,120,426✔
208
          user, db, key);
209
  for (int32_t i = 0; i < epSet.epSet.numOfEps; ++i) {
8,437,109✔
210
    tscInfo("ep:%d, %s:%u", i, epSet.epSet.eps[i].fqdn, epSet.epSet.eps[i].port);
5,316,398✔
211
  }
212
  // for (int32_t i = 0; i < epSet.epSet.numOfEps; i++) {
213
  //   if ((code = taosValidFqdn(tsEnableIpv6, epSet.epSet.eps[i].fqdn)) != 0) {
214
  //     taosMemFree(key);
215
  //     tscError("ipv6 flag %d, the local FQDN %s does not resolve to the ip address since %s", tsEnableIpv6,
216
  //              epSet.epSet.eps[i].fqdn, tstrerror(code));
217
  //     TSC_ERR_RET(code);
218
  //   }
219
  // }
220

221
  SAppInstInfo** pInst = NULL;
3,120,711✔
222
  code = taosThreadMutexLock(&appInfo.mutex);
3,120,711✔
223
  if (TSDB_CODE_SUCCESS != code) {
3,120,711✔
224
    tscError("failed to lock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
225
    TSC_ERR_RET(code);
×
226
  }
227

228
  pInst = taosHashGet(appInfo.pInstMap, key, strlen(key));
3,120,711✔
229
  SAppInstInfo* p = NULL;
3,120,711✔
230
  if (pInst == NULL) {
3,120,711✔
231
    p = taosMemoryCalloc(1, sizeof(struct SAppInstInfo));
1,655,798✔
232
    if (NULL == p) {
1,655,798✔
233
      TSC_ERR_JRET(terrno);
×
234
    }
235
    p->mgmtEp = epSet;
1,655,798✔
236
    code = taosThreadMutexInit(&p->qnodeMutex, NULL);
1,655,798✔
237
    if (TSDB_CODE_SUCCESS != code) {
1,655,798✔
238
      taosMemoryFree(p);
×
239
      TSC_ERR_JRET(code);
×
240
    }
241
    code = openTransporter(user, secretEncrypt, tsNumOfCores / 2, &p->pTransporter);
1,655,798✔
242
    if (TSDB_CODE_SUCCESS != code) {
1,655,798✔
243
      taosMemoryFree(p);
41✔
244
      TSC_ERR_JRET(code);
41✔
245
    }
246
    code = appHbMgrInit(p, key, &p->pAppHbMgr);
1,655,757✔
247
    if (TSDB_CODE_SUCCESS != code) {
1,655,757✔
248
      destroyAppInst(&p);
×
249
      TSC_ERR_JRET(code);
×
250
    }
251
    code = taosHashPut(appInfo.pInstMap, key, strlen(key), &p, POINTER_BYTES);
1,655,757✔
252
    if (TSDB_CODE_SUCCESS != code) {
1,655,757✔
253
      destroyAppInst(&p);
×
254
      TSC_ERR_JRET(code);
×
255
    }
256
    p->instKey = key;
1,655,757✔
257
    key = NULL;
1,655,757✔
258
    tscInfo("new app inst mgr:%p, user:%s, ip:%s, port:%d", p, user, epSet.epSet.eps[0].fqdn, epSet.epSet.eps[0].port);
1,655,757✔
259

260
    pInst = &p;
1,655,757✔
261
  } else {
262
    if (NULL == *pInst || NULL == (*pInst)->pAppHbMgr) {
1,464,913✔
263
      tscError("*pInst:%p, pAppHgMgr:%p", *pInst, (*pInst) ? (*pInst)->pAppHbMgr : NULL);
×
264
      TSC_ERR_JRET(TSDB_CODE_TSC_INTERNAL_ERROR);
×
265
    }
266
    // reset to 0 in case of conn with duplicated user key but its user has ever been dropped.
267
    atomic_store_8(&(*pInst)->pAppHbMgr->connHbFlag, 0);
1,464,913✔
268
  }
269

270
_return:
3,120,711✔
271

272
  if (TSDB_CODE_SUCCESS != code) {
3,120,711✔
273
    (void)taosThreadMutexUnlock(&appInfo.mutex);
41✔
274
    taosMemoryFreeClear(key);
41✔
275
    return code;
41✔
276
  } else {
277
    code = taosThreadMutexUnlock(&appInfo.mutex);
3,120,670✔
278
    taosMemoryFreeClear(key);
3,120,670✔
279
    if (TSDB_CODE_SUCCESS != code) {
3,120,670✔
280
      tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
281
      return code;
×
282
    }
283
    SSessParam pPara = {.type = SESSION_PER_USER, .value = 1};
3,120,670✔
284
    code = sessMgtUpdateUserMetric((char*)user, &pPara);
3,120,670✔
285
    if (TSDB_CODE_SUCCESS != code) {
3,120,670✔
286
      tscError("failed to connect with user:%s, code:%s", user, tstrerror(code));
×
287
      return code;
×
288
    }
289
    return taosConnectImpl(user, &secretEncrypt[0], totpCode, localDb, NULL, NULL, *pInst, connType, pObj);
3,120,670✔
290
  }
291
}
292

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

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

310
int32_t buildRequest(uint64_t connId, const char* sql, int sqlLen, void* param, bool validateSql,
640,207,498✔
311
                     SRequestObj** pRequest, int64_t reqid) {
312
  int32_t code = createRequest(connId, TSDB_SQL_SELECT, reqid, pRequest);
640,207,498✔
313
  if (TSDB_CODE_SUCCESS != code) {
640,205,602✔
314
    tscError("failed to malloc sqlObj, %s", sql);
×
315
    return code;
×
316
  }
317

318
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
640,205,602✔
319
  if ((*pRequest)->sqlstr == NULL) {
640,200,804✔
320
    tscError("req:0x%" PRIx64 ", failed to prepare sql string buffer, %s", (*pRequest)->self, sql);
×
321
    destroyRequest(*pRequest);
×
322
    *pRequest = NULL;
×
323
    return terrno;
×
324
  }
325

326
  (void)strntolower((*pRequest)->sqlstr, sql, (int32_t)sqlLen);
640,199,577✔
327
  (*pRequest)->sqlstr[sqlLen] = 0;
640,216,397✔
328
  (*pRequest)->sqlLen = sqlLen;
640,215,755✔
329
  (*pRequest)->validateOnly = validateSql;
640,216,883✔
330
  (*pRequest)->stmtBindVersion = 0;
640,213,244✔
331

332
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
640,212,991✔
333

334
  STscObj* pTscObj = (*pRequest)->pTscObj;
640,211,839✔
335
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
640,214,736✔
336
                             sizeof((*pRequest)->self));
337
  if (err) {
640,212,710✔
338
    tscError("req:0x%" PRId64 ", failed to add to request container, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
339
             (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
340
    destroyRequest(*pRequest);
×
341
    *pRequest = NULL;
×
342
    return terrno;
×
343
  }
344

345
  (*pRequest)->allocatorRefId = -1;
640,212,710✔
346
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
640,209,831✔
347
    if (TSDB_CODE_SUCCESS !=
189,016,256✔
348
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
189,012,617✔
349
      tscError("req:0x%" PRId64 ", failed to create node allocator, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
350
               (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
351
      destroyRequest(*pRequest);
×
352
      *pRequest = NULL;
×
353
      return terrno;
×
354
    }
355
  }
356

357
  tscDebug("req:0x%" PRIx64 ", build request, QID:0x%" PRIx64, (*pRequest)->self, (*pRequest)->requestId);
640,211,383✔
358
  return TSDB_CODE_SUCCESS;
640,207,636✔
359
}
360

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

373
int32_t parseSql(SRequestObj* pRequest, bool topicQuery, SQuery** pQuery, SStmtCallback* pStmtCb) {
684,210✔
374
  STscObj* pTscObj = pRequest->pTscObj;
684,210✔
375

376
  SParseContext cxt = {
684,450✔
377
      .requestId = pRequest->requestId,
684,229✔
378
      .requestRid = pRequest->self,
684,059✔
379
      .acctId = pTscObj->acctId,
683,859✔
380
      .db = pRequest->pDb,
684,176✔
381
      .topicQuery = topicQuery,
382
      .pSql = pRequest->sqlstr,
684,244✔
383
      .sqlLen = pRequest->sqlLen,
684,586✔
384
      .pMsg = pRequest->msgBuf,
683,842✔
385
      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
386
      .pTransporter = pTscObj->pAppInfo->pTransporter,
684,074✔
387
      .pStmtCb = pStmtCb,
388
      .pUser = pTscObj->user,
683,048✔
389
      .isSuperUser = (0 == strcmp(pTscObj->user, TSDB_DEFAULT_USER)),
683,972✔
390
      .enableSysInfo = pTscObj->sysInfo,
682,751✔
391
      .svrVer = pTscObj->sVer,
682,859✔
392
      .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes),
684,263✔
393
      .stmtBindVersion = pRequest->stmtBindVersion,
683,269✔
394
      .setQueryFp = setQueryRequest,
395
      .timezone = pTscObj->optionInfo.timezone,
682,819✔
396
      .charsetCxt = pTscObj->optionInfo.charsetCxt,
683,972✔
397
  };
398

399
  cxt.mgmtEpSet = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
683,853✔
400
  int32_t code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &cxt.pCatalog);
684,365✔
401
  if (code != TSDB_CODE_SUCCESS) {
684,416✔
402
    return code;
×
403
  }
404

405
  code = qParseSql(&cxt, pQuery);
684,416✔
406
  if (TSDB_CODE_SUCCESS == code) {
684,021✔
407
    if ((*pQuery)->haveResultSet) {
682,307✔
408
      code = setResSchemaInfo(&pRequest->body.resInfo, (*pQuery)->pResSchema, (*pQuery)->numOfResCols,
×
409
                              (*pQuery)->pResExtSchema, pRequest->stmtBindVersion > 0);
×
410
      setResPrecision(&pRequest->body.resInfo, (*pQuery)->precision);
×
411
    }
412
  }
413

414
  if (TSDB_CODE_SUCCESS == code || NEED_CLIENT_HANDLE_ERROR(code)) {
684,008✔
415
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
682,094✔
416
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
682,049✔
417
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
680,922✔
418
  }
419

420
  taosArrayDestroy(cxt.pTableMetaPos);
682,518✔
421
  taosArrayDestroy(cxt.pTableVgroupPos);
682,410✔
422

423
  return code;
682,398✔
424
}
425

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

436
  return code;
×
437
}
438

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

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

450
  STscObj*      pTscObj = pRequest->pTscObj;
343,852✔
451
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
343,852✔
452

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

459
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
1,199,233,478✔
460

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

468
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp,
10,276,030✔
469
                              atomic_load_8(&pRequest->pTscObj->biMode), pRequest->pTscObj->optionInfo.charsetCxt);
10,276,279✔
470
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
5,145,123✔
471
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4,
2,795,930✔
472
                                 pRequest->stmtBindVersion > 0);
2,795,930✔
473
  }
474

475
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
5,145,123✔
476
  pRequest->code = code;
5,145,123✔
477

478
  if (pRequest->code != TSDB_CODE_SUCCESS) {
5,145,123✔
479
    pResultInfo->numOfRows = 0;
3,826✔
480
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
3,826✔
481
             pRequest->requestId);
482
  } else {
483
    tscDebug(
5,141,297✔
484
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
485
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
486
  }
487

488
  doRequestCallback(pRequest, code);
5,145,123✔
489
}
490

491
int32_t asyncExecDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
16,809,535✔
492
  if (pRequest->validateOnly) {
16,809,535✔
493
    doRequestCallback(pRequest, 0);
×
494
    return TSDB_CODE_SUCCESS;
×
495
  }
496

497
  // drop table if exists not_exists_table
498
  if (NULL == pQuery->pCmdMsg) {
16,809,535✔
499
    doRequestCallback(pRequest, 0);
7,839✔
500
    return TSDB_CODE_SUCCESS;
7,839✔
501
  }
502

503
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
16,801,696✔
504
  pRequest->type = pMsgInfo->msgType;
16,801,422✔
505
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
16,801,696✔
506
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
16,800,769✔
507

508
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
16,801,214✔
509
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
16,801,664✔
510

511
  int32_t code = asyncSendMsgToServer(pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg);
16,801,118✔
512
  if (code) {
16,801,696✔
513
    doRequestCallback(pRequest, code);
×
514
  }
515
  return code;
16,801,696✔
516
}
517

518
int compareQueryNodeLoad(const void* elem1, const void* elem2) {
375,402✔
519
  SQueryNodeLoad* node1 = (SQueryNodeLoad*)elem1;
375,402✔
520
  SQueryNodeLoad* node2 = (SQueryNodeLoad*)elem2;
375,402✔
521

522
  if (node1->load < node2->load) {
375,402✔
523
    return -1;
×
524
  }
525

526
  return node1->load > node2->load;
375,402✔
527
}
528

529
int32_t updateQnodeList(SAppInstInfo* pInfo, SArray* pNodeList) {
56,425✔
530
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
56,425✔
531
  if (pInfo->pQnodeList) {
56,425✔
532
    taosArrayDestroy(pInfo->pQnodeList);
53,847✔
533
    pInfo->pQnodeList = NULL;
53,847✔
534
    tscDebug("QnodeList cleared in cluster 0x%" PRIx64, pInfo->clusterId);
53,847✔
535
  }
536

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

545
  return TSDB_CODE_SUCCESS;
56,425✔
546
}
547

548
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
640,262,910✔
549
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
640,262,910✔
550
    *required = false;
640,109,124✔
551
    return TSDB_CODE_SUCCESS;
640,107,485✔
552
  }
553

554
  int32_t       code = TSDB_CODE_SUCCESS;
153,786✔
555
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
153,786✔
556
  *required = false;
153,786✔
557

558
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
153,786✔
559
  *required = (NULL == pInfo->pQnodeList);
153,786✔
560
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
153,786✔
561
  return TSDB_CODE_SUCCESS;
153,786✔
562
}
563

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

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

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

593
  return code;
×
594
}
595

596
int32_t getPlan(SRequestObj* pRequest, SQuery* pQuery, SQueryPlan** pPlan, SArray* pNodeList) {
6,333,484✔
597
  pRequest->type = pQuery->msgType;
6,333,484✔
598
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
6,332,481✔
599

600
  SPlanContext cxt = {.queryId = pRequest->requestId,
7,154,381✔
601
                      .acctId = pRequest->pTscObj->acctId,
6,332,504✔
602
                      .mgmtEpSet = getEpSet_s(&pAppInfo->mgmtEp),
6,332,901✔
603
                      .pAstRoot = pQuery->pRoot,
6,333,722✔
604
                      .showRewrite = pQuery->showRewrite,
6,333,365✔
605
                      .pMsg = pRequest->msgBuf,
6,333,399✔
606
                      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
607
                      .pUser = pRequest->pTscObj->user,
6,333,110✔
608
                      .timezone = pRequest->pTscObj->optionInfo.timezone,
6,331,858✔
609
                      .sysInfo = pRequest->pTscObj->sysInfo};
6,332,158✔
610

611
  return qCreateQueryPlan(&cxt, pPlan, pNodeList);
6,331,592✔
612
}
613

614
int32_t setResSchemaInfo(SReqResultInfo* pResInfo, const SSchema* pSchema, int32_t numOfCols,
113,258,039✔
615
                         const SExtSchema* pExtSchema, bool isStmt) {
616
  if (pResInfo == NULL || pSchema == NULL || numOfCols <= 0) {
113,258,039✔
617
    tscError("invalid paras, pResInfo == NULL || pSchema == NULL || numOfCols <= 0");
×
618
    return TSDB_CODE_INVALID_PARA;
×
619
  }
620

621
  pResInfo->numOfCols = numOfCols;
113,259,067✔
622
  if (pResInfo->fields != NULL) {
113,258,351✔
623
    taosMemoryFree(pResInfo->fields);
19,912✔
624
  }
625
  if (pResInfo->userFields != NULL) {
113,257,198✔
626
    taosMemoryFree(pResInfo->userFields);
19,912✔
627
  }
628
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD_E));
113,257,808✔
629
  if (NULL == pResInfo->fields) return terrno;
113,256,720✔
630
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
113,257,009✔
631
  if (NULL == pResInfo->userFields) {
113,256,950✔
632
    taosMemoryFree(pResInfo->fields);
×
633
    return terrno;
×
634
  }
635
  if (numOfCols != pResInfo->numOfCols) {
113,257,333✔
636
    tscError("numOfCols:%d != pResInfo->numOfCols:%d", numOfCols, pResInfo->numOfCols);
×
637
    return TSDB_CODE_FAILED;
×
638
  }
639

640
  for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
683,442,321✔
641
    pResInfo->fields[i].type = pSchema[i].type;
570,183,831✔
642

643
    pResInfo->userFields[i].type = pSchema[i].type;
570,185,193✔
644
    // userFields must convert to type bytes, no matter isStmt or not
645
    pResInfo->userFields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, false);
570,186,690✔
646
    pResInfo->fields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, isStmt);
570,184,998✔
647
    if (IS_DECIMAL_TYPE(pSchema[i].type) && pExtSchema) {
570,184,204✔
648
      decimalFromTypeMod(pExtSchema[i].typeMod, &pResInfo->fields[i].precision, &pResInfo->fields[i].scale);
1,753,700✔
649
    }
650

651
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
570,185,333✔
652
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
570,184,847✔
653
  }
654
  return TSDB_CODE_SUCCESS;
113,259,258✔
655
}
656

657
void setResPrecision(SReqResultInfo* pResInfo, int32_t precision) {
83,042,214✔
658
  if (precision != TSDB_TIME_PRECISION_MILLI && precision != TSDB_TIME_PRECISION_MICRO &&
83,042,214✔
659
      precision != TSDB_TIME_PRECISION_NANO) {
660
    return;
×
661
  }
662

663
  pResInfo->precision = precision;
83,042,214✔
664
}
665

666
int32_t buildVnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pDbVgList) {
87,096,889✔
667
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
87,096,889✔
668
  if (NULL == nodeList) {
87,102,599✔
669
    return terrno;
34✔
670
  }
671
  char* policy = (tsQueryPolicy == QUERY_POLICY_VNODE) ? "vnode" : "client";
87,103,060✔
672

673
  int32_t dbNum = taosArrayGetSize(pDbVgList);
87,103,060✔
674
  for (int32_t i = 0; i < dbNum; ++i) {
172,020,501✔
675
    SArray* pVg = taosArrayGetP(pDbVgList, i);
84,912,517✔
676
    if (NULL == pVg) {
84,915,479✔
677
      continue;
×
678
    }
679
    int32_t vgNum = taosArrayGetSize(pVg);
84,915,479✔
680
    if (vgNum <= 0) {
84,914,048✔
681
      continue;
682,268✔
682
    }
683

684
    for (int32_t j = 0; j < vgNum; ++j) {
275,899,660✔
685
      SVgroupInfo* pInfo = taosArrayGet(pVg, j);
191,666,110✔
686
      if (NULL == pInfo) {
191,668,797✔
687
        taosArrayDestroy(nodeList);
×
688
        return TSDB_CODE_OUT_OF_RANGE;
×
689
      }
690
      SQueryNodeLoad load = {0};
191,668,797✔
691
      load.addr.nodeId = pInfo->vgId;
191,669,490✔
692
      load.addr.epSet = pInfo->epSet;
191,667,896✔
693

694
      if (NULL == taosArrayPush(nodeList, &load)) {
191,665,349✔
695
        taosArrayDestroy(nodeList);
×
696
        return terrno;
×
697
      }
698
    }
699
  }
700

701
  int32_t vnodeNum = taosArrayGetSize(nodeList);
87,107,984✔
702
  if (vnodeNum > 0) {
87,106,833✔
703
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
83,954,270✔
704
    goto _return;
83,952,076✔
705
  }
706

707
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
3,152,563✔
708
  if (mnodeNum <= 0) {
3,152,173✔
709
    tscDebug("0x%" PRIx64 " %s policy, empty node list", pRequest->requestId, policy);
×
710
    goto _return;
×
711
  }
712

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

723
  tscDebug("0x%" PRIx64 " %s policy, use mnode list, num:%d", pRequest->requestId, policy, mnodeNum);
3,152,173✔
724

725
_return:
47,159✔
726

727
  *pNodeList = nodeList;
87,104,159✔
728

729
  return TSDB_CODE_SUCCESS;
87,104,159✔
730
}
731

732
int32_t buildQnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pQnodeList) {
84,706✔
733
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
84,706✔
734
  if (NULL == nodeList) {
84,706✔
735
    return terrno;
×
736
  }
737

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

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

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

769
  tscDebug("0x%" PRIx64 " qnode policy, use mnode list, num:%d", pRequest->requestId, mnodeNum);
84,328✔
770

771
_return:
×
772

773
  *pNodeList = nodeList;
84,706✔
774

775
  return TSDB_CODE_SUCCESS;
84,706✔
776
}
777

778
void freeVgList(void* list) {
6,288,880✔
779
  SArray* pList = *(SArray**)list;
6,288,880✔
780
  taosArrayDestroy(pList);
6,289,972✔
781
}
6,288,954✔
782

783
int32_t buildAsyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SMetaData* pResultMeta) {
80,854,295✔
784
  SArray* pDbVgList = NULL;
80,854,295✔
785
  SArray* pQnodeList = NULL;
80,854,295✔
786
  FDelete fp = NULL;
80,854,295✔
787
  int32_t code = 0;
80,854,295✔
788

789
  switch (tsQueryPolicy) {
80,854,295✔
790
    case QUERY_POLICY_VNODE:
80,770,078✔
791
    case QUERY_POLICY_CLIENT: {
792
      if (pResultMeta) {
80,770,078✔
793
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
80,770,755✔
794
        if (NULL == pDbVgList) {
80,770,971✔
795
          code = terrno;
×
796
          goto _return;
×
797
        }
798
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
80,770,971✔
799
        for (int32_t i = 0; i < dbNum; ++i) {
159,397,336✔
800
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
78,624,969✔
801
          if (pRes->code || NULL == pRes->pRes) {
78,625,178✔
802
            continue;
1,074✔
803
          }
804

805
          if (NULL == taosArrayPush(pDbVgList, &pRes->pRes)) {
157,248,418✔
806
            code = terrno;
×
807
            goto _return;
×
808
          }
809
        }
810
      } else {
811
        fp = freeVgList;
×
812

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

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

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

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

849
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
80,772,367✔
850
      break;
80,771,858✔
851
    }
852
    case QUERY_POLICY_HYBRID:
84,706✔
853
    case QUERY_POLICY_QNODE: {
854
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
169,202✔
855
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
84,496✔
856
        if (pRes->code) {
84,496✔
857
          pQnodeList = NULL;
×
858
        } else {
859
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
84,496✔
860
          if (NULL == pQnodeList) {
84,496✔
861
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
862
            goto _return;
×
863
          }
864
        }
865
      } else {
866
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
210✔
867
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
210✔
868
        if (pInst->pQnodeList) {
210✔
869
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
210✔
870
          if (NULL == pQnodeList) {
210✔
871
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
872
            goto _return;
×
873
          }
874
        }
875
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
210✔
876
      }
877

878
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
84,706✔
879
      break;
84,706✔
880
    }
881
    default:
3✔
882
      tscError("unknown query policy: %d", tsQueryPolicy);
3✔
883
      return TSDB_CODE_APP_ERROR;
×
884
  }
885

886
_return:
80,856,564✔
887
  taosArrayDestroyEx(pDbVgList, fp);
80,856,564✔
888
  taosArrayDestroy(pQnodeList);
80,855,713✔
889

890
  return code;
80,856,033✔
891
}
892

893
int32_t buildSyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList) {
6,328,999✔
894
  SArray* pDbVgList = NULL;
6,328,999✔
895
  SArray* pQnodeList = NULL;
6,328,999✔
896
  int32_t code = 0;
6,330,057✔
897

898
  switch (tsQueryPolicy) {
6,330,057✔
899
    case QUERY_POLICY_VNODE:
6,328,541✔
900
    case QUERY_POLICY_CLIENT: {
901
      int32_t dbNum = taosArrayGetSize(pRequest->dbList);
6,328,541✔
902
      if (dbNum > 0) {
6,332,807✔
903
        SCatalog*     pCtg = NULL;
6,289,960✔
904
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
6,290,165✔
905
        code = catalogGetHandle(pInst->clusterId, &pCtg);
6,289,116✔
906
        if (code != TSDB_CODE_SUCCESS) {
6,287,575✔
907
          goto _return;
×
908
        }
909

910
        pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
6,287,575✔
911
        if (NULL == pDbVgList) {
6,289,161✔
912
          code = terrno;
210✔
913
          goto _return;
×
914
        }
915
        SArray* pVgList = NULL;
6,288,953✔
916
        for (int32_t i = 0; i < dbNum; ++i) {
12,574,983✔
917
          char*            dbFName = taosArrayGet(pRequest->dbList, i);
6,285,526✔
918
          SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
6,289,283✔
919
                                   .requestId = pRequest->requestId,
6,287,794✔
920
                                   .requestObjRefId = pRequest->self,
6,287,724✔
921
                                   .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
6,288,499✔
922

923
          // catalogGetDBVgList will handle dbFName == null.
924
          code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
6,291,128✔
925
          if (code) {
6,288,066✔
926
            goto _return;
×
927
          }
928

929
          if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
6,289,597✔
930
            code = terrno;
×
931
            goto _return;
×
932
          }
933
        }
934
      }
935

936
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
6,330,662✔
937
      break;
6,331,574✔
938
    }
939
    case QUERY_POLICY_HYBRID:
×
940
    case QUERY_POLICY_QNODE: {
941
      TSC_ERR_JRET(getQnodeList(pRequest, &pQnodeList));
×
942

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

951
_return:
6,331,336✔
952

953
  taosArrayDestroyEx(pDbVgList, freeVgList);
6,331,369✔
954
  taosArrayDestroy(pQnodeList);
6,330,453✔
955

956
  return code;
6,331,432✔
957
}
958

959
int32_t scheduleQuery(SRequestObj* pRequest, SQueryPlan* pDag, SArray* pNodeList) {
6,334,143✔
960
  void* pTransporter = pRequest->pTscObj->pAppInfo->pTransporter;
6,334,143✔
961

962
  SExecResult      res = {0};
6,334,143✔
963
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
6,334,143✔
964
                           .requestId = pRequest->requestId,
6,334,143✔
965
                           .requestObjRefId = pRequest->self};
6,334,143✔
966
  SSchedulerReq    req = {
7,155,036✔
967
         .syncReq = true,
968
         .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
6,334,143✔
969
         .pConn = &conn,
970
         .pNodeList = pNodeList,
971
         .pDag = pDag,
972
         .sql = pRequest->sqlstr,
6,334,143✔
973
         .startTs = pRequest->metric.start,
6,334,143✔
974
         .execFp = NULL,
975
         .cbParam = NULL,
976
         .chkKillFp = chkRequestKilled,
977
         .chkKillParam = (void*)pRequest->self,
6,334,143✔
978
         .pExecRes = &res,
979
         .source = pRequest->source,
6,334,143✔
980
         .pWorkerCb = getTaskPoolWorkerCb(),
6,334,143✔
981
  };
982

983
  int32_t code = schedulerExecJob(&req, &pRequest->body.queryJob);
6,334,143✔
984

985
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
6,334,053✔
986
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
6,334,019✔
987

988
  if (code != TSDB_CODE_SUCCESS) {
6,333,762✔
989
    schedulerFreeJob(&pRequest->body.queryJob, 0);
×
990

991
    pRequest->code = code;
×
992
    terrno = code;
×
993
    return pRequest->code;
×
994
  }
995

996
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_DELETE == pRequest->type ||
6,333,762✔
997
      TDMT_VND_CREATE_TABLE == pRequest->type) {
15,904✔
998
    pRequest->body.resInfo.numOfRows = res.numOfRows;
6,322,328✔
999
    if (TDMT_VND_SUBMIT == pRequest->type) {
6,322,294✔
1000
      STscObj*            pTscObj = pRequest->pTscObj;
6,318,115✔
1001
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
6,318,149✔
1002
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
6,318,149✔
1003
    }
1004

1005
    schedulerFreeJob(&pRequest->body.queryJob, 0);
6,322,679✔
1006
  }
1007

1008
  pRequest->code = res.code;
6,334,045✔
1009
  terrno = res.code;
6,333,210✔
1010
  return pRequest->code;
6,331,552✔
1011
}
1012

1013
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
455,390,943✔
1014
  SArray*      pArray = NULL;
455,390,943✔
1015
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
455,390,943✔
1016
  if (NULL == pRsp->aCreateTbRsp) {
455,390,943✔
1017
    return TSDB_CODE_SUCCESS;
446,681,710✔
1018
  }
1019

1020
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
8,715,601✔
1021
  for (int32_t i = 0; i < tbNum; ++i) {
21,024,870✔
1022
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
12,308,751✔
1023
    if (pTbRsp->pMeta) {
12,308,717✔
1024
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
11,705,575✔
1025
    }
1026
  }
1027

1028
  return TSDB_CODE_SUCCESS;
8,716,119✔
1029
}
1030

1031
int32_t handleQueryExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
68,439,110✔
1032
  int32_t code = 0;
68,439,110✔
1033
  SArray* pArray = NULL;
68,439,110✔
1034
  SArray* pTbArray = (SArray*)res;
68,439,110✔
1035
  int32_t tbNum = taosArrayGetSize(pTbArray);
68,439,110✔
1036
  if (tbNum <= 0) {
68,438,714✔
1037
    return TSDB_CODE_SUCCESS;
×
1038
  }
1039

1040
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
68,438,714✔
1041
  if (NULL == pArray) {
68,438,689✔
1042
    return terrno;
×
1043
  }
1044

1045
  for (int32_t i = 0; i < tbNum; ++i) {
181,255,274✔
1046
    STbVerInfo* tbInfo = taosArrayGet(pTbArray, i);
112,816,388✔
1047
    if (NULL == tbInfo) {
112,815,940✔
1048
      code = terrno;
×
1049
      goto _return;
×
1050
    }
1051
    STbSVersion tbSver = {
112,815,940✔
1052
        .tbFName = tbInfo->tbFName, .sver = tbInfo->sversion, .tver = tbInfo->tversion, .rver = tbInfo->rversion};
112,815,940✔
1053
    if (NULL == taosArrayPush(pArray, &tbSver)) {
112,816,608✔
1054
      code = terrno;
×
1055
      goto _return;
×
1056
    }
1057
  }
1058

1059
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
68,438,886✔
1060
                           .requestId = pRequest->requestId,
68,439,134✔
1061
                           .requestObjRefId = pRequest->self,
68,439,169✔
1062
                           .mgmtEps = *epset};
1063

1064
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
68,439,133✔
1065

1066
_return:
68,439,160✔
1067

1068
  taosArrayDestroy(pArray);
68,438,200✔
1069
  return code;
68,437,817✔
1070
}
1071

1072
int32_t handleAlterTbExecRes(void* res, SCatalog* pCatalog) {
9,167,319✔
1073
  return catalogUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
9,167,319✔
1074
}
1075

1076
int32_t handleCreateTbExecRes(void* res, SCatalog* pCatalog) {
69,317,333✔
1077
  return catalogAsyncUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
69,317,333✔
1078
}
1079

1080
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
603,412,410✔
1081
  if (NULL == pRequest->body.resInfo.execRes.res) {
603,412,410✔
1082
    return pRequest->code;
24,054,785✔
1083
  }
1084

1085
  SCatalog*     pCatalog = NULL;
579,345,681✔
1086
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
579,350,094✔
1087

1088
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
579,363,284✔
1089
  if (code) {
579,351,125✔
1090
    return code;
×
1091
  }
1092

1093
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
579,351,125✔
1094
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
579,360,150✔
1095

1096
  switch (pRes->msgType) {
579,364,595✔
1097
    case TDMT_VND_ALTER_TABLE:
3,897,598✔
1098
    case TDMT_MND_ALTER_STB: {
1099
      code = handleAlterTbExecRes(pRes->res, pCatalog);
3,897,598✔
1100
      break;
3,897,598✔
1101
    }
1102
    case TDMT_VND_CREATE_TABLE: {
51,276,766✔
1103
      SArray* pList = (SArray*)pRes->res;
51,276,766✔
1104
      int32_t num = taosArrayGetSize(pList);
51,289,752✔
1105
      for (int32_t i = 0; i < num; ++i) {
107,015,815✔
1106
        void* res = taosArrayGetP(pList, i);
55,718,820✔
1107
        // handleCreateTbExecRes will handle res == null
1108
        code = handleCreateTbExecRes(res, pCatalog);
55,720,282✔
1109
      }
1110
      break;
51,296,995✔
1111
    }
1112
    case TDMT_MND_CREATE_STB: {
336,047✔
1113
      code = handleCreateTbExecRes(pRes->res, pCatalog);
336,047✔
1114
      break;
336,047✔
1115
    }
1116
    case TDMT_VND_SUBMIT: {
455,389,080✔
1117
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
455,389,080✔
1118

1119
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
455,399,912✔
1120
      break;
455,394,023✔
1121
    }
1122
    case TDMT_SCH_QUERY:
68,438,000✔
1123
    case TDMT_SCH_MERGE_QUERY: {
1124
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
68,438,000✔
1125
      break;
68,442,255✔
1126
    }
1127
    default:
570✔
1128
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self,
570✔
1129
               pRequest->type, pRequest->requestId);
1130
      code = TSDB_CODE_APP_ERROR;
×
1131
  }
1132

1133
  return code;
579,366,918✔
1134
}
1135

1136
static bool incompletaFileParsing(SNode* pStmt) {
595,770,589✔
1137
  return QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pStmt) ? false : ((SVnodeModifyOpStmt*)pStmt)->fileProcessing;
595,770,589✔
1138
}
1139

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

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

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

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

1158
void returnToUser(SRequestObj* pRequest) {
12,450,588✔
1159
  if (pRequest->relation.userRefId == pRequest->self || 0 == pRequest->relation.userRefId) {
12,450,588✔
1160
    // return to client
1161
    doRequestCallback(pRequest, pRequest->code);
12,450,588✔
1162
    return;
12,450,588✔
1163
  }
1164

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

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

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

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

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

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

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

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

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

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

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

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

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

1260
  blockDataDestroy(pBlock);
×
1261
}
1262

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

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

1280
// todo refacto the error code  mgmt
1281
void schedulerExecCb(SExecResult* pResult, void* param, int32_t code) {
596,785,873✔
1282
  SSqlCallbackWrapper* pWrapper = param;
596,785,873✔
1283
  SRequestObj*         pRequest = pWrapper->pRequest;
596,785,873✔
1284
  STscObj*             pTscObj = pRequest->pTscObj;
596,791,334✔
1285

1286
  pRequest->code = code;
596,788,577✔
1287
  if (pResult) {
596,789,379✔
1288
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
596,746,233✔
1289
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
596,750,523✔
1290
  }
1291

1292
  int32_t type = pRequest->type;
596,769,268✔
1293
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
596,754,227✔
1294
    if (pResult) {
503,857,487✔
1295
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
503,850,531✔
1296

1297
      // record the insert rows
1298
      if (TDMT_VND_SUBMIT == type) {
503,862,181✔
1299
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
449,218,976✔
1300
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
449,223,917✔
1301
      }
1302
    }
1303
    schedulerFreeJob(&pRequest->body.queryJob, 0);
503,869,701✔
1304
  }
1305

1306
  taosMemoryFree(pResult);
596,790,288✔
1307
  tscDebug("req:0x%" PRIx64 ", enter scheduler exec cb, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
596,774,182✔
1308
           pRequest->requestId);
1309

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

1321
  tscTrace("req:0x%" PRIx64 ", scheduler exec cb, request type:%s", pRequest->self, TMSG_INFO(pRequest->type));
596,729,667✔
1322
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
596,729,667✔
1323
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
2,867,812✔
1324
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1325
    }
1326
  }
1327

1328
  pRequest->metric.execCostUs = taosGetTimestampUs() - pRequest->metric.execStart;
596,722,865✔
1329
  int32_t code1 = handleQueryExecRsp(pRequest);
596,734,428✔
1330
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
596,743,944✔
1331
    pRequest->code = code1;
×
1332
  }
1333

1334
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
1,192,518,010✔
1335
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
595,769,521✔
1336
    continueInsertFromCsv(pWrapper, pRequest);
11,997✔
1337
    return;
11,997✔
1338
  }
1339

1340
  if (pRequest->relation.nextRefId) {
596,737,542✔
1341
    handlePostSubQuery(pWrapper);
×
1342
  } else {
1343
    destorySqlCallbackWrapper(pWrapper);
596,738,621✔
1344
    pRequest->pWrapper = NULL;
596,728,627✔
1345

1346
    // return to client
1347
    doRequestCallback(pRequest, code);
596,731,923✔
1348
  }
1349
}
1350

1351
void launchQueryImpl(SRequestObj* pRequest, SQuery* pQuery, bool keepQuery, void** res) {
6,675,522✔
1352
  int32_t code = 0;
6,675,522✔
1353
  int32_t subplanNum = 0;
6,675,522✔
1354

1355
  if (pQuery->pRoot) {
6,675,522✔
1356
    pRequest->stmtType = pQuery->pRoot->type;
6,333,397✔
1357
  }
1358

1359
  if (pQuery->pRoot && !pRequest->inRetry) {
6,675,307✔
1360
    STscObj*            pTscObj = pRequest->pTscObj;
6,333,834✔
1361
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
6,333,800✔
1362
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type) {
6,333,664✔
1363
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
6,323,042✔
1364
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
10,360✔
1365
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
10,388✔
1366
    }
1367
  }
1368

1369
  pRequest->body.execMode = pQuery->execMode;
6,675,722✔
1370
  switch (pQuery->execMode) {
6,677,443✔
1371
    case QUERY_EXEC_MODE_LOCAL:
×
1372
      if (!pRequest->validateOnly) {
×
1373
        if (NULL == pQuery->pRoot) {
×
1374
          terrno = TSDB_CODE_INVALID_PARA;
×
1375
          code = terrno;
×
1376
        } else {
1377
          code = execLocalCmd(pRequest, pQuery);
×
1378
        }
1379
      }
1380
      break;
×
1381
    case QUERY_EXEC_MODE_RPC:
343,852✔
1382
      if (!pRequest->validateOnly) {
343,852✔
1383
        code = execDdlQuery(pRequest, pQuery);
343,852✔
1384
      }
1385
      break;
343,852✔
1386
    case QUERY_EXEC_MODE_SCHEDULE: {
6,331,366✔
1387
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
6,331,366✔
1388
      if (NULL == pMnodeList) {
6,333,401✔
1389
        code = terrno;
×
1390
        break;
×
1391
      }
1392
      SQueryPlan* pDag = NULL;
6,333,401✔
1393
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
6,333,112✔
1394
      if (TSDB_CODE_SUCCESS == code) {
6,330,083✔
1395
        pRequest->body.subplanNum = pDag->numOfSubplans;
6,331,745✔
1396
        if (!pRequest->validateOnly) {
6,330,188✔
1397
          SArray* pNodeList = NULL;
6,330,136✔
1398
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
6,329,937✔
1399

1400
          if (TSDB_CODE_SUCCESS == code) {
6,331,823✔
1401
            SSessParam para = {.type = SESSION_MAX_CALL_VNODE_NUM, .value = taosArrayGetSize(pNodeList)};
6,332,758✔
1402
            code = tscUpdateSessMgtMetric(pRequest->pTscObj, &para);
6,332,115✔
1403
          }
1404

1405
          if (TSDB_CODE_SUCCESS == code) {
6,334,113✔
1406
            code = scheduleQuery(pRequest, pDag, pNodeList);
6,334,143✔
1407
          }
1408
          taosArrayDestroy(pNodeList);
6,333,596✔
1409
        }
1410
      }
1411
      taosArrayDestroy(pMnodeList);
6,330,338✔
1412
      break;
6,331,945✔
1413
    }
1414
    case QUERY_EXEC_MODE_EMPTY_RESULT:
×
1415
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
1416
      break;
×
1417
    default:
×
1418
      break;
×
1419
  }
1420

1421
  if (!keepQuery) {
6,675,831✔
1422
    qDestroyQuery(pQuery);
×
1423
  }
1424

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

1433
  if (TSDB_CODE_SUCCESS == code) {
6,675,744✔
1434
    code = handleQueryExecRsp(pRequest);
6,674,936✔
1435
  }
1436

1437
  if (TSDB_CODE_SUCCESS != code) {
6,674,920✔
1438
    pRequest->code = code;
6,045✔
1439
  }
1440

1441
  if (res) {
6,674,920✔
1442
    *res = pRequest->body.resInfo.execRes.res;
×
1443
    pRequest->body.resInfo.execRes.res = NULL;
×
1444
  }
1445
}
6,674,920✔
1446

1447
static int32_t asyncExecSchQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta,
597,256,089✔
1448
                                 SSqlCallbackWrapper* pWrapper) {
1449
  int32_t code = TSDB_CODE_SUCCESS;
597,256,089✔
1450
  pRequest->type = pQuery->msgType;
597,256,089✔
1451
  SArray*     pMnodeList = NULL;
597,224,983✔
1452
  SQueryPlan* pDag = NULL;
597,224,983✔
1453
  int64_t     st = taosGetTimestampUs();
597,222,718✔
1454

1455
  if (!pRequest->parseOnly) {
597,222,718✔
1456
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
597,229,692✔
1457
    if (NULL == pMnodeList) {
597,229,659✔
1458
      code = terrno;
×
1459
    }
1460
    SPlanContext cxt = {.queryId = pRequest->requestId,
602,884,335✔
1461
                        .acctId = pRequest->pTscObj->acctId,
597,266,157✔
1462
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
597,278,593✔
1463
                        .pAstRoot = pQuery->pRoot,
597,288,241✔
1464
                        .showRewrite = pQuery->showRewrite,
597,291,518✔
1465
                        .isView = pWrapper->pParseCtx->isView,
597,281,085✔
1466
                        .isAudit = pWrapper->pParseCtx->isAudit,
597,274,910✔
1467
                        .pMsg = pRequest->msgBuf,
597,270,299✔
1468
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1469
                        .pUser = pRequest->pTscObj->user,
597,269,980✔
1470
                        .sysInfo = pRequest->pTscObj->sysInfo,
597,251,259✔
1471
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
597,244,022✔
1472
                        .allocatorId = pRequest->stmtBindVersion > 0 ? 0 : pRequest->allocatorRefId};
597,261,323✔
1473
    if (TSDB_CODE_SUCCESS == code) {
597,256,835✔
1474
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
597,266,523✔
1475
    }
1476
    if (code) {
597,247,235✔
1477
      tscError("req:0x%" PRIx64 ", failed to create query plan, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
269,806✔
1478
               pRequest->requestId);
1479
    } else {
1480
      pRequest->body.subplanNum = pDag->numOfSubplans;
596,977,429✔
1481
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
596,994,980✔
1482
    }
1483
  }
1484

1485
  pRequest->metric.execStart = taosGetTimestampUs();
597,240,549✔
1486
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
597,236,773✔
1487

1488
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
600,053,694✔
1489
    SArray* pNodeList = NULL;
596,736,255✔
1490
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
596,711,581✔
1491
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
80,855,814✔
1492
    }
1493

1494
    SRequestConnInfo conn = {.pTrans = getAppInfo(pRequest)->pTransporter,
596,749,940✔
1495
                             .requestId = pRequest->requestId,
596,749,096✔
1496
                             .requestObjRefId = pRequest->self};
596,760,416✔
1497
    SSchedulerReq    req = {
599,579,183✔
1498
           .syncReq = false,
1499
           .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
596,726,114✔
1500
           .pConn = &conn,
1501
           .pNodeList = pNodeList,
1502
           .pDag = pDag,
1503
           .allocatorRefId = pRequest->allocatorRefId,
596,726,114✔
1504
           .sql = pRequest->sqlstr,
596,702,588✔
1505
           .startTs = pRequest->metric.start,
596,749,377✔
1506
           .execFp = schedulerExecCb,
1507
           .cbParam = pWrapper,
1508
           .chkKillFp = chkRequestKilled,
1509
           .chkKillParam = (void*)pRequest->self,
596,731,246✔
1510
           .pExecRes = NULL,
1511
           .source = pRequest->source,
596,722,101✔
1512
           .pWorkerCb = getTaskPoolWorkerCb(),
596,708,661✔
1513
    };
1514
    if (TSDB_CODE_SUCCESS == code) {
596,748,483✔
1515
      code = schedulerExecJob(&req, &pRequest->body.queryJob);
596,783,284✔
1516
    }
1517

1518
    taosArrayDestroy(pNodeList);
596,749,647✔
1519
  } else {
1520
    qDestroyQueryPlan(pDag);
506,790✔
1521
    tscDebug("req:0x%" PRIx64 ", plan not executed, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
493,598✔
1522
             pRequest->requestId);
1523
    destorySqlCallbackWrapper(pWrapper);
493,598✔
1524
    pRequest->pWrapper = NULL;
493,598✔
1525
    if (TSDB_CODE_SUCCESS != code) {
493,598✔
1526
      pRequest->code = terrno;
269,806✔
1527
    }
1528

1529
    doRequestCallback(pRequest, code);
493,598✔
1530
  }
1531

1532
  // todo not to be released here
1533
  taosArrayDestroy(pMnodeList);
597,284,448✔
1534

1535
  return code;
597,258,622✔
1536
}
1537

1538
void launchAsyncQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta, SSqlCallbackWrapper* pWrapper) {
619,869,690✔
1539
  int32_t code = 0;
619,869,690✔
1540

1541
  if (pRequest->parseOnly) {
619,869,690✔
1542
    doRequestCallback(pRequest, 0);
287,393✔
1543
    return;
287,393✔
1544
  }
1545

1546
  pRequest->body.execMode = pQuery->execMode;
619,596,581✔
1547
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
619,574,792✔
1548
    destorySqlCallbackWrapper(pWrapper);
22,326,888✔
1549
    pRequest->pWrapper = NULL;
22,327,411✔
1550
  }
1551

1552
  if (pQuery->pRoot && !pRequest->inRetry) {
619,547,398✔
1553
    STscObj*            pTscObj = pRequest->pTscObj;
619,552,321✔
1554
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
619,539,109✔
1555
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
619,583,361✔
1556
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
515,896,354✔
1557
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
449,181,085✔
1558
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
170,413,002✔
1559
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
76,282,778✔
1560
    }
1561
  }
1562

1563
  switch (pQuery->execMode) {
619,548,445✔
1564
    case QUERY_EXEC_MODE_LOCAL:
5,157,408✔
1565
      asyncExecLocalCmd(pRequest, pQuery);
5,157,408✔
1566
      break;
5,157,408✔
1567
    case QUERY_EXEC_MODE_RPC:
16,809,535✔
1568
      code = asyncExecDdlQuery(pRequest, pQuery);
16,809,535✔
1569
      break;
16,809,535✔
1570
    case QUERY_EXEC_MODE_SCHEDULE: {
597,256,120✔
1571
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
597,256,120✔
1572
      break;
597,279,746✔
1573
    }
1574
    case QUERY_EXEC_MODE_EMPTY_RESULT:
360,468✔
1575
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
360,468✔
1576
      doRequestCallback(pRequest, 0);
360,468✔
1577
      break;
360,468✔
1578
    default:
×
1579
      tscError("req:0x%" PRIx64 ", invalid execMode %d", pRequest->self, pQuery->execMode);
×
1580
      doRequestCallback(pRequest, -1);
×
1581
      break;
×
1582
  }
1583
}
1584

1585
int32_t refreshMeta(STscObj* pTscObj, SRequestObj* pRequest) {
10,555✔
1586
  SCatalog* pCatalog = NULL;
10,555✔
1587
  int32_t   code = 0;
10,555✔
1588
  int32_t   dbNum = taosArrayGetSize(pRequest->dbList);
10,555✔
1589
  int32_t   tblNum = taosArrayGetSize(pRequest->tableList);
10,555✔
1590

1591
  if (dbNum <= 0 && tblNum <= 0) {
10,555✔
1592
    return TSDB_CODE_APP_ERROR;
10,523✔
1593
  }
1594

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

1600
  SRequestConnInfo conn = {.pTrans = pTscObj->pAppInfo->pTransporter,
32✔
1601
                           .requestId = pRequest->requestId,
32✔
1602
                           .requestObjRefId = pRequest->self,
32✔
1603
                           .mgmtEps = getEpSet_s(&pTscObj->pAppInfo->mgmtEp)};
32✔
1604

1605
  for (int32_t i = 0; i < dbNum; ++i) {
64✔
1606
    char* dbFName = taosArrayGet(pRequest->dbList, i);
32✔
1607

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

1615
  for (int32_t i = 0; i < tblNum; ++i) {
64✔
1616
    SName* tableName = taosArrayGet(pRequest->tableList, i);
32✔
1617

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

1625
  return code;
32✔
1626
}
1627

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

1636
  if (isView) {
4,165,162✔
1637
    for (int32_t i = 0; i < tbNum; ++i) {
820,320✔
1638
      SName* pViewName = taosArrayGet(tbList, i);
410,160✔
1639
      char   dbFName[TSDB_DB_FNAME_LEN];
407,635✔
1640
      if (NULL == pViewName) {
410,160✔
1641
        continue;
×
1642
      }
1643
      (void)tNameGetFullDbName(pViewName, dbFName);
410,160✔
1644
      TSC_ERR_RET(catalogRemoveViewMeta(pCatalog, dbFName, 0, pViewName->tname, 0));
410,160✔
1645
    }
1646
  } else {
1647
    for (int32_t i = 0; i < tbNum; ++i) {
5,590,678✔
1648
      SName* pTbName = taosArrayGet(tbList, i);
1,835,676✔
1649
      TSC_ERR_RET(catalogRemoveTableMeta(pCatalog, pTbName));
1,835,676✔
1650
    }
1651
  }
1652

1653
  return TSDB_CODE_SUCCESS;
4,165,162✔
1654
}
1655

1656
int32_t initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet) {
3,120,126✔
1657
  pEpSet->version = 0;
3,120,126✔
1658

1659
  // init mnode ip set
1660
  SEpSet* mgmtEpSet = &(pEpSet->epSet);
3,120,885✔
1661
  mgmtEpSet->numOfEps = 0;
3,120,380✔
1662
  mgmtEpSet->inUse = 0;
3,120,885✔
1663

1664
  if (firstEp && firstEp[0] != 0) {
3,120,125✔
1665
    if (strlen(firstEp) >= TSDB_EP_LEN) {
3,119,711✔
1666
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1667
      return -1;
×
1668
    }
1669

1670
    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
3,119,711✔
1671
    if (code != TSDB_CODE_SUCCESS) {
3,120,253✔
1672
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1673
      return terrno;
×
1674
    }
1675
    // uint32_t addr = 0;
1676
    SIpAddr addr = {0};
3,120,253✔
1677
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
3,120,253✔
1678
    if (code) {
3,120,718✔
1679
      tscError("failed to resolve firstEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
553✔
1680
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1681
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
556✔
1682
    } else {
1683
      mgmtEpSet->numOfEps++;
3,120,189✔
1684
    }
1685
  }
1686

1687
  if (secondEp && secondEp[0] != 0) {
3,120,615✔
1688
    if (strlen(secondEp) >= TSDB_EP_LEN) {
2,194,470✔
1689
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1690
      return terrno;
×
1691
    }
1692

1693
    int32_t code = taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
2,194,470✔
1694
    if (code != TSDB_CODE_SUCCESS) {
2,195,432✔
1695
      return code;
×
1696
    }
1697
    SIpAddr addr = {0};
2,195,432✔
1698
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
2,195,687✔
1699
    if (code) {
2,195,432✔
1700
      tscError("failed to resolve secondEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
×
1701
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1702
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
×
1703
    } else {
1704
      mgmtEpSet->numOfEps++;
2,195,432✔
1705
    }
1706
  }
1707

1708
  if (mgmtEpSet->numOfEps == 0) {
3,122,082✔
1709
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
556✔
1710
    return TSDB_CODE_RPC_NETWORK_UNAVAIL;
556✔
1711
  }
1712

1713
  return 0;
3,120,304✔
1714
}
1715

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

1724
  SRequestObj* pRequest = NULL;
3,120,670✔
1725
  code = createRequest((*pTscObj)->id, TDMT_MND_CONNECT, 0, &pRequest);
3,120,670✔
1726
  if (TSDB_CODE_SUCCESS != code) {
3,120,670✔
1727
    destroyTscObj(*pTscObj);
×
1728
    return code;
×
1729
  }
1730

1731
  pRequest->sqlstr = taosStrdup("taos_connect");
3,120,670✔
1732
  if (pRequest->sqlstr) {
3,120,670✔
1733
    pRequest->sqlLen = strlen(pRequest->sqlstr);
3,120,415✔
1734
  } else {
1735
    return terrno;
×
1736
  }
1737

1738
  SMsgSendInfo* body = NULL;
3,120,670✔
1739
  code = buildConnectMsg(pRequest, &body, totpCode);
3,120,415✔
1740
  if (TSDB_CODE_SUCCESS != code) {
3,120,165✔
1741
    destroyTscObj(*pTscObj);
×
1742
    return code;
×
1743
  }
1744

1745
  // int64_t transporterId = 0;
1746
  SEpSet epset = getEpSet_s(&(*pTscObj)->pAppInfo->mgmtEp);
3,120,165✔
1747
  code = asyncSendMsgToServer((*pTscObj)->pAppInfo->pTransporter, &epset, NULL, body);
3,120,176✔
1748
  if (TSDB_CODE_SUCCESS != code) {
3,120,670✔
1749
    destroyTscObj(*pTscObj);
×
1750
    tscError("failed to send connect msg to server, code:%s", tstrerror(code));
×
1751
    return code;
×
1752
  }
1753
  if (TSDB_CODE_SUCCESS != tsem_wait(&pRequest->body.rspSem)) {
3,120,670✔
1754
    destroyTscObj(*pTscObj);
×
1755
    tscError("failed to wait sem, code:%s", terrstr());
×
1756
    return terrno;
×
1757
  }
1758
  if (pRequest->code != TSDB_CODE_SUCCESS) {
3,120,670✔
1759
    const char* errorMsg = (code == TSDB_CODE_RPC_FQDN_ERROR) ? taos_errstr(pRequest) : tstrerror(pRequest->code);
14,043✔
1760
    tscError("failed to connect to server, reason: %s", errorMsg);
14,043✔
1761

1762
    terrno = pRequest->code;
14,043✔
1763
    destroyRequest(pRequest);
14,043✔
1764
    taos_close_internal(*pTscObj);
14,043✔
1765
    *pTscObj = NULL;
14,043✔
1766
    return terrno;
14,043✔
1767
  }
1768
  if (connType == CONN_TYPE__AUTH_TEST) {
3,106,627✔
1769
    terrno = TSDB_CODE_SUCCESS;
×
1770
    destroyRequest(pRequest);
×
1771
    taos_close_internal(*pTscObj);
×
1772
    *pTscObj = NULL;
×
1773
    return TSDB_CODE_SUCCESS;
×
1774
  }
1775

1776
  tscInfo("conn:0x%" PRIx64 ", connection is opening, connId:%u, dnodeConn:%p, QID:0x%" PRIx64, (*pTscObj)->id,
3,106,627✔
1777
          (*pTscObj)->connId, (*pTscObj)->pAppInfo->pTransporter, pRequest->requestId);
1778
  destroyRequest(pRequest);
3,106,627✔
1779
  return code;
3,106,372✔
1780
}
1781

1782
static int32_t buildConnectMsg(SRequestObj* pRequest, SMsgSendInfo** pMsgSendInfo, int32_t totpCode) {
3,120,415✔
1783
  *pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
3,120,415✔
1784
  if (*pMsgSendInfo == NULL) {
3,120,421✔
1785
    return terrno;
×
1786
  }
1787

1788
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
3,120,670✔
1789

1790
  (*pMsgSendInfo)->requestObjRefId = pRequest->self;
3,120,415✔
1791
  (*pMsgSendInfo)->requestId = pRequest->requestId;
3,120,415✔
1792
  (*pMsgSendInfo)->fp = getMsgRspHandle((*pMsgSendInfo)->msgType);
3,120,166✔
1793
  (*pMsgSendInfo)->param = taosMemoryCalloc(1, sizeof(pRequest->self));
3,120,670✔
1794
  if (NULL == (*pMsgSendInfo)->param) {
3,120,615✔
1795
    taosMemoryFree(*pMsgSendInfo);
×
1796
    return terrno;
×
1797
  }
1798

1799
  *(int64_t*)(*pMsgSendInfo)->param = pRequest->self;
3,120,111✔
1800

1801
  SConnectReq connectReq = {0};
3,120,360✔
1802
  STscObj*    pObj = pRequest->pTscObj;
3,120,111✔
1803

1804
  char* db = getDbOfConnection(pObj);
3,120,111✔
1805
  if (db != NULL) {
3,120,670✔
1806
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
1,184,837✔
1807
  } else if (terrno) {
1,935,833✔
1808
    taosMemoryFree(*pMsgSendInfo);
×
1809
    return terrno;
×
1810
  }
1811
  taosMemoryFreeClear(db);
3,120,670✔
1812

1813
  connectReq.connType = pObj->connType;
3,120,660✔
1814
  connectReq.pid = appInfo.pid;
3,120,156✔
1815
  connectReq.startTime = appInfo.startTime;
3,120,615✔
1816
  connectReq.totpCode = totpCode;
3,120,615✔
1817

1818
  tstrncpy(connectReq.app, appInfo.appName, sizeof(connectReq.app));
3,120,615✔
1819
  tstrncpy(connectReq.user, pObj->user, sizeof(connectReq.user));
3,119,901✔
1820
  tstrncpy(connectReq.passwd, pObj->pass, sizeof(connectReq.passwd));
3,119,901✔
1821
  tstrncpy(connectReq.sVer, td_version, sizeof(connectReq.sVer));
3,120,156✔
1822

1823
  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connectReq);
3,120,156✔
1824
  void*   pReq = taosMemoryMalloc(contLen);
3,119,796✔
1825
  if (NULL == pReq) {
3,120,420✔
1826
    taosMemoryFree(*pMsgSendInfo);
×
1827
    return terrno;
×
1828
  }
1829

1830
  if (-1 == tSerializeSConnectReq(pReq, contLen, &connectReq)) {
3,120,420✔
1831
    taosMemoryFree(*pMsgSendInfo);
×
1832
    taosMemoryFree(pReq);
×
1833
    return terrno;
×
1834
  }
1835

1836
  (*pMsgSendInfo)->msgInfo.len = contLen;
3,120,163✔
1837
  (*pMsgSendInfo)->msgInfo.pData = pReq;
3,119,926✔
1838
  return TSDB_CODE_SUCCESS;
3,119,669✔
1839
}
1840

1841
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,006,040,855✔
1842
  if (NULL == pEpSet) {
1,006,040,855✔
1843
    return;
1,001,836,348✔
1844
  }
1845

1846
  switch (pSendInfo->target.type) {
4,204,507✔
1847
    case TARGET_TYPE_MNODE:
940✔
1848
      if (NULL == pTscObj) {
940✔
1849
        tscError("mnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1850
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1851
        return;
×
1852
      }
1853

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

1869
      SCatalog* pCatalog = NULL;
3,967,758✔
1870
      int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
3,968,015✔
1871
      if (code != TSDB_CODE_SUCCESS) {
3,967,446✔
1872
        tscError("fail to get catalog handle, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1873
                 tstrerror(code));
1874
        return;
×
1875
      }
1876

1877
      code = catalogUpdateVgEpSet(pCatalog, pSendInfo->target.dbFName, pSendInfo->target.vgId, pEpSet);
3,967,446✔
1878
      if (code != TSDB_CODE_SUCCESS) {
3,968,133✔
1879
        tscError("fail to update catalog vg epset, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1880
                 tstrerror(code));
1881
        return;
×
1882
      }
1883
      taosMemoryFreeClear(pSendInfo->target.dbFName);
3,968,133✔
1884
      break;
3,968,073✔
1885
    }
1886
    default:
238,523✔
1887
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
238,523✔
1888
      break;
238,613✔
1889
  }
1890
}
1891

1892
int32_t doProcessMsgFromServerImpl(SRpcMsg* pMsg, SEpSet* pEpSet) {
1,006,643,429✔
1893
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
1,006,643,429✔
1894
  if (pMsg->info.ahandle == NULL) {
1,006,645,370✔
1895
    tscError("doProcessMsgFromServer pMsg->info.ahandle == NULL");
599,920✔
1896
    rpcFreeCont(pMsg->pCont);
599,920✔
1897
    taosMemoryFree(pEpSet);
599,920✔
1898
    return TSDB_CODE_TSC_INTERNAL_ERROR;
599,920✔
1899
  }
1900

1901
  STscObj* pTscObj = NULL;
1,006,044,454✔
1902

1903
  STraceId* trace = &pMsg->info.traceId;
1,006,044,454✔
1904
  char      tbuf[40] = {0};
1,006,045,825✔
1905
  TRACE_TO_STR(trace, tbuf);
1,006,045,714✔
1906

1907
  tscDebug("QID:%s, process message from server, handle:%p, message:%s, size:%d, code:%s", tbuf, pMsg->info.handle,
1,006,045,972✔
1908
           TMSG_INFO(pMsg->msgType), pMsg->contLen, tstrerror(pMsg->code));
1909

1910
  if (pSendInfo->requestObjRefId != 0) {
1,006,047,287✔
1911
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
873,076,090✔
1912
    if (pRequest) {
873,075,627✔
1913
      if (pRequest->self != pSendInfo->requestObjRefId) {
872,763,549✔
1914
        tscError("doProcessMsgFromServer req:0x%" PRId64 " != pSendInfo->requestObjRefId:0x%" PRId64, pRequest->self,
×
1915
                 pSendInfo->requestObjRefId);
1916

1917
        if (TSDB_CODE_SUCCESS != taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId)) {
×
1918
          tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1919
        }
1920
        rpcFreeCont(pMsg->pCont);
×
1921
        taosMemoryFree(pEpSet);
×
1922
        destroySendMsgInfo(pSendInfo);
×
1923
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1924
      }
1925
      pTscObj = pRequest->pTscObj;
872,764,550✔
1926
    }
1927
  }
1928

1929
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
1,006,046,762✔
1930

1931
  SDataBuf buf = {.msgType = pMsg->msgType,
1,006,042,704✔
1932
                  .len = pMsg->contLen,
1,006,043,243✔
1933
                  .pData = NULL,
1934
                  .handle = pMsg->info.handle,
1,006,043,132✔
1935
                  .handleRefId = pMsg->info.refId,
1,006,044,515✔
1936
                  .pEpSet = pEpSet};
1937

1938
  if (pMsg->contLen > 0) {
1,006,042,221✔
1939
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
986,949,427✔
1940
    if (buf.pData == NULL) {
986,947,331✔
1941
      pMsg->code = terrno;
×
1942
    } else {
1943
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
986,947,331✔
1944
    }
1945
  }
1946

1947
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
1,006,048,384✔
1948

1949
  if (pTscObj) {
1,006,025,503✔
1950
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
872,747,167✔
1951
    if (TSDB_CODE_SUCCESS != code) {
872,764,207✔
1952
      tscError("doProcessMsgFromServer taosReleaseRef failed");
770✔
1953
      terrno = code;
770✔
1954
      pMsg->code = code;
770✔
1955
    }
1956
  }
1957

1958
  rpcFreeCont(pMsg->pCont);
1,006,042,543✔
1959
  destroySendMsgInfo(pSendInfo);
1,006,023,094✔
1960
  return TSDB_CODE_SUCCESS;
1,006,004,972✔
1961
}
1962

1963
int32_t doProcessMsgFromServer(void* param) {
1,006,644,862✔
1964
  AsyncArg* arg = (AsyncArg*)param;
1,006,644,862✔
1965
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
1,006,644,862✔
1966
  taosMemoryFree(arg);
1,006,604,033✔
1967
  return code;
1,006,601,357✔
1968
}
1969

1970
void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,006,637,668✔
1971
  int32_t code = 0;
1,006,637,668✔
1972
  SEpSet* tEpSet = NULL;
1,006,637,668✔
1973

1974
  tscDebug("msg callback, ahandle %p", pMsg->info.ahandle);
1,006,637,668✔
1975

1976
  if (pEpSet != NULL) {
1,006,636,461✔
1977
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
4,206,965✔
1978
    if (NULL == tEpSet) {
4,207,217✔
1979
      code = terrno;
×
1980
      pMsg->code = terrno;
×
1981
      goto _exit;
×
1982
    }
1983
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
4,207,217✔
1984
  }
1985

1986
  // pMsg is response msg
1987
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
1,006,636,713✔
1988
    // restore origin code
1989
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
3,120,670✔
1990
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1991
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
3,120,670✔
1992
      pMsg->code = TSDB_CODE_RPC_BROKEN_LINK;
×
1993
    }
1994
  } else {
1995
    // uniform to one error code: TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED
1996
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
1,003,519,940✔
1997
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
1998
    }
1999
  }
2000

2001
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
1,006,640,289✔
2002
  if (NULL == arg) {
1,006,632,390✔
2003
    code = terrno;
×
2004
    pMsg->code = code;
×
2005
    goto _exit;
×
2006
  }
2007

2008
  arg->msg = *pMsg;
1,006,632,390✔
2009
  arg->pEpset = tEpSet;
1,006,636,149✔
2010

2011
  if ((code = taosAsyncExec(doProcessMsgFromServer, arg, NULL)) != 0) {
1,006,640,531✔
2012
    pMsg->code = code;
28✔
2013
    taosMemoryFree(arg);
28✔
2014
    goto _exit;
×
2015
  }
2016
  return;
1,006,642,871✔
2017

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

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

2033
  if (pass == NULL) {
×
2034
    pass = TSDB_DEFAULT_PASS;
×
2035
  }
2036

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

2051
  return NULL;
×
2052
}
2053

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

2061
  if (pass == NULL) {
×
2062
    pass = TSDB_DEFAULT_PASS;
×
2063
  }
2064

2065
  STscObj* pObj = NULL;
×
2066
  return taos_connect_internal(ip, user, pass, NULL, totp, db, port, CONN_TYPE__AUTH_TEST, &pObj);
×
2067
}
2068

2069
TAOS* taos_connect_token(const char* ip, const char* token, const char* db, uint16_t port) { return NULL; }
×
2070

2071
TAOS* taos_connect_auth(const char* ip, const char* user, const char* auth, const char* db, uint16_t port) {
552✔
2072
  tscInfo("try to connect to %s:%u by auth, user:%s db:%s", ip, port, user, db);
552✔
2073
  if (user == NULL) {
552✔
2074
    user = TSDB_DEFAULT_USER;
×
2075
  }
2076

2077
  if (auth == NULL) {
552✔
2078
    tscError("No auth info is given, failed to connect to server");
×
2079
    return NULL;
×
2080
  }
2081

2082
  STscObj* pObj = NULL;
552✔
2083
  int32_t  code = taos_connect_internal(ip, user, NULL, auth, NULL, db, port, CONN_TYPE__QUERY, &pObj);
552✔
2084
  if (TSDB_CODE_SUCCESS == code) {
552✔
2085
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
134✔
2086
    if (NULL == rid) {
134✔
2087
      tscError("out of memory when taos connect to %s:%u, user:%s db:%s", ip, port, user, db);
×
2088
    }
2089
    *rid = pObj->id;
134✔
2090
    return (TAOS*)rid;
134✔
2091
  }
2092

2093
  return NULL;
418✔
2094
}
2095

2096
// TAOS* taos_connect_l(const char* ip, int ipLen, const char* user, int userLen, const char* pass, int passLen,
2097
//                      const char* db, int dbLen, uint16_t port) {
2098
//   char ipStr[TSDB_EP_LEN] = {0};
2099
//   char dbStr[TSDB_DB_NAME_LEN] = {0};
2100
//   char userStr[TSDB_USER_LEN] = {0};
2101
//   char passStr[TSDB_PASSWORD_LEN] = {0};
2102
//
2103
//   tstrncpy(ipStr, ip, TMIN(TSDB_EP_LEN - 1, ipLen));
2104
//   tstrncpy(userStr, user, TMIN(TSDB_USER_LEN - 1, userLen));
2105
//   tstrncpy(passStr, pass, TMIN(TSDB_PASSWORD_LEN - 1, passLen));
2106
//   tstrncpy(dbStr, db, TMIN(TSDB_DB_NAME_LEN - 1, dbLen));
2107
//   return taos_connect(ipStr, userStr, passStr, dbStr, port);
2108
// }
2109

2110
void doSetOneRowPtr(SReqResultInfo* pResultInfo) {
2,147,483,647✔
2111
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
2,147,483,647✔
2112
    SResultColumn* pCol = &pResultInfo->pCol[i];
2,147,483,647✔
2113

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

2117
    if (IS_VAR_DATA_TYPE(type)) {
2,147,483,647✔
2118
      if (!IS_VAR_NULL_TYPE(type, schemaBytes) && pCol->offset[pResultInfo->current] != -1) {
2,147,483,647✔
2119
        char* pStart = pResultInfo->pCol[i].offset[pResultInfo->current] + pResultInfo->pCol[i].pData;
1,962,623,520✔
2120

2121
        if (IS_STR_DATA_BLOB(type)) {
1,962,819,095✔
2122
          pResultInfo->length[i] = blobDataLen(pStart);
111,325✔
2123
          pResultInfo->row[i] = blobDataVal(pStart);
55✔
2124
        } else {
2125
          pResultInfo->length[i] = varDataLen(pStart);
1,962,707,770✔
2126
          pResultInfo->row[i] = varDataVal(pStart);
1,962,698,840✔
2127
        }
2128
      } else {
2129
        pResultInfo->row[i] = NULL;
24,469,418✔
2130
        pResultInfo->length[i] = 0;
24,701,351✔
2131
      }
2132
    } else {
2133
      if (!colDataIsNull_f(pCol, pResultInfo->current)) {
2,147,483,647✔
2134
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + schemaBytes * pResultInfo->current;
2,147,483,647✔
2135
        pResultInfo->length[i] = schemaBytes;
2,147,483,647✔
2136
      } else {
2137
        pResultInfo->row[i] = NULL;
157,089,479✔
2138
        pResultInfo->length[i] = 0;
158,718,928✔
2139
      }
2140
    }
2141
  }
2142
}
2,147,483,647✔
2143

2144
void* doFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
×
2145
  if (pRequest == NULL) {
×
2146
    return NULL;
×
2147
  }
2148

2149
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
×
2150
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
×
2151
    // All data has returned to App already, no need to try again
2152
    if (pResultInfo->completed) {
×
2153
      pResultInfo->numOfRows = 0;
×
2154
      return NULL;
×
2155
    }
2156

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

2160
    pRequest->code = schedulerFetchRows(pRequest->body.queryJob, &req);
×
2161
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2162
      pResultInfo->numOfRows = 0;
×
2163
      return NULL;
×
2164
    }
2165

2166
    pRequest->code = setQueryResultFromRsp(&pRequest->body.resInfo, (const SRetrieveTableRsp*)pResInfo->pData,
×
2167
                                           convertUcs4, pRequest->stmtBindVersion > 0);
×
2168
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2169
      pResultInfo->numOfRows = 0;
×
2170
      return NULL;
×
2171
    }
2172

2173
    tscDebug("req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64
×
2174
             ", complete:%d, QID:0x%" PRIx64,
2175
             pRequest->self, pResInfo->numOfRows, pResInfo->totalRows, pResInfo->completed, pRequest->requestId);
2176

2177
    STscObj*            pTscObj = pRequest->pTscObj;
×
2178
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
×
2179
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
×
2180

2181
    if (pResultInfo->numOfRows == 0) {
×
2182
      return NULL;
×
2183
    }
2184
  }
2185

2186
  if (setupOneRowPtr) {
×
2187
    doSetOneRowPtr(pResultInfo);
×
2188
    pResultInfo->current += 1;
×
2189
  }
2190

2191
  return pResultInfo->row;
×
2192
}
2193

2194
static void syncFetchFn(void* param, TAOS_RES* res, int32_t numOfRows) {
89,696,329✔
2195
  tsem_t* sem = param;
89,696,329✔
2196
  if (TSDB_CODE_SUCCESS != tsem_post(sem)) {
89,696,329✔
2197
    tscError("failed to post sem, code:%s", terrstr());
×
2198
  }
2199
}
89,696,750✔
2200

2201
void* doAsyncFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
1,461,460,861✔
2202
  if (pRequest == NULL) {
1,461,460,861✔
2203
    return NULL;
×
2204
  }
2205

2206
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
1,461,460,861✔
2207
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
1,461,488,175✔
2208
    // All data has returned to App already, no need to try again
2209
    if (pResultInfo->completed) {
159,777,963✔
2210
      pResultInfo->numOfRows = 0;
70,090,880✔
2211
      return NULL;
70,090,880✔
2212
    }
2213

2214
    // convert ucs4 to native multi-bytes string
2215
    pResultInfo->convertUcs4 = convertUcs4;
89,695,317✔
2216
    tsem_t sem;
88,788,176✔
2217
    if (TSDB_CODE_SUCCESS != tsem_init(&sem, 0, 0)) {
89,695,935✔
2218
      tscError("failed to init sem, code:%s", terrstr());
×
2219
    }
2220
    taos_fetch_rows_a(pRequest, syncFetchFn, &sem);
89,696,123✔
2221
    if (TSDB_CODE_SUCCESS != tsem_wait(&sem)) {
89,696,750✔
2222
      tscError("failed to wait sem, code:%s", terrstr());
×
2223
    }
2224
    if (TSDB_CODE_SUCCESS != tsem_destroy(&sem)) {
89,696,750✔
2225
      tscError("failed to destroy sem, code:%s", terrstr());
×
2226
    }
2227
    pRequest->inCallback = false;
89,696,750✔
2228
  }
2229

2230
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
1,391,420,328✔
2231
    return NULL;
6,714,520✔
2232
  } else {
2233
    if (setupOneRowPtr) {
1,384,649,762✔
2234
      doSetOneRowPtr(pResultInfo);
1,303,626,033✔
2235
      pResultInfo->current += 1;
1,303,637,086✔
2236
    }
2237

2238
    return pResultInfo->row;
1,384,662,050✔
2239
  }
2240
}
2241

2242
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
117,424,552✔
2243
  if (pResInfo->row == NULL) {
117,424,552✔
2244
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
102,745,700✔
2245
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
102,745,279✔
2246
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
102,744,392✔
2247
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
102,744,826✔
2248

2249
    if (pResInfo->row == NULL || pResInfo->pCol == NULL || pResInfo->length == NULL || pResInfo->convertBuf == NULL) {
102,744,526✔
2250
      taosMemoryFree(pResInfo->row);
364✔
2251
      taosMemoryFree(pResInfo->pCol);
×
2252
      taosMemoryFree(pResInfo->length);
×
2253
      taosMemoryFree(pResInfo->convertBuf);
×
2254
      return terrno;
×
2255
    }
2256
  }
2257

2258
  return TSDB_CODE_SUCCESS;
117,424,370✔
2259
}
2260

2261
static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength, bool isStmt) {
117,178,495✔
2262
  int32_t idx = -1;
117,178,495✔
2263
  iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt);
117,178,768✔
2264
  if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR;
117,177,833✔
2265

2266
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
676,432,251✔
2267
    int32_t type = pResultInfo->fields[i].type;
559,259,544✔
2268
    int32_t schemaBytes =
2269
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
559,259,883✔
2270

2271
    if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) {
559,258,340✔
2272
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
19,250,383✔
2273
      if (p == NULL) {
19,250,383✔
2274
        taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
×
2275
        return terrno;
×
2276
      }
2277

2278
      pResultInfo->convertBuf[i] = p;
19,250,383✔
2279

2280
      SResultColumn* pCol = &pResultInfo->pCol[i];
19,250,383✔
2281
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
2,147,483,647✔
2282
        if (pCol->offset[j] != -1) {
2,147,483,647✔
2283
          char* pStart = pCol->offset[j] + pCol->pData;
2,147,483,647✔
2284

2285
          int32_t len = taosUcs4ToMbsEx((TdUcs4*)varDataVal(pStart), varDataLen(pStart), varDataVal(p), conv);
2,147,483,647✔
2286
          if (len < 0 || len > schemaBytes || (p + len) >= (pResultInfo->convertBuf[i] + colLength[i])) {
2,147,483,647✔
2287
            tscError(
76✔
2288
                "doConvertUCS4 error, invalid data. len:%d, bytes:%d, (p + len):%p, (pResultInfo->convertBuf[i] + "
2289
                "colLength[i]):%p",
2290
                len, schemaBytes, (p + len), (pResultInfo->convertBuf[i] + colLength[i]));
2291
            taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
76✔
2292
            return TSDB_CODE_TSC_INTERNAL_ERROR;
76✔
2293
          }
2294

2295
          varDataSetLen(p, len);
2,147,483,647✔
2296
          pCol->offset[j] = (p - pResultInfo->convertBuf[i]);
2,147,483,647✔
2297
          p += (len + VARSTR_HEADER_SIZE);
2,147,483,647✔
2298
        }
2299
      }
2300

2301
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
19,250,307✔
2302
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
19,250,307✔
2303
    }
2304
  }
2305
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
117,180,143✔
2306
  return TSDB_CODE_SUCCESS;
117,179,521✔
2307
}
2308

2309
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
117,178,256✔
2310
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
676,434,373✔
2311
    TAOS_FIELD_E* pFieldE = pResultInfo->fields + i;
559,260,218✔
2312
    TAOS_FIELD*   pField = pResultInfo->userFields + i;
559,258,702✔
2313
    int32_t       type = pFieldE->type;
559,259,654✔
2314
    int32_t       bufLen = 0;
559,259,518✔
2315
    char*         p = NULL;
559,259,518✔
2316
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
559,259,518✔
2317
      continue;
557,273,987✔
2318
    } else {
2319
      bufLen = 64;
1,985,003✔
2320
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
1,985,003✔
2321
      pFieldE->bytes = bufLen;
1,985,003✔
2322
      pField->bytes = bufLen;
1,985,003✔
2323
    }
2324
    if (!p) return terrno;
1,985,003✔
2325
    pResultInfo->convertBuf[i] = p;
1,985,003✔
2326

2327
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
1,502,958,387✔
2328
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
1,500,973,384✔
2329
                                  pFieldE->precision, pFieldE->scale, p, bufLen);
1,500,973,384✔
2330
      p += bufLen;
1,500,973,384✔
2331
      if (TSDB_CODE_SUCCESS != code) {
1,500,973,384✔
2332
        return code;
×
2333
      }
2334
    }
2335
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
1,985,003✔
2336
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
1,985,003✔
2337
  }
2338
  return 0;
117,179,273✔
2339
}
2340

2341
int32_t getVersion1BlockMetaSize(const char* p, int32_t numOfCols) {
390,928✔
2342
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) * 3 + sizeof(uint64_t) +
781,856✔
2343
         numOfCols * (sizeof(int8_t) + sizeof(int32_t));
390,928✔
2344
}
2345

2346
static int32_t estimateJsonLen(SReqResultInfo* pResultInfo) {
195,464✔
2347
  char*   p = (char*)pResultInfo->pData;
195,464✔
2348
  int32_t blockVersion = *(int32_t*)p;
195,464✔
2349

2350
  int32_t numOfRows = pResultInfo->numOfRows;
195,464✔
2351
  int32_t numOfCols = pResultInfo->numOfCols;
195,464✔
2352

2353
  // | version | total length | total rows | total columns | flag seg| block group id | column schema | each column
2354
  // length |
2355
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
195,464✔
2356
  if (numOfCols != cols) {
195,464✔
2357
    tscError("estimateJsonLen error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2358
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2359
  }
2360

2361
  int32_t  len = getVersion1BlockMetaSize(p, numOfCols);
195,464✔
2362
  int32_t* colLength = (int32_t*)(p + len);
195,464✔
2363
  len += sizeof(int32_t) * numOfCols;
195,464✔
2364

2365
  char* pStart = p + len;
195,464✔
2366
  for (int32_t i = 0; i < numOfCols; ++i) {
849,687✔
2367
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
654,223✔
2368

2369
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
654,223✔
2370
      int32_t* offset = (int32_t*)pStart;
231,470✔
2371
      int32_t  lenTmp = numOfRows * sizeof(int32_t);
231,470✔
2372
      len += lenTmp;
231,470✔
2373
      pStart += lenTmp;
231,470✔
2374

2375
      int32_t estimateColLen = 0;
231,470✔
2376
      for (int32_t j = 0; j < numOfRows; ++j) {
1,208,649✔
2377
        if (offset[j] == -1) {
977,179✔
2378
          continue;
49,198✔
2379
        }
2380
        char* data = offset[j] + pStart;
927,981✔
2381

2382
        int32_t jsonInnerType = *data;
927,981✔
2383
        char*   jsonInnerData = data + CHAR_BYTES;
927,981✔
2384
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
927,981✔
2385
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
13,080✔
2386
        } else if (tTagIsJson(data)) {
914,901✔
2387
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
215,742✔
2388
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
699,159✔
2389
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
650,109✔
2390
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
49,050✔
2391
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
35,970✔
2392
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
13,080✔
2393
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
13,080✔
2394
        } else if (IS_STR_DATA_BLOB(jsonInnerType)) {
×
2395
          estimateColLen += (BLOBSTR_HEADER_SIZE + 32);
×
2396
        } else {
2397
          tscError("estimateJsonLen error: invalid type:%d", jsonInnerType);
×
2398
          return -1;
×
2399
        }
2400
      }
2401
      len += TMAX(colLen, estimateColLen);
231,470✔
2402
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
422,753✔
2403
      int32_t lenTmp = numOfRows * sizeof(int32_t);
54,500✔
2404
      len += (lenTmp + colLen);
54,500✔
2405
      pStart += lenTmp;
54,500✔
2406
    } else {
2407
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
368,253✔
2408
      len += (lenTmp + colLen);
368,253✔
2409
      pStart += lenTmp;
368,253✔
2410
    }
2411
    pStart += colLen;
654,223✔
2412
  }
2413

2414
  // Ensure the complete structure of the block, including the blankfill field,
2415
  // even though it is not used on the client side.
2416
  len += sizeof(bool);
195,464✔
2417
  return len;
195,464✔
2418
}
2419

2420
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
117,424,958✔
2421
  int32_t numOfRows = pResultInfo->numOfRows;
117,424,958✔
2422
  int32_t numOfCols = pResultInfo->numOfCols;
117,425,519✔
2423
  bool    needConvert = false;
117,424,774✔
2424
  for (int32_t i = 0; i < numOfCols; ++i) {
677,881,804✔
2425
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
560,651,203✔
2426
      needConvert = true;
195,464✔
2427
      break;
195,464✔
2428
    }
2429
  }
2430

2431
  if (!needConvert) {
117,426,065✔
2432
    return TSDB_CODE_SUCCESS;
117,230,601✔
2433
  }
2434

2435
  tscDebug("start to convert form json format string");
195,464✔
2436

2437
  char*   p = (char*)pResultInfo->pData;
195,464✔
2438
  int32_t blockVersion = *(int32_t*)p;
195,464✔
2439
  int32_t dataLen = estimateJsonLen(pResultInfo);
195,464✔
2440
  if (dataLen <= 0) {
195,464✔
2441
    tscError("doConvertJson error: estimateJsonLen failed");
×
2442
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2443
  }
2444

2445
  taosMemoryFreeClear(pResultInfo->convertJson);
195,464✔
2446
  pResultInfo->convertJson = taosMemoryCalloc(1, dataLen);
195,464✔
2447
  if (pResultInfo->convertJson == NULL) return terrno;
195,464✔
2448
  char* p1 = pResultInfo->convertJson;
195,464✔
2449

2450
  int32_t totalLen = 0;
195,464✔
2451
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
195,464✔
2452
  if (numOfCols != cols) {
195,464✔
2453
    tscError("doConvertJson error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2454
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2455
  }
2456

2457
  int32_t len = getVersion1BlockMetaSize(p, numOfCols);
195,464✔
2458
  (void)memcpy(p1, p, len);
195,464✔
2459

2460
  p += len;
195,464✔
2461
  p1 += len;
195,464✔
2462
  totalLen += len;
195,464✔
2463

2464
  len = sizeof(int32_t) * numOfCols;
195,464✔
2465
  int32_t* colLength = (int32_t*)p;
195,464✔
2466
  int32_t* colLength1 = (int32_t*)p1;
195,464✔
2467
  (void)memcpy(p1, p, len);
195,464✔
2468
  p += len;
195,464✔
2469
  p1 += len;
195,464✔
2470
  totalLen += len;
195,464✔
2471

2472
  char* pStart = p;
195,464✔
2473
  char* pStart1 = p1;
195,464✔
2474
  for (int32_t i = 0; i < numOfCols; ++i) {
849,687✔
2475
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
654,223✔
2476
    int32_t colLen1 = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength1[i]) : colLength1[i];
654,223✔
2477
    if (colLen >= dataLen) {
654,223✔
2478
      tscError("doConvertJson error: colLen:%d >= dataLen:%d", colLen, dataLen);
×
2479
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2480
    }
2481
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
654,223✔
2482
      int32_t* offset = (int32_t*)pStart;
231,470✔
2483
      int32_t* offset1 = (int32_t*)pStart1;
231,470✔
2484
      len = numOfRows * sizeof(int32_t);
231,470✔
2485
      (void)memcpy(pStart1, pStart, len);
231,470✔
2486
      pStart += len;
231,470✔
2487
      pStart1 += len;
231,470✔
2488
      totalLen += len;
231,470✔
2489

2490
      len = 0;
231,470✔
2491
      for (int32_t j = 0; j < numOfRows; ++j) {
1,208,649✔
2492
        if (offset[j] == -1) {
977,179✔
2493
          continue;
49,198✔
2494
        }
2495
        char* data = offset[j] + pStart;
927,981✔
2496

2497
        int32_t jsonInnerType = *data;
927,981✔
2498
        char*   jsonInnerData = data + CHAR_BYTES;
927,981✔
2499
        char    dst[TSDB_MAX_JSON_TAG_LEN] = {0};
927,981✔
2500
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
927,981✔
2501
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s", TSDB_DATA_NULL_STR_L);
13,080✔
2502
          varDataSetLen(dst, strlen(varDataVal(dst)));
13,080✔
2503
        } else if (tTagIsJson(data)) {
914,901✔
2504
          char* jsonString = NULL;
215,742✔
2505
          parseTagDatatoJson(data, &jsonString, pResultInfo->charsetCxt);
215,742✔
2506
          if (jsonString == NULL) {
215,742✔
2507
            tscError("doConvertJson error: parseTagDatatoJson failed");
×
2508
            return terrno;
×
2509
          }
2510
          STR_TO_VARSTR(dst, jsonString);
215,742✔
2511
          taosMemoryFree(jsonString);
215,742✔
2512
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
699,159✔
2513
          *(char*)varDataVal(dst) = '\"';
650,109✔
2514
          char    tmp[TSDB_MAX_JSON_TAG_LEN] = {0};
650,109✔
2515
          int32_t length = taosUcs4ToMbs((TdUcs4*)varDataVal(jsonInnerData), varDataLen(jsonInnerData), varDataVal(tmp),
650,109✔
2516
                                         pResultInfo->charsetCxt);
2517
          if (length <= 0) {
650,109✔
2518
            tscError("charset:%s to %s. convert failed.", DEFAULT_UNICODE_ENCODEC,
545✔
2519
                     pResultInfo->charsetCxt != NULL ? ((SConvInfo*)(pResultInfo->charsetCxt))->charset : tsCharset);
2520
            length = 0;
545✔
2521
          }
2522
          int32_t escapeLength = escapeToPrinted(varDataVal(dst) + CHAR_BYTES, TSDB_MAX_JSON_TAG_LEN - CHAR_BYTES * 2,
650,109✔
2523
                                                 varDataVal(tmp), length);
2524
          varDataSetLen(dst, escapeLength + CHAR_BYTES * 2);
650,109✔
2525
          *(char*)POINTER_SHIFT(varDataVal(dst), escapeLength + CHAR_BYTES) = '\"';
650,109✔
2526
          tscError("value:%s.", varDataVal(dst));
650,109✔
2527
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
49,050✔
2528
          double jsonVd = *(double*)(jsonInnerData);
35,970✔
2529
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%.9lf", jsonVd);
35,970✔
2530
          varDataSetLen(dst, strlen(varDataVal(dst)));
35,970✔
2531
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
13,080✔
2532
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s",
13,080✔
2533
                         (*((char*)jsonInnerData) == 1) ? "true" : "false");
13,080✔
2534
          varDataSetLen(dst, strlen(varDataVal(dst)));
13,080✔
2535
        } else {
2536
          tscError("doConvertJson error: invalid type:%d", jsonInnerType);
×
2537
          return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2538
        }
2539

2540
        offset1[j] = len;
927,981✔
2541
        (void)memcpy(pStart1 + len, dst, varDataTLen(dst));
927,981✔
2542
        len += varDataTLen(dst);
927,981✔
2543
      }
2544
      colLen1 = len;
231,470✔
2545
      totalLen += colLen1;
231,470✔
2546
      colLength1[i] = (blockVersion == BLOCK_VERSION_1) ? htonl(len) : len;
231,470✔
2547
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
422,753✔
2548
      len = numOfRows * sizeof(int32_t);
54,500✔
2549
      (void)memcpy(pStart1, pStart, len);
54,500✔
2550
      pStart += len;
54,500✔
2551
      pStart1 += len;
54,500✔
2552
      totalLen += len;
54,500✔
2553
      totalLen += colLen;
54,500✔
2554
      (void)memcpy(pStart1, pStart, colLen);
54,500✔
2555
    } else {
2556
      len = BitmapLen(pResultInfo->numOfRows);
368,253✔
2557
      (void)memcpy(pStart1, pStart, len);
368,253✔
2558
      pStart += len;
368,253✔
2559
      pStart1 += len;
368,253✔
2560
      totalLen += len;
368,253✔
2561
      totalLen += colLen;
368,253✔
2562
      (void)memcpy(pStart1, pStart, colLen);
368,253✔
2563
    }
2564
    pStart += colLen;
654,223✔
2565
    pStart1 += colLen1;
654,223✔
2566
  }
2567

2568
  // Ensure the complete structure of the block, including the blankfill field,
2569
  // even though it is not used on the client side.
2570
  // (void)memcpy(pStart1, pStart, sizeof(bool));
2571
  totalLen += sizeof(bool);
195,464✔
2572

2573
  *(int32_t*)(pResultInfo->convertJson + 4) = totalLen;
195,464✔
2574
  pResultInfo->pData = pResultInfo->convertJson;
195,464✔
2575
  return TSDB_CODE_SUCCESS;
195,464✔
2576
}
2577

2578
int32_t setResultDataPtr(SReqResultInfo* pResultInfo, bool convertUcs4, bool isStmt) {
124,164,890✔
2579
  bool convertForDecimal = convertUcs4;
124,164,890✔
2580
  if (pResultInfo == NULL || pResultInfo->numOfCols <= 0 || pResultInfo->fields == NULL) {
124,164,890✔
2581
    tscError("setResultDataPtr paras error");
165✔
2582
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2583
  }
2584

2585
  if (pResultInfo->numOfRows == 0) {
124,164,853✔
2586
    return TSDB_CODE_SUCCESS;
6,740,200✔
2587
  }
2588

2589
  if (pResultInfo->pData == NULL) {
117,425,147✔
2590
    tscError("setResultDataPtr error: pData is NULL");
×
2591
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2592
  }
2593

2594
  int32_t code = doPrepareResPtr(pResultInfo);
117,425,303✔
2595
  if (code != TSDB_CODE_SUCCESS) {
117,424,137✔
2596
    return code;
×
2597
  }
2598
  code = doConvertJson(pResultInfo);
117,424,137✔
2599
  if (code != TSDB_CODE_SUCCESS) {
117,424,203✔
2600
    return code;
×
2601
  }
2602

2603
  char* p = (char*)pResultInfo->pData;
117,424,203✔
2604

2605
  // version:
2606
  int32_t blockVersion = *(int32_t*)p;
117,424,385✔
2607
  p += sizeof(int32_t);
117,424,774✔
2608

2609
  int32_t dataLen = *(int32_t*)p;
117,424,840✔
2610
  p += sizeof(int32_t);
117,424,947✔
2611

2612
  int32_t rows = *(int32_t*)p;
117,425,005✔
2613
  p += sizeof(int32_t);
117,424,965✔
2614

2615
  int32_t cols = *(int32_t*)p;
117,425,031✔
2616
  p += sizeof(int32_t);
117,424,593✔
2617

2618
  if (rows != pResultInfo->numOfRows || cols != pResultInfo->numOfCols) {
117,425,179✔
UNCOV
2619
    tscError("setResultDataPtr paras error:rows;%d numOfRows:%" PRId64 " cols:%d numOfCols:%d", rows,
×
2620
             pResultInfo->numOfRows, cols, pResultInfo->numOfCols);
2621
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2622
  }
2623

2624
  int32_t hasColumnSeg = *(int32_t*)p;
117,424,825✔
2625
  p += sizeof(int32_t);
117,423,499✔
2626

2627
  uint64_t groupId = taosGetUInt64Aligned((uint64_t*)p);
117,425,088✔
2628
  p += sizeof(uint64_t);
117,425,088✔
2629

2630
  // check fields
2631
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
678,125,959✔
2632
    int8_t type = *(int8_t*)p;
560,703,801✔
2633
    p += sizeof(int8_t);
560,703,090✔
2634

2635
    int32_t bytes = *(int32_t*)p;
560,702,963✔
2636
    p += sizeof(int32_t);
560,704,298✔
2637

2638
    if (IS_DECIMAL_TYPE(type) && pResultInfo->fields[i].precision == 0) {
560,702,394✔
2639
      extractDecimalTypeInfoFromBytes(&bytes, &pResultInfo->fields[i].precision, &pResultInfo->fields[i].scale);
316,228✔
2640
    }
2641
  }
2642

2643
  int32_t* colLength = (int32_t*)p;
117,425,750✔
2644
  p += sizeof(int32_t) * pResultInfo->numOfCols;
117,425,750✔
2645

2646
  char* pStart = p;
117,425,644✔
2647
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
678,130,175✔
2648
    if ((pStart - pResultInfo->pData) >= dataLen) {
560,703,918✔
2649
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2650
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2651
    }
2652
    if (blockVersion == BLOCK_VERSION_1) {
560,703,191✔
2653
      colLength[i] = htonl(colLength[i]);
423,149,951✔
2654
    }
2655
    if (colLength[i] >= dataLen) {
560,704,241✔
2656
      tscError("invalid colLength %d, dataLen %d", colLength[i], dataLen);
×
2657
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2658
    }
2659
    if (IS_INVALID_TYPE(pResultInfo->fields[i].type)) {
560,704,350✔
2660
      tscError("invalid type %d", pResultInfo->fields[i].type);
9✔
2661
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2662
    }
2663
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
560,705,234✔
2664
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
138,415,227✔
2665
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
138,412,629✔
2666
    } else {
2667
      pResultInfo->pCol[i].nullbitmap = pStart;
422,295,106✔
2668
      pStart += BitmapLen(pResultInfo->numOfRows);
422,295,999✔
2669
    }
2670

2671
    pResultInfo->pCol[i].pData = pStart;
560,707,573✔
2672
    pResultInfo->length[i] =
1,121,411,110✔
2673
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
1,115,213,750✔
2674
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
560,704,837✔
2675

2676
    pStart += colLength[i];
560,704,612✔
2677
  }
2678

2679
  p = pStart;
117,426,065✔
2680
  // bool blankFill = *(bool*)p;
2681
  p += sizeof(bool);
117,426,065✔
2682
  int32_t offset = p - pResultInfo->pData;
117,426,156✔
2683
  if (offset > dataLen) {
117,424,681✔
2684
    tscError("invalid offset %d, dataLen %d", offset, dataLen);
×
2685
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2686
  }
2687

2688
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
2689
  if (convertUcs4) {
117,424,681✔
2690
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
117,178,747✔
2691
  }
2692
#endif
2693
  if (TSDB_CODE_SUCCESS == code && convertForDecimal) {
117,425,531✔
2694
    code = convertDecimalType(pResultInfo);
117,179,521✔
2695
  }
2696
  return code;
117,425,104✔
2697
}
2698

2699
char* getDbOfConnection(STscObj* pObj) {
646,450,062✔
2700
  terrno = TSDB_CODE_SUCCESS;
646,450,062✔
2701
  char* p = NULL;
646,449,282✔
2702
  (void)taosThreadMutexLock(&pObj->mutex);
646,449,282✔
2703
  size_t len = strlen(pObj->db);
646,454,653✔
2704
  if (len > 0) {
646,455,901✔
2705
    p = taosStrndup(pObj->db, tListLen(pObj->db));
575,999,429✔
2706
    if (p == NULL) {
575,996,765✔
2707
      tscError("failed to taosStrndup db name");
×
2708
    }
2709
  }
2710

2711
  (void)taosThreadMutexUnlock(&pObj->mutex);
646,453,237✔
2712
  return p;
646,448,440✔
2713
}
2714

2715
void setConnectionDB(STscObj* pTscObj, const char* db) {
2,466,208✔
2716
  if (db == NULL || pTscObj == NULL) {
2,466,208✔
2717
    tscError("setConnectionDB para is NULL");
×
2718
    return;
×
2719
  }
2720

2721
  (void)taosThreadMutexLock(&pTscObj->mutex);
2,466,208✔
2722
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
2,466,208✔
2723
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
2,466,208✔
2724
}
2725

2726
void resetConnectDB(STscObj* pTscObj) {
×
2727
  if (pTscObj == NULL) {
×
2728
    return;
×
2729
  }
2730

2731
  (void)taosThreadMutexLock(&pTscObj->mutex);
×
2732
  pTscObj->db[0] = 0;
×
2733
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
×
2734
}
2735

2736
int32_t setQueryResultFromRsp(SReqResultInfo* pResultInfo, const SRetrieveTableRsp* pRsp, bool convertUcs4,
93,950,079✔
2737
                              bool isStmt) {
2738
  if (pResultInfo == NULL || pRsp == NULL) {
93,950,079✔
2739
    tscError("setQueryResultFromRsp paras is null");
×
2740
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2741
  }
2742

2743
  taosMemoryFreeClear(pResultInfo->pRspMsg);
93,950,079✔
2744
  pResultInfo->pRspMsg = (const char*)pRsp;
93,949,829✔
2745
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
93,949,855✔
2746
  pResultInfo->current = 0;
93,950,303✔
2747
  pResultInfo->completed = (pRsp->completed == 1);
93,950,303✔
2748
  pResultInfo->precision = pRsp->precision;
93,950,079✔
2749

2750
  // decompress data if needed
2751
  int32_t payloadLen = htonl(pRsp->payloadLen);
93,949,594✔
2752

2753
  if (pRsp->compressed) {
93,950,303✔
2754
    if (pResultInfo->decompBuf == NULL) {
×
2755
      pResultInfo->decompBuf = taosMemoryMalloc(payloadLen);
×
2756
      if (pResultInfo->decompBuf == NULL) {
×
2757
        tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2758
        return terrno;
×
2759
      }
2760
      pResultInfo->decompBufSize = payloadLen;
×
2761
    } else {
2762
      if (pResultInfo->decompBufSize < payloadLen) {
×
2763
        char* p = taosMemoryRealloc(pResultInfo->decompBuf, payloadLen);
×
2764
        if (p == NULL) {
×
2765
          tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2766
          return terrno;
×
2767
        }
2768

2769
        pResultInfo->decompBuf = p;
×
2770
        pResultInfo->decompBufSize = payloadLen;
×
2771
      }
2772
    }
2773
  }
2774

2775
  if (payloadLen > 0) {
93,949,594✔
2776
    int32_t compLen = *(int32_t*)pRsp->data;
87,210,269✔
2777
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
87,210,493✔
2778

2779
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
87,210,232✔
2780

2781
    if (pRsp->compressed && compLen < rawLen) {
87,210,269✔
2782
      int32_t len = tsDecompressString(pStart, compLen, 1, pResultInfo->decompBuf, rawLen, ONE_STAGE_COMP, NULL, 0);
×
2783
      if (len < 0) {
×
2784
        tscError("tsDecompressString failed");
×
2785
        return terrno ? terrno : TSDB_CODE_FAILED;
×
2786
      }
2787
      if (len != rawLen) {
×
2788
        tscError("tsDecompressString failed, len:%d != rawLen:%d", len, rawLen);
×
2789
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2790
      }
2791
      pResultInfo->pData = pResultInfo->decompBuf;
×
2792
      pResultInfo->payloadLen = rawLen;
×
2793
    } else {
2794
      pResultInfo->pData = pStart;
87,210,045✔
2795
      pResultInfo->payloadLen = htonl(pRsp->compLen);
87,210,008✔
2796
      if (pRsp->compLen != pRsp->payloadLen) {
87,209,337✔
2797
        tscError("pRsp->compLen:%d != pRsp->payloadLen:%d", pRsp->compLen, pRsp->payloadLen);
×
2798
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2799
      }
2800
    }
2801
  }
2802

2803
  // TODO handle the compressed case
2804
  pResultInfo->totalRows += pResultInfo->numOfRows;
93,948,707✔
2805

2806
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
93,950,106✔
2807
  return code;
93,949,829✔
2808
}
2809

2810
TSDB_SERVER_STATUS taos_check_server_status(const char* fqdn, int port, char* details, int maxlen) {
704✔
2811
  TSDB_SERVER_STATUS code = TSDB_SRV_STATUS_UNAVAILABLE;
704✔
2812
  void*              clientRpc = NULL;
704✔
2813
  SServerStatusRsp   statusRsp = {0};
704✔
2814
  SEpSet             epSet = {.inUse = 0, .numOfEps = 1};
704✔
2815
  SRpcMsg  rpcMsg = {.info.ahandle = (void*)0x9527, .info.notFreeAhandle = 1, .msgType = TDMT_DND_SERVER_STATUS};
704✔
2816
  SRpcMsg  rpcRsp = {0};
704✔
2817
  SRpcInit rpcInit = {0};
704✔
2818
  char     pass[TSDB_PASSWORD_LEN + 1] = {0};
704✔
2819

2820
  rpcInit.label = "CHK";
704✔
2821
  rpcInit.numOfThreads = 1;
704✔
2822
  rpcInit.cfp = NULL;
704✔
2823
  rpcInit.sessions = 16;
704✔
2824
  rpcInit.connType = TAOS_CONN_CLIENT;
704✔
2825
  rpcInit.idleTime = tsShellActivityTimer * 1000;
704✔
2826
  rpcInit.compressSize = tsCompressMsgSize;
704✔
2827
  rpcInit.user = "_dnd";
704✔
2828

2829
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
704✔
2830
  connLimitNum = TMAX(connLimitNum, 10);
704✔
2831
  connLimitNum = TMIN(connLimitNum, 500);
704✔
2832
  rpcInit.connLimitNum = connLimitNum;
704✔
2833
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
704✔
2834
  rpcInit.readTimeout = tsReadTimeout;
704✔
2835
  rpcInit.ipv6 = tsEnableIpv6;
704✔
2836
  rpcInit.enableSSL = tsEnableTLS;
704✔
2837

2838
  memcpy(rpcInit.caPath, tsTLSCaPath, strlen(tsTLSCaPath));
704✔
2839
  memcpy(rpcInit.certPath, tsTLSSvrCertPath, strlen(tsTLSSvrCertPath));
704✔
2840
  memcpy(rpcInit.keyPath, tsTLSSvrKeyPath, strlen(tsTLSSvrKeyPath));
704✔
2841
  memcpy(rpcInit.cliCertPath, tsTLSCliCertPath, strlen(tsTLSCliCertPath));
704✔
2842
  memcpy(rpcInit.cliKeyPath, tsTLSCliKeyPath, strlen(tsTLSCliKeyPath));
704✔
2843

2844
  if (TSDB_CODE_SUCCESS != taosVersionStrToInt(td_version, &rpcInit.compatibilityVer)) {
704✔
2845
    tscError("faild to convert taos version from str to int, errcode:%s", terrstr());
×
2846
    goto _OVER;
×
2847
  }
2848

2849
  clientRpc = rpcOpen(&rpcInit);
704✔
2850
  if (clientRpc == NULL) {
704✔
2851
    code = terrno;
×
2852
    tscError("failed to init server status client since %s", tstrerror(code));
×
2853
    goto _OVER;
×
2854
  }
2855

2856
  if (fqdn == NULL) {
704✔
2857
    fqdn = tsLocalFqdn;
704✔
2858
  }
2859

2860
  if (port == 0) {
704✔
2861
    port = tsServerPort;
704✔
2862
  }
2863

2864
  tstrncpy(epSet.eps[0].fqdn, fqdn, TSDB_FQDN_LEN);
704✔
2865
  epSet.eps[0].port = (uint16_t)port;
704✔
2866
  int32_t ret = rpcSendRecv(clientRpc, &epSet, &rpcMsg, &rpcRsp);
704✔
2867
  if (TSDB_CODE_SUCCESS != ret) {
704✔
2868
    tscError("failed to send recv since %s", tstrerror(ret));
×
2869
    goto _OVER;
×
2870
  }
2871

2872
  if (rpcRsp.code != 0 || rpcRsp.contLen <= 0 || rpcRsp.pCont == NULL) {
704✔
2873
    tscError("failed to send server status req since %s", terrstr());
134✔
2874
    goto _OVER;
134✔
2875
  }
2876

2877
  if (tDeserializeSServerStatusRsp(rpcRsp.pCont, rpcRsp.contLen, &statusRsp) != 0) {
570✔
2878
    tscError("failed to parse server status rsp since %s", terrstr());
×
2879
    goto _OVER;
×
2880
  }
2881

2882
  code = statusRsp.statusCode;
570✔
2883
  if (details != NULL) {
570✔
2884
    tstrncpy(details, statusRsp.details, maxlen);
570✔
2885
  }
2886

2887
_OVER:
671✔
2888
  if (clientRpc != NULL) {
704✔
2889
    rpcClose(clientRpc);
704✔
2890
  }
2891
  if (rpcRsp.pCont != NULL) {
704✔
2892
    rpcFreeCont(rpcRsp.pCont);
570✔
2893
  }
2894
  return code;
704✔
2895
}
2896

2897
int32_t appendTbToReq(SHashObj* pHash, int32_t pos1, int32_t len1, int32_t pos2, int32_t len2, const char* str,
1,254✔
2898
                      int32_t acctId, char* db) {
2899
  SName name = {0};
1,254✔
2900

2901
  if (len1 <= 0) {
1,254✔
2902
    return -1;
×
2903
  }
2904

2905
  const char* dbName = db;
1,254✔
2906
  const char* tbName = NULL;
1,254✔
2907
  int32_t     dbLen = 0;
1,254✔
2908
  int32_t     tbLen = 0;
1,254✔
2909
  if (len2 > 0) {
1,254✔
2910
    dbName = str + pos1;
×
2911
    dbLen = len1;
×
2912
    tbName = str + pos2;
×
2913
    tbLen = len2;
×
2914
  } else {
2915
    dbLen = strlen(db);
1,254✔
2916
    tbName = str + pos1;
1,254✔
2917
    tbLen = len1;
1,254✔
2918
  }
2919

2920
  if (dbLen <= 0 || tbLen <= 0) {
1,254✔
2921
    return -1;
×
2922
  }
2923

2924
  if (tNameSetDbName(&name, acctId, dbName, dbLen)) {
1,254✔
2925
    return -1;
×
2926
  }
2927

2928
  if (tNameAddTbName(&name, tbName, tbLen)) {
1,254✔
2929
    return -1;
×
2930
  }
2931

2932
  char dbFName[TSDB_DB_FNAME_LEN] = {0};
1,254✔
2933
  (void)snprintf(dbFName, TSDB_DB_FNAME_LEN, "%d.%.*s", acctId, dbLen, dbName);
1,254✔
2934

2935
  STablesReq* pDb = taosHashGet(pHash, dbFName, strlen(dbFName));
1,254✔
2936
  if (pDb) {
1,254✔
2937
    if (NULL == taosArrayPush(pDb->pTables, &name)) {
×
2938
      return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
2939
    }
2940
  } else {
2941
    STablesReq db;
1,254✔
2942
    db.pTables = taosArrayInit(20, sizeof(SName));
1,254✔
2943
    if (NULL == db.pTables) {
1,254✔
2944
      return terrno;
×
2945
    }
2946
    tstrncpy(db.dbFName, dbFName, TSDB_DB_FNAME_LEN);
1,254✔
2947
    if (NULL == taosArrayPush(db.pTables, &name)) {
2,508✔
2948
      return terrno;
×
2949
    }
2950
    TSC_ERR_RET(taosHashPut(pHash, dbFName, strlen(dbFName), &db, sizeof(db)));
1,254✔
2951
  }
2952

2953
  return TSDB_CODE_SUCCESS;
1,254✔
2954
}
2955

2956
int32_t transferTableNameList(const char* tbList, int32_t acctId, char* dbName, SArray** pReq) {
1,254✔
2957
  SHashObj* pHash = taosHashInit(3, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
1,254✔
2958
  if (NULL == pHash) {
1,254✔
2959
    return terrno;
×
2960
  }
2961

2962
  bool    inEscape = false;
1,254✔
2963
  int32_t code = 0;
1,254✔
2964
  void*   pIter = NULL;
1,254✔
2965

2966
  int32_t vIdx = 0;
1,254✔
2967
  int32_t vPos[2];
1,254✔
2968
  int32_t vLen[2];
1,254✔
2969

2970
  (void)memset(vPos, -1, sizeof(vPos));
1,254✔
2971
  (void)memset(vLen, 0, sizeof(vLen));
1,254✔
2972

2973
  for (int32_t i = 0;; ++i) {
6,270✔
2974
    if (0 == *(tbList + i)) {
6,270✔
2975
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
1,254✔
2976
        vLen[vIdx] = i - vPos[vIdx];
1,254✔
2977
      }
2978

2979
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
1,254✔
2980
      if (code) {
1,254✔
2981
        goto _return;
×
2982
      }
2983

2984
      break;
1,254✔
2985
    }
2986

2987
    if ('`' == *(tbList + i)) {
5,016✔
2988
      inEscape = !inEscape;
×
2989
      if (!inEscape) {
×
2990
        if (vPos[vIdx] >= 0) {
×
2991
          vLen[vIdx] = i - vPos[vIdx];
×
2992
        } else {
2993
          goto _return;
×
2994
        }
2995
      }
2996

2997
      continue;
×
2998
    }
2999

3000
    if (inEscape) {
5,016✔
3001
      if (vPos[vIdx] < 0) {
×
3002
        vPos[vIdx] = i;
×
3003
      }
3004
      continue;
×
3005
    }
3006

3007
    if ('.' == *(tbList + i)) {
5,016✔
3008
      if (vPos[vIdx] < 0) {
×
3009
        goto _return;
×
3010
      }
3011
      if (vLen[vIdx] <= 0) {
×
3012
        vLen[vIdx] = i - vPos[vIdx];
×
3013
      }
3014
      vIdx++;
×
3015
      if (vIdx >= 2) {
×
3016
        goto _return;
×
3017
      }
3018
      continue;
×
3019
    }
3020

3021
    if (',' == *(tbList + i)) {
5,016✔
3022
      if (vPos[vIdx] < 0) {
×
3023
        goto _return;
×
3024
      }
3025
      if (vLen[vIdx] <= 0) {
×
3026
        vLen[vIdx] = i - vPos[vIdx];
×
3027
      }
3028

3029
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
×
3030
      if (code) {
×
3031
        goto _return;
×
3032
      }
3033

3034
      (void)memset(vPos, -1, sizeof(vPos));
×
3035
      (void)memset(vLen, 0, sizeof(vLen));
×
3036
      vIdx = 0;
×
3037
      continue;
×
3038
    }
3039

3040
    if (' ' == *(tbList + i) || '\r' == *(tbList + i) || '\t' == *(tbList + i) || '\n' == *(tbList + i)) {
5,016✔
3041
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
×
3042
        vLen[vIdx] = i - vPos[vIdx];
×
3043
      }
3044
      continue;
×
3045
    }
3046

3047
    if (('a' <= *(tbList + i) && 'z' >= *(tbList + i)) || ('A' <= *(tbList + i) && 'Z' >= *(tbList + i)) ||
5,016✔
3048
        ('0' <= *(tbList + i) && '9' >= *(tbList + i)) || ('_' == *(tbList + i))) {
627✔
3049
      if (vLen[vIdx] > 0) {
5,016✔
3050
        goto _return;
×
3051
      }
3052
      if (vPos[vIdx] < 0) {
5,016✔
3053
        vPos[vIdx] = i;
1,254✔
3054
      }
3055
      continue;
5,016✔
3056
    }
3057

3058
    goto _return;
×
3059
  }
3060

3061
  int32_t dbNum = taosHashGetSize(pHash);
1,254✔
3062
  *pReq = taosArrayInit(dbNum, sizeof(STablesReq));
1,254✔
3063
  if (NULL == pReq) {
1,254✔
3064
    TSC_ERR_JRET(terrno);
×
3065
  }
3066
  pIter = taosHashIterate(pHash, NULL);
1,254✔
3067
  while (pIter) {
2,508✔
3068
    STablesReq* pDb = (STablesReq*)pIter;
1,254✔
3069
    if (NULL == taosArrayPush(*pReq, pDb)) {
2,508✔
3070
      TSC_ERR_JRET(terrno);
×
3071
    }
3072
    pIter = taosHashIterate(pHash, pIter);
1,254✔
3073
  }
3074

3075
  taosHashCleanup(pHash);
1,254✔
3076

3077
  return TSDB_CODE_SUCCESS;
1,254✔
3078

3079
_return:
×
3080

3081
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
3082

3083
  pIter = taosHashIterate(pHash, NULL);
×
3084
  while (pIter) {
×
3085
    STablesReq* pDb = (STablesReq*)pIter;
×
3086
    taosArrayDestroy(pDb->pTables);
×
3087
    pIter = taosHashIterate(pHash, pIter);
×
3088
  }
3089

3090
  taosHashCleanup(pHash);
×
3091

3092
  return terrno;
×
3093
}
3094

3095
void syncCatalogFn(SMetaData* pResult, void* param, int32_t code) {
1,254✔
3096
  SSyncQueryParam* pParam = param;
1,254✔
3097
  pParam->pRequest->code = code;
1,254✔
3098

3099
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
1,254✔
3100
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3101
  }
3102
}
1,254✔
3103

3104
void syncQueryFn(void* param, void* res, int32_t code) {
638,477,528✔
3105
  SSyncQueryParam* pParam = param;
638,477,528✔
3106
  pParam->pRequest = res;
638,477,528✔
3107

3108
  if (pParam->pRequest) {
638,483,356✔
3109
    pParam->pRequest->code = code;
638,459,476✔
3110
    clientOperateReport(pParam->pRequest);
638,462,601✔
3111
  }
3112

3113
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
638,459,644✔
3114
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3115
  }
3116
}
638,491,342✔
3117

3118
void taosAsyncQueryImpl(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
637,967,772✔
3119
                        int8_t source) {
3120
  if (sql == NULL || NULL == fp) {
637,967,772✔
3121
    terrno = TSDB_CODE_INVALID_PARA;
110✔
3122
    if (fp) {
×
3123
      fp(param, NULL, terrno);
×
3124
    }
3125

3126
    return;
×
3127
  }
3128

3129
  size_t sqlLen = strlen(sql);
637,967,913✔
3130
  if (sqlLen > (size_t)tsMaxSQLLength) {
637,967,913✔
3131
    tscError("conn:0x%" PRIx64 ", sql string exceeds max length:%d", connId, tsMaxSQLLength);
1,272✔
3132
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
1,272✔
3133
    fp(param, NULL, terrno);
1,272✔
3134
    return;
1,272✔
3135
  }
3136

3137
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, sql:%s", connId, sql);
637,966,641✔
3138

3139
  SRequestObj* pRequest = NULL;
637,966,641✔
3140
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
637,967,835✔
3141
  if (code != TSDB_CODE_SUCCESS) {
637,963,898✔
3142
    terrno = code;
×
3143
    fp(param, NULL, terrno);
×
3144
    return;
×
3145
  }
3146

3147
  SSessParam para = {.type = SESSION_MAX_CONCURRENCY, .value = 1};
637,963,898✔
3148
  code = connUpdateSessMgtMetric(connId, &para);
637,964,775✔
3149
  if (code != TSDB_CODE_SUCCESS) {
637,975,466✔
3150
    terrno = code;
×
3151
    fp(param, NULL, terrno);
×
3152
    return;
×
3153
  }
3154

3155
  pRequest->source = source;
637,975,466✔
3156
  pRequest->body.queryFp = fp;
637,975,637✔
3157
  doAsyncQuery(pRequest, false);
637,975,808✔
3158
}
3159

3160
void taosAsyncQueryImplWithReqid(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
838✔
3161
                                 int64_t reqid) {
3162
  if (sql == NULL || NULL == fp) {
838✔
3163
    terrno = TSDB_CODE_INVALID_PARA;
×
3164
    if (fp) {
×
3165
      fp(param, NULL, terrno);
×
3166
    }
3167

3168
    return;
×
3169
  }
3170

3171
  size_t sqlLen = strlen(sql);
838✔
3172
  if (sqlLen > (size_t)tsMaxSQLLength) {
838✔
3173
    tscError("conn:0x%" PRIx64 ", QID:0x%" PRIx64 ", sql string exceeds max length:%d", connId, reqid, tsMaxSQLLength);
×
3174
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
3175
    fp(param, NULL, terrno);
×
3176
    return;
×
3177
  }
3178

3179
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, QID:0x%" PRIx64 ", sql:%s", connId, reqid, sql);
838✔
3180

3181
  SRequestObj* pRequest = NULL;
838✔
3182
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, reqid);
838✔
3183
  if (code != TSDB_CODE_SUCCESS) {
838✔
3184
    terrno = code;
×
3185
    fp(param, NULL, terrno);
×
3186
    return;
×
3187
  }
3188

3189
  SSessParam para = {.type = SESSION_MAX_CONCURRENCY, .value = 1};
838✔
3190
  code = connUpdateSessMgtMetric(connId, &para);
838✔
3191
  if (code != TSDB_CODE_SUCCESS) {
838✔
3192
    terrno = code;
×
3193
    fp(param, NULL, terrno);
×
3194
    return;
×
3195
  }
3196

3197
  pRequest->body.queryFp = fp;
838✔
3198

3199
  doAsyncQuery(pRequest, false);
838✔
3200
}
3201

3202
int32_t connUpdateSessMgtMetric(int64_t connId, SSessParam* pParam) {
637,965,520✔
3203
  int32_t code = 0;
637,965,520✔
3204

3205
  STscObj* pTscObj = acquireTscObj(connId);
637,965,520✔
3206
  if (pTscObj == NULL) {
637,976,475✔
3207
    code = TSDB_CODE_INVALID_PARA;
×
3208
    return code;
×
3209
  }
3210
  code = sessMgtUpdateUserMetric(pTscObj->user, pParam);
637,976,475✔
3211

3212
  releaseTscObj(connId);
637,976,616✔
3213
  return code;
637,976,304✔
3214
}
3215

3216
int32_t tscUpdateSessMgtMetric(STscObj* pTscObj, SSessParam* pParam) {
649,531,521✔
3217
  int32_t code = 0;
649,531,521✔
3218

3219
  if (pTscObj == NULL) {
649,531,521✔
3220
    code = TSDB_CODE_INVALID_PARA;
×
3221
    return code;
×
3222
  }
3223
  code = sessMgtUpdateUserMetric(pTscObj->user, pParam);
649,531,521✔
3224

3225
  return code;
649,542,605✔
3226
}
3227

3228
TAOS_RES* taosQueryImpl(TAOS* taos, const char* sql, bool validateOnly, int8_t source) {
637,927,902✔
3229
  if (NULL == taos) {
637,927,902✔
3230
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3231
    return NULL;
×
3232
  }
3233

3234
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
637,927,902✔
3235
  if (NULL == param) {
637,929,220✔
3236
    return NULL;
×
3237
  }
3238

3239
  int32_t code = tsem_init(&param->sem, 0, 0);
637,929,220✔
3240
  if (TSDB_CODE_SUCCESS != code) {
637,922,988✔
3241
    taosMemoryFree(param);
×
3242
    return NULL;
×
3243
  }
3244

3245
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
637,922,988✔
3246
  code = tsem_wait(&param->sem);
637,926,581✔
3247
  if (TSDB_CODE_SUCCESS != code) {
637,935,517✔
3248
    taosMemoryFree(param);
×
3249
    return NULL;
×
3250
  }
3251
  code = tsem_destroy(&param->sem);
637,935,517✔
3252
  if (TSDB_CODE_SUCCESS != code) {
637,937,324✔
3253
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3254
  }
3255

3256
  SRequestObj* pRequest = NULL;
637,937,324✔
3257
  if (param->pRequest != NULL) {
637,937,324✔
3258
    param->pRequest->syncQuery = true;
637,935,941✔
3259
    pRequest = param->pRequest;
637,935,568✔
3260
    param->pRequest->inCallback = false;
637,934,371✔
3261
  }
3262
  taosMemoryFree(param);
637,934,989✔
3263

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

3267
  return pRequest;
637,935,676✔
3268
}
3269

3270
TAOS_RES* taosQueryImplWithReqid(TAOS* taos, const char* sql, bool validateOnly, int64_t reqid) {
838✔
3271
  if (NULL == taos) {
838✔
3272
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3273
    return NULL;
×
3274
  }
3275

3276
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
838✔
3277
  if (param == NULL) {
838✔
3278
    return NULL;
×
3279
  }
3280
  int32_t code = tsem_init(&param->sem, 0, 0);
838✔
3281
  if (TSDB_CODE_SUCCESS != code) {
838✔
3282
    taosMemoryFree(param);
×
3283
    return NULL;
×
3284
  }
3285

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

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

3302
  return pRequest;
838✔
3303
}
3304

3305
static void fetchCallback(void* pResult, void* param, int32_t code) {
91,061,076✔
3306
  SRequestObj* pRequest = (SRequestObj*)param;
91,061,076✔
3307

3308
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
91,061,076✔
3309

3310
  tscDebug("req:0x%" PRIx64 ", enter scheduler fetch cb, code:%d - %s, QID:0x%" PRIx64, pRequest->self, code,
91,061,039✔
3311
           tstrerror(code), pRequest->requestId);
3312

3313
  pResultInfo->pData = pResult;
91,061,039✔
3314
  pResultInfo->numOfRows = 0;
91,061,300✔
3315

3316
  if (code != TSDB_CODE_SUCCESS) {
91,060,815✔
3317
    pRequest->code = code;
×
3318
    taosMemoryFreeClear(pResultInfo->pData);
×
3319
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
×
3320
    return;
×
3321
  }
3322

3323
  if (pRequest->code != TSDB_CODE_SUCCESS) {
91,060,815✔
3324
    taosMemoryFreeClear(pResultInfo->pData);
×
3325
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pRequest->code);
×
3326
    return;
×
3327
  }
3328

3329
  pRequest->code = setQueryResultFromRsp(pResultInfo, (const SRetrieveTableRsp*)pResultInfo->pData,
91,971,160✔
3330
                                         pResultInfo->convertUcs4, pRequest->stmtBindVersion > 0);
91,061,050✔
3331
  if (pRequest->code != TSDB_CODE_SUCCESS) {
91,060,852✔
3332
    pResultInfo->numOfRows = 0;
76✔
3333
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self,
76✔
3334
             tstrerror(pRequest->code), pRequest->requestId);
3335
  } else {
3336
    tscDebug(
91,060,073✔
3337
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
3338
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
3339

3340
    STscObj*            pTscObj = pRequest->pTscObj;
91,060,073✔
3341
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
91,060,320✔
3342
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
91,061,224✔
3343
  }
3344

3345
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
91,061,300✔
3346
}
3347

3348
void taosAsyncFetchImpl(SRequestObj* pRequest, __taos_async_fn_t fp, void* param) {
93,943,771✔
3349
  pRequest->body.fetchFp = fp;
93,943,771✔
3350
  ((SSyncQueryParam*)pRequest->body.interParam)->userParam = param;
93,943,771✔
3351

3352
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
93,944,219✔
3353

3354
  // this query has no results or error exists, return directly
3355
  if (taos_num_fields(pRequest) == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
93,944,416✔
3356
    pResultInfo->numOfRows = 0;
197✔
3357
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
×
3358
    return;
687✔
3359
  }
3360

3361
  // all data has returned to App already, no need to try again
3362
  if (pResultInfo->completed) {
93,944,219✔
3363
    // it is a local executed query, no need to do async fetch
3364
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
2,883,116✔
3365
      if (pResultInfo->localResultFetched) {
1,543,934✔
3366
        pResultInfo->numOfRows = 0;
771,967✔
3367
        pResultInfo->current = 0;
771,967✔
3368
      } else {
3369
        pResultInfo->localResultFetched = true;
771,967✔
3370
      }
3371
    } else {
3372
      pResultInfo->numOfRows = 0;
1,339,182✔
3373
    }
3374

3375
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
2,883,116✔
3376
    return;
2,883,116✔
3377
  }
3378

3379
  SSchedulerReq req = {
91,061,103✔
3380
      .syncReq = false,
3381
      .fetchFp = fetchCallback,
3382
      .cbParam = pRequest,
3383
  };
3384

3385
  int32_t code = schedulerFetchRows(pRequest->body.queryJob, &req);
91,061,103✔
3386
  if (TSDB_CODE_SUCCESS != code) {
91,061,300✔
3387
    tscError("0x%" PRIx64 " failed to schedule fetch rows", pRequest->requestId);
×
3388
    // pRequest->body.fetchFp(param, pRequest, code);
3389
  }
3390
}
3391

3392
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
638,462,315✔
3393
  pRequest->inCallback = true;
638,462,315✔
3394
  int64_t this = pRequest->self;
638,468,370✔
3395
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
638,447,130✔
3396
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
84,300✔
3397
    code = TSDB_CODE_SUCCESS;
×
3398
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3399
  }
3400

3401
  tscDebug("QID:0x%" PRIx64 ", taos_query end, req:0x%" PRIx64 ", res:%p", pRequest->requestId, pRequest->self,
638,447,130✔
3402
           pRequest);
3403

3404
  if (pRequest->body.queryFp != NULL) {
638,448,376✔
3405
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
638,458,478✔
3406
  }
3407

3408

3409
  SRequestObj* pReq = acquireRequest(this);
638,470,872✔
3410
  if (pReq != NULL) {
638,472,434✔
3411
    pReq->inCallback = false;
637,467,882✔
3412
    (void)releaseRequest(this);
637,467,882✔
3413
  }
3414
}
638,468,513✔
3415

3416
int32_t clientParseSql(void* param, const char* dbName, const char* sql, bool parseOnly, const char* effectiveUser,
555,250✔
3417
                       SParseSqlRes* pRes) {
3418
#ifndef TD_ENTERPRISE
3419
  return TSDB_CODE_SUCCESS;
3420
#else
3421
  return clientParseSqlImpl(param, dbName, sql, parseOnly, effectiveUser, pRes);
555,250✔
3422
#endif
3423
}
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