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

taosdata / TDengine / #4944

30 Jan 2026 06:19AM UTC coverage: 66.849% (+0.1%) from 66.718%
#4944

push

travis-ci

web-flow
merge: from main to 3.0 #34453

1124 of 2018 new or added lines in 72 files covered. (55.7%)

13677 existing lines in 155 files now uncovered.

205211 of 306978 relevant lines covered (66.85%)

125657591.7 hits per line

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

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

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

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

39
void setQueryRequest(int64_t rId) {
462,960,487✔
40
  SRequestObj* pReq = acquireRequest(rId);
462,960,487✔
41
  if (pReq != NULL) {
462,962,766✔
42
    pReq->isQuery = true;
462,951,120✔
43
    (void)releaseRequest(rId);
462,951,120✔
44
  }
45
}
462,961,550✔
46

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

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

57
  return true;
5,265,596✔
58
}
59

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

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

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

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

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

81
  size_t escapeLength = 0;
526,962✔
82
  for (size_t i = 0; i < srcLength; ++i) {
14,971,056✔
83
    if (src[i] == '\"' || src[i] == '\\' || src[i] == '\b' || src[i] == '\f' || src[i] == '\n' || src[i] == '\r' ||
14,444,094✔
84
        src[i] == '\t') {
14,444,094✔
85
      escapeLength += 1;
×
86
    }
87
  }
88

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

130
  return dstLength;
526,962✔
131
}
132

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

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

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

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

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

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

159
  if (user == NULL) {
2,394,233✔
160
    if (auth == NULL || strlen(auth) != (TSDB_TOKEN_LEN - 1)) {
2,737✔
161
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_TOKEN);
683✔
162
    }
163
  } else if (!validateUserName(user)) {
2,391,496✔
164
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
165
  }
166
  int32_t code = 0;
2,393,423✔
167

168
  char localDb[TSDB_DB_NAME_LEN] = {0};
2,393,423✔
169
  if (db != NULL && strlen(db) > 0) {
2,393,936✔
170
    if (!validateDbName(db)) {
481,078✔
171
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_DB_LENGTH);
×
172
    }
173

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

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

187
  SCorEpSet epSet = {0};
2,394,114✔
188
  if (ip) {
2,393,292✔
189
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
831,428✔
190
  } else {
191
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
1,561,864✔
192
  }
193

194
  if (port) {
2,393,708✔
195
    epSet.epSet.eps[0].port = port;
192,032✔
196
    epSet.epSet.eps[1].port = port;
192,032✔
197
  }
198

199
  char* key = getClusterKey(user, auth, ip, port);
2,393,708✔
200
  if (NULL == key) {
2,393,631✔
201
    TSC_ERR_RET(terrno);
×
202
  }
203
  tscInfo("connecting to server, numOfEps:%d inUse:%d user:%s db:%s key:%s", epSet.epSet.numOfEps, epSet.epSet.inUse,
2,393,631✔
204
          user ? user : "", db, key);
205
  for (int32_t i = 0; i < epSet.epSet.numOfEps; ++i) {
6,350,792✔
206
    tscInfo("ep:%d, %s:%u", i, epSet.epSet.eps[i].fqdn, epSet.epSet.eps[i].port);
3,956,760✔
207
  }
208

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

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

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

259
_return:
2,394,032✔
260

261
  if (TSDB_CODE_SUCCESS != code) {
2,394,032✔
262
    (void)taosThreadMutexUnlock(&appInfo.mutex);
×
263
    taosMemoryFreeClear(key);
×
264
    return code;
×
265
  } else {
266
    code = taosThreadMutexUnlock(&appInfo.mutex);
2,394,032✔
267
    taosMemoryFreeClear(key);
2,394,032✔
268
    if (TSDB_CODE_SUCCESS != code) {
2,394,032✔
269
      tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
270
      return code;
×
271
    }
272
    return taosConnectImpl(user, auth, totpCode, localDb, NULL, NULL, *pInst, connType, pObj);
2,394,032✔
273
  }
274
}
275

276
int32_t taos_connect_internal(const char* ip, const char* user, const char* pass, const char* totp, const char* db,
2,391,922✔
277
                              uint16_t port, int connType, STscObj** pObj) {
278
  char auth[TSDB_PASSWORD_LEN + 1] = {0};
2,391,922✔
279
  if (!validatePassword(pass)) {
2,391,922✔
280
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_PASS_LENGTH);
×
281
  }
282

283
  taosEncryptPass_c((uint8_t*)pass, strlen(pass), auth);
2,391,971✔
284
  return taos_connect_by_auth(ip, user, auth, totp, db, port, connType, pObj);
2,391,883✔
285
}
286

287
// SAppInstInfo* getAppInstInfo(const char* clusterKey) {
288
//   SAppInstInfo** ppAppInstInfo = taosHashGet(appInfo.pInstMap, clusterKey, strlen(clusterKey));
289
//   if (ppAppInstInfo != NULL && *ppAppInstInfo != NULL) {
290
//     return *ppAppInstInfo;
291
//   } else {
292
//     return NULL;
293
//   }
294
// }
295

296
void freeQueryParam(SSyncQueryParam* param) {
462,619✔
297
  if (param == NULL) return;
462,619✔
298
  if (TSDB_CODE_SUCCESS != tsem_destroy(&param->sem)) {
462,619✔
299
    tscError("failed to destroy semaphore in freeQueryParam");
×
300
  }
301
  taosMemoryFree(param);
462,619✔
302
}
303

304
int32_t buildRequest(uint64_t connId, const char* sql, int sqlLen, void* param, bool validateSql,
804,259,391✔
305
                     SRequestObj** pRequest, int64_t reqid) {
306
  int32_t code = createRequest(connId, TSDB_SQL_SELECT, reqid, pRequest);
804,259,391✔
307
  if (TSDB_CODE_SUCCESS != code) {
804,256,159✔
308
    tscError("failed to malloc sqlObj, %s", sql);
×
309
    return code;
×
310
  }
311

312
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
804,256,159✔
313
  if ((*pRequest)->sqlstr == NULL) {
804,253,153✔
314
    tscError("req:0x%" PRIx64 ", failed to prepare sql string buffer, %s", (*pRequest)->self, sql);
×
315
    destroyRequest(*pRequest);
×
316
    *pRequest = NULL;
×
317
    return terrno;
×
318
  }
319

320
  (void)strntolower((*pRequest)->sqlstr, sql, (int32_t)sqlLen);
804,254,617✔
321
  (*pRequest)->sqlstr[sqlLen] = 0;
804,269,178✔
322
  (*pRequest)->sqlLen = sqlLen;
804,268,527✔
323
  (*pRequest)->validateOnly = validateSql;
804,269,118✔
324
  (*pRequest)->stmtBindVersion = 0;
804,268,332✔
325

326
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
804,269,126✔
327

328
  STscObj* pTscObj = (*pRequest)->pTscObj;
804,265,762✔
329
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
804,266,191✔
330
                             sizeof((*pRequest)->self));
331
  if (err) {
804,260,806✔
332
    tscError("req:0x%" PRId64 ", failed to add to request container, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
333
             (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
334
    destroyRequest(*pRequest);
×
335
    *pRequest = NULL;
×
336
    return terrno;
×
337
  }
338

339
  (*pRequest)->allocatorRefId = -1;
804,260,806✔
340
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
804,258,874✔
341
    if (TSDB_CODE_SUCCESS !=
269,893,623✔
342
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
269,885,704✔
343
      tscError("req:0x%" PRId64 ", failed to create node allocator, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
344
               (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
345
      destroyRequest(*pRequest);
×
346
      *pRequest = NULL;
×
347
      return terrno;
×
348
    }
349
  }
350

351
  tscDebug("req:0x%" PRIx64 ", build request, QID:0x%" PRIx64, (*pRequest)->self, (*pRequest)->requestId);
804,266,026✔
352
  return TSDB_CODE_SUCCESS;
804,258,951✔
353
}
354

355
int32_t buildPreviousRequest(SRequestObj* pRequest, const char* sql, SRequestObj** pNewRequest) {
×
356
  int32_t code =
357
      buildRequest(pRequest->pTscObj->id, sql, strlen(sql), pRequest, pRequest->validateOnly, pNewRequest, 0);
×
358
  if (TSDB_CODE_SUCCESS == code) {
×
359
    pRequest->relation.prevRefId = (*pNewRequest)->self;
×
360
    (*pNewRequest)->relation.nextRefId = pRequest->self;
×
361
    (*pNewRequest)->relation.userRefId = pRequest->self;
×
362
    (*pNewRequest)->isSubReq = true;
×
363
  }
364
  return code;
×
365
}
366

367
int32_t parseSql(SRequestObj* pRequest, bool topicQuery, SQuery** pQuery, SStmtCallback* pStmtCb) {
6,289,557✔
368
  STscObj* pTscObj = pRequest->pTscObj;
6,289,557✔
369

370
  SParseContext cxt = {
6,292,170✔
371
      .requestId = pRequest->requestId,
6,292,378✔
372
      .requestRid = pRequest->self,
6,288,148✔
373
      .acctId = pTscObj->acctId,
6,292,948✔
374
      .db = pRequest->pDb,
6,292,829✔
375
      .topicQuery = topicQuery,
376
      .pSql = pRequest->sqlstr,
6,293,170✔
377
      .sqlLen = pRequest->sqlLen,
6,294,404✔
378
      .pMsg = pRequest->msgBuf,
6,295,325✔
379
      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
380
      .pTransporter = pTscObj->pAppInfo->pTransporter,
6,287,936✔
381
      .pStmtCb = pStmtCb,
382
      .pUser = pTscObj->user,
6,292,914✔
383
      .userId = pTscObj->userId,
6,289,654✔
384
      .isSuperUser = (0 == strcmp(pTscObj->user, TSDB_DEFAULT_USER)),
6,287,060✔
385
      .enableSysInfo = pTscObj->sysInfo,
6,290,071✔
386
      .svrVer = pTscObj->sVer,
6,283,060✔
387
      .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes),
6,291,962✔
388
      .stmtBindVersion = pRequest->stmtBindVersion,
6,289,738✔
389
      .setQueryFp = setQueryRequest,
390
      .timezone = pTscObj->optionInfo.timezone,
6,285,209✔
391
      .charsetCxt = pTscObj->optionInfo.charsetCxt,
6,286,921✔
392
  };
393

394
  cxt.mgmtEpSet = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
6,288,890✔
395
  int32_t code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &cxt.pCatalog);
6,293,175✔
396
  if (code != TSDB_CODE_SUCCESS) {
6,291,742✔
397
    return code;
×
398
  }
399

400
  code = qParseSql(&cxt, pQuery);
6,291,742✔
401
  if (TSDB_CODE_SUCCESS == code) {
6,287,049✔
402
    if ((*pQuery)->haveResultSet) {
6,289,328✔
403
      code = setResSchemaInfo(&pRequest->body.resInfo, (*pQuery)->pResSchema, (*pQuery)->numOfResCols,
×
404
                              (*pQuery)->pResExtSchema, pRequest->stmtBindVersion > 0);
×
405
      setResPrecision(&pRequest->body.resInfo, (*pQuery)->precision);
×
406
    }
407
  }
408

409
  if (TSDB_CODE_SUCCESS == code || NEED_CLIENT_HANDLE_ERROR(code)) {
6,286,647✔
410
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
6,284,933✔
411
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
6,285,557✔
412
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
6,279,990✔
413
  }
414

415
  taosArrayDestroy(cxt.pTableMetaPos);
6,280,447✔
416
  taosArrayDestroy(cxt.pTableVgroupPos);
6,275,185✔
417

418
  return code;
6,277,995✔
419
}
420

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

431
  return code;
×
432
}
433

434
int32_t execDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
390,445✔
435
  // drop table if exists not_exists_table
436
  if (NULL == pQuery->pCmdMsg) {
390,445✔
437
    return TSDB_CODE_SUCCESS;
×
438
  }
439

440
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
390,445✔
441
  pRequest->type = pMsgInfo->msgType;
390,445✔
442
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
390,445✔
443
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
390,445✔
444

445
  STscObj*      pTscObj = pRequest->pTscObj;
390,445✔
446
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
390,445✔
447

448
  // int64_t transporterId = 0;
449
  TSC_ERR_RET(asyncSendMsgToServer(pTscObj->pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg));
390,445✔
450
  TSC_ERR_RET(tsem_wait(&pRequest->body.rspSem));
390,445✔
451
  return TSDB_CODE_SUCCESS;
390,445✔
452
}
453

454
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
1,413,760,146✔
455

456
void asyncExecLocalCmd(SRequestObj* pRequest, SQuery* pQuery) {
5,271,301✔
457
  SRetrieveTableRsp* pRsp = NULL;
5,271,301✔
458
  if (pRequest->validateOnly) {
5,271,301✔
459
    doRequestCallback(pRequest, 0);
9,531✔
460
    return;
9,531✔
461
  }
462

463
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp,
10,512,311✔
464
                              atomic_load_8(&pRequest->pTscObj->biMode), pRequest->pTscObj->optionInfo.charsetCxt);
10,512,311✔
465
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
5,261,770✔
466
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4,
2,915,041✔
467
                                 pRequest->stmtBindVersion > 0);
2,915,041✔
468
  }
469

470
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
5,261,770✔
471
  pRequest->code = code;
5,261,770✔
472

473
  if (pRequest->code != TSDB_CODE_SUCCESS) {
5,261,770✔
474
    pResultInfo->numOfRows = 0;
1,549✔
475
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
1,549✔
476
             pRequest->requestId);
477
  } else {
478
    tscDebug(
5,260,221✔
479
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
480
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
481
  }
482

483
  doRequestCallback(pRequest, code);
5,261,770✔
484
}
485

486
int32_t asyncExecDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
14,801,321✔
487
  if (pRequest->validateOnly) {
14,801,321✔
488
    doRequestCallback(pRequest, 0);
×
489
    return TSDB_CODE_SUCCESS;
×
490
  }
491

492
  // drop table if exists not_exists_table
493
  if (NULL == pQuery->pCmdMsg) {
14,801,326✔
494
    doRequestCallback(pRequest, 0);
6,174✔
495
    return TSDB_CODE_SUCCESS;
6,174✔
496
  }
497

498
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
14,795,148✔
499
  pRequest->type = pMsgInfo->msgType;
14,795,143✔
500
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
14,794,345✔
501
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
14,795,284✔
502

503
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
14,795,678✔
504
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
14,793,975✔
505

506
  int32_t code = asyncSendMsgToServer(pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg);
14,795,686✔
507
  if (code) {
14,795,703✔
508
    doRequestCallback(pRequest, code);
×
509
  }
510
  return code;
14,795,703✔
511
}
512

513
int compareQueryNodeLoad(const void* elem1, const void* elem2) {
118,777✔
514
  SQueryNodeLoad* node1 = (SQueryNodeLoad*)elem1;
118,777✔
515
  SQueryNodeLoad* node2 = (SQueryNodeLoad*)elem2;
118,777✔
516

517
  if (node1->load < node2->load) {
118,777✔
518
    return -1;
×
519
  }
520

521
  return node1->load > node2->load;
118,777✔
522
}
523

524
int32_t updateQnodeList(SAppInstInfo* pInfo, SArray* pNodeList) {
243,089✔
525
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
243,089✔
526
  if (pInfo->pQnodeList) {
243,089✔
527
    taosArrayDestroy(pInfo->pQnodeList);
239,746✔
528
    pInfo->pQnodeList = NULL;
239,746✔
529
    tscDebug("QnodeList cleared in cluster 0x%" PRIx64, pInfo->clusterId);
239,746✔
530
  }
531

532
  if (pNodeList) {
243,089✔
533
    pInfo->pQnodeList = taosArrayDup(pNodeList, NULL);
243,089✔
534
    taosArraySort(pInfo->pQnodeList, compareQueryNodeLoad);
243,089✔
535
    tscDebug("QnodeList updated in cluster 0x%" PRIx64 ", num:%ld", pInfo->clusterId,
243,089✔
536
             taosArrayGetSize(pInfo->pQnodeList));
537
  }
538
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
243,089✔
539

540
  return TSDB_CODE_SUCCESS;
243,089✔
541
}
542

543
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
798,776,544✔
544
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
798,776,544✔
545
    *required = false;
787,524,184✔
546
    return TSDB_CODE_SUCCESS;
787,521,091✔
547
  }
548

549
  int32_t       code = TSDB_CODE_SUCCESS;
11,252,360✔
550
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
11,252,360✔
551
  *required = false;
11,252,360✔
552

553
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
11,252,360✔
554
  *required = (NULL == pInfo->pQnodeList);
11,252,360✔
555
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
11,252,360✔
556
  return TSDB_CODE_SUCCESS;
11,252,360✔
557
}
558

559
int32_t getQnodeList(SRequestObj* pRequest, SArray** pNodeList) {
×
560
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
×
561
  int32_t       code = 0;
×
562

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

583
    if (TSDB_CODE_SUCCESS == code && *pNodeList) {
×
584
      code = updateQnodeList(pInfo, *pNodeList);
×
585
    }
586
  }
587

588
  return code;
×
589
}
590

591
int32_t getPlan(SRequestObj* pRequest, SQuery* pQuery, SQueryPlan** pPlan, SArray* pNodeList) {
7,414,989✔
592
  pRequest->type = pQuery->msgType;
7,414,989✔
593
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
7,413,803✔
594

595
  SPlanContext cxt = {.queryId = pRequest->requestId,
7,706,285✔
596
                      .acctId = pRequest->pTscObj->acctId,
7,413,604✔
597
                      .mgmtEpSet = getEpSet_s(&pAppInfo->mgmtEp),
7,408,898✔
598
                      .pAstRoot = pQuery->pRoot,
7,418,628✔
599
                      .showRewrite = pQuery->showRewrite,
7,418,628✔
600
                      .pMsg = pRequest->msgBuf,
7,416,578✔
601
                      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
602
                      .pUser = pRequest->pTscObj->user,
7,412,952✔
603
                      .userId = pRequest->pTscObj->userId,
7,407,953✔
604
                      .timezone = pRequest->pTscObj->optionInfo.timezone,
7,408,274✔
605
                      .sysInfo = pRequest->pTscObj->sysInfo};
7,411,509✔
606

607
  return qCreateQueryPlan(&cxt, pPlan, pNodeList);
7,401,082✔
608
}
609

610
int32_t setResSchemaInfo(SReqResultInfo* pResInfo, const SSchema* pSchema, int32_t numOfCols,
245,757,200✔
611
                         const SExtSchema* pExtSchema, bool isStmt) {
612
  if (pResInfo == NULL || pSchema == NULL || numOfCols <= 0) {
245,757,200✔
613
    tscError("invalid paras, pResInfo == NULL || pSchema == NULL || numOfCols <= 0");
×
614
    return TSDB_CODE_INVALID_PARA;
×
615
  }
616

617
  pResInfo->numOfCols = numOfCols;
245,760,143✔
618
  if (pResInfo->fields != NULL) {
245,759,385✔
619
    taosMemoryFree(pResInfo->fields);
15,392✔
620
  }
621
  if (pResInfo->userFields != NULL) {
245,756,708✔
622
    taosMemoryFree(pResInfo->userFields);
15,392✔
623
  }
624
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD_E));
245,752,950✔
625
  if (NULL == pResInfo->fields) return terrno;
245,752,721✔
626
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
245,746,556✔
627
  if (NULL == pResInfo->userFields) {
245,754,909✔
628
    taosMemoryFree(pResInfo->fields);
×
629
    return terrno;
×
630
  }
631
  if (numOfCols != pResInfo->numOfCols) {
245,752,669✔
632
    tscError("numOfCols:%d != pResInfo->numOfCols:%d", numOfCols, pResInfo->numOfCols);
×
633
    return TSDB_CODE_FAILED;
×
634
  }
635

636
  for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
1,357,502,822✔
637
    pResInfo->fields[i].type = pSchema[i].type;
1,111,744,319✔
638

639
    pResInfo->userFields[i].type = pSchema[i].type;
1,111,749,090✔
640
    // userFields must convert to type bytes, no matter isStmt or not
641
    pResInfo->userFields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, false);
1,111,756,367✔
642
    pResInfo->fields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, isStmt);
1,111,735,582✔
643
    if (IS_DECIMAL_TYPE(pSchema[i].type) && pExtSchema) {
1,111,728,180✔
644
      decimalFromTypeMod(pExtSchema[i].typeMod, &pResInfo->fields[i].precision, &pResInfo->fields[i].scale);
1,265,939✔
645
    }
646

647
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
1,111,724,973✔
648
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
1,111,728,733✔
649
  }
650
  return TSDB_CODE_SUCCESS;
245,761,745✔
651
}
652

653
void setResPrecision(SReqResultInfo* pResInfo, int32_t precision) {
139,953,164✔
654
  if (precision != TSDB_TIME_PRECISION_MILLI && precision != TSDB_TIME_PRECISION_MICRO &&
139,953,164✔
655
      precision != TSDB_TIME_PRECISION_NANO) {
656
    return;
×
657
  }
658

659
  pResInfo->precision = precision;
139,953,164✔
660
}
661

662
int32_t buildVnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pDbVgList) {
143,757,726✔
663
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
143,757,726✔
664
  if (NULL == nodeList) {
143,751,858✔
665
    return terrno;
×
666
  }
667
  char* policy = (tsQueryPolicy == QUERY_POLICY_VNODE) ? "vnode" : "client";
143,755,267✔
668

669
  int32_t dbNum = taosArrayGetSize(pDbVgList);
143,755,267✔
670
  for (int32_t i = 0; i < dbNum; ++i) {
285,450,005✔
671
    SArray* pVg = taosArrayGetP(pDbVgList, i);
141,676,499✔
672
    if (NULL == pVg) {
141,679,648✔
673
      continue;
×
674
    }
675
    int32_t vgNum = taosArrayGetSize(pVg);
141,679,648✔
676
    if (vgNum <= 0) {
141,678,714✔
677
      continue;
525,309✔
678
    }
679

680
    for (int32_t j = 0; j < vgNum; ++j) {
508,282,623✔
681
      SVgroupInfo* pInfo = taosArrayGet(pVg, j);
367,121,387✔
682
      if (NULL == pInfo) {
367,139,197✔
683
        taosArrayDestroy(nodeList);
×
684
        return TSDB_CODE_OUT_OF_RANGE;
×
685
      }
686
      SQueryNodeLoad load = {0};
367,139,197✔
687
      load.addr.nodeId = pInfo->vgId;
367,140,720✔
688
      load.addr.epSet = pInfo->epSet;
367,155,932✔
689

690
      if (NULL == taosArrayPush(nodeList, &load)) {
367,075,641✔
691
        taosArrayDestroy(nodeList);
×
692
        return terrno;
×
693
      }
694
    }
695
  }
696

697
  int32_t vnodeNum = taosArrayGetSize(nodeList);
143,773,506✔
698
  if (vnodeNum > 0) {
143,768,891✔
699
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
140,916,475✔
700
    goto _return;
140,915,269✔
701
  }
702

703
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
2,852,416✔
704
  if (mnodeNum <= 0) {
2,851,328✔
705
    tscDebug("0x%" PRIx64 " %s policy, empty node list", pRequest->requestId, policy);
×
706
    goto _return;
×
707
  }
708

709
  void* pData = taosArrayGet(pMnodeList, 0);
2,851,328✔
710
  if (NULL == pData) {
2,851,340✔
711
    taosArrayDestroy(nodeList);
×
712
    return TSDB_CODE_OUT_OF_RANGE;
×
713
  }
714
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
2,851,340✔
715
    taosArrayDestroy(nodeList);
×
716
    return terrno;
×
717
  }
718

719
  tscDebug("0x%" PRIx64 " %s policy, use mnode list, num:%d", pRequest->requestId, policy, mnodeNum);
2,851,340✔
720

721
_return:
66,106✔
722

723
  *pNodeList = nodeList;
143,766,551✔
724

725
  return TSDB_CODE_SUCCESS;
143,762,671✔
726
}
727

728
int32_t buildQnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pQnodeList) {
1,416,740✔
729
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
1,416,740✔
730
  if (NULL == nodeList) {
1,416,740✔
731
    return terrno;
×
732
  }
733

734
  int32_t qNodeNum = taosArrayGetSize(pQnodeList);
1,416,740✔
735
  if (qNodeNum > 0) {
1,416,740✔
736
    void* pData = taosArrayGet(pQnodeList, 0);
1,396,640✔
737
    if (NULL == pData) {
1,396,640✔
738
      taosArrayDestroy(nodeList);
×
739
      return TSDB_CODE_OUT_OF_RANGE;
×
740
    }
741
    if (NULL == taosArrayAddBatch(nodeList, pData, qNodeNum)) {
1,396,640✔
742
      taosArrayDestroy(nodeList);
×
743
      return terrno;
×
744
    }
745
    tscDebug("0x%" PRIx64 " qnode policy, use qnode list, num:%d", pRequest->requestId, qNodeNum);
1,396,640✔
746
    goto _return;
1,396,640✔
747
  }
748

749
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
20,100✔
750
  if (mnodeNum <= 0) {
20,100✔
751
    tscDebug("0x%" PRIx64 " qnode policy, empty node list", pRequest->requestId);
×
752
    goto _return;
×
753
  }
754

755
  void* pData = taosArrayGet(pMnodeList, 0);
20,100✔
756
  if (NULL == pData) {
20,100✔
757
    taosArrayDestroy(nodeList);
×
758
    return TSDB_CODE_OUT_OF_RANGE;
×
759
  }
760
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
20,100✔
761
    taosArrayDestroy(nodeList);
×
762
    return terrno;
×
763
  }
764

765
  tscDebug("0x%" PRIx64 " qnode policy, use mnode list, num:%d", pRequest->requestId, mnodeNum);
20,100✔
766

767
_return:
×
768

769
  *pNodeList = nodeList;
1,416,740✔
770

771
  return TSDB_CODE_SUCCESS;
1,416,740✔
772
}
773

774
void freeVgList(void* list) {
7,351,695✔
775
  SArray* pList = *(SArray**)list;
7,351,695✔
776
  taosArrayDestroy(pList);
7,352,961✔
777
}
7,343,378✔
778

779
int32_t buildAsyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SMetaData* pResultMeta) {
137,762,820✔
780
  SArray* pDbVgList = NULL;
137,762,820✔
781
  SArray* pQnodeList = NULL;
137,762,820✔
782
  FDelete fp = NULL;
137,762,820✔
783
  int32_t code = 0;
137,762,820✔
784

785
  switch (tsQueryPolicy) {
137,762,820✔
786
    case QUERY_POLICY_VNODE:
136,346,075✔
787
    case QUERY_POLICY_CLIENT: {
788
      if (pResultMeta) {
136,346,075✔
789
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
136,346,208✔
790
        if (NULL == pDbVgList) {
136,346,228✔
791
          code = terrno;
×
792
          goto _return;
×
793
        }
794
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
136,346,228✔
795
        for (int32_t i = 0; i < dbNum; ++i) {
270,671,846✔
796
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
134,325,606✔
797
          if (pRes->code || NULL == pRes->pRes) {
134,325,584✔
798
            continue;
500✔
799
          }
800

801
          if (NULL == taosArrayPush(pDbVgList, &pRes->pRes)) {
268,650,183✔
802
            code = terrno;
×
803
            goto _return;
×
804
          }
805
        }
806
      } else {
807
        fp = freeVgList;
×
808

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

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

831
            // catalogGetDBVgList will handle dbFName == null.
832
            code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
×
833
            if (code) {
×
834
              goto _return;
×
835
            }
836

837
            if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
×
838
              code = terrno;
×
839
              goto _return;
×
840
            }
841
          }
842
        }
843
      }
844

845
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
136,346,240✔
846
      break;
136,346,217✔
847
    }
848
    case QUERY_POLICY_HYBRID:
1,416,740✔
849
    case QUERY_POLICY_QNODE: {
850
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
1,444,728✔
851
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
27,988✔
852
        if (pRes->code) {
27,988✔
853
          pQnodeList = NULL;
×
854
        } else {
855
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
27,988✔
856
          if (NULL == pQnodeList) {
27,988✔
857
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
858
            goto _return;
×
859
          }
860
        }
861
      } else {
862
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
1,388,752✔
863
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
1,388,752✔
864
        if (pInst->pQnodeList) {
1,388,752✔
865
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
1,388,752✔
866
          if (NULL == pQnodeList) {
1,388,752✔
867
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
868
            goto _return;
×
869
          }
870
        }
871
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
1,388,752✔
872
      }
873

874
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
1,416,740✔
875
      break;
1,416,740✔
876
    }
877
    default:
40✔
878
      tscError("unknown query policy: %d", tsQueryPolicy);
40✔
879
      return TSDB_CODE_APP_ERROR;
×
880
  }
881

882
_return:
137,762,957✔
883
  taosArrayDestroyEx(pDbVgList, fp);
137,762,957✔
884
  taosArrayDestroy(pQnodeList);
137,762,966✔
885

886
  return code;
137,763,003✔
887
}
888

889
int32_t buildSyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList) {
7,407,792✔
890
  SArray* pDbVgList = NULL;
7,407,792✔
891
  SArray* pQnodeList = NULL;
7,407,792✔
892
  int32_t code = 0;
7,411,519✔
893

894
  switch (tsQueryPolicy) {
7,411,519✔
895
    case QUERY_POLICY_VNODE:
7,403,171✔
896
    case QUERY_POLICY_CLIENT: {
897
      int32_t dbNum = taosArrayGetSize(pRequest->dbList);
7,403,171✔
898
      if (dbNum > 0) {
7,415,292✔
899
        SCatalog*     pCtg = NULL;
7,354,325✔
900
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
7,353,981✔
901
        code = catalogGetHandle(pInst->clusterId, &pCtg);
7,349,094✔
902
        if (code != TSDB_CODE_SUCCESS) {
7,350,880✔
903
          goto _return;
×
904
        }
905

906
        pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
7,350,880✔
907
        if (NULL == pDbVgList) {
7,348,041✔
908
          code = terrno;
×
909
          goto _return;
×
910
        }
911
        SArray* pVgList = NULL;
7,348,041✔
912
        for (int32_t i = 0; i < dbNum; ++i) {
14,698,404✔
913
          char*            dbFName = taosArrayGet(pRequest->dbList, i);
7,348,746✔
914
          SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
7,355,440✔
915
                                   .requestId = pRequest->requestId,
7,353,257✔
916
                                   .requestObjRefId = pRequest->self,
7,347,294✔
917
                                   .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
7,346,940✔
918

919
          // catalogGetDBVgList will handle dbFName == null.
920
          code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
7,355,990✔
921
          if (code) {
7,351,251✔
922
            goto _return;
×
923
          }
924

925
          if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
7,355,447✔
926
            code = terrno;
×
927
            goto _return;
×
928
          }
929
        }
930
      }
931

932
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
7,418,648✔
933
      break;
7,414,361✔
934
    }
935
    case QUERY_POLICY_HYBRID:
×
936
    case QUERY_POLICY_QNODE: {
937
      TSC_ERR_JRET(getQnodeList(pRequest, &pQnodeList));
×
938

939
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
×
940
      break;
×
941
    }
942
    default:
8,348✔
943
      tscError("unknown query policy: %d", tsQueryPolicy);
8,348✔
944
      return TSDB_CODE_APP_ERROR;
×
945
  }
946

947
_return:
7,414,978✔
948

949
  taosArrayDestroyEx(pDbVgList, freeVgList);
7,412,451✔
950
  taosArrayDestroy(pQnodeList);
7,409,422✔
951

952
  return code;
7,414,382✔
953
}
954

955
int32_t scheduleQuery(SRequestObj* pRequest, SQueryPlan* pDag, SArray* pNodeList) {
7,411,642✔
956
  void* pTransporter = pRequest->pTscObj->pAppInfo->pTransporter;
7,411,642✔
957

958
  SExecResult      res = {0};
7,413,737✔
959
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
7,413,580✔
960
                           .requestId = pRequest->requestId,
7,408,395✔
961
                           .requestObjRefId = pRequest->self};
7,402,376✔
962
  SSchedulerReq    req = {
7,706,049✔
963
         .syncReq = true,
964
         .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
7,409,294✔
965
         .pConn = &conn,
966
         .pNodeList = pNodeList,
967
         .pDag = pDag,
968
         .sql = pRequest->sqlstr,
7,409,294✔
969
         .startTs = pRequest->metric.start,
7,407,485✔
970
         .execFp = NULL,
971
         .cbParam = NULL,
972
         .chkKillFp = chkRequestKilled,
973
         .chkKillParam = (void*)pRequest->self,
7,403,061✔
974
         .pExecRes = &res,
975
         .source = pRequest->source,
7,411,621✔
976
         .pWorkerCb = getTaskPoolWorkerCb(),
7,406,411✔
977
  };
978

979
  int32_t code = schedulerExecJob(&req, &pRequest->body.queryJob);
7,412,339✔
980

981
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
7,422,575✔
982
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
7,423,245✔
983

984
  if (code != TSDB_CODE_SUCCESS) {
7,421,263✔
985
    schedulerFreeJob(&pRequest->body.queryJob, 0);
×
986

987
    pRequest->code = code;
×
988
    terrno = code;
×
989
    return pRequest->code;
×
990
  }
991

992
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_DELETE == pRequest->type ||
7,421,263✔
993
      TDMT_VND_CREATE_TABLE == pRequest->type) {
50,077✔
994
    pRequest->body.resInfo.numOfRows = res.numOfRows;
7,405,760✔
995
    if (TDMT_VND_SUBMIT == pRequest->type) {
7,406,405✔
996
      STscObj*            pTscObj = pRequest->pTscObj;
7,369,932✔
997
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
7,369,660✔
998
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
7,372,817✔
999
    }
1000

1001
    schedulerFreeJob(&pRequest->body.queryJob, 0);
7,406,379✔
1002
  }
1003

1004
  pRequest->code = res.code;
7,421,635✔
1005
  terrno = res.code;
7,422,623✔
1006
  return pRequest->code;
7,419,460✔
1007
}
1008

1009
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
534,219,914✔
1010
  SArray*      pArray = NULL;
534,219,914✔
1011
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
534,219,914✔
1012
  if (NULL == pRsp->aCreateTbRsp) {
534,219,914✔
1013
    return TSDB_CODE_SUCCESS;
523,052,505✔
1014
  }
1015

1016
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
11,180,820✔
1017
  for (int32_t i = 0; i < tbNum; ++i) {
25,186,866✔
1018
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
14,004,694✔
1019
    if (pTbRsp->pMeta) {
14,004,992✔
1020
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
13,751,503✔
1021
    }
1022
  }
1023

1024
  return TSDB_CODE_SUCCESS;
11,182,172✔
1025
}
1026

1027
int32_t handleQueryExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
102,635,428✔
1028
  int32_t code = 0;
102,635,428✔
1029
  SArray* pArray = NULL;
102,635,428✔
1030
  SArray* pTbArray = (SArray*)res;
102,635,428✔
1031
  int32_t tbNum = taosArrayGetSize(pTbArray);
102,635,428✔
1032
  if (tbNum <= 0) {
102,635,719✔
1033
    return TSDB_CODE_SUCCESS;
×
1034
  }
1035

1036
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
102,635,719✔
1037
  if (NULL == pArray) {
102,635,238✔
1038
    return terrno;
×
1039
  }
1040

1041
  for (int32_t i = 0; i < tbNum; ++i) {
328,710,349✔
1042
    STbVerInfo* tbInfo = taosArrayGet(pTbArray, i);
226,075,090✔
1043
    if (NULL == tbInfo) {
226,075,620✔
1044
      code = terrno;
×
1045
      goto _return;
×
1046
    }
1047
    STbSVersion tbSver = {
226,075,620✔
1048
        .tbFName = tbInfo->tbFName, .sver = tbInfo->sversion, .tver = tbInfo->tversion, .rver = tbInfo->rversion};
226,075,141✔
1049
    if (NULL == taosArrayPush(pArray, &tbSver)) {
226,075,139✔
1050
      code = terrno;
×
1051
      goto _return;
×
1052
    }
1053
  }
1054

1055
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
102,635,259✔
1056
                           .requestId = pRequest->requestId,
102,634,830✔
1057
                           .requestObjRefId = pRequest->self,
102,635,766✔
1058
                           .mgmtEps = *epset};
1059

1060
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
102,634,835✔
1061

1062
_return:
102,635,729✔
1063

1064
  taosArrayDestroy(pArray);
102,635,695✔
1065
  return code;
102,635,748✔
1066
}
1067

1068
int32_t handleAlterTbExecRes(void* res, SCatalog* pCatalog) {
8,008,586✔
1069
  return catalogUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
8,008,586✔
1070
}
1071

1072
int32_t handleCreateTbExecRes(void* res, SCatalog* pCatalog) {
57,390,787✔
1073
  return catalogAsyncUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
57,390,787✔
1074
}
1075

1076
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
722,764,523✔
1077
  if (NULL == pRequest->body.resInfo.execRes.res) {
722,764,523✔
1078
    return pRequest->code;
46,231,274✔
1079
  }
1080

1081
  SCatalog*     pCatalog = NULL;
676,523,407✔
1082
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
676,524,813✔
1083

1084
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
676,537,071✔
1085
  if (code) {
676,531,528✔
1086
    return code;
×
1087
  }
1088

1089
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
676,531,528✔
1090
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
676,538,596✔
1091

1092
  switch (pRes->msgType) {
676,536,983✔
1093
    case TDMT_VND_ALTER_TABLE:
3,608,564✔
1094
    case TDMT_MND_ALTER_STB: {
1095
      code = handleAlterTbExecRes(pRes->res, pCatalog);
3,608,564✔
1096
      break;
3,608,564✔
1097
    }
1098
    case TDMT_VND_CREATE_TABLE: {
35,682,966✔
1099
      SArray* pList = (SArray*)pRes->res;
35,682,966✔
1100
      int32_t num = taosArrayGetSize(pList);
35,681,220✔
1101
      for (int32_t i = 0; i < num; ++i) {
77,659,719✔
1102
        void* res = taosArrayGetP(pList, i);
41,968,397✔
1103
        // handleCreateTbExecRes will handle res == null
1104
        code = handleCreateTbExecRes(res, pCatalog);
41,968,445✔
1105
      }
1106
      break;
35,691,322✔
1107
    }
1108
    case TDMT_MND_CREATE_STB: {
367,985✔
1109
      code = handleCreateTbExecRes(pRes->res, pCatalog);
367,985✔
1110
      break;
367,985✔
1111
    }
1112
    case TDMT_VND_SUBMIT: {
534,228,274✔
1113
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
534,228,274✔
1114

1115
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
534,238,952✔
1116
      break;
534,231,265✔
1117
    }
1118
    case TDMT_SCH_QUERY:
102,635,600✔
1119
    case TDMT_SCH_MERGE_QUERY: {
1120
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
102,635,600✔
1121
      break;
102,635,986✔
1122
    }
1123
    default:
32✔
1124
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self,
32✔
1125
               pRequest->type, pRequest->requestId);
1126
      code = TSDB_CODE_APP_ERROR;
×
1127
  }
1128

1129
  return code;
676,535,122✔
1130
}
1131

1132
static bool incompletaFileParsing(SNode* pStmt) {
707,761,566✔
1133
  return QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pStmt) ? false : ((SVnodeModifyOpStmt*)pStmt)->fileProcessing;
707,761,566✔
1134
}
1135

1136
void continuePostSubQuery(SRequestObj* pRequest, SSDataBlock* pBlock) {
×
1137
  SSqlCallbackWrapper* pWrapper = pRequest->pWrapper;
×
1138

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

1146
  if (TSDB_CODE_SUCCESS == code) {
×
1147
    code = qContinuePlanPostQuery(pRequest->pPostPlan);
×
1148
  }
1149

1150
  code = nodesReleaseAllocator(pWrapper->pParseCtx->allocatorId);
×
1151
  handleQueryAnslyseRes(pWrapper, NULL, code);
×
1152
}
×
1153

1154
void returnToUser(SRequestObj* pRequest) {
49,882,540✔
1155
  if (pRequest->relation.userRefId == pRequest->self || 0 == pRequest->relation.userRefId) {
49,882,540✔
1156
    // return to client
1157
    doRequestCallback(pRequest, pRequest->code);
49,882,540✔
1158
    return;
49,882,540✔
1159
  }
1160

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

1174
static int32_t createResultBlock(TAOS_RES* pRes, int32_t numOfRows, SSDataBlock** pBlock) {
×
1175
  int64_t     lastTs = 0;
×
1176
  TAOS_FIELD* pResFields = taos_fetch_fields(pRes);
×
1177
  int32_t     numOfFields = taos_num_fields(pRes);
×
1178

1179
  int32_t code = createDataBlock(pBlock);
×
1180
  if (code) {
×
1181
    return code;
×
1182
  }
1183

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

1193
  code = blockDataEnsureCapacity(*pBlock, numOfRows);
×
1194
  if (TSDB_CODE_SUCCESS != code) {
×
1195
    blockDataDestroy(*pBlock);
×
1196
    return code;
×
1197
  }
1198

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

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

1220
    tscInfo("[create stream with histroy] lastKey:%" PRId64 " vgId:%d, vgVer:%" PRId64, ts, *(int32_t*)pRow[1],
×
1221
            *(int64_t*)pRow[2]);
1222
  }
1223

1224
  (*pBlock)->info.window.ekey = lastTs;
×
1225
  (*pBlock)->info.rows = numOfRows;
×
1226

1227
  tscInfo("[create stream with histroy] lastKey:%" PRId64 " numOfRows:%d from all vgroups", lastTs, numOfRows);
×
1228
  return TSDB_CODE_SUCCESS;
×
1229
}
1230

1231
void postSubQueryFetchCb(void* param, TAOS_RES* res, int32_t rowNum) {
×
1232
  SRequestObj* pRequest = (SRequestObj*)res;
×
1233
  if (pRequest->code) {
×
1234
    returnToUser(pRequest);
×
1235
    return;
×
1236
  }
1237

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

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

1256
  blockDataDestroy(pBlock);
×
1257
}
1258

1259
void handlePostSubQuery(SSqlCallbackWrapper* pWrapper) {
×
1260
  SRequestObj* pRequest = pWrapper->pRequest;
×
1261
  if (TD_RES_QUERY(pRequest)) {
×
1262
    taosAsyncFetchImpl(pRequest, postSubQueryFetchCb, pWrapper);
×
1263
    return;
×
1264
  }
1265

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

1276
// todo refacto the error code  mgmt
1277
void schedulerExecCb(SExecResult* pResult, void* param, int32_t code) {
715,036,037✔
1278
  SSqlCallbackWrapper* pWrapper = param;
715,036,037✔
1279
  SRequestObj*         pRequest = pWrapper->pRequest;
715,036,037✔
1280
  STscObj*             pTscObj = pRequest->pTscObj;
715,042,859✔
1281

1282
  pRequest->code = code;
715,039,820✔
1283
  if (pResult) {
715,038,779✔
1284
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
714,969,927✔
1285
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
714,982,982✔
1286
  }
1287

1288
  int32_t type = pRequest->type;
715,027,854✔
1289
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
715,007,324✔
1290
    if (pResult) {
565,899,313✔
1291
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
565,876,023✔
1292

1293
      // record the insert rows
1294
      if (TDMT_VND_SUBMIT == type) {
565,874,323✔
1295
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
527,197,766✔
1296
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
527,202,437✔
1297
      }
1298
    }
1299
    schedulerFreeJob(&pRequest->body.queryJob, 0);
565,901,345✔
1300
  }
1301

1302
  taosMemoryFree(pResult);
715,042,365✔
1303
  tscDebug("req:0x%" PRIx64 ", enter scheduler exec cb, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
715,035,558✔
1304
           pRequest->requestId);
1305

1306
  if (code != TSDB_CODE_SUCCESS && NEED_CLIENT_HANDLE_ERROR(code) && pRequest->sqlstr != NULL &&
715,022,629✔
1307
      pRequest->stmtBindVersion == 0) {
81,089✔
1308
    tscDebug("req:0x%" PRIx64 ", client retry to handle the error, code:%s, tryCount:%d, QID:0x%" PRIx64,
81,089✔
1309
             pRequest->self, tstrerror(code), pRequest->retry, pRequest->requestId);
1310
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
81,089✔
1311
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1312
    }
1313
    restartAsyncQuery(pRequest, code);
81,089✔
1314
    return;
81,089✔
1315
  }
1316

1317
  tscTrace("req:0x%" PRIx64 ", scheduler exec cb, request type:%s", pRequest->self, TMSG_INFO(pRequest->type));
714,941,540✔
1318
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
714,941,540✔
1319
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
2,986,437✔
1320
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1321
    }
1322
  }
1323

1324
  pRequest->metric.execCostUs = taosGetTimestampUs() - pRequest->metric.execStart;
714,957,105✔
1325
  int32_t code1 = handleQueryExecRsp(pRequest);
714,946,129✔
1326
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
714,960,610✔
1327
    pRequest->code = code1;
×
1328
  }
1329

1330
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
1,422,724,045✔
1331
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
707,755,962✔
1332
    continueInsertFromCsv(pWrapper, pRequest);
11,424✔
1333
    return;
11,424✔
1334
  }
1335

1336
  if (pRequest->relation.nextRefId) {
714,954,166✔
1337
    handlePostSubQuery(pWrapper);
×
1338
  } else {
1339
    destorySqlCallbackWrapper(pWrapper);
714,955,831✔
1340
    pRequest->pWrapper = NULL;
714,945,876✔
1341

1342
    // return to client
1343
    doRequestCallback(pRequest, code);
714,949,856✔
1344
  }
1345
}
1346

1347
void launchQueryImpl(SRequestObj* pRequest, SQuery* pQuery, bool keepQuery, void** res) {
7,801,848✔
1348
  int32_t code = 0;
7,801,848✔
1349
  int32_t subplanNum = 0;
7,801,848✔
1350

1351
  if (pQuery->pRoot) {
7,801,848✔
1352
    pRequest->stmtType = pQuery->pRoot->type;
7,416,878✔
1353
  }
1354

1355
  if (pQuery->pRoot && !pRequest->inRetry) {
7,802,809✔
1356
    STscObj*            pTscObj = pRequest->pTscObj;
7,417,675✔
1357
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
7,412,226✔
1358
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type) {
7,418,931✔
1359
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
7,406,142✔
1360
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
9,125✔
1361
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
9,113✔
1362
    }
1363
  }
1364

1365
  pRequest->body.execMode = pQuery->execMode;
7,806,132✔
1366
  switch (pQuery->execMode) {
7,810,508✔
1367
    case QUERY_EXEC_MODE_LOCAL:
×
1368
      if (!pRequest->validateOnly) {
×
1369
        if (NULL == pQuery->pRoot) {
×
1370
          terrno = TSDB_CODE_INVALID_PARA;
×
1371
          code = terrno;
×
1372
        } else {
1373
          code = execLocalCmd(pRequest, pQuery);
×
1374
        }
1375
      }
1376
      break;
×
1377
    case QUERY_EXEC_MODE_RPC:
390,433✔
1378
      if (!pRequest->validateOnly) {
390,433✔
1379
        code = execDdlQuery(pRequest, pQuery);
390,445✔
1380
      }
1381
      break;
390,445✔
1382
    case QUERY_EXEC_MODE_SCHEDULE: {
7,405,759✔
1383
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
7,405,759✔
1384
      if (NULL == pMnodeList) {
7,409,765✔
1385
        code = terrno;
×
1386
        break;
×
1387
      }
1388
      SQueryPlan* pDag = NULL;
7,409,765✔
1389
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
7,410,075✔
1390
      if (TSDB_CODE_SUCCESS == code) {
7,413,327✔
1391
        pRequest->body.subplanNum = pDag->numOfSubplans;
7,411,104✔
1392
        if (!pRequest->validateOnly) {
7,413,326✔
1393
          SArray* pNodeList = NULL;
7,406,684✔
1394
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
7,408,392✔
1395

1396
          if (TSDB_CODE_SUCCESS == code) {
7,414,080✔
1397
            code = sessMetricCheckValue((SSessMetric*)pRequest->pTscObj->pSessMetric, SESSION_MAX_CALL_VNODE_NUM,
7,415,735✔
1398
                                        taosArrayGetSize(pNodeList));
7,416,615✔
1399
          }
1400

1401
          if (TSDB_CODE_SUCCESS == code) {
7,408,440✔
1402
            code = scheduleQuery(pRequest, pDag, pNodeList);
7,408,440✔
1403
          }
1404
          taosArrayDestroy(pNodeList);
7,418,421✔
1405
        }
1406
      }
1407
      taosArrayDestroy(pMnodeList);
7,416,778✔
1408
      break;
7,420,335✔
1409
    }
1410
    case QUERY_EXEC_MODE_EMPTY_RESULT:
×
1411
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
1412
      break;
×
1413
    default:
×
1414
      break;
×
1415
  }
1416

1417
  if (!keepQuery) {
7,811,085✔
1418
    qDestroyQuery(pQuery);
×
1419
  }
1420

1421
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
7,811,085✔
1422
    int ret = removeMeta(pRequest->pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type));
23,311✔
1423
    if (TSDB_CODE_SUCCESS != ret) {
23,311✔
1424
      tscError("req:0x%" PRIx64 ", remove meta failed,code:%d, QID:0x%" PRIx64, pRequest->self, ret,
×
1425
               pRequest->requestId);
1426
    }
1427
  }
1428

1429
  if (TSDB_CODE_SUCCESS == code) {
7,809,224✔
1430
    code = handleQueryExecRsp(pRequest);
7,808,361✔
1431
  }
1432

1433
  if (TSDB_CODE_SUCCESS != code) {
7,812,334✔
1434
    pRequest->code = code;
7,491✔
1435
  }
1436

1437
  if (res) {
7,812,334✔
1438
    *res = pRequest->body.resInfo.execRes.res;
×
1439
    pRequest->body.resInfo.execRes.res = NULL;
×
1440
  }
1441
}
7,812,334✔
1442

1443
static int32_t asyncExecSchQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta,
715,412,766✔
1444
                                 SSqlCallbackWrapper* pWrapper) {
1445
  int32_t code = TSDB_CODE_SUCCESS;
715,412,766✔
1446
  pRequest->type = pQuery->msgType;
715,412,766✔
1447
  SArray*     pMnodeList = NULL;
715,407,284✔
1448
  SArray*     pNodeList = NULL;
715,407,284✔
1449
  SQueryPlan* pDag = NULL;
715,386,901✔
1450
  int64_t     st = taosGetTimestampUs();
715,397,986✔
1451

1452
  if (!pRequest->parseOnly) {
715,397,986✔
1453
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
715,395,387✔
1454
    if (NULL == pMnodeList) {
715,382,267✔
1455
      code = terrno;
×
1456
    }
1457
    SPlanContext cxt = {.queryId = pRequest->requestId,
779,258,609✔
1458
                        .acctId = pRequest->pTscObj->acctId,
715,424,253✔
1459
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
715,428,206✔
1460
                        .pAstRoot = pQuery->pRoot,
715,439,013✔
1461
                        .showRewrite = pQuery->showRewrite,
715,434,915✔
1462
                        .isView = pWrapper->pParseCtx->isView,
715,429,471✔
1463
                        .isAudit = pWrapper->pParseCtx->isAudit,
715,412,240✔
1464
                        .privInfo = pWrapper->pParseCtx->privInfo,
715,408,110✔
1465
                        .pMsg = pRequest->msgBuf,
715,424,364✔
1466
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1467
                        .pUser = pRequest->pTscObj->user,
715,412,020✔
1468
                        .userId = pRequest->pTscObj->userId,
715,401,679✔
1469
                        .sysInfo = pRequest->pTscObj->sysInfo,
715,414,280✔
1470
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
715,408,054✔
1471
                        .allocatorId = pRequest->stmtBindVersion > 0 ? 0 : pRequest->allocatorRefId};
715,398,174✔
1472
    if (TSDB_CODE_SUCCESS == code) {
715,409,455✔
1473
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
715,411,089✔
1474
    }
1475
    if (code) {
715,409,650✔
1476
      tscError("req:0x%" PRIx64 " requestId:0x%" PRIx64 ", failed to create query plan, code:%s msg:%s", pRequest->self,
219,220✔
1477
               pRequest->requestId, tstrerror(code), cxt.pMsg);
1478
    } else {
1479
      pRequest->body.subplanNum = pDag->numOfSubplans;
715,190,430✔
1480
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
715,193,260✔
1481
    }
1482
  }
1483

1484
  pRequest->metric.execStart = taosGetTimestampUs();
715,415,199✔
1485
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
715,417,540✔
1486

1487
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
715,406,021✔
1488
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
715,020,577✔
1489
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
137,762,908✔
1490
    }
1491

1492
    if (code == TSDB_CODE_SUCCESS) {
715,020,362✔
1493
      code = sessMetricCheckValue((SSessMetric*)pRequest->pTscObj->pSessMetric, SESSION_MAX_CALL_VNODE_NUM,
714,996,008✔
1494
                                  taosArrayGetSize(pNodeList));
715,015,317✔
1495
    }
1496

1497
    if (code == TSDB_CODE_SUCCESS) {
715,020,372✔
1498
      SRequestConnInfo conn = {.pTrans = getAppInfo(pRequest)->pTransporter,
715,017,812✔
1499
                               .requestId = pRequest->requestId,
715,020,597✔
1500
                               .requestObjRefId = pRequest->self};
715,032,443✔
1501
      SSchedulerReq    req = {
746,961,492✔
1502
             .syncReq = false,
1503
             .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
715,004,578✔
1504
             .pConn = &conn,
1505
             .pNodeList = pNodeList,
1506
             .pDag = pDag,
1507
             .allocatorRefId = pRequest->allocatorRefId,
715,004,578✔
1508
             .sql = pRequest->sqlstr,
715,003,854✔
1509
             .startTs = pRequest->metric.start,
714,998,831✔
1510
             .execFp = schedulerExecCb,
1511
             .cbParam = pWrapper,
1512
             .chkKillFp = chkRequestKilled,
1513
             .chkKillParam = (void*)pRequest->self,
714,999,523✔
1514
             .pExecRes = NULL,
1515
             .source = pRequest->source,
715,006,114✔
1516
             .pWorkerCb = getTaskPoolWorkerCb(),
715,011,951✔
1517
      };
1518

1519
      if (TSDB_CODE_SUCCESS == code) {
715,022,431✔
1520
        code = schedulerExecJob(&req, &pRequest->body.queryJob);
715,043,751✔
1521
      }
1522
      taosArrayDestroy(pNodeList);
715,014,664✔
1523
      taosArrayDestroy(pMnodeList);
715,042,034✔
1524
      return code;
715,025,734✔
1525
    }
1526
  }
1527

1528
  qDestroyQueryPlan(pDag);
378,725✔
1529
  tscDebug("req:0x%" PRIx64 ", plan not executed, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
391,288✔
1530
           pRequest->requestId);
1531
  destorySqlCallbackWrapper(pWrapper);
391,288✔
1532
  pRequest->pWrapper = NULL;
391,288✔
1533
  if (TSDB_CODE_SUCCESS != code) {
391,288✔
1534
    pRequest->code = code;
221,780✔
1535
  }
1536

1537
  doRequestCallback(pRequest, code);
391,288✔
1538

1539
  // todo not to be released here
1540
  taosArrayDestroy(pMnodeList);
391,288✔
1541
  taosArrayDestroy(pNodeList);
391,288✔
1542

1543
  return code;
391,268✔
1544
}
1545

1546
void launchAsyncQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta, SSqlCallbackWrapper* pWrapper) {
736,260,891✔
1547
  int32_t code = 0;
736,260,891✔
1548

1549
  if (pRequest->parseOnly) {
736,260,891✔
1550
    doRequestCallback(pRequest, 0);
258,597✔
1551
    return;
258,597✔
1552
  }
1553

1554
  pRequest->body.execMode = pQuery->execMode;
736,008,750✔
1555
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
735,997,146✔
1556
    destorySqlCallbackWrapper(pWrapper);
20,586,616✔
1557
    pRequest->pWrapper = NULL;
20,586,076✔
1558
  }
1559

1560
  if (pQuery->pRoot && !pRequest->inRetry) {
735,967,220✔
1561
    STscObj*            pTscObj = pRequest->pTscObj;
735,991,389✔
1562
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
735,990,322✔
1563
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
735,996,947✔
1564
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
577,273,421✔
1565
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
527,001,167✔
1566
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
208,977,607✔
1567
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
98,621,098✔
1568
    }
1569
  }
1570

1571
  switch (pQuery->execMode) {
735,954,658✔
1572
    case QUERY_EXEC_MODE_LOCAL:
5,271,301✔
1573
      asyncExecLocalCmd(pRequest, pQuery);
5,271,301✔
1574
      break;
5,271,301✔
1575
    case QUERY_EXEC_MODE_RPC:
14,801,322✔
1576
      code = asyncExecDdlQuery(pRequest, pQuery);
14,801,322✔
1577
      break;
14,801,877✔
1578
    case QUERY_EXEC_MODE_SCHEDULE: {
715,396,303✔
1579
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
715,396,303✔
1580
      break;
715,431,766✔
1581
    }
1582
    case QUERY_EXEC_MODE_EMPTY_RESULT:
513,442✔
1583
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
513,442✔
1584
      doRequestCallback(pRequest, 0);
513,442✔
1585
      break;
513,442✔
UNCOV
1586
    default:
×
1587
      tscError("req:0x%" PRIx64 ", invalid execMode %d", pRequest->self, pQuery->execMode);
×
1588
      doRequestCallback(pRequest, -1);
×
1589
      break;
×
1590
  }
1591
}
1592

1593
int32_t refreshMeta(STscObj* pTscObj, SRequestObj* pRequest) {
10,850✔
1594
  SCatalog* pCatalog = NULL;
10,850✔
1595
  int32_t   code = 0;
10,850✔
1596
  int32_t   dbNum = taosArrayGetSize(pRequest->dbList);
10,850✔
1597
  int32_t   tblNum = taosArrayGetSize(pRequest->tableList);
10,850✔
1598

1599
  if (dbNum <= 0 && tblNum <= 0) {
10,850✔
1600
    return TSDB_CODE_APP_ERROR;
10,850✔
1601
  }
1602

UNCOV
1603
  code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
×
1604
  if (code != TSDB_CODE_SUCCESS) {
×
1605
    return code;
×
1606
  }
1607

UNCOV
1608
  SRequestConnInfo conn = {.pTrans = pTscObj->pAppInfo->pTransporter,
×
1609
                           .requestId = pRequest->requestId,
×
1610
                           .requestObjRefId = pRequest->self,
×
1611
                           .mgmtEps = getEpSet_s(&pTscObj->pAppInfo->mgmtEp)};
×
1612

UNCOV
1613
  for (int32_t i = 0; i < dbNum; ++i) {
×
1614
    char* dbFName = taosArrayGet(pRequest->dbList, i);
×
1615

1616
    // catalogRefreshDBVgInfo will handle dbFName == null.
UNCOV
1617
    code = catalogRefreshDBVgInfo(pCatalog, &conn, dbFName);
×
1618
    if (code != TSDB_CODE_SUCCESS) {
×
1619
      return code;
×
1620
    }
1621
  }
1622

UNCOV
1623
  for (int32_t i = 0; i < tblNum; ++i) {
×
1624
    SName* tableName = taosArrayGet(pRequest->tableList, i);
×
1625

1626
    // catalogRefreshTableMeta will handle tableName == null.
UNCOV
1627
    code = catalogRefreshTableMeta(pCatalog, &conn, tableName, -1);
×
1628
    if (code != TSDB_CODE_SUCCESS) {
×
1629
      return code;
×
1630
    }
1631
  }
1632

UNCOV
1633
  return code;
×
1634
}
1635

1636
int32_t removeMeta(STscObj* pTscObj, SArray* tbList, bool isView) {
4,235,799✔
1637
  SCatalog* pCatalog = NULL;
4,235,799✔
1638
  int32_t   tbNum = taosArrayGetSize(tbList);
4,235,799✔
1639
  int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
4,235,799✔
1640
  if (code != TSDB_CODE_SUCCESS) {
4,235,799✔
UNCOV
1641
    return code;
×
1642
  }
1643

1644
  if (isView) {
4,235,799✔
1645
    for (int32_t i = 0; i < tbNum; ++i) {
626,860✔
1646
      SName* pViewName = taosArrayGet(tbList, i);
313,430✔
1647
      char   dbFName[TSDB_DB_FNAME_LEN];
310,304✔
1648
      if (NULL == pViewName) {
313,430✔
UNCOV
1649
        continue;
×
1650
      }
1651
      (void)tNameGetFullDbName(pViewName, dbFName);
313,430✔
1652
      TSC_ERR_RET(catalogRemoveViewMeta(pCatalog, dbFName, 0, pViewName->tname, 0));
313,430✔
1653
    }
1654
  } else {
1655
    for (int32_t i = 0; i < tbNum; ++i) {
6,089,344✔
1656
      SName* pTbName = taosArrayGet(tbList, i);
2,166,975✔
1657
      TSC_ERR_RET(catalogRemoveTableMeta(pCatalog, pTbName));
2,166,975✔
1658
    }
1659
  }
1660

1661
  return TSDB_CODE_SUCCESS;
4,235,799✔
1662
}
1663

1664
int32_t initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet) {
2,392,628✔
1665
  pEpSet->version = 0;
2,392,628✔
1666

1667
  // init mnode ip set
1668
  SEpSet* mgmtEpSet = &(pEpSet->epSet);
2,394,014✔
1669
  mgmtEpSet->numOfEps = 0;
2,393,984✔
1670
  mgmtEpSet->inUse = 0;
2,394,014✔
1671

1672
  if (firstEp && firstEp[0] != 0) {
2,393,488✔
1673
    if (strlen(firstEp) >= TSDB_EP_LEN) {
2,393,453✔
UNCOV
1674
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1675
      return -1;
×
1676
    }
1677

1678
    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
2,393,453✔
1679
    if (code != TSDB_CODE_SUCCESS) {
2,392,936✔
UNCOV
1680
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1681
      return terrno;
×
1682
    }
1683
    // uint32_t addr = 0;
1684
    SIpAddr addr = {0};
2,392,936✔
1685
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
2,393,282✔
1686
    if (code) {
2,393,123✔
1687
      tscError("failed to resolve firstEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
148✔
1688
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1689
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
136✔
1690
    } else {
1691
      mgmtEpSet->numOfEps++;
2,392,975✔
1692
    }
1693
  }
1694

1695
  if (secondEp && secondEp[0] != 0) {
2,393,656✔
1696
    if (strlen(secondEp) >= TSDB_EP_LEN) {
1,562,146✔
UNCOV
1697
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1698
      return terrno;
×
1699
    }
1700

1701
    int32_t code = taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
1,562,146✔
1702
    if (code != TSDB_CODE_SUCCESS) {
1,562,593✔
UNCOV
1703
      return code;
×
1704
    }
1705
    SIpAddr addr = {0};
1,562,593✔
1706
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
1,562,286✔
1707
    if (code) {
1,562,623✔
UNCOV
1708
      tscError("failed to resolve secondEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
×
1709
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
UNCOV
1710
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
×
1711
    } else {
1712
      mgmtEpSet->numOfEps++;
1,562,623✔
1713
    }
1714
  }
1715

1716
  if (mgmtEpSet->numOfEps == 0) {
2,394,133✔
1717
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
136✔
1718
    return TSDB_CODE_RPC_NETWORK_UNAVAIL;
136✔
1719
  }
1720

1721
  return 0;
2,393,760✔
1722
}
1723

1724
int32_t taosConnectImpl(const char* user, const char* auth, int32_t totpCode, const char* db, __taos_async_fn_t fp,
2,394,032✔
1725
                        void* param, SAppInstInfo* pAppInfo, int connType, STscObj** pTscObj) {
1726
  *pTscObj = NULL;
2,394,032✔
1727
  int32_t code = createTscObj(user, auth, db, connType, pAppInfo, pTscObj);
2,394,032✔
1728
  if (TSDB_CODE_SUCCESS != code) {
2,394,032✔
UNCOV
1729
    return code;
×
1730
  }
1731

1732
  SRequestObj* pRequest = NULL;
2,394,032✔
1733
  code = createRequest((*pTscObj)->id, TDMT_MND_CONNECT, 0, &pRequest);
2,394,032✔
1734
  if (TSDB_CODE_SUCCESS != code) {
2,393,824✔
UNCOV
1735
    destroyTscObj(*pTscObj);
×
1736
    return code;
×
1737
  }
1738

1739
  pRequest->sqlstr = taosStrdup("taos_connect");
2,393,824✔
1740
  if (pRequest->sqlstr) {
2,394,002✔
1741
    pRequest->sqlLen = strlen(pRequest->sqlstr);
2,394,032✔
1742
  } else {
UNCOV
1743
    return terrno;
×
1744
  }
1745

1746
  SMsgSendInfo* body = NULL;
2,394,032✔
1747
  code = buildConnectMsg(pRequest, &body, totpCode);
2,394,032✔
1748
  if (TSDB_CODE_SUCCESS != code) {
2,392,629✔
UNCOV
1749
    destroyTscObj(*pTscObj);
×
1750
    return code;
×
1751
  }
1752

1753
  // int64_t transporterId = 0;
1754
  SEpSet epset = getEpSet_s(&(*pTscObj)->pAppInfo->mgmtEp);
2,392,629✔
1755
  code = asyncSendMsgToServer((*pTscObj)->pAppInfo->pTransporter, &epset, NULL, body);
2,393,929✔
1756
  if (TSDB_CODE_SUCCESS != code) {
2,394,032✔
UNCOV
1757
    destroyTscObj(*pTscObj);
×
1758
    tscError("failed to send connect msg to server, code:%s", tstrerror(code));
×
1759
    return code;
×
1760
  }
1761
  if (TSDB_CODE_SUCCESS != tsem_wait(&pRequest->body.rspSem)) {
2,394,032✔
UNCOV
1762
    destroyTscObj(*pTscObj);
×
1763
    tscError("failed to wait sem, code:%s", terrstr());
×
1764
    return terrno;
×
1765
  }
1766
  if (pRequest->code != TSDB_CODE_SUCCESS) {
2,394,032✔
1767
    const char* errorMsg = (code == TSDB_CODE_RPC_FQDN_ERROR) ? taos_errstr(pRequest) : tstrerror(pRequest->code);
11,949✔
1768
    tscError("failed to connect to server, reason: %s", errorMsg);
11,949✔
1769

1770
    terrno = pRequest->code;
11,949✔
1771
    destroyRequest(pRequest);
11,949✔
1772
    taos_close_internal(*pTscObj);
11,949✔
1773
    *pTscObj = NULL;
11,949✔
1774
    return terrno;
11,949✔
1775
  }
1776
  if (connType == CONN_TYPE__AUTH_TEST) {
2,382,083✔
UNCOV
1777
    terrno = TSDB_CODE_SUCCESS;
×
1778
    destroyRequest(pRequest);
×
1779
    taos_close_internal(*pTscObj);
×
1780
    *pTscObj = NULL;
×
1781
    return TSDB_CODE_SUCCESS;
×
1782
  }
1783

1784
  tscInfo("conn:0x%" PRIx64 ", connection is opening, connId:%u, dnodeConn:%p, QID:0x%" PRIx64, (*pTscObj)->id,
2,382,083✔
1785
          (*pTscObj)->connId, (*pTscObj)->pAppInfo->pTransporter, pRequest->requestId);
1786
  destroyRequest(pRequest);
2,382,083✔
1787
  return code;
2,382,083✔
1788
}
1789

1790
static int32_t buildConnectMsg(SRequestObj* pRequest, SMsgSendInfo** pMsgSendInfo, int32_t totpCode) {
2,394,032✔
1791
  *pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
2,394,032✔
1792
  if (*pMsgSendInfo == NULL) {
2,394,002✔
UNCOV
1793
    return terrno;
×
1794
  }
1795

1796
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
2,394,032✔
1797

1798
  (*pMsgSendInfo)->requestObjRefId = pRequest->self;
2,394,027✔
1799
  (*pMsgSendInfo)->requestId = pRequest->requestId;
2,394,027✔
1800
  (*pMsgSendInfo)->fp = getMsgRspHandle((*pMsgSendInfo)->msgType);
2,394,002✔
1801
  (*pMsgSendInfo)->param = taosMemoryCalloc(1, sizeof(pRequest->self));
2,394,032✔
1802
  if (NULL == (*pMsgSendInfo)->param) {
2,393,990✔
UNCOV
1803
    taosMemoryFree(*pMsgSendInfo);
×
1804
    return terrno;
×
1805
  }
1806

1807
  *(int64_t*)(*pMsgSendInfo)->param = pRequest->self;
2,393,782✔
1808

1809
  SConnectReq connectReq = {0};
2,394,015✔
1810
  STscObj*    pObj = pRequest->pTscObj;
2,393,985✔
1811

1812
  char* db = getDbOfConnection(pObj);
2,392,754✔
1813
  if (db != NULL) {
2,394,032✔
1814
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
482,226✔
1815
  } else if (terrno) {
1,911,806✔
UNCOV
1816
    taosMemoryFree(*pMsgSendInfo);
×
1817
    return terrno;
×
1818
  }
1819
  taosMemoryFreeClear(db);
2,394,032✔
1820

1821
  connectReq.connType = pObj->connType;
2,394,002✔
1822
  connectReq.pid = appInfo.pid;
2,393,482✔
1823
  connectReq.startTime = appInfo.startTime;
2,393,720✔
1824
  connectReq.totpCode = totpCode;
2,393,720✔
1825
  connectReq.connectTime = taosGetTimestampMs();
2,393,291✔
1826

1827
  tstrncpy(connectReq.app, appInfo.appName, sizeof(connectReq.app));
2,393,291✔
1828
  tstrncpy(connectReq.user, pObj->user, sizeof(connectReq.user));
2,393,477✔
1829
  tstrncpy(connectReq.passwd, pObj->pass, sizeof(connectReq.passwd));
2,393,720✔
1830
  tstrncpy(connectReq.token, pObj->token, sizeof(connectReq.token));
2,393,512✔
1831
  tstrncpy(connectReq.sVer, td_version, sizeof(connectReq.sVer));
2,392,771✔
1832
  tSignConnectReq(&connectReq);
2,392,771✔
1833

1834
  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connectReq);
2,393,965✔
1835
  void*   pReq = taosMemoryMalloc(contLen);
2,390,961✔
1836
  if (NULL == pReq) {
2,393,247✔
UNCOV
1837
    taosMemoryFree(*pMsgSendInfo);
×
1838
    return terrno;
×
1839
  }
1840

1841
  if (-1 == tSerializeSConnectReq(pReq, contLen, &connectReq)) {
2,393,247✔
UNCOV
1842
    taosMemoryFree(*pMsgSendInfo);
×
UNCOV
1843
    taosMemoryFree(pReq);
×
1844
    return terrno;
×
1845
  }
1846

1847
  (*pMsgSendInfo)->msgInfo.len = contLen;
2,392,744✔
1848
  (*pMsgSendInfo)->msgInfo.pData = pReq;
2,392,229✔
1849
  return TSDB_CODE_SUCCESS;
2,392,591✔
1850
}
1851

1852
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,409,694,903✔
1853
  if (NULL == pEpSet) {
1,409,694,903✔
1854
    return;
1,406,239,698✔
1855
  }
1856

1857
  switch (pSendInfo->target.type) {
3,456,415✔
1858
    case TARGET_TYPE_MNODE:
420✔
1859
      if (NULL == pTscObj) {
420✔
UNCOV
1860
        tscError("mnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1861
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
UNCOV
1862
        return;
×
1863
      }
1864

1865
      SEpSet  originEpset = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
420✔
1866
      SEpSet* pOrig = &originEpset;
420✔
1867
      SEp*    pOrigEp = &pOrig->eps[pOrig->inUse];
420✔
1868
      SEp*    pNewEp = &pEpSet->eps[pEpSet->inUse];
420✔
1869
      tscDebug("mnode epset updated from %d/%d=>%s:%d to %d/%d=>%s:%d in client", pOrig->inUse, pOrig->numOfEps,
420✔
1870
               pOrigEp->fqdn, pOrigEp->port, pEpSet->inUse, pEpSet->numOfEps, pNewEp->fqdn, pNewEp->port);
1871
      updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
420✔
1872
      break;
338,653✔
1873
    case TARGET_TYPE_VNODE: {
3,259,113✔
1874
      if (NULL == pTscObj) {
3,259,113✔
UNCOV
1875
        tscError("vnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1876
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
UNCOV
1877
        return;
×
1878
      }
1879

1880
      SCatalog* pCatalog = NULL;
3,259,113✔
1881
      int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
3,259,069✔
1882
      if (code != TSDB_CODE_SUCCESS) {
3,259,107✔
UNCOV
1883
        tscError("fail to get catalog handle, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1884
                 tstrerror(code));
UNCOV
1885
        return;
×
1886
      }
1887

1888
      code = catalogUpdateVgEpSet(pCatalog, pSendInfo->target.dbFName, pSendInfo->target.vgId, pEpSet);
3,259,107✔
1889
      if (code != TSDB_CODE_SUCCESS) {
3,259,208✔
1890
        tscError("fail to update catalog vg epset, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
10✔
1891
                 tstrerror(code));
UNCOV
1892
        return;
×
1893
      }
1894
      taosMemoryFreeClear(pSendInfo->target.dbFName);
3,259,198✔
1895
      break;
3,259,162✔
1896
    }
1897
    default:
198,358✔
1898
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
198,358✔
1899
      break;
198,640✔
1900
  }
1901
}
1902

1903
int32_t doProcessMsgFromServerImpl(SRpcMsg* pMsg, SEpSet* pEpSet) {
1,410,309,378✔
1904
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
1,410,309,378✔
1905
  if (pMsg->info.ahandle == NULL) {
1,410,312,042✔
1906
    tscError("doProcessMsgFromServer pMsg->info.ahandle == NULL");
548,957✔
1907
    rpcFreeCont(pMsg->pCont);
548,957✔
1908
    taosMemoryFree(pEpSet);
548,957✔
1909
    return TSDB_CODE_TSC_INTERNAL_ERROR;
548,957✔
1910
  }
1911

1912
  STscObj* pTscObj = NULL;
1,409,758,285✔
1913

1914
  STraceId* trace = &pMsg->info.traceId;
1,409,758,285✔
1915
  char      tbuf[40] = {0};
1,409,764,595✔
1916
  TRACE_TO_STR(trace, tbuf);
1,409,759,599✔
1917

1918
  tscDebug("QID:%s, process message from server, handle:%p, message:%s, size:%d, code:%s", tbuf, pMsg->info.handle,
1,409,763,187✔
1919
           TMSG_INFO(pMsg->msgType), pMsg->contLen, tstrerror(pMsg->code));
1920

1921
  if (pSendInfo->requestObjRefId != 0) {
1,409,764,810✔
1922
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
1,186,781,014✔
1923
    if (pRequest) {
1,186,779,627✔
1924
      if (pRequest->self != pSendInfo->requestObjRefId) {
1,179,651,134✔
UNCOV
1925
        tscError("doProcessMsgFromServer req:0x%" PRId64 " != pSendInfo->requestObjRefId:0x%" PRId64, pRequest->self,
×
1926
                 pSendInfo->requestObjRefId);
1927

UNCOV
1928
        if (TSDB_CODE_SUCCESS != taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId)) {
×
1929
          tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1930
        }
UNCOV
1931
        rpcFreeCont(pMsg->pCont);
×
1932
        taosMemoryFree(pEpSet);
×
1933
        destroySendMsgInfo(pSendInfo);
×
1934
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1935
      }
1936
      pTscObj = pRequest->pTscObj;
1,179,650,694✔
1937
    }
1938
  }
1939

1940
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
1,409,764,522✔
1941

1942
  SDataBuf buf = {.msgType = pMsg->msgType,
1,409,696,702✔
1943
                  .len = pMsg->contLen,
1,409,699,413✔
1944
                  .pData = NULL,
1945
                  .handle = pMsg->info.handle,
1,409,703,367✔
1946
                  .handleRefId = pMsg->info.refId,
1,409,702,813✔
1947
                  .pEpSet = pEpSet};
1948

1949
  if (pMsg->contLen > 0) {
1,409,702,090✔
1950
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
1,378,121,349✔
1951
    if (buf.pData == NULL) {
1,378,139,801✔
UNCOV
1952
      pMsg->code = terrno;
×
1953
    } else {
1954
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
1,378,139,801✔
1955
    }
1956
  }
1957

1958
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
1,409,736,275✔
1959

1960
  if (pTscObj) {
1,409,728,947✔
1961
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
1,179,641,408✔
1962
    if (TSDB_CODE_SUCCESS != code) {
1,179,673,995✔
1963
      tscError("doProcessMsgFromServer taosReleaseRef failed");
57✔
1964
      terrno = code;
57✔
1965
      pMsg->code = code;
57✔
1966
    }
1967
  }
1968

1969
  rpcFreeCont(pMsg->pCont);
1,409,761,534✔
1970
  destroySendMsgInfo(pSendInfo);
1,409,738,176✔
1971
  return TSDB_CODE_SUCCESS;
1,409,731,927✔
1972
}
1973

1974
int32_t doProcessMsgFromServer(void* param) {
1,410,321,538✔
1975
  AsyncArg* arg = (AsyncArg*)param;
1,410,321,538✔
1976
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
1,410,321,538✔
1977
  taosMemoryFree(arg);
1,410,277,494✔
1978
  return code;
1,410,286,311✔
1979
}
1980

1981
void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,410,217,269✔
1982
  int32_t code = 0;
1,410,217,269✔
1983
  SEpSet* tEpSet = NULL;
1,410,217,269✔
1984

1985
  tscDebug("msg callback, ahandle %p", pMsg->info.ahandle);
1,410,217,269✔
1986

1987
  if (pEpSet != NULL) {
1,410,221,261✔
1988
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
3,458,201✔
1989
    if (NULL == tEpSet) {
3,458,222✔
UNCOV
1990
      code = terrno;
×
1991
      pMsg->code = terrno;
×
1992
      goto _exit;
×
1993
    }
1994
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
3,458,222✔
1995
  }
1996

1997
  // pMsg is response msg
1998
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
1,410,221,282✔
1999
    // restore origin code
2000
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
2,394,032✔
UNCOV
2001
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
2002
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
2,393,993✔
UNCOV
2003
      pMsg->code = TSDB_CODE_RPC_BROKEN_LINK;
×
2004
    }
2005
  } else {
2006
    // uniform to one error code: TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED
2007
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
1,407,820,286✔
UNCOV
2008
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
2009
    }
2010
  }
2011

2012
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
1,410,225,023✔
2013
  if (NULL == arg) {
1,410,228,229✔
UNCOV
2014
    code = terrno;
×
2015
    pMsg->code = code;
×
2016
    goto _exit;
×
2017
  }
2018

2019
  arg->msg = *pMsg;
1,410,228,229✔
2020
  arg->pEpset = tEpSet;
1,410,230,435✔
2021

2022
  if ((code = taosAsyncExec(doProcessMsgFromServer, arg, NULL)) != 0) {
1,410,245,299✔
2023
    pMsg->code = code;
9,297✔
2024
    taosMemoryFree(arg);
9,297✔
UNCOV
2025
    goto _exit;
×
2026
  }
2027
  return;
1,410,286,710✔
2028

UNCOV
2029
_exit:
×
2030
  tscError("failed to sched msg to tsc since %s", tstrerror(code));
×
2031
  code = doProcessMsgFromServerImpl(pMsg, tEpSet);
×
2032
  if (code != 0) {
×
2033
    tscError("failed to sched msg to tsc, tsc ready quit");
×
2034
  }
2035
}
2036

2037
TAOS* taos_connect_totp(const char* ip, const char* user, const char* pass, const char* totp, const char* db,
1,797✔
2038
                        uint16_t port) {
2039
  tscInfo("try to connect to %s:%u by totp, user:%s db:%s", ip, port, user, db);
1,797✔
2040
  if (user == NULL) {
1,797✔
UNCOV
2041
    user = TSDB_DEFAULT_USER;
×
2042
  }
2043

2044
  if (pass == NULL) {
1,797✔
UNCOV
2045
    pass = TSDB_DEFAULT_PASS;
×
2046
  }
2047

2048
  STscObj* pObj = NULL;
1,797✔
2049
  int32_t  code = taos_connect_internal(ip, user, pass, totp, db, port, CONN_TYPE__QUERY, &pObj);
1,797✔
2050
  if (TSDB_CODE_SUCCESS == code) {
1,797✔
2051
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
1,219✔
2052
    if (NULL == rid) {
1,219✔
UNCOV
2053
      tscError("out of memory when taos_connect_totp to %s:%u, user:%s db:%s", ip, port, user, db);
×
2054
      return NULL;
×
2055
    }
2056
    *rid = pObj->id;
1,219✔
2057
    return (TAOS*)rid;
1,219✔
2058
  } else {
2059
    terrno = code;
578✔
2060
  }
2061

2062
  return NULL;
578✔
2063
}
2064

UNCOV
2065
int taos_connect_test(const char* ip, const char* user, const char* pass, const char* totp, const char* db,
×
2066
                      uint16_t port) {
UNCOV
2067
  tscInfo("try to test connect to %s:%u by totp, user:%s db:%s", ip, port, user, db);
×
2068
  if (user == NULL) {
×
2069
    user = TSDB_DEFAULT_USER;
×
2070
  }
2071

UNCOV
2072
  if (pass == NULL) {
×
2073
    pass = TSDB_DEFAULT_PASS;
×
2074
  }
2075

UNCOV
2076
  STscObj* pObj = NULL;
×
2077
  return taos_connect_internal(ip, user, pass, totp, db, port, CONN_TYPE__AUTH_TEST, &pObj);
×
2078
}
2079

2080
TAOS* taos_connect_token(const char* ip, const char* token, const char* db, uint16_t port) {
2,141✔
2081
  tscInfo("try to connect to %s:%u by token, db:%s", ip, port, db);
2,141✔
2082

2083
  STscObj* pObj = NULL;
2,141✔
2084
  int32_t  code = taos_connect_by_auth(ip, NULL, token, NULL, db, port, CONN_TYPE__QUERY, &pObj);
2,141✔
2085
  if (TSDB_CODE_SUCCESS == code) {
2,141✔
2086
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
1,000✔
2087
    if (NULL == rid) {
1,000✔
UNCOV
2088
      tscError("out of memory when taos_connect_token to %s:%u db:%s", ip, port, db);
×
2089
      return NULL;
×
2090
    }
2091
    *rid = pObj->id;
1,000✔
2092
    return (TAOS*)rid;
1,000✔
2093
  } else {
2094
    terrno = code;
1,141✔
2095
  }
2096

2097
  return NULL;
1,141✔
2098
}
2099

2100
TAOS* taos_connect_auth(const char* ip, const char* user, const char* auth, const char* db, uint16_t port) {
143✔
2101
  tscInfo("try to connect to %s:%u by auth, user:%s db:%s", ip, port, user, db);
143✔
2102
  if (user == NULL) {
143✔
UNCOV
2103
    user = TSDB_DEFAULT_USER;
×
2104
  }
2105

2106
  if (auth == NULL) {
143✔
UNCOV
2107
    tscError("No auth info is given, failed to connect to server");
×
2108
    return NULL;
×
2109
  }
2110

2111
  STscObj* pObj = NULL;
143✔
2112
  int32_t  code = taos_connect_by_auth(ip, user, auth, NULL, db, port, CONN_TYPE__QUERY, &pObj);
143✔
2113
  if (TSDB_CODE_SUCCESS == code) {
143✔
2114
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
46✔
2115
    if (NULL == rid) {
46✔
2116
      tscError("out of memory when taos connect to %s:%u, user:%s db:%s", ip, port, user, db);
×
2117
    }
2118
    *rid = pObj->id;
46✔
2119
    return (TAOS*)rid;
46✔
2120
  }
2121

2122
  return NULL;
97✔
2123
}
2124

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

2139
void doSetOneRowPtr(SReqResultInfo* pResultInfo) {
2,147,483,647✔
2140
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
2,147,483,647✔
2141
    SResultColumn* pCol = &pResultInfo->pCol[i];
2,147,483,647✔
2142

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

2146
    if (IS_VAR_DATA_TYPE(type)) {
2,147,483,647✔
2147
      if (!IS_VAR_NULL_TYPE(type, schemaBytes) && pCol->offset[pResultInfo->current] != -1) {
2,147,483,647✔
2148
        char* pStart = pResultInfo->pCol[i].offset[pResultInfo->current] + pResultInfo->pCol[i].pData;
2,147,483,647✔
2149

2150
        if (IS_STR_DATA_BLOB(type)) {
2,147,483,647✔
UNCOV
2151
          pResultInfo->length[i] = blobDataLen(pStart);
×
UNCOV
2152
          pResultInfo->row[i] = blobDataVal(pStart);
×
2153
        } else {
2154
          pResultInfo->length[i] = varDataLen(pStart);
2,147,483,647✔
2155
          pResultInfo->row[i] = varDataVal(pStart);
2,147,483,647✔
2156
        }
2157
      } else {
2158
        pResultInfo->row[i] = NULL;
251,578,735✔
2159
        pResultInfo->length[i] = 0;
251,576,780✔
2160
      }
2161
    } else {
2162
      if (!colDataIsNull_f(pCol, pResultInfo->current)) {
2,147,483,647✔
2163
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + schemaBytes * pResultInfo->current;
2,147,483,647✔
2164
        pResultInfo->length[i] = schemaBytes;
2,147,483,647✔
2165
      } else {
2166
        pResultInfo->row[i] = NULL;
963,653,695✔
2167
        pResultInfo->length[i] = 0;
964,077,599✔
2168
      }
2169
    }
2170
  }
2171
}
2,147,483,647✔
2172

UNCOV
2173
void* doFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
×
2174
  if (pRequest == NULL) {
×
2175
    return NULL;
×
2176
  }
2177

UNCOV
2178
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
×
2179
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
×
2180
    // All data has returned to App already, no need to try again
UNCOV
2181
    if (pResultInfo->completed) {
×
2182
      pResultInfo->numOfRows = 0;
×
2183
      return NULL;
×
2184
    }
2185

UNCOV
2186
    SReqResultInfo* pResInfo = &pRequest->body.resInfo;
×
2187
    SSchedulerReq   req = {.syncReq = true, .pFetchRes = (void**)&pResInfo->pData};
×
2188

UNCOV
2189
    pRequest->code = schedulerFetchRows(pRequest->body.queryJob, &req);
×
2190
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2191
      pResultInfo->numOfRows = 0;
×
2192
      return NULL;
×
2193
    }
2194

UNCOV
2195
    pRequest->code = setQueryResultFromRsp(&pRequest->body.resInfo, (const SRetrieveTableRsp*)pResInfo->pData,
×
2196
                                           convertUcs4, pRequest->stmtBindVersion > 0);
×
2197
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2198
      pResultInfo->numOfRows = 0;
×
2199
      return NULL;
×
2200
    }
2201

UNCOV
2202
    tscDebug("req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64
×
2203
             ", complete:%d, QID:0x%" PRIx64,
2204
             pRequest->self, pResInfo->numOfRows, pResInfo->totalRows, pResInfo->completed, pRequest->requestId);
2205

UNCOV
2206
    STscObj*            pTscObj = pRequest->pTscObj;
×
2207
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
×
2208
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
×
2209

UNCOV
2210
    if (pResultInfo->numOfRows == 0) {
×
2211
      return NULL;
×
2212
    }
2213
  }
2214

UNCOV
2215
  if (setupOneRowPtr) {
×
2216
    doSetOneRowPtr(pResultInfo);
×
2217
    pResultInfo->current += 1;
×
2218
  }
2219

UNCOV
2220
  return pResultInfo->row;
×
2221
}
2222

2223
static void syncFetchFn(void* param, TAOS_RES* res, int32_t numOfRows) {
121,036,539✔
2224
  tsem_t* sem = param;
121,036,539✔
2225
  if (TSDB_CODE_SUCCESS != tsem_post(sem)) {
121,036,539✔
UNCOV
2226
    tscError("failed to post sem, code:%s", terrstr());
×
2227
  }
2228
}
121,036,539✔
2229

2230
void* doAsyncFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
2,018,705,467✔
2231
  if (pRequest == NULL) {
2,018,705,467✔
UNCOV
2232
    return NULL;
×
2233
  }
2234

2235
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
2,018,705,467✔
2236
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
2,018,710,860✔
2237
    // All data has returned to App already, no need to try again
2238
    if (pResultInfo->completed) {
205,921,040✔
2239
      pResultInfo->numOfRows = 0;
84,886,115✔
2240
      return NULL;
84,886,103✔
2241
    }
2242

2243
    // convert ucs4 to native multi-bytes string
2244
    pResultInfo->convertUcs4 = convertUcs4;
121,036,527✔
2245
    tsem_t sem;
120,580,211✔
2246
    if (TSDB_CODE_SUCCESS != tsem_init(&sem, 0, 0)) {
121,036,533✔
UNCOV
2247
      tscError("failed to init sem, code:%s", terrstr());
×
2248
    }
2249
    taos_fetch_rows_a(pRequest, syncFetchFn, &sem);
121,036,468✔
2250
    if (TSDB_CODE_SUCCESS != tsem_wait(&sem)) {
121,036,539✔
UNCOV
2251
      tscError("failed to wait sem, code:%s", terrstr());
×
2252
    }
2253
    if (TSDB_CODE_SUCCESS != tsem_destroy(&sem)) {
121,036,539✔
UNCOV
2254
      tscError("failed to destroy sem, code:%s", terrstr());
×
2255
    }
2256
    pRequest->inCallback = false;
121,036,539✔
2257
  }
2258

2259
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
1,933,828,977✔
2260
    return NULL;
9,937,645✔
2261
  } else {
2262
    if (setupOneRowPtr) {
1,923,891,283✔
2263
      doSetOneRowPtr(pResultInfo);
1,811,466,621✔
2264
      pResultInfo->current += 1;
1,811,456,453✔
2265
    }
2266

2267
    return pResultInfo->row;
1,923,891,017✔
2268
  }
2269
}
2270

2271
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
249,158,143✔
2272
  if (pResInfo->row == NULL) {
249,158,143✔
2273
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
219,605,616✔
2274
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
219,605,690✔
2275
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
219,599,321✔
2276
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
219,602,814✔
2277

2278
    if (pResInfo->row == NULL || pResInfo->pCol == NULL || pResInfo->length == NULL || pResInfo->convertBuf == NULL) {
219,603,630✔
2279
      taosMemoryFree(pResInfo->row);
4,969✔
UNCOV
2280
      taosMemoryFree(pResInfo->pCol);
×
2281
      taosMemoryFree(pResInfo->length);
×
2282
      taosMemoryFree(pResInfo->convertBuf);
×
2283
      return terrno;
×
2284
    }
2285
  }
2286

2287
  return TSDB_CODE_SUCCESS;
249,159,652✔
2288
}
2289

2290
static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength, bool isStmt) {
249,021,260✔
2291
  int32_t idx = -1;
249,021,260✔
2292
  iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt);
249,021,591✔
2293
  if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR;
249,015,039✔
2294

2295
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
1,416,240,812✔
2296
    int32_t type = pResultInfo->fields[i].type;
1,167,246,985✔
2297
    int32_t schemaBytes =
2298
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
1,167,245,521✔
2299

2300
    if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) {
1,167,238,248✔
2301
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
61,436,347✔
2302
      if (p == NULL) {
61,436,347✔
UNCOV
2303
        taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
×
2304
        return terrno;
×
2305
      }
2306

2307
      pResultInfo->convertBuf[i] = p;
61,436,347✔
2308

2309
      SResultColumn* pCol = &pResultInfo->pCol[i];
61,436,347✔
2310
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
2,147,483,647✔
2311
        if (pCol->offset[j] != -1) {
2,147,483,647✔
2312
          char* pStart = pCol->offset[j] + pCol->pData;
2,147,483,647✔
2313

2314
          int32_t len = taosUcs4ToMbsEx((TdUcs4*)varDataVal(pStart), varDataLen(pStart), varDataVal(p), conv);
2,147,483,647✔
2315
          if (len < 0 || len > schemaBytes || (p + len) >= (pResultInfo->convertBuf[i] + colLength[i])) {
2,147,483,647✔
2316
            tscError(
2,931✔
2317
                "doConvertUCS4 error, invalid data. len:%d, bytes:%d, (p + len):%p, (pResultInfo->convertBuf[i] + "
2318
                "colLength[i]):%p",
2319
                len, schemaBytes, (p + len), (pResultInfo->convertBuf[i] + colLength[i]));
2320
            taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
2,931✔
2321
            return TSDB_CODE_TSC_INTERNAL_ERROR;
443✔
2322
          }
2323

2324
          varDataSetLen(p, len);
2,147,483,647✔
2325
          pCol->offset[j] = (p - pResultInfo->convertBuf[i]);
2,147,483,647✔
2326
          p += (len + VARSTR_HEADER_SIZE);
2,147,483,647✔
2327
        }
2328
      }
2329

2330
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
61,435,904✔
2331
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
61,435,904✔
2332
    }
2333
  }
2334
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
249,019,329✔
2335
  return TSDB_CODE_SUCCESS;
249,021,458✔
2336
}
2337

2338
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
249,015,871✔
2339
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
1,416,237,636✔
2340
    TAOS_FIELD_E* pFieldE = pResultInfo->fields + i;
1,167,235,846✔
2341
    TAOS_FIELD*   pField = pResultInfo->userFields + i;
1,167,233,434✔
2342
    int32_t       type = pFieldE->type;
1,167,232,743✔
2343
    int32_t       bufLen = 0;
1,167,240,160✔
2344
    char*         p = NULL;
1,167,240,160✔
2345
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
1,167,240,160✔
2346
      continue;
1,165,848,504✔
2347
    } else {
2348
      bufLen = 64;
1,379,114✔
2349
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
1,379,114✔
2350
      pFieldE->bytes = bufLen;
1,379,114✔
2351
      pField->bytes = bufLen;
1,379,114✔
2352
    }
2353
    if (!p) return terrno;
1,379,114✔
2354
    pResultInfo->convertBuf[i] = p;
1,379,114✔
2355

2356
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
931,940,543✔
2357
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
930,561,429✔
2358
                                  pFieldE->precision, pFieldE->scale, p, bufLen);
930,561,429✔
2359
      p += bufLen;
930,561,429✔
2360
      if (TSDB_CODE_SUCCESS != code) {
930,561,429✔
UNCOV
2361
        return code;
×
2362
      }
2363
    }
2364
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
1,379,114✔
2365
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
1,379,114✔
2366
  }
2367
  return 0;
249,017,273✔
2368
}
2369

2370
int32_t getVersion1BlockMetaSize(const char* p, int32_t numOfCols) {
348,130✔
2371
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) * 3 + sizeof(uint64_t) +
696,260✔
2372
         numOfCols * (sizeof(int8_t) + sizeof(int32_t));
348,130✔
2373
}
2374

2375
static int32_t estimateJsonLen(SReqResultInfo* pResultInfo) {
174,065✔
2376
  char*   p = (char*)pResultInfo->pData;
174,065✔
2377
  int32_t blockVersion = *(int32_t*)p;
174,065✔
2378

2379
  int32_t numOfRows = pResultInfo->numOfRows;
174,065✔
2380
  int32_t numOfCols = pResultInfo->numOfCols;
174,065✔
2381

2382
  // | version | total length | total rows | total columns | flag seg| block group id | column schema | each column
2383
  // length |
2384
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
174,065✔
2385
  if (numOfCols != cols) {
174,065✔
UNCOV
2386
    tscError("estimateJsonLen error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2387
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2388
  }
2389

2390
  int32_t  len = getVersion1BlockMetaSize(p, numOfCols);
174,065✔
2391
  int32_t* colLength = (int32_t*)(p + len);
174,065✔
2392
  len += sizeof(int32_t) * numOfCols;
174,065✔
2393

2394
  char* pStart = p + len;
174,065✔
2395
  for (int32_t i = 0; i < numOfCols; ++i) {
754,521✔
2396
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
580,456✔
2397

2398
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
580,456✔
2399
      int32_t* offset = (int32_t*)pStart;
203,220✔
2400
      int32_t  lenTmp = numOfRows * sizeof(int32_t);
203,220✔
2401
      len += lenTmp;
203,220✔
2402
      pStart += lenTmp;
203,220✔
2403

2404
      int32_t estimateColLen = 0;
203,220✔
2405
      for (int32_t j = 0; j < numOfRows; ++j) {
1,018,800✔
2406
        if (offset[j] == -1) {
815,580✔
2407
          continue;
45,236✔
2408
        }
2409
        char* data = offset[j] + pStart;
770,344✔
2410

2411
        int32_t jsonInnerType = *data;
770,344✔
2412
        char*   jsonInnerData = data + CHAR_BYTES;
770,344✔
2413
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
770,344✔
2414
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
10,800✔
2415
        } else if (tTagIsJson(data)) {
759,544✔
2416
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
191,632✔
2417
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
567,912✔
2418
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
527,412✔
2419
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
40,500✔
2420
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
29,700✔
2421
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
10,800✔
2422
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
10,800✔
UNCOV
2423
        } else if (IS_STR_DATA_BLOB(jsonInnerType)) {
×
2424
          estimateColLen += (BLOBSTR_HEADER_SIZE + 32);
×
2425
        } else {
UNCOV
2426
          tscError("estimateJsonLen error: invalid type:%d", jsonInnerType);
×
2427
          return -1;
×
2428
        }
2429
      }
2430
      len += TMAX(colLen, estimateColLen);
203,220✔
2431
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
377,236✔
2432
      int32_t lenTmp = numOfRows * sizeof(int32_t);
45,000✔
2433
      len += (lenTmp + colLen);
45,000✔
2434
      pStart += lenTmp;
45,000✔
2435
    } else {
2436
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
332,236✔
2437
      len += (lenTmp + colLen);
332,236✔
2438
      pStart += lenTmp;
332,236✔
2439
    }
2440
    pStart += colLen;
580,456✔
2441
  }
2442

2443
  // Ensure the complete structure of the block, including the blankfill field,
2444
  // even though it is not used on the client side.
2445
  len += sizeof(bool);
174,065✔
2446
  return len;
174,065✔
2447
}
2448

2449
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
249,156,142✔
2450
  int32_t numOfRows = pResultInfo->numOfRows;
249,156,142✔
2451
  int32_t numOfCols = pResultInfo->numOfCols;
249,159,121✔
2452
  bool    needConvert = false;
249,162,797✔
2453
  for (int32_t i = 0; i < numOfCols; ++i) {
1,416,868,272✔
2454
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
1,167,880,562✔
2455
      needConvert = true;
174,065✔
2456
      break;
174,065✔
2457
    }
2458
  }
2459

2460
  if (!needConvert) {
249,161,775✔
2461
    return TSDB_CODE_SUCCESS;
248,987,710✔
2462
  }
2463

2464
  tscDebug("start to convert form json format string");
174,065✔
2465

2466
  char*   p = (char*)pResultInfo->pData;
174,065✔
2467
  int32_t blockVersion = *(int32_t*)p;
174,065✔
2468
  int32_t dataLen = estimateJsonLen(pResultInfo);
174,065✔
2469
  if (dataLen <= 0) {
174,065✔
UNCOV
2470
    tscError("doConvertJson error: estimateJsonLen failed");
×
2471
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2472
  }
2473

2474
  taosMemoryFreeClear(pResultInfo->convertJson);
174,065✔
2475
  pResultInfo->convertJson = taosMemoryCalloc(1, dataLen);
174,065✔
2476
  if (pResultInfo->convertJson == NULL) return terrno;
174,065✔
2477
  char* p1 = pResultInfo->convertJson;
174,065✔
2478

2479
  int32_t totalLen = 0;
174,065✔
2480
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
174,065✔
2481
  if (numOfCols != cols) {
174,065✔
UNCOV
2482
    tscError("doConvertJson error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2483
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2484
  }
2485

2486
  int32_t len = getVersion1BlockMetaSize(p, numOfCols);
174,065✔
2487
  (void)memcpy(p1, p, len);
174,065✔
2488

2489
  p += len;
174,065✔
2490
  p1 += len;
174,065✔
2491
  totalLen += len;
174,065✔
2492

2493
  len = sizeof(int32_t) * numOfCols;
174,065✔
2494
  int32_t* colLength = (int32_t*)p;
174,065✔
2495
  int32_t* colLength1 = (int32_t*)p1;
174,065✔
2496
  (void)memcpy(p1, p, len);
174,065✔
2497
  p += len;
174,065✔
2498
  p1 += len;
174,065✔
2499
  totalLen += len;
174,065✔
2500

2501
  char* pStart = p;
174,065✔
2502
  char* pStart1 = p1;
174,065✔
2503
  for (int32_t i = 0; i < numOfCols; ++i) {
754,521✔
2504
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
580,456✔
2505
    int32_t colLen1 = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength1[i]) : colLength1[i];
580,456✔
2506
    if (colLen >= dataLen) {
580,456✔
UNCOV
2507
      tscError("doConvertJson error: colLen:%d >= dataLen:%d", colLen, dataLen);
×
2508
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2509
    }
2510
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
580,456✔
2511
      int32_t* offset = (int32_t*)pStart;
203,220✔
2512
      int32_t* offset1 = (int32_t*)pStart1;
203,220✔
2513
      len = numOfRows * sizeof(int32_t);
203,220✔
2514
      (void)memcpy(pStart1, pStart, len);
203,220✔
2515
      pStart += len;
203,220✔
2516
      pStart1 += len;
203,220✔
2517
      totalLen += len;
203,220✔
2518

2519
      len = 0;
203,220✔
2520
      for (int32_t j = 0; j < numOfRows; ++j) {
1,018,800✔
2521
        if (offset[j] == -1) {
815,580✔
2522
          continue;
45,236✔
2523
        }
2524
        char* data = offset[j] + pStart;
770,344✔
2525

2526
        int32_t jsonInnerType = *data;
770,344✔
2527
        char*   jsonInnerData = data + CHAR_BYTES;
770,344✔
2528
        char    dst[TSDB_MAX_JSON_TAG_LEN] = {0};
770,344✔
2529
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
770,344✔
2530
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s", TSDB_DATA_NULL_STR_L);
10,800✔
2531
          varDataSetLen(dst, strlen(varDataVal(dst)));
10,800✔
2532
        } else if (tTagIsJson(data)) {
759,544✔
2533
          char* jsonString = NULL;
191,632✔
2534
          parseTagDatatoJson(data, &jsonString, pResultInfo->charsetCxt);
191,632✔
2535
          if (jsonString == NULL) {
191,632✔
UNCOV
2536
            tscError("doConvertJson error: parseTagDatatoJson failed");
×
2537
            return terrno;
×
2538
          }
2539
          STR_TO_VARSTR(dst, jsonString);
191,632✔
2540
          taosMemoryFree(jsonString);
191,632✔
2541
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
567,912✔
2542
          *(char*)varDataVal(dst) = '\"';
527,412✔
2543
          char    tmp[TSDB_MAX_JSON_TAG_LEN] = {0};
527,412✔
2544
          int32_t length = taosUcs4ToMbs((TdUcs4*)varDataVal(jsonInnerData), varDataLen(jsonInnerData), varDataVal(tmp),
527,412✔
2545
                                         pResultInfo->charsetCxt);
2546
          if (length <= 0) {
527,412✔
2547
            tscError("charset:%s to %s. convert failed.", DEFAULT_UNICODE_ENCODEC,
450✔
2548
                     pResultInfo->charsetCxt != NULL ? ((SConvInfo*)(pResultInfo->charsetCxt))->charset : tsCharset);
2549
            length = 0;
450✔
2550
          }
2551
          int32_t escapeLength = escapeToPrinted(varDataVal(dst) + CHAR_BYTES, TSDB_MAX_JSON_TAG_LEN - CHAR_BYTES * 2,
527,412✔
2552
                                                 varDataVal(tmp), length);
2553
          varDataSetLen(dst, escapeLength + CHAR_BYTES * 2);
527,412✔
2554
          *(char*)POINTER_SHIFT(varDataVal(dst), escapeLength + CHAR_BYTES) = '\"';
527,412✔
2555
          tscError("value:%s.", varDataVal(dst));
527,412✔
2556
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
40,500✔
2557
          double jsonVd = *(double*)(jsonInnerData);
29,700✔
2558
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%.9lf", jsonVd);
29,700✔
2559
          varDataSetLen(dst, strlen(varDataVal(dst)));
29,700✔
2560
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
10,800✔
2561
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s",
10,800✔
2562
                         (*((char*)jsonInnerData) == 1) ? "true" : "false");
10,800✔
2563
          varDataSetLen(dst, strlen(varDataVal(dst)));
10,800✔
2564
        } else {
UNCOV
2565
          tscError("doConvertJson error: invalid type:%d", jsonInnerType);
×
2566
          return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2567
        }
2568

2569
        offset1[j] = len;
770,344✔
2570
        (void)memcpy(pStart1 + len, dst, varDataTLen(dst));
770,344✔
2571
        len += varDataTLen(dst);
770,344✔
2572
      }
2573
      colLen1 = len;
203,220✔
2574
      totalLen += colLen1;
203,220✔
2575
      colLength1[i] = (blockVersion == BLOCK_VERSION_1) ? htonl(len) : len;
203,220✔
2576
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
377,236✔
2577
      len = numOfRows * sizeof(int32_t);
45,000✔
2578
      (void)memcpy(pStart1, pStart, len);
45,000✔
2579
      pStart += len;
45,000✔
2580
      pStart1 += len;
45,000✔
2581
      totalLen += len;
45,000✔
2582
      totalLen += colLen;
45,000✔
2583
      (void)memcpy(pStart1, pStart, colLen);
45,000✔
2584
    } else {
2585
      len = BitmapLen(pResultInfo->numOfRows);
332,236✔
2586
      (void)memcpy(pStart1, pStart, len);
332,236✔
2587
      pStart += len;
332,236✔
2588
      pStart1 += len;
332,236✔
2589
      totalLen += len;
332,236✔
2590
      totalLen += colLen;
332,236✔
2591
      (void)memcpy(pStart1, pStart, colLen);
332,236✔
2592
    }
2593
    pStart += colLen;
580,456✔
2594
    pStart1 += colLen1;
580,456✔
2595
  }
2596

2597
  // Ensure the complete structure of the block, including the blankfill field,
2598
  // even though it is not used on the client side.
2599
  // (void)memcpy(pStart1, pStart, sizeof(bool));
2600
  totalLen += sizeof(bool);
174,065✔
2601

2602
  *(int32_t*)(pResultInfo->convertJson + 4) = totalLen;
174,065✔
2603
  pResultInfo->pData = pResultInfo->convertJson;
174,065✔
2604
  return TSDB_CODE_SUCCESS;
174,065✔
2605
}
2606

2607
int32_t setResultDataPtr(SReqResultInfo* pResultInfo, bool convertUcs4, bool isStmt) {
261,532,390✔
2608
  bool convertForDecimal = convertUcs4;
261,532,390✔
2609
  if (pResultInfo == NULL || pResultInfo->numOfCols <= 0 || pResultInfo->fields == NULL) {
261,532,390✔
2610
    tscError("setResultDataPtr paras error");
151✔
UNCOV
2611
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2612
  }
2613

2614
  if (pResultInfo->numOfRows == 0) {
261,550,477✔
2615
    return TSDB_CODE_SUCCESS;
12,387,495✔
2616
  }
2617

2618
  if (pResultInfo->pData == NULL) {
249,162,096✔
UNCOV
2619
    tscError("setResultDataPtr error: pData is NULL");
×
2620
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2621
  }
2622

2623
  int32_t code = doPrepareResPtr(pResultInfo);
249,158,807✔
2624
  if (code != TSDB_CODE_SUCCESS) {
249,159,648✔
UNCOV
2625
    return code;
×
2626
  }
2627
  code = doConvertJson(pResultInfo);
249,159,648✔
2628
  if (code != TSDB_CODE_SUCCESS) {
249,154,160✔
UNCOV
2629
    return code;
×
2630
  }
2631

2632
  char* p = (char*)pResultInfo->pData;
249,154,160✔
2633

2634
  // version:
2635
  int32_t blockVersion = *(int32_t*)p;
249,154,822✔
2636
  p += sizeof(int32_t);
249,156,831✔
2637

2638
  int32_t dataLen = *(int32_t*)p;
249,158,155✔
2639
  p += sizeof(int32_t);
249,157,824✔
2640

2641
  int32_t rows = *(int32_t*)p;
249,160,803✔
2642
  p += sizeof(int32_t);
249,160,628✔
2643

2644
  int32_t cols = *(int32_t*)p;
249,161,290✔
2645
  p += sizeof(int32_t);
249,160,959✔
2646

2647
  if (rows != pResultInfo->numOfRows || cols != pResultInfo->numOfCols) {
249,160,649✔
2648
    tscError("setResultDataPtr paras error:rows;%d numOfRows:%" PRId64 " cols:%d numOfCols:%d", rows,
4,418✔
2649
             pResultInfo->numOfRows, cols, pResultInfo->numOfCols);
UNCOV
2650
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2651
  }
2652

2653
  int32_t hasColumnSeg = *(int32_t*)p;
249,157,043✔
2654
  p += sizeof(int32_t);
249,157,374✔
2655

2656
  uint64_t groupId = taosGetUInt64Aligned((uint64_t*)p);
249,162,651✔
2657
  p += sizeof(uint64_t);
249,162,651✔
2658

2659
  // check fields
2660
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
1,417,060,915✔
2661
    int8_t type = *(int8_t*)p;
1,167,910,449✔
2662
    p += sizeof(int8_t);
1,167,900,720✔
2663

2664
    int32_t bytes = *(int32_t*)p;
1,167,906,741✔
2665
    p += sizeof(int32_t);
1,167,909,476✔
2666

2667
    if (IS_DECIMAL_TYPE(type) && pResultInfo->fields[i].precision == 0) {
1,167,903,469✔
2668
      extractDecimalTypeInfoFromBytes(&bytes, &pResultInfo->fields[i].precision, &pResultInfo->fields[i].scale);
178,506✔
2669
    }
2670
  }
2671

2672
  int32_t* colLength = (int32_t*)p;
249,164,092✔
2673
  p += sizeof(int32_t) * pResultInfo->numOfCols;
249,164,092✔
2674

2675
  char* pStart = p;
249,162,787✔
2676
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
1,417,076,015✔
2677
    if ((pStart - pResultInfo->pData) >= dataLen) {
1,167,917,444✔
UNCOV
2678
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2679
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2680
    }
2681
    if (blockVersion == BLOCK_VERSION_1) {
1,167,904,070✔
2682
      colLength[i] = htonl(colLength[i]);
601,538,053✔
2683
    }
2684
    if (colLength[i] >= dataLen) {
1,167,903,955✔
UNCOV
2685
      tscError("invalid colLength %d, dataLen %d", colLength[i], dataLen);
×
2686
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2687
    }
2688
    if (IS_INVALID_TYPE(pResultInfo->fields[i].type)) {
1,167,904,538✔
2689
      tscError("invalid type %d", pResultInfo->fields[i].type);
102✔
UNCOV
2690
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2691
    }
2692
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
1,167,919,095✔
2693
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
288,610,011✔
2694
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
288,605,439✔
2695
    } else {
2696
      pResultInfo->pCol[i].nullbitmap = pStart;
879,332,716✔
2697
      pStart += BitmapLen(pResultInfo->numOfRows);
879,329,260✔
2698
    }
2699

2700
    pResultInfo->pCol[i].pData = pStart;
1,167,929,673✔
2701
    pResultInfo->length[i] =
2,147,483,647✔
2702
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
2,147,483,647✔
2703
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
1,167,906,193✔
2704

2705
    pStart += colLength[i];
1,167,917,848✔
2706
  }
2707

2708
  p = pStart;
249,165,717✔
2709
  // bool blankFill = *(bool*)p;
2710
  p += sizeof(bool);
249,165,717✔
2711
  int32_t offset = p - pResultInfo->pData;
249,166,381✔
2712
  if (offset > dataLen) {
249,163,889✔
UNCOV
2713
    tscError("invalid offset %d, dataLen %d", offset, dataLen);
×
2714
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2715
  }
2716

2717
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
2718
  if (convertUcs4) {
249,163,889✔
2719
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
249,020,709✔
2720
  }
2721
#endif
2722
  if (TSDB_CODE_SUCCESS == code && convertForDecimal) {
249,165,077✔
2723
    code = convertDecimalType(pResultInfo);
249,021,789✔
2724
  }
2725
  return code;
249,160,565✔
2726
}
2727

2728
char* getDbOfConnection(STscObj* pObj) {
809,046,558✔
2729
  terrno = TSDB_CODE_SUCCESS;
809,046,558✔
2730
  char* p = NULL;
809,051,264✔
2731
  (void)taosThreadMutexLock(&pObj->mutex);
809,051,264✔
2732
  size_t len = strlen(pObj->db);
809,056,278✔
2733
  if (len > 0) {
809,055,850✔
2734
    p = taosStrndup(pObj->db, tListLen(pObj->db));
711,036,174✔
2735
    if (p == NULL) {
711,039,564✔
UNCOV
2736
      tscError("failed to taosStrndup db name");
×
2737
    }
2738
  }
2739

2740
  (void)taosThreadMutexUnlock(&pObj->mutex);
809,059,240✔
2741
  return p;
809,045,563✔
2742
}
2743

2744
void setConnectionDB(STscObj* pTscObj, const char* db) {
2,108,298✔
2745
  if (db == NULL || pTscObj == NULL) {
2,108,298✔
UNCOV
2746
    tscError("setConnectionDB para is NULL");
×
2747
    return;
×
2748
  }
2749

2750
  (void)taosThreadMutexLock(&pTscObj->mutex);
2,108,298✔
2751
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
2,108,082✔
2752
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
2,108,247✔
2753
}
2754

UNCOV
2755
void resetConnectDB(STscObj* pTscObj) {
×
2756
  if (pTscObj == NULL) {
×
2757
    return;
×
2758
  }
2759

UNCOV
2760
  (void)taosThreadMutexLock(&pTscObj->mutex);
×
2761
  pTscObj->db[0] = 0;
×
2762
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
×
2763
}
2764

2765
int32_t setQueryResultFromRsp(SReqResultInfo* pResultInfo, const SRetrieveTableRsp* pRsp, bool convertUcs4,
155,745,350✔
2766
                              bool isStmt) {
2767
  if (pResultInfo == NULL || pRsp == NULL) {
155,745,350✔
UNCOV
2768
    tscError("setQueryResultFromRsp paras is null");
×
2769
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2770
  }
2771

2772
  taosMemoryFreeClear(pResultInfo->pRspMsg);
155,746,320✔
2773
  pResultInfo->pRspMsg = (const char*)pRsp;
155,746,320✔
2774
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
155,746,320✔
2775
  pResultInfo->current = 0;
155,746,320✔
2776
  pResultInfo->completed = (pRsp->completed == 1);
155,746,320✔
2777
  pResultInfo->precision = pRsp->precision;
155,746,320✔
2778

2779
  // decompress data if needed
2780
  int32_t payloadLen = htonl(pRsp->payloadLen);
155,746,318✔
2781

2782
  if (pRsp->compressed) {
155,746,314✔
UNCOV
2783
    if (pResultInfo->decompBuf == NULL) {
×
2784
      pResultInfo->decompBuf = taosMemoryMalloc(payloadLen);
×
2785
      if (pResultInfo->decompBuf == NULL) {
×
2786
        tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2787
        return terrno;
×
2788
      }
UNCOV
2789
      pResultInfo->decompBufSize = payloadLen;
×
2790
    } else {
UNCOV
2791
      if (pResultInfo->decompBufSize < payloadLen) {
×
2792
        char* p = taosMemoryRealloc(pResultInfo->decompBuf, payloadLen);
×
2793
        if (p == NULL) {
×
2794
          tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2795
          return terrno;
×
2796
        }
2797

UNCOV
2798
        pResultInfo->decompBuf = p;
×
2799
        pResultInfo->decompBufSize = payloadLen;
×
2800
      }
2801
    }
2802
  }
2803

2804
  if (payloadLen > 0) {
155,746,320✔
2805
    int32_t compLen = *(int32_t*)pRsp->data;
143,359,201✔
2806
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
143,359,201✔
2807

2808
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
143,359,201✔
2809

2810
    if (pRsp->compressed && compLen < rawLen) {
143,359,201✔
UNCOV
2811
      int32_t len = tsDecompressString(pStart, compLen, 1, pResultInfo->decompBuf, rawLen, ONE_STAGE_COMP, NULL, 0);
×
2812
      if (len < 0) {
×
2813
        tscError("tsDecompressString failed");
×
2814
        return terrno ? terrno : TSDB_CODE_FAILED;
×
2815
      }
UNCOV
2816
      if (len != rawLen) {
×
2817
        tscError("tsDecompressString failed, len:%d != rawLen:%d", len, rawLen);
×
2818
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2819
      }
UNCOV
2820
      pResultInfo->pData = pResultInfo->decompBuf;
×
2821
      pResultInfo->payloadLen = rawLen;
×
2822
    } else {
2823
      pResultInfo->pData = pStart;
143,359,193✔
2824
      pResultInfo->payloadLen = htonl(pRsp->compLen);
143,359,201✔
2825
      if (pRsp->compLen != pRsp->payloadLen) {
143,359,193✔
UNCOV
2826
        tscError("pRsp->compLen:%d != pRsp->payloadLen:%d", pRsp->compLen, pRsp->payloadLen);
×
2827
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2828
      }
2829
    }
2830
  }
2831

2832
  // TODO handle the compressed case
2833
  pResultInfo->totalRows += pResultInfo->numOfRows;
155,746,314✔
2834

2835
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
155,746,310✔
2836
  return code;
155,744,465✔
2837
}
2838

2839
TSDB_SERVER_STATUS taos_check_server_status(const char* fqdn, int port, char* details, int maxlen) {
194✔
2840
  TSDB_SERVER_STATUS code = TSDB_SRV_STATUS_UNAVAILABLE;
194✔
2841
  void*              clientRpc = NULL;
194✔
2842
  SServerStatusRsp   statusRsp = {0};
194✔
2843
  SEpSet             epSet = {.inUse = 0, .numOfEps = 1};
194✔
2844
  SRpcMsg  rpcMsg = {.info.ahandle = (void*)0x9527, .info.notFreeAhandle = 1, .msgType = TDMT_DND_SERVER_STATUS};
194✔
2845
  SRpcMsg  rpcRsp = {0};
194✔
2846
  SRpcInit rpcInit = {0};
194✔
2847
  char     pass[TSDB_PASSWORD_LEN + 1] = {0};
194✔
2848

2849
  rpcInit.label = "CHK";
194✔
2850
  rpcInit.numOfThreads = 1;
194✔
2851
  rpcInit.cfp = NULL;
194✔
2852
  rpcInit.sessions = 16;
194✔
2853
  rpcInit.connType = TAOS_CONN_CLIENT;
194✔
2854
  rpcInit.idleTime = tsShellActivityTimer * 1000;
194✔
2855
  rpcInit.compressSize = tsCompressMsgSize;
194✔
2856
  rpcInit.user = "_dnd";
194✔
2857

2858
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
194✔
2859
  connLimitNum = TMAX(connLimitNum, 10);
194✔
2860
  connLimitNum = TMIN(connLimitNum, 500);
194✔
2861
  rpcInit.connLimitNum = connLimitNum;
194✔
2862
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
194✔
2863
  rpcInit.readTimeout = tsReadTimeout;
194✔
2864
  rpcInit.ipv6 = tsEnableIpv6;
194✔
2865
  rpcInit.enableSSL = tsEnableTLS;
194✔
2866

2867
  memcpy(rpcInit.caPath, tsTLSCaPath, strlen(tsTLSCaPath));
194✔
2868
  memcpy(rpcInit.certPath, tsTLSSvrCertPath, strlen(tsTLSSvrCertPath));
194✔
2869
  memcpy(rpcInit.keyPath, tsTLSSvrKeyPath, strlen(tsTLSSvrKeyPath));
194✔
2870
  memcpy(rpcInit.cliCertPath, tsTLSCliCertPath, strlen(tsTLSCliCertPath));
194✔
2871
  memcpy(rpcInit.cliKeyPath, tsTLSCliKeyPath, strlen(tsTLSCliKeyPath));
194✔
2872

2873
  if (TSDB_CODE_SUCCESS != taosVersionStrToInt(td_version, &rpcInit.compatibilityVer)) {
194✔
UNCOV
2874
    tscError("faild to convert taos version from str to int, errcode:%s", terrstr());
×
2875
    goto _OVER;
×
2876
  }
2877

2878
  clientRpc = rpcOpen(&rpcInit);
194✔
2879
  if (clientRpc == NULL) {
194✔
UNCOV
2880
    code = terrno;
×
2881
    tscError("failed to init server status client since %s", tstrerror(code));
×
2882
    goto _OVER;
×
2883
  }
2884

2885
  if (fqdn == NULL) {
194✔
2886
    fqdn = tsLocalFqdn;
194✔
2887
  }
2888

2889
  if (port == 0) {
194✔
2890
    port = tsServerPort;
194✔
2891
  }
2892

2893
  tstrncpy(epSet.eps[0].fqdn, fqdn, TSDB_FQDN_LEN);
194✔
2894
  epSet.eps[0].port = (uint16_t)port;
194✔
2895
  int32_t ret = rpcSendRecv(clientRpc, &epSet, &rpcMsg, &rpcRsp);
194✔
2896
  if (TSDB_CODE_SUCCESS != ret) {
194✔
UNCOV
2897
    tscError("failed to send recv since %s", tstrerror(ret));
×
2898
    goto _OVER;
×
2899
  }
2900

2901
  if (rpcRsp.code != 0 || rpcRsp.contLen <= 0 || rpcRsp.pCont == NULL) {
194✔
2902
    tscError("failed to send server status req since %s", terrstr());
46✔
2903
    goto _OVER;
46✔
2904
  }
2905

2906
  if (tDeserializeSServerStatusRsp(rpcRsp.pCont, rpcRsp.contLen, &statusRsp) != 0) {
148✔
UNCOV
2907
    tscError("failed to parse server status rsp since %s", terrstr());
×
2908
    goto _OVER;
×
2909
  }
2910

2911
  code = statusRsp.statusCode;
148✔
2912
  if (details != NULL) {
148✔
2913
    tstrncpy(details, statusRsp.details, maxlen);
148✔
2914
  }
2915

2916
_OVER:
181✔
2917
  if (clientRpc != NULL) {
194✔
2918
    rpcClose(clientRpc);
194✔
2919
  }
2920
  if (rpcRsp.pCont != NULL) {
194✔
2921
    rpcFreeCont(rpcRsp.pCont);
148✔
2922
  }
2923
  return code;
194✔
2924
}
2925

2926
int32_t appendTbToReq(SHashObj* pHash, int32_t pos1, int32_t len1, int32_t pos2, int32_t len2, const char* str,
1,140✔
2927
                      int32_t acctId, char* db) {
2928
  SName name = {0};
1,140✔
2929

2930
  if (len1 <= 0) {
1,140✔
UNCOV
2931
    return -1;
×
2932
  }
2933

2934
  const char* dbName = db;
1,140✔
2935
  const char* tbName = NULL;
1,140✔
2936
  int32_t     dbLen = 0;
1,140✔
2937
  int32_t     tbLen = 0;
1,140✔
2938
  if (len2 > 0) {
1,140✔
UNCOV
2939
    dbName = str + pos1;
×
2940
    dbLen = len1;
×
2941
    tbName = str + pos2;
×
2942
    tbLen = len2;
×
2943
  } else {
2944
    dbLen = strlen(db);
1,140✔
2945
    tbName = str + pos1;
1,140✔
2946
    tbLen = len1;
1,140✔
2947
  }
2948

2949
  if (dbLen <= 0 || tbLen <= 0) {
1,140✔
UNCOV
2950
    return -1;
×
2951
  }
2952

2953
  if (tNameSetDbName(&name, acctId, dbName, dbLen)) {
1,140✔
UNCOV
2954
    return -1;
×
2955
  }
2956

2957
  if (tNameAddTbName(&name, tbName, tbLen)) {
1,140✔
UNCOV
2958
    return -1;
×
2959
  }
2960

2961
  char dbFName[TSDB_DB_FNAME_LEN] = {0};
1,140✔
2962
  (void)snprintf(dbFName, TSDB_DB_FNAME_LEN, "%d.%.*s", acctId, dbLen, dbName);
1,140✔
2963

2964
  STablesReq* pDb = taosHashGet(pHash, dbFName, strlen(dbFName));
1,140✔
2965
  if (pDb) {
1,140✔
UNCOV
2966
    if (NULL == taosArrayPush(pDb->pTables, &name)) {
×
2967
      return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
2968
    }
2969
  } else {
2970
    STablesReq db;
1,140✔
2971
    db.pTables = taosArrayInit(20, sizeof(SName));
1,140✔
2972
    if (NULL == db.pTables) {
1,140✔
UNCOV
2973
      return terrno;
×
2974
    }
2975
    tstrncpy(db.dbFName, dbFName, TSDB_DB_FNAME_LEN);
1,140✔
2976
    if (NULL == taosArrayPush(db.pTables, &name)) {
2,280✔
UNCOV
2977
      return terrno;
×
2978
    }
2979
    TSC_ERR_RET(taosHashPut(pHash, dbFName, strlen(dbFName), &db, sizeof(db)));
1,140✔
2980
  }
2981

2982
  return TSDB_CODE_SUCCESS;
1,140✔
2983
}
2984

2985
int32_t transferTableNameList(const char* tbList, int32_t acctId, char* dbName, SArray** pReq) {
1,140✔
2986
  SHashObj* pHash = taosHashInit(3, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
1,140✔
2987
  if (NULL == pHash) {
1,140✔
UNCOV
2988
    return terrno;
×
2989
  }
2990

2991
  bool    inEscape = false;
1,140✔
2992
  int32_t code = 0;
1,140✔
2993
  void*   pIter = NULL;
1,140✔
2994

2995
  int32_t vIdx = 0;
1,140✔
2996
  int32_t vPos[2];
1,140✔
2997
  int32_t vLen[2];
1,140✔
2998

2999
  (void)memset(vPos, -1, sizeof(vPos));
1,140✔
3000
  (void)memset(vLen, 0, sizeof(vLen));
1,140✔
3001

3002
  for (int32_t i = 0;; ++i) {
5,700✔
3003
    if (0 == *(tbList + i)) {
5,700✔
3004
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
1,140✔
3005
        vLen[vIdx] = i - vPos[vIdx];
1,140✔
3006
      }
3007

3008
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
1,140✔
3009
      if (code) {
1,140✔
UNCOV
3010
        goto _return;
×
3011
      }
3012

3013
      break;
1,140✔
3014
    }
3015

3016
    if ('`' == *(tbList + i)) {
4,560✔
UNCOV
3017
      inEscape = !inEscape;
×
3018
      if (!inEscape) {
×
3019
        if (vPos[vIdx] >= 0) {
×
3020
          vLen[vIdx] = i - vPos[vIdx];
×
3021
        } else {
UNCOV
3022
          goto _return;
×
3023
        }
3024
      }
3025

UNCOV
3026
      continue;
×
3027
    }
3028

3029
    if (inEscape) {
4,560✔
UNCOV
3030
      if (vPos[vIdx] < 0) {
×
3031
        vPos[vIdx] = i;
×
3032
      }
UNCOV
3033
      continue;
×
3034
    }
3035

3036
    if ('.' == *(tbList + i)) {
4,560✔
UNCOV
3037
      if (vPos[vIdx] < 0) {
×
3038
        goto _return;
×
3039
      }
UNCOV
3040
      if (vLen[vIdx] <= 0) {
×
3041
        vLen[vIdx] = i - vPos[vIdx];
×
3042
      }
UNCOV
3043
      vIdx++;
×
3044
      if (vIdx >= 2) {
×
3045
        goto _return;
×
3046
      }
UNCOV
3047
      continue;
×
3048
    }
3049

3050
    if (',' == *(tbList + i)) {
4,560✔
UNCOV
3051
      if (vPos[vIdx] < 0) {
×
3052
        goto _return;
×
3053
      }
UNCOV
3054
      if (vLen[vIdx] <= 0) {
×
3055
        vLen[vIdx] = i - vPos[vIdx];
×
3056
      }
3057

UNCOV
3058
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
×
3059
      if (code) {
×
3060
        goto _return;
×
3061
      }
3062

UNCOV
3063
      (void)memset(vPos, -1, sizeof(vPos));
×
3064
      (void)memset(vLen, 0, sizeof(vLen));
×
3065
      vIdx = 0;
×
3066
      continue;
×
3067
    }
3068

3069
    if (' ' == *(tbList + i) || '\r' == *(tbList + i) || '\t' == *(tbList + i) || '\n' == *(tbList + i)) {
4,560✔
UNCOV
3070
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
×
3071
        vLen[vIdx] = i - vPos[vIdx];
×
3072
      }
UNCOV
3073
      continue;
×
3074
    }
3075

3076
    if (('a' <= *(tbList + i) && 'z' >= *(tbList + i)) || ('A' <= *(tbList + i) && 'Z' >= *(tbList + i)) ||
4,560✔
3077
        ('0' <= *(tbList + i) && '9' >= *(tbList + i)) || ('_' == *(tbList + i))) {
570✔
3078
      if (vLen[vIdx] > 0) {
4,560✔
UNCOV
3079
        goto _return;
×
3080
      }
3081
      if (vPos[vIdx] < 0) {
4,560✔
3082
        vPos[vIdx] = i;
1,140✔
3083
      }
3084
      continue;
4,560✔
3085
    }
3086

UNCOV
3087
    goto _return;
×
3088
  }
3089

3090
  int32_t dbNum = taosHashGetSize(pHash);
1,140✔
3091
  *pReq = taosArrayInit(dbNum, sizeof(STablesReq));
1,140✔
3092
  if (NULL == pReq) {
1,140✔
UNCOV
3093
    TSC_ERR_JRET(terrno);
×
3094
  }
3095
  pIter = taosHashIterate(pHash, NULL);
1,140✔
3096
  while (pIter) {
2,280✔
3097
    STablesReq* pDb = (STablesReq*)pIter;
1,140✔
3098
    if (NULL == taosArrayPush(*pReq, pDb)) {
2,280✔
UNCOV
3099
      TSC_ERR_JRET(terrno);
×
3100
    }
3101
    pIter = taosHashIterate(pHash, pIter);
1,140✔
3102
  }
3103

3104
  taosHashCleanup(pHash);
1,140✔
3105

3106
  return TSDB_CODE_SUCCESS;
1,140✔
3107

UNCOV
3108
_return:
×
3109

UNCOV
3110
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
3111

UNCOV
3112
  pIter = taosHashIterate(pHash, NULL);
×
3113
  while (pIter) {
×
3114
    STablesReq* pDb = (STablesReq*)pIter;
×
3115
    taosArrayDestroy(pDb->pTables);
×
3116
    pIter = taosHashIterate(pHash, pIter);
×
3117
  }
3118

UNCOV
3119
  taosHashCleanup(pHash);
×
3120

UNCOV
3121
  return terrno;
×
3122
}
3123

3124
void syncCatalogFn(SMetaData* pResult, void* param, int32_t code) {
1,140✔
3125
  SSyncQueryParam* pParam = param;
1,140✔
3126
  pParam->pRequest->code = code;
1,140✔
3127

3128
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
1,140✔
UNCOV
3129
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3130
  }
3131
}
1,140✔
3132

3133
void syncQueryFn(void* param, void* res, int32_t code) {
796,866,306✔
3134
  SSyncQueryParam* pParam = param;
796,866,306✔
3135
  pParam->pRequest = res;
796,866,306✔
3136

3137
  if (pParam->pRequest) {
796,868,824✔
3138
    pParam->pRequest->code = code;
796,837,431✔
3139
    clientOperateReport(pParam->pRequest);
796,849,909✔
3140
  }
3141

3142
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
796,828,339✔
UNCOV
3143
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3144
  }
3145
}
796,873,195✔
3146

3147
void taosAsyncQueryImpl(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
796,524,780✔
3148
                        int8_t source) {
3149
  if (sql == NULL || NULL == fp) {
796,524,780✔
3150
    terrno = TSDB_CODE_INVALID_PARA;
481✔
3151
    if (fp) {
×
3152
      fp(param, NULL, terrno);
×
3153
    }
3154

UNCOV
3155
    return;
×
3156
  }
3157

3158
  size_t sqlLen = strlen(sql);
796,524,468✔
3159
  if (sqlLen > (size_t)tsMaxSQLLength) {
796,524,468✔
3160
    tscError("conn:0x%" PRIx64 ", sql string exceeds max length:%d", connId, tsMaxSQLLength);
792✔
3161
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
792✔
3162
    fp(param, NULL, terrno);
792✔
3163
    return;
792✔
3164
  }
3165

3166
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, sql:%s", connId, sql);
796,523,676✔
3167

3168
  SRequestObj* pRequest = NULL;
796,524,306✔
3169
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
796,525,537✔
3170
  if (code != TSDB_CODE_SUCCESS) {
796,525,165✔
UNCOV
3171
    terrno = code;
×
3172
    fp(param, NULL, terrno);
×
3173
    return;
×
3174
  }
3175

3176
  code = connCheckAndUpateMetric(connId);
796,525,165✔
3177
  if (code != TSDB_CODE_SUCCESS) {
796,518,276✔
3178
    terrno = code;
256✔
3179
    fp(param, NULL, terrno);
256✔
3180
    return;
256✔
3181
  }
3182

3183
  pRequest->source = source;
796,518,020✔
3184
  pRequest->body.queryFp = fp;
796,521,716✔
3185
  doAsyncQuery(pRequest, false);
796,517,475✔
3186
}
3187

3188
void taosAsyncQueryImplWithReqid(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
212✔
3189
                                 int64_t reqid) {
3190
  if (sql == NULL || NULL == fp) {
212✔
UNCOV
3191
    terrno = TSDB_CODE_INVALID_PARA;
×
3192
    if (fp) {
×
3193
      fp(param, NULL, terrno);
×
3194
    }
3195

UNCOV
3196
    return;
×
3197
  }
3198

3199
  size_t sqlLen = strlen(sql);
212✔
3200
  if (sqlLen > (size_t)tsMaxSQLLength) {
212✔
UNCOV
3201
    tscError("conn:0x%" PRIx64 ", QID:0x%" PRIx64 ", sql string exceeds max length:%d", connId, reqid, tsMaxSQLLength);
×
3202
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
3203
    fp(param, NULL, terrno);
×
3204
    return;
×
3205
  }
3206

3207
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, QID:0x%" PRIx64 ", sql:%s", connId, reqid, sql);
212✔
3208

3209
  SRequestObj* pRequest = NULL;
212✔
3210
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, reqid);
212✔
3211
  if (code != TSDB_CODE_SUCCESS) {
212✔
UNCOV
3212
    terrno = code;
×
3213
    fp(param, NULL, terrno);
×
3214
    return;
×
3215
  }
3216

3217
  code = connCheckAndUpateMetric(connId);
212✔
3218

3219
  if (code != TSDB_CODE_SUCCESS) {
212✔
UNCOV
3220
    terrno = code;
×
3221
    fp(param, NULL, terrno);
×
3222
    return;
×
3223
  }
3224

3225
  pRequest->body.queryFp = fp;
212✔
3226

3227
  doAsyncQuery(pRequest, false);
212✔
3228
}
3229

3230
TAOS_RES* taosQueryImpl(TAOS* taos, const char* sql, bool validateOnly, int8_t source) {
796,403,097✔
3231
  if (NULL == taos) {
796,403,097✔
UNCOV
3232
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3233
    return NULL;
×
3234
  }
3235

3236
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
796,403,097✔
3237
  if (NULL == param) {
796,406,982✔
UNCOV
3238
    return NULL;
×
3239
  }
3240

3241
  int32_t code = tsem_init(&param->sem, 0, 0);
796,406,982✔
3242
  if (TSDB_CODE_SUCCESS != code) {
796,400,076✔
UNCOV
3243
    taosMemoryFree(param);
×
3244
    return NULL;
×
3245
  }
3246

3247
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
796,400,076✔
3248
  code = tsem_wait(&param->sem);
796,402,389✔
3249
  if (TSDB_CODE_SUCCESS != code) {
796,407,624✔
UNCOV
3250
    taosMemoryFree(param);
×
3251
    return NULL;
×
3252
  }
3253
  code = tsem_destroy(&param->sem);
796,407,624✔
3254
  if (TSDB_CODE_SUCCESS != code) {
796,409,497✔
UNCOV
3255
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3256
  }
3257

3258
  SRequestObj* pRequest = NULL;
796,409,497✔
3259
  if (param->pRequest != NULL) {
796,409,497✔
3260
    param->pRequest->syncQuery = true;
796,408,602✔
3261
    pRequest = param->pRequest;
796,408,817✔
3262
    param->pRequest->inCallback = false;
796,411,221✔
3263
  }
3264
  taosMemoryFree(param);
796,409,420✔
3265

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

3269
  return pRequest;
796,408,379✔
3270
}
3271

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

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

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

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

3304
  return pRequest;
212✔
3305
}
3306

3307
static void fetchCallback(void* pResult, void* param, int32_t code) {
152,749,955✔
3308
  SRequestObj* pRequest = (SRequestObj*)param;
152,749,955✔
3309

3310
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
152,749,955✔
3311

3312
  tscDebug("req:0x%" PRIx64 ", enter scheduler fetch cb, code:%d - %s, QID:0x%" PRIx64, pRequest->self, code,
152,749,949✔
3313
           tstrerror(code), pRequest->requestId);
3314

3315
  pResultInfo->pData = pResult;
152,749,949✔
3316
  pResultInfo->numOfRows = 0;
152,749,949✔
3317

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

3325
  if (pRequest->code != TSDB_CODE_SUCCESS) {
152,749,955✔
UNCOV
3326
    taosMemoryFreeClear(pResultInfo->pData);
×
3327
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pRequest->code);
×
3328
    return;
×
3329
  }
3330

3331
  pRequest->code = setQueryResultFromRsp(pResultInfo, (const SRetrieveTableRsp*)pResultInfo->pData,
176,725,491✔
3332
                                         pResultInfo->convertUcs4, pRequest->stmtBindVersion > 0);
152,749,953✔
3333
  if (pRequest->code != TSDB_CODE_SUCCESS) {
152,748,567✔
3334
    pResultInfo->numOfRows = 0;
443✔
3335
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self,
443✔
3336
             tstrerror(pRequest->code), pRequest->requestId);
3337
  } else {
3338
    tscDebug(
152,748,059✔
3339
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
3340
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
3341

3342
    STscObj*            pTscObj = pRequest->pTscObj;
152,749,472✔
3343
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
152,749,512✔
3344
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
152,749,508✔
3345
  }
3346

3347
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
152,749,949✔
3348
}
3349

3350
void taosAsyncFetchImpl(SRequestObj* pRequest, __taos_async_fn_t fp, void* param) {
182,162,769✔
3351
  pRequest->body.fetchFp = fp;
182,162,769✔
3352
  ((SSyncQueryParam*)pRequest->body.interParam)->userParam = param;
182,162,769✔
3353

3354
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
182,162,773✔
3355

3356
  // this query has no results or error exists, return directly
3357
  if (taos_num_fields(pRequest) == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
182,162,769✔
UNCOV
3358
    pResultInfo->numOfRows = 0;
×
UNCOV
3359
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
×
3360
    return;
21,889,964✔
3361
  }
3362

3363
  // all data has returned to App already, no need to try again
3364
  if (pResultInfo->completed) {
182,162,815✔
3365
    // it is a local executed query, no need to do async fetch
3366
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
29,412,860✔
3367
      if (pResultInfo->localResultFetched) {
1,320,722✔
3368
        pResultInfo->numOfRows = 0;
660,361✔
3369
        pResultInfo->current = 0;
660,361✔
3370
      } else {
3371
        pResultInfo->localResultFetched = true;
660,361✔
3372
      }
3373
    } else {
3374
      pResultInfo->numOfRows = 0;
28,092,138✔
3375
    }
3376

3377
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
29,412,860✔
3378
    return;
29,412,860✔
3379
  }
3380

3381
  SSchedulerReq req = {
152,749,951✔
3382
      .syncReq = false,
3383
      .fetchFp = fetchCallback,
3384
      .cbParam = pRequest,
3385
  };
3386

3387
  int32_t code = schedulerFetchRows(pRequest->body.queryJob, &req);
152,749,951✔
3388
  if (TSDB_CODE_SUCCESS != code) {
152,749,489✔
UNCOV
3389
    tscError("0x%" PRIx64 " failed to schedule fetch rows", pRequest->requestId);
×
3390
    // pRequest->body.fetchFp(param, pRequest, code);
3391
  }
3392
}
3393

3394
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
796,896,709✔
3395
  pRequest->inCallback = true;
796,896,709✔
3396
  int64_t this = pRequest->self;
796,902,223✔
3397
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
796,872,871✔
3398
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
20,100✔
UNCOV
3399
    code = TSDB_CODE_SUCCESS;
×
3400
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3401
  }
3402

3403
  tscDebug("QID:0x%" PRIx64 ", taos_query end, req:0x%" PRIx64 ", res:%p", pRequest->requestId, pRequest->self,
796,872,871✔
3404
           pRequest);
3405

3406
  if (pRequest->body.queryFp != NULL) {
796,874,209✔
3407
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
796,893,725✔
3408
  }
3409

3410
  SRequestObj* pReq = acquireRequest(this);
796,908,942✔
3411
  if (pReq != NULL) {
796,906,368✔
3412
    pReq->inCallback = false;
795,760,197✔
3413
    (void)releaseRequest(this);
795,762,478✔
3414
  }
3415
}
796,908,157✔
3416

3417
int32_t clientParseSql(void* param, const char* dbName, const char* sql, bool parseOnly, const char* effectiveUser,
462,619✔
3418
                       SParseSqlRes* pRes) {
3419
#ifndef TD_ENTERPRISE
3420
  return TSDB_CODE_SUCCESS;
3421
#else
3422
  return clientParseSqlImpl(param, dbName, sql, parseOnly, effectiveUser, pRes);
462,619✔
3423
#endif
3424
}
3425

3426
void updateConnAccessInfo(SConnAccessInfo* pInfo) {
798,914,241✔
3427
  if (pInfo == NULL) {
798,914,241✔
UNCOV
3428
    return;
×
3429
  }
3430
  int64_t ts = taosGetTimestampMs();
798,917,242✔
3431
  if (pInfo->startTime == 0) {
798,917,242✔
3432
    pInfo->startTime = ts;
2,393,999✔
3433
  }
3434
  pInfo->lastAccessTime = ts;
798,916,864✔
3435
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc