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

taosdata / TDengine / #4878

11 Dec 2025 02:43AM UTC coverage: 64.569% (-0.02%) from 64.586%
#4878

push

travis-ci

guanshengliang
feat(TS-7270): internal dependence

307 of 617 new or added lines in 24 files covered. (49.76%)

3821 existing lines in 123 files now uncovered.

163630 of 253417 relevant lines covered (64.57%)

107598827.89 hits per line

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

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

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

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

38
void setQueryRequest(int64_t rId) {
117,928,681✔
39
  SRequestObj* pReq = acquireRequest(rId);
117,928,681✔
40
  if (pReq != NULL) {
117,929,413✔
41
    pReq->isQuery = true;
117,919,147✔
42
    (void)releaseRequest(rId);
117,919,369✔
43
  }
44
}
117,928,925✔
45

46
static bool stringLengthCheck(const char* str, size_t maxsize) {
8,463,705✔
47
  if (str == NULL) {
8,463,705✔
48
    return false;
×
49
  }
50

51
  size_t len = strlen(str);
8,463,705✔
52
  if (len <= 0 || len > maxsize) {
8,463,705✔
53
    return false;
×
54
  }
55

56
  return true;
8,464,718✔
57
}
58

59
static bool validateUserName(const char* user) { return stringLengthCheck(user, TSDB_USER_LEN - 1); }
3,519,450✔
60

61
static bool validatePassword(const char* passwd) { return stringLengthCheck(passwd, TSDB_PASSWORD_MAX_LEN); }
3,519,226✔
62

63
static bool validateDbName(const char* db) { return stringLengthCheck(db, TSDB_DB_NAME_LEN - 1); }
1,425,211✔
64

65
static char* getClusterKey(const char* user, const char* auth, const char* ip, int32_t port) {
3,517,377✔
66
  char key[512] = {0};
3,517,377✔
67
  (void)snprintf(key, sizeof(key), "%s:%s:%s:%d", user, auth, ip, port);
3,518,412✔
68
  return taosStrdup(key);
3,518,412✔
69
}
70

71
static int32_t escapeToPrinted(char* dst, size_t maxDstLength, const char* src, size_t srcLength) {
640,431✔
72
  if (dst == NULL || src == NULL || srcLength == 0) {
640,431✔
73
    return 0;
533✔
74
  }
75
  
76
  size_t escapeLength = 0;
639,898✔
77
  for(size_t i = 0; i < srcLength; ++i) {
18,167,414✔
78
    if( src[i] == '\"' || src[i] == '\\' || src[i] == '\b' || src[i] == '\f' || src[i] == '\n' ||
17,527,516✔
79
        src[i] == '\r' || src[i] == '\t') {
17,527,516✔
80
      escapeLength += 1; 
×
81
    }    
82
  }
83

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

125
  return dstLength;
639,898✔
126
}
127

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

135
  (void)releaseRequest((int64_t)param);
2,147,483,647✔
136

137
  return killed;
2,147,483,647✔
138
}
139

140
void cleanupAppInfo() {
1,673,888✔
141
  taosHashCleanup(appInfo.pInstMap);
1,673,888✔
142
  taosHashCleanup(appInfo.pInstMapByClusterId);
1,673,888✔
143
  tscInfo("cluster instance map cleaned");
1,673,888✔
144
}
1,673,888✔
145

146
static int32_t taosConnectImpl(const char* user, const char* auth, int32_t totpCode, const char* db, __taos_async_fn_t fp, void* param,
147
                               SAppInstInfo* pAppInfo, int connType, STscObj** pTscObj);
148

149
int32_t taos_connect_internal(const char* ip, const char* user, const char* pass, const char* auth, const char* totp, const char* db,
3,520,275✔
150
                              uint16_t port, int connType, STscObj** pObj) {
151
  TSC_ERR_RET(taos_init());
3,520,275✔
152
  if (!validateUserName(user)) {
3,520,164✔
153
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
154
  }
155
  int32_t code = 0;
3,520,059✔
156

157
  char localDb[TSDB_DB_NAME_LEN] = {0};
3,520,059✔
158
  if (db != NULL && strlen(db) > 0) {
3,520,059✔
159
    if (!validateDbName(db)) {
1,425,211✔
160
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_DB_LENGTH);
×
161
    }
162

163
    tstrncpy(localDb, db, sizeof(localDb));
1,425,211✔
164
    (void)strdequote(localDb);
1,425,211✔
165
  }
166

167
  char secretEncrypt[TSDB_PASSWORD_LEN + 1] = {0};
3,519,840✔
168
  if (auth == NULL) {
3,519,840✔
169
    if (!validatePassword(pass)) {
3,519,226✔
170
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_PASS_LENGTH);
×
171
    }
172

173
    taosEncryptPass_c((uint8_t*)pass, strlen(pass), secretEncrypt);
3,519,610✔
174
  } else {
175
    tstrncpy(secretEncrypt, auth, tListLen(secretEncrypt));
614✔
176
  }
177

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

187
  SCorEpSet epSet = {0};
3,519,244✔
188
  if (ip) {
3,518,693✔
189
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
1,113,370✔
190
  } else {
191
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
2,405,323✔
192
  }
193

194
  if (port) {
3,517,163✔
195
    epSet.epSet.eps[0].port = port;
139,116✔
196
    epSet.epSet.eps[1].port = port;
139,116✔
197
  }
198

199
  char* key = getClusterKey(user, secretEncrypt, ip, port);
3,517,163✔
200
  if (NULL == key) {
3,517,413✔
UNCOV
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,
3,517,413✔
204
          user, db, key);
205
  for (int32_t i = 0; i < epSet.epSet.numOfEps; ++i) {
9,445,908✔
206
    tscInfo("ep:%d, %s:%u", i, epSet.epSet.eps[i].fqdn, epSet.epSet.eps[i].port);
5,926,324✔
207
  }
208
  // for (int32_t i = 0; i < epSet.epSet.numOfEps; i++) {
209
  //   if ((code = taosValidFqdn(tsEnableIpv6, epSet.epSet.eps[i].fqdn)) != 0) {
210
  //     taosMemFree(key);
211
  //     tscError("ipv6 flag %d, the local FQDN %s does not resolve to the ip address since %s", tsEnableIpv6,
212
  //              epSet.epSet.eps[i].fqdn, tstrerror(code));
213
  //     TSC_ERR_RET(code);
214
  //   }
215
  // }
216

217
  SAppInstInfo** pInst = NULL;
3,519,584✔
218
  code = taosThreadMutexLock(&appInfo.mutex);
3,519,584✔
219
  if (TSDB_CODE_SUCCESS != code) {
3,519,584✔
UNCOV
220
    tscError("failed to lock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
UNCOV
221
    TSC_ERR_RET(code);
×
222
  }
223

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

256
    pInst = &p;
1,736,431✔
257
  } else {
258
    if (NULL == *pInst || NULL == (*pInst)->pAppHbMgr) {
1,783,111✔
259
      tscError("*pInst:%p, pAppHgMgr:%p", *pInst, (*pInst) ? (*pInst)->pAppHbMgr : NULL);
×
UNCOV
260
      TSC_ERR_JRET(TSDB_CODE_TSC_INTERNAL_ERROR);
×
261
    }
262
    // reset to 0 in case of conn with duplicated user key but its user has ever been dropped.
263
    atomic_store_8(&(*pInst)->pAppHbMgr->connHbFlag, 0);
1,783,111✔
264
  }
265

266
_return:
3,519,584✔
267

268
  if (TSDB_CODE_SUCCESS != code) {
3,519,584✔
269
    (void)taosThreadMutexUnlock(&appInfo.mutex);
42✔
270
    taosMemoryFreeClear(key);
42✔
271
    return code;
42✔
272
  } else {
273
    code = taosThreadMutexUnlock(&appInfo.mutex);
3,519,542✔
274
    taosMemoryFreeClear(key);
3,519,542✔
275
    if (TSDB_CODE_SUCCESS != code) {
3,519,542✔
UNCOV
276
      tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
UNCOV
277
      return code;
×
278
    }
279
    return taosConnectImpl(user, &secretEncrypt[0], totpCode, localDb, NULL, NULL, *pInst, connType, pObj);
3,519,542✔
280
  }
281
}
282

283
// SAppInstInfo* getAppInstInfo(const char* clusterKey) {
284
//   SAppInstInfo** ppAppInstInfo = taosHashGet(appInfo.pInstMap, clusterKey, strlen(clusterKey));
285
//   if (ppAppInstInfo != NULL && *ppAppInstInfo != NULL) {
286
//     return *ppAppInstInfo;
287
//   } else {
288
//     return NULL;
289
//   }
290
// }
291

292
void freeQueryParam(SSyncQueryParam* param) {
559,403✔
293
  if (param == NULL) return;
559,403✔
294
  if (TSDB_CODE_SUCCESS != tsem_destroy(&param->sem)) {
559,403✔
UNCOV
295
    tscError("failed to destroy semaphore in freeQueryParam");
×
296
  }
297
  taosMemoryFree(param);
559,403✔
298
}
299

300
int32_t buildRequest(uint64_t connId, const char* sql, int sqlLen, void* param, bool validateSql,
626,862,390✔
301
                     SRequestObj** pRequest, int64_t reqid) {
302
  int32_t code = createRequest(connId, TSDB_SQL_SELECT, reqid, pRequest);
626,862,390✔
303
  if (TSDB_CODE_SUCCESS != code) {
626,862,786✔
304
    tscError("failed to malloc sqlObj, %s", sql);
×
UNCOV
305
    return code;
×
306
  }
307

308
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
626,862,786✔
309
  if ((*pRequest)->sqlstr == NULL) {
626,859,379✔
UNCOV
310
    tscError("req:0x%" PRIx64 ", failed to prepare sql string buffer, %s", (*pRequest)->self, sql);
×
UNCOV
311
    destroyRequest(*pRequest);
×
UNCOV
312
    *pRequest = NULL;
×
313
    return terrno;
×
314
  }
315

316
  (void)strntolower((*pRequest)->sqlstr, sql, (int32_t)sqlLen);
626,863,563✔
317
  (*pRequest)->sqlstr[sqlLen] = 0;
626,875,167✔
318
  (*pRequest)->sqlLen = sqlLen;
626,873,373✔
319
  (*pRequest)->validateOnly = validateSql;
626,873,648✔
320
  (*pRequest)->stmtBindVersion = 0;
626,872,259✔
321

322
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
626,870,214✔
323

324
  STscObj* pTscObj = (*pRequest)->pTscObj;
626,871,836✔
325
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
626,867,744✔
326
                             sizeof((*pRequest)->self));
327
  if (err) {
626,868,983✔
UNCOV
328
    tscError("req:0x%" PRId64 ", failed to add to request container, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
329
             (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
UNCOV
330
    destroyRequest(*pRequest);
×
UNCOV
331
    *pRequest = NULL;
×
UNCOV
332
    return terrno;
×
333
  }
334

335
  (*pRequest)->allocatorRefId = -1;
626,868,983✔
336
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
626,874,776✔
337
    if (TSDB_CODE_SUCCESS !=
178,475,111✔
338
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
178,467,351✔
339
      tscError("req:0x%" PRId64 ", failed to create node allocator, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
340
               (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
341
      destroyRequest(*pRequest);
×
UNCOV
342
      *pRequest = NULL;
×
UNCOV
343
      return terrno;
×
344
    }
345
  }
346

347
  tscDebug("req:0x%" PRIx64 ", build request, QID:0x%" PRIx64, (*pRequest)->self, (*pRequest)->requestId);
626,882,636✔
348
  return TSDB_CODE_SUCCESS;
626,863,796✔
349
}
350

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

363
int32_t parseSql(SRequestObj* pRequest, bool topicQuery, SQuery** pQuery, SStmtCallback* pStmtCb) {
715,425✔
364
  STscObj* pTscObj = pRequest->pTscObj;
715,425✔
365

366
  SParseContext cxt = {
715,673✔
367
      .requestId = pRequest->requestId,
715,891✔
368
      .requestRid = pRequest->self,
715,891✔
369
      .acctId = pTscObj->acctId,
715,766✔
370
      .db = pRequest->pDb,
715,853✔
371
      .topicQuery = topicQuery,
372
      .pSql = pRequest->sqlstr,
715,636✔
373
      .sqlLen = pRequest->sqlLen,
715,984✔
374
      .pMsg = pRequest->msgBuf,
715,735✔
375
      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
376
      .pTransporter = pTscObj->pAppInfo->pTransporter,
715,953✔
377
      .pStmtCb = pStmtCb,
378
      .pUser = pTscObj->user,
715,797✔
379
      .isSuperUser = (0 == strcmp(pTscObj->user, TSDB_DEFAULT_USER)),
715,473✔
380
      .enableSysInfo = pTscObj->sysInfo,
715,511✔
381
      .svrVer = pTscObj->sVer,
715,673✔
382
      .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes),
715,698✔
383
      .stmtBindVersion = pRequest->stmtBindVersion,
715,735✔
384
      .setQueryFp = setQueryRequest,
385
      .timezone = pTscObj->optionInfo.timezone,
715,667✔
386
      .charsetCxt = pTscObj->optionInfo.charsetCxt,
715,598✔
387
  };
388

389
  cxt.mgmtEpSet = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
715,829✔
390
  int32_t code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &cxt.pCatalog);
716,294✔
391
  if (code != TSDB_CODE_SUCCESS) {
715,786✔
UNCOV
392
    return code;
×
393
  }
394

395
  code = qParseSql(&cxt, pQuery);
715,786✔
396
  if (TSDB_CODE_SUCCESS == code) {
715,526✔
397
    if ((*pQuery)->haveResultSet) {
713,945✔
UNCOV
398
      code = setResSchemaInfo(&pRequest->body.resInfo, (*pQuery)->pResSchema, (*pQuery)->numOfResCols,
×
UNCOV
399
                              (*pQuery)->pResExtSchema, pRequest->stmtBindVersion > 0);
×
UNCOV
400
      setResPrecision(&pRequest->body.resInfo, (*pQuery)->precision);
×
401
    }
402
  }
403

404
  if (TSDB_CODE_SUCCESS == code || NEED_CLIENT_HANDLE_ERROR(code)) {
715,557✔
405
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
713,685✔
406
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
713,739✔
407
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
713,902✔
408
  }
409

410
  taosArrayDestroy(cxt.pTableMetaPos);
715,456✔
411
  taosArrayDestroy(cxt.pTableVgroupPos);
715,487✔
412

413
  return code;
715,790✔
414
}
415

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

426
  return code;
×
427
}
428

429
int32_t execDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
383,256✔
430
  // drop table if exists not_exists_table
431
  if (NULL == pQuery->pCmdMsg) {
383,256✔
432
    return TSDB_CODE_SUCCESS;
×
433
  }
434

435
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
383,256✔
436
  pRequest->type = pMsgInfo->msgType;
383,256✔
437
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
383,256✔
438
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
383,256✔
439

440
  STscObj*      pTscObj = pRequest->pTscObj;
383,256✔
441
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
383,256✔
442

443
  // int64_t transporterId = 0;
444
  TSC_ERR_RET(asyncSendMsgToServer(pTscObj->pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg));
383,256✔
445
  TSC_ERR_RET(tsem_wait(&pRequest->body.rspSem));
383,256✔
446
  return TSDB_CODE_SUCCESS;
383,256✔
447
}
448

449
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
1,180,373,722✔
450

451
void asyncExecLocalCmd(SRequestObj* pRequest, SQuery* pQuery) {
5,304,659✔
452
  SRetrieveTableRsp* pRsp = NULL;
5,304,659✔
453
  if (pRequest->validateOnly) {
5,304,659✔
454
    doRequestCallback(pRequest, 0);
12,123✔
455
    return;
12,123✔
456
  }
457

458
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp,
10,493,829✔
459
                              atomic_load_8(&pRequest->pTscObj->biMode), pRequest->pTscObj->optionInfo.charsetCxt);
10,493,829✔
460
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
5,292,536✔
461
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4,
2,780,294✔
462
                                 pRequest->stmtBindVersion > 0);
2,780,294✔
463
  }
464

465
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
5,292,536✔
466
  pRequest->code = code;
5,292,536✔
467

468
  if (pRequest->code != TSDB_CODE_SUCCESS) {
5,292,536✔
469
    pResultInfo->numOfRows = 0;
3,938✔
470
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
3,938✔
471
             pRequest->requestId);
472
  } else {
473
    tscDebug(
5,288,598✔
474
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
475
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
476
  }
477

478
  doRequestCallback(pRequest, code);
5,292,536✔
479
}
480

481
int32_t asyncExecDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
17,518,479✔
482
  if (pRequest->validateOnly) {
17,518,479✔
UNCOV
483
    doRequestCallback(pRequest, 0);
×
UNCOV
484
    return TSDB_CODE_SUCCESS;
×
485
  }
486

487
  // drop table if exists not_exists_table
488
  if (NULL == pQuery->pCmdMsg) {
17,519,336✔
489
    doRequestCallback(pRequest, 0);
7,681✔
490
    return TSDB_CODE_SUCCESS;
7,681✔
491
  }
492

493
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
17,511,398✔
494
  pRequest->type = pMsgInfo->msgType;
17,511,709✔
495
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
17,511,709✔
496
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
17,511,398✔
497

498
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
17,511,398✔
499
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
17,511,551✔
500

501
  int32_t code = asyncSendMsgToServer(pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg);
17,512,131✔
502
  if (code) {
17,512,211✔
UNCOV
503
    doRequestCallback(pRequest, code);
×
504
  }
505
  return code;
17,512,211✔
506
}
507

508
int compareQueryNodeLoad(const void* elem1, const void* elem2) {
362,524✔
509
  SQueryNodeLoad* node1 = (SQueryNodeLoad*)elem1;
362,524✔
510
  SQueryNodeLoad* node2 = (SQueryNodeLoad*)elem2;
362,524✔
511

512
  if (node1->load < node2->load) {
362,524✔
UNCOV
513
    return -1;
×
514
  }
515

516
  return node1->load > node2->load;
362,524✔
517
}
518

519
int32_t updateQnodeList(SAppInstInfo* pInfo, SArray* pNodeList) {
85,108✔
520
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
85,108✔
521
  if (pInfo->pQnodeList) {
85,108✔
522
    taosArrayDestroy(pInfo->pQnodeList);
79,544✔
523
    pInfo->pQnodeList = NULL;
79,544✔
524
    tscDebug("QnodeList cleared in cluster 0x%" PRIx64, pInfo->clusterId);
79,544✔
525
  }
526

527
  if (pNodeList) {
85,108✔
528
    pInfo->pQnodeList = taosArrayDup(pNodeList, NULL);
85,108✔
529
    taosArraySort(pInfo->pQnodeList, compareQueryNodeLoad);
85,108✔
530
    tscDebug("QnodeList updated in cluster 0x%" PRIx64 ", num:%ld", pInfo->clusterId,
85,108✔
531
             taosArrayGetSize(pInfo->pQnodeList));
532
  }
533
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
85,108✔
534

535
  return TSDB_CODE_SUCCESS;
85,108✔
536
}
537

538
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
626,752,635✔
539
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
626,752,635✔
540
    *required = false;
626,348,334✔
541
    return TSDB_CODE_SUCCESS;
626,346,138✔
542
  }
543

544
  int32_t       code = TSDB_CODE_SUCCESS;
404,301✔
545
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
404,301✔
546
  *required = false;
404,301✔
547

548
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
404,301✔
549
  *required = (NULL == pInfo->pQnodeList);
404,301✔
550
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
404,301✔
551
  return TSDB_CODE_SUCCESS;
404,301✔
552
}
553

UNCOV
554
int32_t getQnodeList(SRequestObj* pRequest, SArray** pNodeList) {
×
UNCOV
555
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
×
UNCOV
556
  int32_t       code = 0;
×
557

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

578
    if (TSDB_CODE_SUCCESS == code && *pNodeList) {
×
UNCOV
579
      code = updateQnodeList(pInfo, *pNodeList);
×
580
    }
581
  }
582

583
  return code;
×
584
}
585

586
int32_t getPlan(SRequestObj* pRequest, SQuery* pQuery, SQueryPlan** pPlan, SArray* pNodeList) {
11,534,312✔
587
  pRequest->type = pQuery->msgType;
11,534,312✔
588
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
11,534,821✔
589

590
  SPlanContext cxt = {.queryId = pRequest->requestId,
17,751,757✔
591
                      .acctId = pRequest->pTscObj->acctId,
11,535,132✔
592
                      .mgmtEpSet = getEpSet_s(&pAppInfo->mgmtEp),
11,534,816✔
593
                      .pAstRoot = pQuery->pRoot,
11,537,301✔
594
                      .showRewrite = pQuery->showRewrite,
11,537,270✔
595
                      .pMsg = pRequest->msgBuf,
11,537,020✔
596
                      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
597
                      .pUser = pRequest->pTscObj->user,
11,537,019✔
598
                      .timezone = pRequest->pTscObj->optionInfo.timezone,
11,537,149✔
599
                      .sysInfo = pRequest->pTscObj->sysInfo};
11,536,860✔
600

601
  return qCreateQueryPlan(&cxt, pPlan, pNodeList);
11,536,732✔
602
}
603

604
int32_t setResSchemaInfo(SReqResultInfo* pResInfo, const SSchema* pSchema, int32_t numOfCols,
119,524,352✔
605
                         const SExtSchema* pExtSchema, bool isStmt) {
606
  if (pResInfo == NULL || pSchema == NULL || numOfCols <= 0) {
119,524,352✔
UNCOV
607
    tscError("invalid paras, pResInfo == NULL || pSchema == NULL || numOfCols <= 0");
×
UNCOV
608
    return TSDB_CODE_INVALID_PARA;
×
609
  }
610

611
  pResInfo->numOfCols = numOfCols;
119,526,392✔
612
  if (pResInfo->fields != NULL) {
119,526,961✔
613
    taosMemoryFree(pResInfo->fields);
19,766✔
614
  }
615
  if (pResInfo->userFields != NULL) {
119,523,689✔
616
    taosMemoryFree(pResInfo->userFields);
19,766✔
617
  }
618
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD_E));
119,524,456✔
619
  if (NULL == pResInfo->fields) return terrno;
119,521,622✔
620
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
119,523,294✔
621
  if (NULL == pResInfo->userFields) {
119,522,197✔
UNCOV
622
    taosMemoryFree(pResInfo->fields);
×
UNCOV
623
    return terrno;
×
624
  }
625
  if (numOfCols != pResInfo->numOfCols) {
119,520,322✔
UNCOV
626
    tscError("numOfCols:%d != pResInfo->numOfCols:%d", numOfCols, pResInfo->numOfCols);
×
UNCOV
627
    return TSDB_CODE_FAILED;
×
628
  }
629

630
  for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
714,330,182✔
631
    pResInfo->fields[i].type = pSchema[i].type;
594,808,825✔
632

633
    pResInfo->userFields[i].type = pSchema[i].type;
594,808,251✔
634
    // userFields must convert to type bytes, no matter isStmt or not
635
    pResInfo->userFields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, false);
594,806,839✔
636
    pResInfo->fields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, isStmt);
594,809,439✔
637
    if (IS_DECIMAL_TYPE(pSchema[i].type) && pExtSchema) {
594,810,173✔
638
      decimalFromTypeMod(pExtSchema[i].typeMod, &pResInfo->fields[i].precision, &pResInfo->fields[i].scale);
1,785,231✔
639
    }
640

641
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
594,807,554✔
642
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
594,809,365✔
643
  }
644
  return TSDB_CODE_SUCCESS;
119,527,107✔
645
}
646

647
void setResPrecision(SReqResultInfo* pResInfo, int32_t precision) {
87,201,808✔
648
  if (precision != TSDB_TIME_PRECISION_MILLI && precision != TSDB_TIME_PRECISION_MICRO &&
87,201,808✔
649
      precision != TSDB_TIME_PRECISION_NANO) {
UNCOV
650
    return;
×
651
  }
652

653
  pResInfo->precision = precision;
87,201,808✔
654
}
655

656
int32_t buildVnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pDbVgList) {
96,197,846✔
657
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
96,197,846✔
658
  if (NULL == nodeList) {
96,205,265✔
659
    return terrno;
×
660
  }
661
  char* policy = (tsQueryPolicy == QUERY_POLICY_VNODE) ? "vnode" : "client";
96,206,977✔
662

663
  int32_t dbNum = taosArrayGetSize(pDbVgList);
96,206,977✔
664
  for (int32_t i = 0; i < dbNum; ++i) {
189,979,174✔
665
    SArray* pVg = taosArrayGetP(pDbVgList, i);
93,762,672✔
666
    if (NULL == pVg) {
93,765,120✔
UNCOV
667
      continue;
×
668
    }
669
    int32_t vgNum = taosArrayGetSize(pVg);
93,765,120✔
670
    if (vgNum <= 0) {
93,765,071✔
671
      continue;
679,910✔
672
    }
673

674
    for (int32_t j = 0; j < vgNum; ++j) {
302,366,357✔
675
      SVgroupInfo* pInfo = taosArrayGet(pVg, j);
209,276,243✔
676
      if (NULL == pInfo) {
209,277,781✔
UNCOV
677
        taosArrayDestroy(nodeList);
×
UNCOV
678
        return TSDB_CODE_OUT_OF_RANGE;
×
679
      }
680
      SQueryNodeLoad load = {0};
209,277,781✔
681
      load.addr.nodeId = pInfo->vgId;
209,275,022✔
682
      load.addr.epSet = pInfo->epSet;
209,277,006✔
683

684
      if (NULL == taosArrayPush(nodeList, &load)) {
209,276,199✔
UNCOV
685
        taosArrayDestroy(nodeList);
×
686
        return terrno;
×
687
      }
688
    }
689
  }
690

691
  int32_t vnodeNum = taosArrayGetSize(nodeList);
96,216,502✔
692
  if (vnodeNum > 0) {
96,212,651✔
693
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
92,782,765✔
694
    goto _return;
92,783,100✔
695
  }
696

697
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
3,429,886✔
698
  if (mnodeNum <= 0) {
3,427,206✔
UNCOV
699
    tscDebug("0x%" PRIx64 " %s policy, empty node list", pRequest->requestId, policy);
×
UNCOV
700
    goto _return;
×
701
  }
702

703
  void* pData = taosArrayGet(pMnodeList, 0);
3,427,206✔
704
  if (NULL == pData) {
3,427,206✔
UNCOV
705
    taosArrayDestroy(nodeList);
×
UNCOV
706
    return TSDB_CODE_OUT_OF_RANGE;
×
707
  }
708
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
3,427,206✔
709
    taosArrayDestroy(nodeList);
×
UNCOV
710
    return terrno;
×
711
  }
712

713
  tscDebug("0x%" PRIx64 " %s policy, use mnode list, num:%d", pRequest->requestId, policy, mnodeNum);
3,427,364✔
714

715
_return:
105,881✔
716

717
  *pNodeList = nodeList;
96,208,853✔
718

719
  return TSDB_CODE_SUCCESS;
96,208,239✔
720
}
721

722
int32_t buildQnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pQnodeList) {
311,171✔
723
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
311,171✔
724
  if (NULL == nodeList) {
311,171✔
UNCOV
725
    return terrno;
×
726
  }
727

728
  int32_t qNodeNum = taosArrayGetSize(pQnodeList);
311,171✔
729
  if (qNodeNum > 0) {
311,171✔
730
    void* pData = taosArrayGet(pQnodeList, 0);
224,337✔
731
    if (NULL == pData) {
224,337✔
UNCOV
732
      taosArrayDestroy(nodeList);
×
UNCOV
733
      return TSDB_CODE_OUT_OF_RANGE;
×
734
    }
735
    if (NULL == taosArrayAddBatch(nodeList, pData, qNodeNum)) {
224,337✔
UNCOV
736
      taosArrayDestroy(nodeList);
×
UNCOV
737
      return terrno;
×
738
    }
739
    tscDebug("0x%" PRIx64 " qnode policy, use qnode list, num:%d", pRequest->requestId, qNodeNum);
224,337✔
740
    goto _return;
224,337✔
741
  }
742

743
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
86,834✔
744
  if (mnodeNum <= 0) {
86,834✔
745
    tscDebug("0x%" PRIx64 " qnode policy, empty node list", pRequest->requestId);
5,052✔
746
    goto _return;
5,052✔
747
  }
748

749
  void* pData = taosArrayGet(pMnodeList, 0);
81,782✔
750
  if (NULL == pData) {
81,782✔
UNCOV
751
    taosArrayDestroy(nodeList);
×
UNCOV
752
    return TSDB_CODE_OUT_OF_RANGE;
×
753
  }
754
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
81,782✔
UNCOV
755
    taosArrayDestroy(nodeList);
×
UNCOV
756
    return terrno;
×
757
  }
758

759
  tscDebug("0x%" PRIx64 " qnode policy, use mnode list, num:%d", pRequest->requestId, mnodeNum);
81,782✔
760

761
_return:
×
762

763
  *pNodeList = nodeList;
311,171✔
764

765
  return TSDB_CODE_SUCCESS;
311,171✔
766
}
767

768
void freeVgList(void* list) {
11,482,677✔
769
  SArray* pList = *(SArray**)list;
11,482,677✔
770
  taosArrayDestroy(pList);
11,483,415✔
771
}
11,487,448✔
772

773
int32_t buildAsyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SMetaData* pResultMeta) {
84,983,276✔
774
  SArray* pDbVgList = NULL;
84,983,276✔
775
  SArray* pQnodeList = NULL;
84,983,276✔
776
  FDelete fp = NULL;
84,983,276✔
777
  int32_t code = 0;
84,983,276✔
778

779
  switch (tsQueryPolicy) {
84,983,276✔
780
    case QUERY_POLICY_VNODE:
84,672,581✔
781
    case QUERY_POLICY_CLIENT: {
782
      if (pResultMeta) {
84,672,581✔
783
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
84,673,535✔
784
        if (NULL == pDbVgList) {
84,674,042✔
UNCOV
785
          code = terrno;
×
UNCOV
786
          goto _return;
×
787
        }
788
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
84,674,042✔
789
        for (int32_t i = 0; i < dbNum; ++i) {
166,950,711✔
790
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
82,277,691✔
791
          if (pRes->code || NULL == pRes->pRes) {
82,277,398✔
792
            continue;
1,054✔
793
          }
794

795
          if (NULL == taosArrayPush(pDbVgList, &pRes->pRes)) {
164,551,036✔
UNCOV
796
            code = terrno;
×
UNCOV
797
            goto _return;
×
798
          }
799
        }
800
      } else {
UNCOV
801
        fp = freeVgList;
×
802

UNCOV
803
        int32_t dbNum = taosArrayGetSize(pRequest->dbList);
×
UNCOV
804
        if (dbNum > 0) {
×
805
          SCatalog*     pCtg = NULL;
×
806
          SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
×
UNCOV
807
          code = catalogGetHandle(pInst->clusterId, &pCtg);
×
UNCOV
808
          if (code != TSDB_CODE_SUCCESS) {
×
UNCOV
809
            goto _return;
×
810
          }
811

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

825
            // catalogGetDBVgList will handle dbFName == null.
826
            code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
×
827
            if (code) {
×
828
              goto _return;
×
829
            }
830

831
            if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
×
832
              code = terrno;
×
UNCOV
833
              goto _return;
×
834
            }
835
          }
836
        }
837
      }
838

839
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
84,673,020✔
840
      break;
84,673,974✔
841
    }
842
    case QUERY_POLICY_HYBRID:
311,171✔
843
    case QUERY_POLICY_QNODE: {
844
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
401,835✔
845
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
90,664✔
846
        if (pRes->code) {
90,664✔
UNCOV
847
          pQnodeList = NULL;
×
848
        } else {
849
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
90,664✔
850
          if (NULL == pQnodeList) {
90,664✔
UNCOV
851
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
UNCOV
852
            goto _return;
×
853
          }
854
        }
855
      } else {
856
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
220,507✔
857
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
220,507✔
858
        if (pInst->pQnodeList) {
220,507✔
859
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
220,507✔
860
          if (NULL == pQnodeList) {
220,507✔
861
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
UNCOV
862
            goto _return;
×
863
          }
864
        }
865
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
220,507✔
866
      }
867

868
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
311,171✔
869
      break;
311,171✔
870
    }
871
    default:
8✔
872
      tscError("unknown query policy: %d", tsQueryPolicy);
8✔
UNCOV
873
      return TSDB_CODE_APP_ERROR;
×
874
  }
875

876
_return:
84,985,145✔
877
  taosArrayDestroyEx(pDbVgList, fp);
84,985,145✔
878
  taosArrayDestroy(pQnodeList);
84,984,173✔
879

880
  return code;
84,985,138✔
881
}
882

883
int32_t buildSyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList) {
11,526,678✔
884
  SArray* pDbVgList = NULL;
11,526,678✔
885
  SArray* pQnodeList = NULL;
11,526,678✔
886
  int32_t code = 0;
11,526,650✔
887

888
  switch (tsQueryPolicy) {
11,526,650✔
889
    case QUERY_POLICY_VNODE:
11,525,958✔
890
    case QUERY_POLICY_CLIENT: {
891
      int32_t dbNum = taosArrayGetSize(pRequest->dbList);
11,525,958✔
892
      if (dbNum > 0) {
11,534,922✔
893
        SCatalog*     pCtg = NULL;
11,488,222✔
894
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
11,487,172✔
895
        code = catalogGetHandle(pInst->clusterId, &pCtg);
11,487,269✔
896
        if (code != TSDB_CODE_SUCCESS) {
11,482,758✔
UNCOV
897
          goto _return;
×
898
        }
899

900
        pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
11,482,758✔
901
        if (NULL == pDbVgList) {
11,486,199✔
UNCOV
902
          code = terrno;
×
UNCOV
903
          goto _return;
×
904
        }
905
        SArray* pVgList = NULL;
11,487,128✔
906
        for (int32_t i = 0; i < dbNum; ++i) {
22,973,572✔
907
          char*            dbFName = taosArrayGet(pRequest->dbList, i);
11,478,400✔
908
          SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
11,485,120✔
909
                                   .requestId = pRequest->requestId,
11,484,084✔
910
                                   .requestObjRefId = pRequest->self,
11,483,162✔
911
                                   .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
11,484,115✔
912

913
          // catalogGetDBVgList will handle dbFName == null.
914
          code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
11,490,072✔
915
          if (code) {
11,487,512✔
UNCOV
916
            goto _return;
×
917
          }
918

919
          if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
11,489,111✔
UNCOV
920
            code = terrno;
×
UNCOV
921
            goto _return;
×
922
          }
923
        }
924
      }
925

926
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
11,542,787✔
927
      break;
11,533,181✔
928
    }
929
    case QUERY_POLICY_HYBRID:
×
930
    case QUERY_POLICY_QNODE: {
UNCOV
931
      TSC_ERR_JRET(getQnodeList(pRequest, &pQnodeList));
×
932

UNCOV
933
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
×
UNCOV
934
      break;
×
935
    }
936
    default:
1,243✔
937
      tscError("unknown query policy: %d", tsQueryPolicy);
1,243✔
938
      return TSDB_CODE_APP_ERROR;
×
939
  }
940

941
_return:
11,533,559✔
942

943
  taosArrayDestroyEx(pDbVgList, freeVgList);
11,532,796✔
944
  taosArrayDestroy(pQnodeList);
11,534,043✔
945

946
  return code;
11,536,286✔
947
}
948

949
int32_t scheduleQuery(SRequestObj* pRequest, SQueryPlan* pDag, SArray* pNodeList) {
11,528,855✔
950
  void* pTransporter = pRequest->pTscObj->pAppInfo->pTransporter;
11,528,855✔
951

952
  SExecResult      res = {0};
11,530,229✔
953
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
11,529,724✔
954
                           .requestId = pRequest->requestId,
11,529,402✔
955
                           .requestObjRefId = pRequest->self};
11,529,481✔
956
  SSchedulerReq    req = {
17,741,782✔
957
         .syncReq = true,
958
         .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
11,528,641✔
959
         .pConn = &conn,
960
         .pNodeList = pNodeList,
961
         .pDag = pDag,
962
         .sql = pRequest->sqlstr,
11,528,641✔
963
         .startTs = pRequest->metric.start,
11,528,527✔
964
         .execFp = NULL,
965
         .cbParam = NULL,
966
         .chkKillFp = chkRequestKilled,
967
         .chkKillParam = (void*)pRequest->self,
11,528,767✔
968
         .pExecRes = &res,
969
         .source = pRequest->source,
11,529,121✔
970
         .pWorkerCb = getTaskPoolWorkerCb(),
11,529,793✔
971
  };
972

973
  int32_t code = schedulerExecJob(&req, &pRequest->body.queryJob);
11,532,137✔
974

975
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
11,537,361✔
976
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
11,536,694✔
977

978
  if (code != TSDB_CODE_SUCCESS) {
11,535,895✔
UNCOV
979
    schedulerFreeJob(&pRequest->body.queryJob, 0);
×
980

UNCOV
981
    pRequest->code = code;
×
UNCOV
982
    terrno = code;
×
UNCOV
983
    return pRequest->code;
×
984
  }
985

986
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_DELETE == pRequest->type ||
11,535,895✔
987
      TDMT_VND_CREATE_TABLE == pRequest->type) {
15,179✔
988
    pRequest->body.resInfo.numOfRows = res.numOfRows;
11,524,819✔
989
    if (TDMT_VND_SUBMIT == pRequest->type) {
11,525,650✔
990
      STscObj*            pTscObj = pRequest->pTscObj;
11,519,523✔
991
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
11,520,273✔
992
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
11,520,084✔
993
    }
994

995
    schedulerFreeJob(&pRequest->body.queryJob, 0);
11,527,903✔
996
  }
997

998
  pRequest->code = res.code;
11,537,382✔
999
  terrno = res.code;
11,537,772✔
1000
  return pRequest->code;
11,537,011✔
1001
}
1002

1003
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
457,737,262✔
1004
  SArray*      pArray = NULL;
457,737,262✔
1005
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
457,737,262✔
1006
  if (NULL == pRsp->aCreateTbRsp) {
457,737,262✔
1007
    return TSDB_CODE_SUCCESS;
449,026,074✔
1008
  }
1009

1010
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
8,718,006✔
1011
  for (int32_t i = 0; i < tbNum; ++i) {
21,036,998✔
1012
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
12,317,057✔
1013
    if (pTbRsp->pMeta) {
12,317,026✔
1014
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
11,614,052✔
1015
    }
1016
  }
1017

1018
  return TSDB_CODE_SUCCESS;
8,719,941✔
1019
}
1020

1021
int32_t handleQueryExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
71,125,413✔
1022
  int32_t code = 0;
71,125,413✔
1023
  SArray* pArray = NULL;
71,125,413✔
1024
  SArray* pTbArray = (SArray*)res;
71,125,413✔
1025
  int32_t tbNum = taosArrayGetSize(pTbArray);
71,125,413✔
1026
  if (tbNum <= 0) {
71,124,449✔
UNCOV
1027
    return TSDB_CODE_SUCCESS;
×
1028
  }
1029

1030
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
71,124,449✔
1031
  if (NULL == pArray) {
71,124,703✔
UNCOV
1032
    return terrno;
×
1033
  }
1034

1035
  for (int32_t i = 0; i < tbNum; ++i) {
188,843,327✔
1036
    STbVerInfo* tbInfo = taosArrayGet(pTbArray, i);
117,719,312✔
1037
    if (NULL == tbInfo) {
117,719,312✔
UNCOV
1038
      code = terrno;
×
UNCOV
1039
      goto _return;
×
1040
    }
1041
    STbSVersion tbSver = {
117,719,312✔
1042
        .tbFName = tbInfo->tbFName, .sver = tbInfo->sversion, .tver = tbInfo->tversion, .rver = tbInfo->rversion};
117,719,556✔
1043
    if (NULL == taosArrayPush(pArray, &tbSver)) {
117,719,090✔
UNCOV
1044
      code = terrno;
×
UNCOV
1045
      goto _return;
×
1046
    }
1047
  }
1048

1049
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
71,124,015✔
1050
                           .requestId = pRequest->requestId,
71,125,413✔
1051
                           .requestObjRefId = pRequest->self,
71,125,413✔
1052
                           .mgmtEps = *epset};
1053

1054
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
71,123,793✔
1055

1056
_return:
71,124,693✔
1057

1058
  taosArrayDestroy(pArray);
71,124,227✔
1059
  return code;
71,124,747✔
1060
}
1061

1062
int32_t handleAlterTbExecRes(void* res, SCatalog* pCatalog) {
8,652,009✔
1063
  return catalogUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
8,652,009✔
1064
}
1065

1066
int32_t handleCreateTbExecRes(void* res, SCatalog* pCatalog) {
54,066,612✔
1067
  return catalogAsyncUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
54,066,612✔
1068
}
1069

1070
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
594,221,614✔
1071
  if (NULL == pRequest->body.resInfo.execRes.res) {
594,221,614✔
1072
    return pRequest->code;
25,208,608✔
1073
  }
1074

1075
  SCatalog*     pCatalog = NULL;
569,013,252✔
1076
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
569,015,200✔
1077

1078
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
569,020,754✔
1079
  if (code) {
569,014,040✔
UNCOV
1080
    return code;
×
1081
  }
1082

1083
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
569,014,040✔
1084
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
569,023,062✔
1085

1086
  switch (pRes->msgType) {
569,022,707✔
1087
    case TDMT_VND_ALTER_TABLE:
3,796,516✔
1088
    case TDMT_MND_ALTER_STB: {
1089
      code = handleAlterTbExecRes(pRes->res, pCatalog);
3,796,516✔
1090
      break;
3,796,516✔
1091
    }
1092
    case TDMT_VND_CREATE_TABLE: {
35,996,127✔
1093
      SArray* pList = (SArray*)pRes->res;
35,996,127✔
1094
      int32_t num = taosArrayGetSize(pList);
36,000,736✔
1095
      for (int32_t i = 0; i < num; ++i) {
76,479,052✔
1096
        void* res = taosArrayGetP(pList, i);
40,474,759✔
1097
        // handleCreateTbExecRes will handle res == null
1098
        code = handleCreateTbExecRes(res, pCatalog);
40,476,934✔
1099
      }
1100
      break;
36,004,293✔
1101
    }
1102
    case TDMT_MND_CREATE_STB: {
352,783✔
1103
      code = handleCreateTbExecRes(pRes->res, pCatalog);
352,783✔
1104
      break;
352,783✔
1105
    }
1106
    case TDMT_VND_SUBMIT: {
457,736,941✔
1107
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
457,736,941✔
1108

1109
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
457,745,195✔
1110
      break;
457,738,821✔
1111
    }
1112
    case TDMT_SCH_QUERY:
71,125,413✔
1113
    case TDMT_SCH_MERGE_QUERY: {
1114
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
71,125,413✔
1115
      break;
71,126,844✔
1116
    }
1117
    default:
2,128✔
1118
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self,
2,128✔
1119
               pRequest->type, pRequest->requestId);
UNCOV
1120
      code = TSDB_CODE_APP_ERROR;
×
1121
  }
1122

1123
  return code;
569,019,257✔
1124
}
1125

1126
static bool incompletaFileParsing(SNode* pStmt) {
581,267,502✔
1127
  return QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pStmt) ? false : ((SVnodeModifyOpStmt*)pStmt)->fileProcessing;
581,267,502✔
1128
}
1129

UNCOV
1130
void continuePostSubQuery(SRequestObj* pRequest, SSDataBlock* pBlock) {
×
UNCOV
1131
  SSqlCallbackWrapper* pWrapper = pRequest->pWrapper;
×
1132

UNCOV
1133
  int32_t code = nodesAcquireAllocator(pWrapper->pParseCtx->allocatorId);
×
UNCOV
1134
  if (TSDB_CODE_SUCCESS == code) {
×
UNCOV
1135
    int64_t analyseStart = taosGetTimestampUs();
×
UNCOV
1136
    code = qContinueParsePostQuery(pWrapper->pParseCtx, pRequest->pQuery, pBlock);
×
UNCOV
1137
    pRequest->metric.analyseCostUs += taosGetTimestampUs() - analyseStart;
×
1138
  }
1139

1140
  if (TSDB_CODE_SUCCESS == code) {
×
UNCOV
1141
    code = qContinuePlanPostQuery(pRequest->pPostPlan);
×
1142
  }
1143

1144
  code = nodesReleaseAllocator(pWrapper->pParseCtx->allocatorId);
×
1145
  handleQueryAnslyseRes(pWrapper, NULL, code);
×
1146
}
×
1147

1148
void returnToUser(SRequestObj* pRequest) {
12,434,683✔
1149
  if (pRequest->relation.userRefId == pRequest->self || 0 == pRequest->relation.userRefId) {
12,434,683✔
1150
    // return to client
1151
    doRequestCallback(pRequest, pRequest->code);
12,434,683✔
1152
    return;
12,434,683✔
1153
  }
1154

1155
  SRequestObj* pUserReq = acquireRequest(pRequest->relation.userRefId);
×
UNCOV
1156
  if (pUserReq) {
×
UNCOV
1157
    pUserReq->code = pRequest->code;
×
1158
    // return to client
UNCOV
1159
    doRequestCallback(pUserReq, pUserReq->code);
×
UNCOV
1160
    (void)releaseRequest(pRequest->relation.userRefId);
×
UNCOV
1161
    return;
×
1162
  } else {
UNCOV
1163
    tscError("req:0x%" PRIx64 ", user ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1164
             pRequest->relation.userRefId, pRequest->requestId);
1165
  }
1166
}
1167

1168
static int32_t createResultBlock(TAOS_RES* pRes, int32_t numOfRows, SSDataBlock** pBlock) {
×
1169
  int64_t     lastTs = 0;
×
1170
  TAOS_FIELD* pResFields = taos_fetch_fields(pRes);
×
UNCOV
1171
  int32_t     numOfFields = taos_num_fields(pRes);
×
1172

UNCOV
1173
  int32_t code = createDataBlock(pBlock);
×
UNCOV
1174
  if (code) {
×
UNCOV
1175
    return code;
×
1176
  }
1177

1178
  for (int32_t i = 0; i < numOfFields; ++i) {
×
1179
    SColumnInfoData colInfoData = createColumnInfoData(pResFields[i].type, pResFields[i].bytes, i + 1);
×
1180
    code = blockDataAppendColInfo(*pBlock, &colInfoData);
×
UNCOV
1181
    if (TSDB_CODE_SUCCESS != code) {
×
1182
      blockDataDestroy(*pBlock);
×
1183
      return code;
×
1184
    }
1185
  }
1186

1187
  code = blockDataEnsureCapacity(*pBlock, numOfRows);
×
1188
  if (TSDB_CODE_SUCCESS != code) {
×
1189
    blockDataDestroy(*pBlock);
×
1190
    return code;
×
1191
  }
1192

UNCOV
1193
  for (int32_t i = 0; i < numOfRows; ++i) {
×
UNCOV
1194
    TAOS_ROW pRow = taos_fetch_row(pRes);
×
UNCOV
1195
    if (NULL == pRow[0] || NULL == pRow[1] || NULL == pRow[2]) {
×
1196
      tscError("invalid data from vnode");
×
1197
      blockDataDestroy(*pBlock);
×
1198
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1199
    }
UNCOV
1200
    int64_t ts = *(int64_t*)pRow[0];
×
UNCOV
1201
    if (lastTs < ts) {
×
1202
      lastTs = ts;
×
1203
    }
1204

1205
    for (int32_t j = 0; j < numOfFields; ++j) {
×
1206
      SColumnInfoData* pColInfoData = taosArrayGet((*pBlock)->pDataBlock, j);
×
1207
      code = colDataSetVal(pColInfoData, i, pRow[j], false);
×
UNCOV
1208
      if (TSDB_CODE_SUCCESS != code) {
×
1209
        blockDataDestroy(*pBlock);
×
1210
        return code;
×
1211
      }
1212
    }
1213

1214
    tscInfo("[create stream with histroy] lastKey:%" PRId64 " vgId:%d, vgVer:%" PRId64, ts, *(int32_t*)pRow[1],
×
1215
            *(int64_t*)pRow[2]);
1216
  }
1217

1218
  (*pBlock)->info.window.ekey = lastTs;
×
1219
  (*pBlock)->info.rows = numOfRows;
×
1220

UNCOV
1221
  tscInfo("[create stream with histroy] lastKey:%" PRId64 " numOfRows:%d from all vgroups", lastTs, numOfRows);
×
UNCOV
1222
  return TSDB_CODE_SUCCESS;
×
1223
}
1224

UNCOV
1225
void postSubQueryFetchCb(void* param, TAOS_RES* res, int32_t rowNum) {
×
UNCOV
1226
  SRequestObj* pRequest = (SRequestObj*)res;
×
1227
  if (pRequest->code) {
×
1228
    returnToUser(pRequest);
×
UNCOV
1229
    return;
×
1230
  }
1231

UNCOV
1232
  SSDataBlock* pBlock = NULL;
×
UNCOV
1233
  pRequest->code = createResultBlock(res, rowNum, &pBlock);
×
1234
  if (TSDB_CODE_SUCCESS != pRequest->code) {
×
1235
    tscError("req:0x%" PRIx64 ", create result block failed, QID:0x%" PRIx64 " %s", pRequest->self, pRequest->requestId,
×
1236
             tstrerror(pRequest->code));
1237
    returnToUser(pRequest);
×
1238
    return;
×
1239
  }
1240

1241
  SRequestObj* pNextReq = acquireRequest(pRequest->relation.nextRefId);
×
1242
  if (pNextReq) {
×
1243
    continuePostSubQuery(pNextReq, pBlock);
×
1244
    (void)releaseRequest(pRequest->relation.nextRefId);
×
1245
  } else {
1246
    tscError("req:0x%" PRIx64 ", next req ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1247
             pRequest->relation.nextRefId, pRequest->requestId);
1248
  }
1249

1250
  blockDataDestroy(pBlock);
×
1251
}
1252

1253
void handlePostSubQuery(SSqlCallbackWrapper* pWrapper) {
×
UNCOV
1254
  SRequestObj* pRequest = pWrapper->pRequest;
×
1255
  if (TD_RES_QUERY(pRequest)) {
×
UNCOV
1256
    taosAsyncFetchImpl(pRequest, postSubQueryFetchCb, pWrapper);
×
UNCOV
1257
    return;
×
1258
  }
1259

UNCOV
1260
  SRequestObj* pNextReq = acquireRequest(pRequest->relation.nextRefId);
×
UNCOV
1261
  if (pNextReq) {
×
1262
    continuePostSubQuery(pNextReq, NULL);
×
1263
    (void)releaseRequest(pRequest->relation.nextRefId);
×
1264
  } else {
1265
    tscError("req:0x%" PRIx64 ", next req ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1266
             pRequest->relation.nextRefId, pRequest->requestId);
1267
  }
1268
}
1269

1270
// todo refacto the error code  mgmt
1271
void schedulerExecCb(SExecResult* pResult, void* param, int32_t code) {
582,348,565✔
1272
  SSqlCallbackWrapper* pWrapper = param;
582,348,565✔
1273
  SRequestObj*         pRequest = pWrapper->pRequest;
582,348,565✔
1274
  STscObj*             pTscObj = pRequest->pTscObj;
582,357,522✔
1275

1276
  pRequest->code = code;
582,355,372✔
1277
  if (pResult) {
582,361,324✔
1278
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
582,315,634✔
1279
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
582,326,282✔
1280
  }
1281

1282
  int32_t type = pRequest->type;
582,358,311✔
1283
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
582,336,978✔
1284
    if (pResult) {
485,616,962✔
1285
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
485,603,967✔
1286

1287
      // record the insert rows
1288
      if (TDMT_VND_SUBMIT == type) {
485,610,737✔
1289
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
446,364,044✔
1290
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
446,367,167✔
1291
      }
1292
    }
1293
    schedulerFreeJob(&pRequest->body.queryJob, 0);
485,626,872✔
1294
  }
1295

1296
  taosMemoryFree(pResult);
582,358,308✔
1297
  tscDebug("req:0x%" PRIx64 ", enter scheduler exec cb, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
582,348,768✔
1298
           pRequest->requestId);
1299

1300
  if (code != TSDB_CODE_SUCCESS && NEED_CLIENT_HANDLE_ERROR(code) && pRequest->sqlstr != NULL &&
582,349,236✔
1301
      pRequest->stmtBindVersion == 0) {
44,299✔
1302
    tscDebug("req:0x%" PRIx64 ", client retry to handle the error, code:%s, tryCount:%d, QID:0x%" PRIx64,
44,299✔
1303
             pRequest->self, tstrerror(code), pRequest->retry, pRequest->requestId);
1304
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
44,299✔
UNCOV
1305
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1306
    }
1307
    restartAsyncQuery(pRequest, code);
44,299✔
1308
    return;
44,299✔
1309
  }
1310

1311
  tscTrace("req:0x%" PRIx64 ", scheduler exec cb, request type:%s", pRequest->self, TMSG_INFO(pRequest->type));
582,304,937✔
1312
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
582,304,937✔
1313
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
2,765,205✔
1314
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1315
    }
1316
  }
1317

1318
  pRequest->metric.execCostUs = taosGetTimestampUs() - pRequest->metric.execStart;
582,315,289✔
1319
  int32_t code1 = handleQueryExecRsp(pRequest);
582,304,589✔
1320
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
582,308,643✔
UNCOV
1321
    pRequest->code = code1;
×
1322
  }
1323

1324
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
1,163,577,313✔
1325
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
581,265,661✔
1326
    continueInsertFromCsv(pWrapper, pRequest);
12,049✔
1327
    return;
12,049✔
1328
  }
1329

1330
  if (pRequest->relation.nextRefId) {
582,304,880✔
UNCOV
1331
    handlePostSubQuery(pWrapper);
×
1332
  } else {
1333
    destorySqlCallbackWrapper(pWrapper);
582,304,639✔
1334
    pRequest->pWrapper = NULL;
582,292,796✔
1335

1336
    // return to client
1337
    doRequestCallback(pRequest, code);
582,297,226✔
1338
  }
1339
}
1340

1341
void launchQueryImpl(SRequestObj* pRequest, SQuery* pQuery, bool keepQuery, void** res) {
11,916,044✔
1342
  int32_t code = 0;
11,916,044✔
1343
  int32_t subplanNum = 0;
11,916,044✔
1344

1345
  if (pQuery->pRoot) {
11,916,044✔
1346
    pRequest->stmtType = pQuery->pRoot->type;
11,535,224✔
1347
  }
1348

1349
  if (pQuery->pRoot && !pRequest->inRetry) {
11,916,678✔
1350
    STscObj*            pTscObj = pRequest->pTscObj;
11,535,794✔
1351
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
11,535,410✔
1352
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type) {
11,536,665✔
1353
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
11,526,477✔
1354
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
10,291✔
1355
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
10,488✔
1356
    }
1357
  }
1358

1359
  pRequest->body.execMode = pQuery->execMode;
11,919,860✔
1360
  switch (pQuery->execMode) {
11,919,719✔
UNCOV
1361
    case QUERY_EXEC_MODE_LOCAL:
×
UNCOV
1362
      if (!pRequest->validateOnly) {
×
UNCOV
1363
        if (NULL == pQuery->pRoot) {
×
UNCOV
1364
          terrno = TSDB_CODE_INVALID_PARA;
×
UNCOV
1365
          code = terrno;
×
1366
        } else {
UNCOV
1367
          code = execLocalCmd(pRequest, pQuery);
×
1368
        }
1369
      }
1370
      break;
×
1371
    case QUERY_EXEC_MODE_RPC:
383,256✔
1372
      if (!pRequest->validateOnly) {
383,256✔
1373
        code = execDdlQuery(pRequest, pQuery);
383,256✔
1374
      }
1375
      break;
383,256✔
1376
    case QUERY_EXEC_MODE_SCHEDULE: {
11,535,370✔
1377
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
11,535,370✔
1378
      if (NULL == pMnodeList) {
11,536,095✔
1379
        code = terrno;
×
UNCOV
1380
        break;
×
1381
      }
1382
      SQueryPlan* pDag = NULL;
11,536,095✔
1383
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
11,535,873✔
1384
      if (TSDB_CODE_SUCCESS == code) {
11,531,820✔
1385
        pRequest->body.subplanNum = pDag->numOfSubplans;
11,532,029✔
1386
        if (!pRequest->validateOnly) {
11,532,367✔
1387
          SArray* pNodeList = NULL;
11,532,131✔
1388
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
11,531,270✔
1389
          if (TSDB_CODE_SUCCESS == code) {
11,533,357✔
1390
            code = scheduleQuery(pRequest, pDag, pNodeList);
11,535,339✔
1391
          }
1392
          taosArrayDestroy(pNodeList);
11,534,415✔
1393
        }
1394
      }
1395
      taosArrayDestroy(pMnodeList);
11,535,974✔
1396
      break;
11,536,530✔
1397
    }
UNCOV
1398
    case QUERY_EXEC_MODE_EMPTY_RESULT:
×
UNCOV
1399
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
UNCOV
1400
      break;
×
UNCOV
1401
    default:
×
UNCOV
1402
      break;
×
1403
  }
1404

1405
  if (!keepQuery) {
11,919,786✔
UNCOV
1406
    qDestroyQuery(pQuery);
×
1407
  }
1408

1409
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
11,919,786✔
1410
    int ret = removeMeta(pRequest->pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type));
30,590✔
1411
    if (TSDB_CODE_SUCCESS != ret) {
30,590✔
UNCOV
1412
      tscError("req:0x%" PRIx64 ", remove meta failed,code:%d, QID:0x%" PRIx64, pRequest->self, ret,
×
1413
               pRequest->requestId);
1414
    }
1415
  }
1416

1417
  if (TSDB_CODE_SUCCESS == code) {
11,919,737✔
1418
    code = handleQueryExecRsp(pRequest);
11,918,698✔
1419
  }
1420

1421
  if (TSDB_CODE_SUCCESS != code) {
11,919,806✔
1422
    pRequest->code = code;
25,886✔
1423
  }
1424

1425
  if (res) {
11,919,806✔
UNCOV
1426
    *res = pRequest->body.resInfo.execRes.res;
×
UNCOV
1427
    pRequest->body.resInfo.execRes.res = NULL;
×
1428
  }
1429
}
11,919,806✔
1430

1431
static int32_t asyncExecSchQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta,
582,818,937✔
1432
                                 SSqlCallbackWrapper* pWrapper) {
1433
  int32_t code = TSDB_CODE_SUCCESS;
582,818,937✔
1434
  pRequest->type = pQuery->msgType;
582,818,937✔
1435
  SArray*     pMnodeList = NULL;
582,833,065✔
1436
  SQueryPlan* pDag = NULL;
582,833,065✔
1437
  int64_t     st = taosGetTimestampUs();
582,807,920✔
1438

1439
  if (!pRequest->parseOnly) {
582,807,920✔
1440
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
582,823,446✔
1441
    if (NULL == pMnodeList) {
582,814,479✔
UNCOV
1442
      code = terrno;
×
1443
    }
1444
    SPlanContext cxt = {.queryId = pRequest->requestId,
624,833,409✔
1445
                        .acctId = pRequest->pTscObj->acctId,
582,834,118✔
1446
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
582,840,782✔
1447
                        .pAstRoot = pQuery->pRoot,
582,850,270✔
1448
                        .showRewrite = pQuery->showRewrite,
582,851,635✔
1449
                        .isView = pWrapper->pParseCtx->isView,
582,831,165✔
1450
                        .isAudit = pWrapper->pParseCtx->isAudit,
582,849,345✔
1451
                        .pMsg = pRequest->msgBuf,
582,824,172✔
1452
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1453
                        .pUser = pRequest->pTscObj->user,
582,836,038✔
1454
                        .sysInfo = pRequest->pTscObj->sysInfo,
582,835,929✔
1455
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
582,834,798✔
1456
                        .allocatorId = pRequest->stmtBindVersion > 0 ? 0 : pRequest->allocatorRefId};
582,828,981✔
1457
    if (TSDB_CODE_SUCCESS == code) {
582,836,493✔
1458
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
582,835,455✔
1459
    }
1460
    if (code) {
582,820,342✔
1461
      tscError("req:0x%" PRIx64 ", failed to create query plan, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
264,987✔
1462
               pRequest->requestId);
1463
    } else {
1464
      pRequest->body.subplanNum = pDag->numOfSubplans;
582,555,355✔
1465
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
582,563,275✔
1466
    }
1467
  }
1468

1469
  pRequest->metric.execStart = taosGetTimestampUs();
582,835,148✔
1470
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
582,834,956✔
1471

1472
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
603,817,671✔
1473
    SArray* pNodeList = NULL;
582,317,321✔
1474
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
582,341,085✔
1475
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
84,983,291✔
1476
    }
1477

1478
    SRequestConnInfo conn = {.pTrans = getAppInfo(pRequest)->pTransporter,
582,339,508✔
1479
                             .requestId = pRequest->requestId,
582,342,143✔
1480
                             .requestObjRefId = pRequest->self};
582,338,523✔
1481
    SSchedulerReq    req = {
603,333,911✔
1482
           .syncReq = false,
1483
           .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
582,321,223✔
1484
           .pConn = &conn,
1485
           .pNodeList = pNodeList,
1486
           .pDag = pDag,
1487
           .allocatorRefId = pRequest->allocatorRefId,
582,321,223✔
1488
           .sql = pRequest->sqlstr,
582,317,609✔
1489
           .startTs = pRequest->metric.start,
582,335,589✔
1490
           .execFp = schedulerExecCb,
1491
           .cbParam = pWrapper,
1492
           .chkKillFp = chkRequestKilled,
1493
           .chkKillParam = (void*)pRequest->self,
582,321,613✔
1494
           .pExecRes = NULL,
1495
           .source = pRequest->source,
582,318,363✔
1496
           .pWorkerCb = getTaskPoolWorkerCb(),
582,300,263✔
1497
    };
1498
    if (TSDB_CODE_SUCCESS == code) {
582,325,082✔
1499
      code = schedulerExecJob(&req, &pRequest->body.queryJob);
582,353,237✔
1500
    }
1501

1502
    taosArrayDestroy(pNodeList);
582,324,587✔
1503
  } else {
1504
    qDestroyQueryPlan(pDag);
513,594✔
1505
    tscDebug("req:0x%" PRIx64 ", plan not executed, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
492,181✔
1506
             pRequest->requestId);
1507
    destorySqlCallbackWrapper(pWrapper);
492,181✔
1508
    pRequest->pWrapper = NULL;
492,181✔
1509
    if (TSDB_CODE_SUCCESS != code) {
492,181✔
1510
      pRequest->code = terrno;
264,987✔
1511
    }
1512

1513
    doRequestCallback(pRequest, code);
492,181✔
1514
  }
1515

1516
  // todo not to be released here
1517
  taosArrayDestroy(pMnodeList);
582,844,338✔
1518

1519
  return code;
582,840,507✔
1520
}
1521

1522
void launchAsyncQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta, SSqlCallbackWrapper* pWrapper) {
606,281,890✔
1523
  int32_t code = 0;
606,281,890✔
1524

1525
  if (pRequest->parseOnly) {
606,281,890✔
1526
    doRequestCallback(pRequest, 0);
288,736✔
1527
    return;
288,736✔
1528
  }
1529

1530
  pRequest->body.execMode = pQuery->execMode;
606,006,634✔
1531
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
606,000,432✔
1532
    destorySqlCallbackWrapper(pWrapper);
23,171,367✔
1533
    pRequest->pWrapper = NULL;
23,171,736✔
1534
  }
1535

1536
  if (pQuery->pRoot && !pRequest->inRetry) {
605,981,489✔
1537
    STscObj*            pTscObj = pRequest->pTscObj;
605,994,505✔
1538
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
606,012,664✔
1539
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
606,004,105✔
1540
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
497,363,618✔
1541
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
446,321,613✔
1542
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
159,681,834✔
1543
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
79,598,707✔
1544
    }
1545
  }
1546

1547
  switch (pQuery->execMode) {
606,010,427✔
1548
    case QUERY_EXEC_MODE_LOCAL:
5,304,659✔
1549
      asyncExecLocalCmd(pRequest, pQuery);
5,304,659✔
1550
      break;
5,304,659✔
1551
    case QUERY_EXEC_MODE_RPC:
17,518,955✔
1552
      code = asyncExecDdlQuery(pRequest, pQuery);
17,518,955✔
1553
      break;
17,519,892✔
1554
    case QUERY_EXEC_MODE_SCHEDULE: {
582,829,902✔
1555
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
582,829,902✔
1556
      break;
582,841,095✔
1557
    }
1558
    case QUERY_EXEC_MODE_EMPTY_RESULT:
348,353✔
1559
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
348,353✔
1560
      doRequestCallback(pRequest, 0);
348,353✔
1561
      break;
348,353✔
UNCOV
1562
    default:
×
UNCOV
1563
      tscError("req:0x%" PRIx64 ", invalid execMode %d", pRequest->self, pQuery->execMode);
×
UNCOV
1564
      doRequestCallback(pRequest, -1);
×
UNCOV
1565
      break;
×
1566
  }
1567
}
1568

1569
int32_t refreshMeta(STscObj* pTscObj, SRequestObj* pRequest) {
11,371✔
1570
  SCatalog* pCatalog = NULL;
11,371✔
1571
  int32_t   code = 0;
11,371✔
1572
  int32_t   dbNum = taosArrayGetSize(pRequest->dbList);
11,371✔
1573
  int32_t   tblNum = taosArrayGetSize(pRequest->tableList);
11,371✔
1574

1575
  if (dbNum <= 0 && tblNum <= 0) {
11,371✔
1576
    return TSDB_CODE_APP_ERROR;
11,371✔
1577
  }
1578

UNCOV
1579
  code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
×
UNCOV
1580
  if (code != TSDB_CODE_SUCCESS) {
×
UNCOV
1581
    return code;
×
1582
  }
1583

UNCOV
1584
  SRequestConnInfo conn = {.pTrans = pTscObj->pAppInfo->pTransporter,
×
UNCOV
1585
                           .requestId = pRequest->requestId,
×
UNCOV
1586
                           .requestObjRefId = pRequest->self,
×
UNCOV
1587
                           .mgmtEps = getEpSet_s(&pTscObj->pAppInfo->mgmtEp)};
×
1588

UNCOV
1589
  for (int32_t i = 0; i < dbNum; ++i) {
×
1590
    char* dbFName = taosArrayGet(pRequest->dbList, i);
×
1591

1592
    // catalogRefreshDBVgInfo will handle dbFName == null.
UNCOV
1593
    code = catalogRefreshDBVgInfo(pCatalog, &conn, dbFName);
×
UNCOV
1594
    if (code != TSDB_CODE_SUCCESS) {
×
UNCOV
1595
      return code;
×
1596
    }
1597
  }
1598

UNCOV
1599
  for (int32_t i = 0; i < tblNum; ++i) {
×
UNCOV
1600
    SName* tableName = taosArrayGet(pRequest->tableList, i);
×
1601

1602
    // catalogRefreshTableMeta will handle tableName == null.
UNCOV
1603
    code = catalogRefreshTableMeta(pCatalog, &conn, tableName, -1);
×
1604
    if (code != TSDB_CODE_SUCCESS) {
×
UNCOV
1605
      return code;
×
1606
    }
1607
  }
1608

UNCOV
1609
  return code;
×
1610
}
1611

1612
int32_t removeMeta(STscObj* pTscObj, SArray* tbList, bool isView) {
4,078,675✔
1613
  SCatalog* pCatalog = NULL;
4,078,675✔
1614
  int32_t   tbNum = taosArrayGetSize(tbList);
4,078,675✔
1615
  int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
4,078,675✔
1616
  if (code != TSDB_CODE_SUCCESS) {
4,078,675✔
UNCOV
1617
    return code;
×
1618
  }
1619

1620
  if (isView) {
4,078,675✔
1621
    for (int32_t i = 0; i < tbNum; ++i) {
821,726✔
1622
      SName* pViewName = taosArrayGet(tbList, i);
410,863✔
1623
      char   dbFName[TSDB_DB_FNAME_LEN];
401,363✔
1624
      if (NULL == pViewName) {
410,863✔
UNCOV
1625
        continue;
×
1626
      }
1627
      (void)tNameGetFullDbName(pViewName, dbFName);
410,863✔
1628
      TSC_ERR_RET(catalogRemoveViewMeta(pCatalog, dbFName, 0, pViewName->tname, 0));
410,863✔
1629
    }
1630
  } else {
1631
    for (int32_t i = 0; i < tbNum; ++i) {
5,460,829✔
1632
      SName* pTbName = taosArrayGet(tbList, i);
1,793,017✔
1633
      TSC_ERR_RET(catalogRemoveTableMeta(pCatalog, pTbName));
1,793,017✔
1634
    }
1635
  }
1636

1637
  return TSDB_CODE_SUCCESS;
4,078,675✔
1638
}
1639

1640
int32_t initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet) {
3,516,041✔
1641
  pEpSet->version = 0;
3,516,041✔
1642

1643
  // init mnode ip set
1644
  SEpSet* mgmtEpSet = &(pEpSet->epSet);
3,518,213✔
1645
  mgmtEpSet->numOfEps = 0;
3,518,747✔
1646
  mgmtEpSet->inUse = 0;
3,519,187✔
1647

1648
  if (firstEp && firstEp[0] != 0) {
3,518,747✔
1649
    if (strlen(firstEp) >= TSDB_EP_LEN) {
3,517,983✔
UNCOV
1650
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
UNCOV
1651
      return -1;
×
1652
    }
1653

1654
    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
3,517,983✔
1655
    if (code != TSDB_CODE_SUCCESS) {
3,517,245✔
UNCOV
1656
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
UNCOV
1657
      return terrno;
×
1658
    }
1659
    // uint32_t addr = 0;
1660
    SIpAddr addr = {0};
3,517,245✔
1661
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
3,517,450✔
1662
    if (code) {
3,517,491✔
1663
      tscError("failed to resolve firstEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
509✔
1664
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1665
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
751✔
1666
    } else {
1667
      mgmtEpSet->numOfEps++;
3,517,264✔
1668
    }
1669
  }
1670

1671
  if (secondEp && secondEp[0] != 0) {
3,517,684✔
1672
    if (strlen(secondEp) >= TSDB_EP_LEN) {
2,405,642✔
UNCOV
1673
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
UNCOV
1674
      return terrno;
×
1675
    }
1676

1677
    int32_t code = taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
2,405,642✔
1678
    if (code != TSDB_CODE_SUCCESS) {
2,405,795✔
UNCOV
1679
      return code;
×
1680
    }
1681
    SIpAddr addr = {0};
2,405,795✔
1682
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
2,405,795✔
1683
    if (code) {
2,406,138✔
1684
      tscError("failed to resolve secondEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
420✔
1685
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
UNCOV
1686
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
×
1687
    } else {
1688
      mgmtEpSet->numOfEps++;
2,405,718✔
1689
    }
1690
  }
1691

1692
  if (mgmtEpSet->numOfEps == 0) {
3,517,760✔
1693
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
751✔
1694
    return TSDB_CODE_RPC_NETWORK_UNAVAIL;
751✔
1695
  }
1696

1697
  return 0;
3,516,102✔
1698
}
1699

1700
int32_t taosConnectImpl(const char* user, const char* auth, int32_t totpCode, const char* db, __taos_async_fn_t fp, void* param,
3,519,542✔
1701
                        SAppInstInfo* pAppInfo, int connType, STscObj** pTscObj) {
1702
  *pTscObj = NULL;
3,519,542✔
1703
  int32_t code = createTscObj(user, auth, db, connType, pAppInfo, pTscObj);
3,519,542✔
1704
  if (TSDB_CODE_SUCCESS != code) {
3,519,542✔
UNCOV
1705
    return code;
×
1706
  }
1707

1708
  SRequestObj* pRequest = NULL;
3,519,542✔
1709
  code = createRequest((*pTscObj)->id, TDMT_MND_CONNECT, 0, &pRequest);
3,519,542✔
1710
  if (TSDB_CODE_SUCCESS != code) {
3,519,359✔
UNCOV
1711
    destroyTscObj(*pTscObj);
×
UNCOV
1712
    return code;
×
1713
  }
1714

1715
  pRequest->sqlstr = taosStrdup("taos_connect");
3,519,359✔
1716
  if (pRequest->sqlstr) {
3,519,002✔
1717
    pRequest->sqlLen = strlen(pRequest->sqlstr);
3,519,002✔
1718
  } else {
UNCOV
1719
    return terrno;
×
1720
  }
1721

1722
  SMsgSendInfo* body = NULL;
3,519,002✔
1723
  code = buildConnectMsg(pRequest, &body, totpCode);
3,519,002✔
1724
  if (TSDB_CODE_SUCCESS != code) {
3,518,018✔
UNCOV
1725
    destroyTscObj(*pTscObj);
×
UNCOV
1726
    return code;
×
1727
  }
1728

1729
  // int64_t transporterId = 0;
1730
  SEpSet epset = getEpSet_s(&(*pTscObj)->pAppInfo->mgmtEp);
3,518,018✔
1731
  code = asyncSendMsgToServer((*pTscObj)->pAppInfo->pTransporter, &epset, NULL, body);
3,517,453✔
1732
  if (TSDB_CODE_SUCCESS != code) {
3,519,163✔
UNCOV
1733
    destroyTscObj(*pTscObj);
×
1734
    tscError("failed to send connect msg to server, code:%s", tstrerror(code));
×
1735
    return code;
×
1736
  }
1737
  if (TSDB_CODE_SUCCESS != tsem_wait(&pRequest->body.rspSem)) {
3,519,163✔
UNCOV
1738
    destroyTscObj(*pTscObj);
×
UNCOV
1739
    tscError("failed to wait sem, code:%s", terrstr());
×
UNCOV
1740
    return terrno;
×
1741
  }
1742
  if (pRequest->code != TSDB_CODE_SUCCESS) {
3,519,542✔
1743
    const char* errorMsg = (code == TSDB_CODE_RPC_FQDN_ERROR) ? taos_errstr(pRequest) : tstrerror(pRequest->code);
15,408✔
1744
    tscError("failed to connect to server, reason: %s", errorMsg);
15,408✔
1745

1746
    terrno = pRequest->code;
15,408✔
1747
    destroyRequest(pRequest);
15,408✔
1748
    taos_close_internal(*pTscObj);
15,408✔
1749
    *pTscObj = NULL;
15,408✔
1750
    return terrno;
15,408✔
1751
  }
1752
  if (connType == CONN_TYPE__AUTH_TEST) {
3,504,134✔
NEW
1753
    terrno = TSDB_CODE_SUCCESS;
×
UNCOV
1754
    destroyRequest(pRequest);
×
NEW
1755
    taos_close_internal(*pTscObj);
×
NEW
1756
    *pTscObj = NULL;
×
NEW
1757
    return TSDB_CODE_SUCCESS;
×
1758
  }
1759

1760
  tscInfo("conn:0x%" PRIx64 ", connection is opening, connId:%u, dnodeConn:%p, QID:0x%" PRIx64, (*pTscObj)->id,
3,504,134✔
1761
          (*pTscObj)->connId, (*pTscObj)->pAppInfo->pTransporter, pRequest->requestId);
1762
  destroyRequest(pRequest);
3,504,201✔
1763
  return code;
3,503,704✔
1764
}
1765

1766
static int32_t buildConnectMsg(SRequestObj* pRequest, SMsgSendInfo** pMsgSendInfo, int32_t totpCode) {
3,518,612✔
1767
  *pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
3,518,612✔
1768
  if (*pMsgSendInfo == NULL) {
3,518,708✔
1769
    return terrno;
×
1770
  }
1771

1772
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
3,518,708✔
1773

1774
  (*pMsgSendInfo)->requestObjRefId = pRequest->self;
3,518,708✔
1775
  (*pMsgSendInfo)->requestId = pRequest->requestId;
3,519,098✔
1776
  (*pMsgSendInfo)->fp = getMsgRspHandle((*pMsgSendInfo)->msgType);
3,519,098✔
1777
  (*pMsgSendInfo)->param = taosMemoryCalloc(1, sizeof(pRequest->self));
3,519,085✔
1778
  if (NULL == (*pMsgSendInfo)->param) {
3,518,455✔
UNCOV
1779
    taosMemoryFree(*pMsgSendInfo);
×
UNCOV
1780
    return terrno;
×
1781
  }
1782

1783
  *(int64_t*)(*pMsgSendInfo)->param = pRequest->self;
3,518,455✔
1784

1785
  SConnectReq connectReq = {0};
3,518,845✔
1786
  STscObj*    pObj = pRequest->pTscObj;
3,518,372✔
1787

1788
  char* db = getDbOfConnection(pObj);
3,518,598✔
1789
  if (db != NULL) {
3,519,085✔
1790
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
1,424,859✔
1791
  } else if (terrno) {
2,094,226✔
UNCOV
1792
    taosMemoryFree(*pMsgSendInfo);
×
UNCOV
1793
    return terrno;
×
1794
  }
1795
  taosMemoryFreeClear(db);
3,519,085✔
1796

1797
  connectReq.connType = pObj->connType;
3,519,400✔
1798
  connectReq.pid = appInfo.pid;
3,519,400✔
1799
  connectReq.startTime = appInfo.startTime;
3,519,257✔
1800
  connectReq.totpCode = totpCode;
3,519,257✔
1801

1802
  tstrncpy(connectReq.app, appInfo.appName, sizeof(connectReq.app));
3,519,257✔
1803
  tstrncpy(connectReq.user, pObj->user, sizeof(connectReq.user));
3,519,400✔
1804
  tstrncpy(connectReq.passwd, pObj->pass, sizeof(connectReq.passwd));
3,519,257✔
1805
  tstrncpy(connectReq.sVer, td_version, sizeof(connectReq.sVer));
3,519,257✔
1806

1807
  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connectReq);
3,519,257✔
1808
  void*   pReq = taosMemoryMalloc(contLen);
3,518,739✔
1809
  if (NULL == pReq) {
3,518,619✔
1810
    taosMemoryFree(*pMsgSendInfo);
×
UNCOV
1811
    return terrno;
×
1812
  }
1813

1814
  if (-1 == tSerializeSConnectReq(pReq, contLen, &connectReq)) {
3,518,619✔
1815
    taosMemoryFree(*pMsgSendInfo);
105✔
UNCOV
1816
    taosMemoryFree(pReq);
×
UNCOV
1817
    return terrno;
×
1818
  }
1819

1820
  (*pMsgSendInfo)->msgInfo.len = contLen;
3,518,507✔
1821
  (*pMsgSendInfo)->msgInfo.pData = pReq;
3,518,650✔
1822
  return TSDB_CODE_SUCCESS;
3,518,650✔
1823
}
1824

1825
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,030,033,624✔
1826
  if (NULL == pEpSet) {
1,030,033,624✔
1827
    return;
1,017,602,995✔
1828
  }
1829

1830
  switch (pSendInfo->target.type) {
12,430,629✔
1831
    case TARGET_TYPE_MNODE:
876✔
1832
      if (NULL == pTscObj) {
876✔
1833
        tscError("mnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1834
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
UNCOV
1835
        return;
×
1836
      }
1837

1838
      SEpSet  originEpset = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
876✔
1839
      SEpSet* pOrig = &originEpset;
876✔
1840
      SEp*    pOrigEp = &pOrig->eps[pOrig->inUse];
876✔
1841
      SEp*    pNewEp = &pEpSet->eps[pEpSet->inUse];
876✔
1842
      tscDebug("mnode epset updated from %d/%d=>%s:%d to %d/%d=>%s:%d in client", pOrig->inUse, pOrig->numOfEps,
876✔
1843
               pOrigEp->fqdn, pOrigEp->port, pEpSet->inUse, pEpSet->numOfEps, pNewEp->fqdn, pNewEp->port);
1844
      updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
876✔
1845
      break;
7,905,342✔
1846
    case TARGET_TYPE_VNODE: {
12,223,165✔
1847
      if (NULL == pTscObj) {
12,223,165✔
UNCOV
1848
        tscError("vnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1849
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1850
        return;
×
1851
      }
1852

1853
      SCatalog* pCatalog = NULL;
12,223,165✔
1854
      int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
12,223,165✔
1855
      if (code != TSDB_CODE_SUCCESS) {
12,223,253✔
UNCOV
1856
        tscError("fail to get catalog handle, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1857
                 tstrerror(code));
UNCOV
1858
        return;
×
1859
      }
1860

1861
      code = catalogUpdateVgEpSet(pCatalog, pSendInfo->target.dbFName, pSendInfo->target.vgId, pEpSet);
12,223,253✔
1862
      if (code != TSDB_CODE_SUCCESS) {
12,224,496✔
1863
        tscError("fail to update catalog vg epset, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
193✔
1864
                 tstrerror(code));
1865
        return;
×
1866
      }
1867
      taosMemoryFreeClear(pSendInfo->target.dbFName);
12,224,303✔
1868
      break;
12,224,155✔
1869
    }
1870
    default:
208,536✔
1871
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
208,536✔
1872
      break;
208,920✔
1873
  }
1874
}
1875

1876
int32_t doProcessMsgFromServerImpl(SRpcMsg* pMsg, SEpSet* pEpSet) {
1,030,738,167✔
1877
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
1,030,738,167✔
1878
  if (pMsg->info.ahandle == NULL) {
1,030,738,167✔
1879
    tscError("doProcessMsgFromServer pMsg->info.ahandle == NULL");
698,495✔
1880
    rpcFreeCont(pMsg->pCont);
698,495✔
1881
    taosMemoryFree(pEpSet);
698,495✔
1882
    return TSDB_CODE_TSC_INTERNAL_ERROR;
698,495✔
1883
  }
1884

1885
  STscObj* pTscObj = NULL;
1,030,039,196✔
1886

1887
  STraceId* trace = &pMsg->info.traceId;
1,030,039,196✔
1888
  char      tbuf[40] = {0};
1,030,040,632✔
1889
  TRACE_TO_STR(trace, tbuf);
1,030,041,306✔
1890

1891
  tscDebug("QID:%s, process message from server, handle:%p, message:%s, size:%d, code:%s", tbuf, pMsg->info.handle,
1,030,040,820✔
1892
           TMSG_INFO(pMsg->msgType), pMsg->contLen, tstrerror(pMsg->code));
1893

1894
  if (pSendInfo->requestObjRefId != 0) {
1,030,042,169✔
1895
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
884,047,657✔
1896
    if (pRequest) {
884,043,854✔
1897
      if (pRequest->self != pSendInfo->requestObjRefId) {
883,701,828✔
UNCOV
1898
        tscError("doProcessMsgFromServer req:0x%" PRId64 " != pSendInfo->requestObjRefId:0x%" PRId64, pRequest->self,
×
1899
                 pSendInfo->requestObjRefId);
1900

UNCOV
1901
        if (TSDB_CODE_SUCCESS != taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId)) {
×
UNCOV
1902
          tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1903
        }
UNCOV
1904
        rpcFreeCont(pMsg->pCont);
×
UNCOV
1905
        taosMemoryFree(pEpSet);
×
UNCOV
1906
        destroySendMsgInfo(pSendInfo);
×
UNCOV
1907
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1908
      }
1909
      pTscObj = pRequest->pTscObj;
883,700,196✔
1910
    }
1911
  }
1912

1913
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
1,030,036,827✔
1914

1915
  SDataBuf buf = {.msgType = pMsg->msgType,
1,030,034,078✔
1916
                  .len = pMsg->contLen,
1,030,035,807✔
1917
                  .pData = NULL,
1918
                  .handle = pMsg->info.handle,
1,030,037,827✔
1919
                  .handleRefId = pMsg->info.refId,
1,030,035,725✔
1920
                  .pEpSet = pEpSet};
1921

1922
  if (pMsg->contLen > 0) {
1,030,039,090✔
1923
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
1,005,714,090✔
1924
    if (buf.pData == NULL) {
1,005,710,685✔
UNCOV
1925
      pMsg->code = terrno;
×
1926
    } else {
1927
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
1,005,710,685✔
1928
    }
1929
  }
1930

1931
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
1,030,039,757✔
1932

1933
  if (pTscObj) {
1,030,022,359✔
1934
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
883,689,198✔
1935
    if (TSDB_CODE_SUCCESS != code) {
883,702,314✔
1936
      tscError("doProcessMsgFromServer taosReleaseRef failed");
1,541✔
1937
      terrno = code;
1,541✔
1938
      pMsg->code = code;
1,541✔
1939
    }
1940
  }
1941

1942
  rpcFreeCont(pMsg->pCont);
1,030,035,475✔
1943
  destroySendMsgInfo(pSendInfo);
1,030,022,363✔
1944
  return TSDB_CODE_SUCCESS;
1,030,018,489✔
1945
}
1946

1947
int32_t doProcessMsgFromServer(void* param) {
1,030,736,713✔
1948
  AsyncArg* arg = (AsyncArg*)param;
1,030,736,713✔
1949
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
1,030,736,713✔
1950
  taosMemoryFree(arg);
1,030,711,146✔
1951
  return code;
1,030,720,289✔
1952
}
1953

1954
void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,030,723,383✔
1955
  int32_t code = 0;
1,030,723,383✔
1956
  SEpSet* tEpSet = NULL;
1,030,723,383✔
1957

1958
  tscDebug("msg callback, ahandle %p", pMsg->info.ahandle);
1,030,723,383✔
1959

1960
  if (pEpSet != NULL) {
1,030,732,901✔
1961
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
12,432,061✔
1962
    if (NULL == tEpSet) {
12,431,400✔
UNCOV
1963
      code = terrno;
×
UNCOV
1964
      pMsg->code = terrno;
×
UNCOV
1965
      goto _exit;
×
1966
    }
1967
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
12,431,400✔
1968
  }
1969

1970
  // pMsg is response msg
1971
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
1,030,732,240✔
1972
    // restore origin code
1973
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
3,519,087✔
UNCOV
1974
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1975
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
3,519,087✔
UNCOV
1976
      pMsg->code = TSDB_CODE_RPC_BROKEN_LINK;
×
1977
    }
1978
  } else {
1979
    // uniform to one error code: TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED
1980
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
1,027,210,972✔
1981
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
1982
    }
1983
  }
1984

1985
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
1,030,733,058✔
1986
  if (NULL == arg) {
1,030,723,362✔
UNCOV
1987
    code = terrno;
×
UNCOV
1988
    pMsg->code = code;
×
UNCOV
1989
    goto _exit;
×
1990
  }
1991

1992
  arg->msg = *pMsg;
1,030,723,362✔
1993
  arg->pEpset = tEpSet;
1,030,727,487✔
1994

1995
  if ((code = taosAsyncExec(doProcessMsgFromServer, arg, NULL)) != 0) {
1,030,730,326✔
1996
    pMsg->code = code;
589✔
1997
    taosMemoryFree(arg);
589✔
1998
    goto _exit;
×
1999
  }
2000
  return;
1,030,732,653✔
2001

UNCOV
2002
_exit:
×
UNCOV
2003
  tscError("failed to sched msg to tsc since %s", tstrerror(code));
×
2004
  code = doProcessMsgFromServerImpl(pMsg, tEpSet);
×
2005
  if (code != 0) {
×
2006
    tscError("failed to sched msg to tsc, tsc ready quit");
×
2007
  }
2008
}
2009

2010

2011

NEW
2012
TAOS *taos_connect_totp(const char *ip, const char *user, const char *pass, const char* totp, const char *db, uint16_t port) {
×
NEW
2013
  tscInfo("try to connect to %s:%u by totp, user:%s db:%s", ip, port, user, db);
×
NEW
2014
  if (user == NULL) {
×
NEW
2015
    user = TSDB_DEFAULT_USER;
×
2016
  }
2017

NEW
2018
  if (pass == NULL) {
×
NEW
2019
    pass = TSDB_DEFAULT_PASS;
×
2020
  }
2021

NEW
2022
  STscObj *pObj = NULL;
×
NEW
2023
  int32_t  code = taos_connect_internal(ip, user, pass, NULL, totp, db, port, CONN_TYPE__QUERY, &pObj);
×
NEW
2024
  if (TSDB_CODE_SUCCESS == code) {
×
NEW
2025
    int64_t *rid = taosMemoryCalloc(1, sizeof(int64_t));
×
NEW
2026
    if (NULL == rid) {
×
NEW
2027
      tscError("out of memory when taos connect to %s:%u, user:%s db:%s", ip, port, user, db);
×
NEW
2028
      return NULL;
×
2029
    }
NEW
2030
    *rid = pObj->id;
×
NEW
2031
    return (TAOS *)rid;
×
2032
  } else {
NEW
2033
    terrno = code;
×
2034
  }
2035

NEW
2036
  return NULL;
×
2037
}
2038

2039

NEW
2040
int taos_connect_test(const char *ip, const char *user, const char *pass, const char* totp, const char *db, uint16_t port) {
×
NEW
2041
  tscInfo("try to connect to %s:%u by totp, user:%s db:%s", ip, port, user, db);
×
NEW
2042
  if (user == NULL) {
×
NEW
2043
    user = TSDB_DEFAULT_USER;
×
2044
  }
2045

NEW
2046
  if (pass == NULL) {
×
NEW
2047
    pass = TSDB_DEFAULT_PASS;
×
2048
  }
2049

NEW
2050
  STscObj *pObj = NULL;
×
NEW
2051
  return taos_connect_internal(ip, user, pass, NULL, totp, db, port, CONN_TYPE__AUTH_TEST, &pObj);
×
2052
}
2053

2054

NEW
2055
TAOS *taos_connect_token(const char *ip, const char *token, const char *db, uint16_t port) {
×
NEW
2056
  return NULL;
×
2057
}
2058

2059

2060
TAOS* taos_connect_auth(const char* ip, const char* user, const char* auth, const char* db, uint16_t port) {
614✔
2061
  tscInfo("try to connect to %s:%u by auth, user:%s db:%s", ip, port, user, db);
614✔
2062
  if (user == NULL) {
614✔
UNCOV
2063
    user = TSDB_DEFAULT_USER;
×
2064
  }
2065

2066
  if (auth == NULL) {
614✔
UNCOV
2067
    tscError("No auth info is given, failed to connect to server");
×
UNCOV
2068
    return NULL;
×
2069
  }
2070

2071
  STscObj* pObj = NULL;
614✔
2072
  int32_t  code = taos_connect_internal(ip, user, NULL, auth, NULL, db, port, CONN_TYPE__QUERY, &pObj);
614✔
2073
  if (TSDB_CODE_SUCCESS == code) {
614✔
UNCOV
2074
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
×
UNCOV
2075
    if (NULL == rid) {
×
UNCOV
2076
      tscError("out of memory when taos connect to %s:%u, user:%s db:%s", ip, port, user, db);
×
2077
    }
UNCOV
2078
    *rid = pObj->id;
×
2079
    return (TAOS*)rid;
×
2080
  }
2081

2082
  return NULL;
614✔
2083
}
2084

2085
// TAOS* taos_connect_l(const char* ip, int ipLen, const char* user, int userLen, const char* pass, int passLen,
2086
//                      const char* db, int dbLen, uint16_t port) {
2087
//   char ipStr[TSDB_EP_LEN] = {0};
2088
//   char dbStr[TSDB_DB_NAME_LEN] = {0};
2089
//   char userStr[TSDB_USER_LEN] = {0};
2090
//   char passStr[TSDB_PASSWORD_LEN] = {0};
2091
//
2092
//   tstrncpy(ipStr, ip, TMIN(TSDB_EP_LEN - 1, ipLen));
2093
//   tstrncpy(userStr, user, TMIN(TSDB_USER_LEN - 1, userLen));
2094
//   tstrncpy(passStr, pass, TMIN(TSDB_PASSWORD_LEN - 1, passLen));
2095
//   tstrncpy(dbStr, db, TMIN(TSDB_DB_NAME_LEN - 1, dbLen));
2096
//   return taos_connect(ipStr, userStr, passStr, dbStr, port);
2097
// }
2098

2099
void doSetOneRowPtr(SReqResultInfo* pResultInfo) {
2,147,483,647✔
2100
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
2,147,483,647✔
2101
    SResultColumn* pCol = &pResultInfo->pCol[i];
2,147,483,647✔
2102

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

2106
    if (IS_VAR_DATA_TYPE(type)) {
2,147,483,647✔
2107
      if (!IS_VAR_NULL_TYPE(type, schemaBytes) && pCol->offset[pResultInfo->current] != -1) {
2,147,483,647✔
2108
        char* pStart = pResultInfo->pCol[i].offset[pResultInfo->current] + pResultInfo->pCol[i].pData;
1,998,535,825✔
2109

2110
        if (IS_STR_DATA_BLOB(type)) {
1,998,792,581✔
2111
          pResultInfo->length[i] = blobDataLen(pStart);
38,281✔
2112
          pResultInfo->row[i] = blobDataVal(pStart);
27✔
2113
        } else {
2114
          pResultInfo->length[i] = varDataLen(pStart);
1,998,755,675✔
2115
          pResultInfo->row[i] = varDataVal(pStart);
1,998,787,781✔
2116
        }
2117
      } else {
2118
        pResultInfo->row[i] = NULL;
165,836,221✔
2119
        pResultInfo->length[i] = 0;
165,680,884✔
2120
      }
2121
    } else {
2122
      if (!colDataIsNull_f(pCol, pResultInfo->current)) {
2,147,483,647✔
2123
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + schemaBytes * pResultInfo->current;
2,147,483,647✔
2124
        pResultInfo->length[i] = schemaBytes;
2,147,483,647✔
2125
      } else {
2126
        pResultInfo->row[i] = NULL;
565,797,348✔
2127
        pResultInfo->length[i] = 0;
566,808,408✔
2128
      }
2129
    }
2130
  }
2131
}
2,147,483,647✔
2132

UNCOV
2133
void* doFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
×
2134
  if (pRequest == NULL) {
×
2135
    return NULL;
×
2136
  }
2137

UNCOV
2138
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
×
UNCOV
2139
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
×
2140
    // All data has returned to App already, no need to try again
UNCOV
2141
    if (pResultInfo->completed) {
×
UNCOV
2142
      pResultInfo->numOfRows = 0;
×
2143
      return NULL;
×
2144
    }
2145

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

UNCOV
2149
    pRequest->code = schedulerFetchRows(pRequest->body.queryJob, &req);
×
UNCOV
2150
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
UNCOV
2151
      pResultInfo->numOfRows = 0;
×
UNCOV
2152
      return NULL;
×
2153
    }
2154

UNCOV
2155
    pRequest->code = setQueryResultFromRsp(&pRequest->body.resInfo, (const SRetrieveTableRsp*)pResInfo->pData,
×
UNCOV
2156
                                           convertUcs4, pRequest->stmtBindVersion > 0);
×
UNCOV
2157
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
UNCOV
2158
      pResultInfo->numOfRows = 0;
×
UNCOV
2159
      return NULL;
×
2160
    }
2161

UNCOV
2162
    tscDebug("req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64
×
2163
             ", complete:%d, QID:0x%" PRIx64,
2164
             pRequest->self, pResInfo->numOfRows, pResInfo->totalRows, pResInfo->completed, pRequest->requestId);
2165

UNCOV
2166
    STscObj*            pTscObj = pRequest->pTscObj;
×
UNCOV
2167
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
×
UNCOV
2168
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
×
2169

UNCOV
2170
    if (pResultInfo->numOfRows == 0) {
×
UNCOV
2171
      return NULL;
×
2172
    }
2173
  }
2174

UNCOV
2175
  if (setupOneRowPtr) {
×
UNCOV
2176
    doSetOneRowPtr(pResultInfo);
×
UNCOV
2177
    pResultInfo->current += 1;
×
2178
  }
2179

UNCOV
2180
  return pResultInfo->row;
×
2181
}
2182

2183
static void syncFetchFn(void* param, TAOS_RES* res, int32_t numOfRows) {
95,730,683✔
2184
  tsem_t* sem = param;
95,730,683✔
2185
  if (TSDB_CODE_SUCCESS != tsem_post(sem)) {
95,730,683✔
UNCOV
2186
    tscError("failed to post sem, code:%s", terrstr());
×
2187
  }
2188
}
95,730,927✔
2189

2190
void* doAsyncFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
1,613,765,762✔
2191
  if (pRequest == NULL) {
1,613,765,762✔
UNCOV
2192
    return NULL;
×
2193
  }
2194

2195
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
1,613,765,762✔
2196
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
1,613,810,983✔
2197
    // All data has returned to App already, no need to try again
2198
    if (pResultInfo->completed) {
168,520,705✔
2199
      pResultInfo->numOfRows = 0;
72,813,035✔
2200
      return NULL;
72,813,303✔
2201
    }
2202

2203
    // convert ucs4 to native multi-bytes string
2204
    pResultInfo->convertUcs4 = convertUcs4;
95,730,158✔
2205
    tsem_t sem;
87,435,659✔
2206
    if (TSDB_CODE_SUCCESS != tsem_init(&sem, 0, 0)) {
95,729,389✔
UNCOV
2207
      tscError("failed to init sem, code:%s", terrstr());
×
2208
    }
2209
    taos_fetch_rows_a(pRequest, syncFetchFn, &sem);
95,729,153✔
2210
    if (TSDB_CODE_SUCCESS != tsem_wait(&sem)) {
95,730,927✔
UNCOV
2211
      tscError("failed to wait sem, code:%s", terrstr());
×
2212
    }
2213
    if (TSDB_CODE_SUCCESS != tsem_destroy(&sem)) {
95,730,096✔
2214
      tscError("failed to destroy sem, code:%s", terrstr());
×
2215
    }
2216
    pRequest->inCallback = false;
95,730,927✔
2217
  }
2218

2219
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
1,541,051,327✔
2220
    return NULL;
6,865,970✔
2221
  } else {
2222
    if (setupOneRowPtr) {
1,534,180,061✔
2223
      doSetOneRowPtr(pResultInfo);
1,447,369,108✔
2224
      pResultInfo->current += 1;
1,447,372,447✔
2225
    }
2226

2227
    return pResultInfo->row;
1,534,181,416✔
2228
  }
2229
}
2230

2231
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
126,466,490✔
2232
  if (pResInfo->row == NULL) {
126,466,490✔
2233
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
108,590,045✔
2234
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
108,590,196✔
2235
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
108,589,816✔
2236
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
108,590,196✔
2237

2238
    if (pResInfo->row == NULL || pResInfo->pCol == NULL || pResInfo->length == NULL || pResInfo->convertBuf == NULL) {
108,589,794✔
2239
      taosMemoryFree(pResInfo->row);
290✔
UNCOV
2240
      taosMemoryFree(pResInfo->pCol);
×
UNCOV
2241
      taosMemoryFree(pResInfo->length);
×
2242
      taosMemoryFree(pResInfo->convertBuf);
×
2243
      return terrno;
×
2244
    }
2245
  }
2246

2247
  return TSDB_CODE_SUCCESS;
126,467,664✔
2248
}
2249

2250
static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength, bool isStmt) {
125,259,771✔
2251
  int32_t idx = -1;
125,259,771✔
2252
  iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt);
125,259,838✔
2253
  if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR;
125,257,406✔
2254

2255
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
699,745,648✔
2256
    int32_t type = pResultInfo->fields[i].type;
574,489,773✔
2257
    int32_t schemaBytes =
2258
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
574,490,795✔
2259

2260
    if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) {
574,489,962✔
2261
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
20,649,301✔
2262
      if (p == NULL) {
20,649,301✔
UNCOV
2263
        taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
×
UNCOV
2264
        return terrno;
×
2265
      }
2266

2267
      pResultInfo->convertBuf[i] = p;
20,649,301✔
2268

2269
      SResultColumn* pCol = &pResultInfo->pCol[i];
20,649,301✔
2270
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
2,147,483,647✔
2271
        if (pCol->offset[j] != -1) {
2,147,483,647✔
2272
          char* pStart = pCol->offset[j] + pCol->pData;
2,147,483,647✔
2273

2274
          int32_t len = taosUcs4ToMbsEx((TdUcs4*)varDataVal(pStart), varDataLen(pStart), varDataVal(p), conv);
2,147,483,647✔
2275
          if (len < 0 || len > schemaBytes || (p + len) >= (pResultInfo->convertBuf[i] + colLength[i])) {
2,147,483,647✔
2276
            tscError(
1,095✔
2277
                "doConvertUCS4 error, invalid data. len:%d, bytes:%d, (p + len):%p, (pResultInfo->convertBuf[i] + "
2278
                "colLength[i]):%p",
2279
                len, schemaBytes, (p + len), (pResultInfo->convertBuf[i] + colLength[i]));
2280
            taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
1,095✔
2281
            return TSDB_CODE_TSC_INTERNAL_ERROR;
325✔
2282
          }
2283

2284
          varDataSetLen(p, len);
2,147,483,647✔
2285
          pCol->offset[j] = (p - pResultInfo->convertBuf[i]);
2,147,483,647✔
2286
          p += (len + VARSTR_HEADER_SIZE);
2,147,483,647✔
2287
        }
2288
      }
2289

2290
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
20,648,976✔
2291
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
20,648,976✔
2292
    }
2293
  }
2294
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
125,258,186✔
2295
  return TSDB_CODE_SUCCESS;
125,258,224✔
2296
}
2297

2298
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
125,258,829✔
2299
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
699,744,004✔
2300
    TAOS_FIELD_E* pFieldE = pResultInfo->fields + i;
574,488,647✔
2301
    TAOS_FIELD*   pField = pResultInfo->userFields + i;
574,488,127✔
2302
    int32_t       type = pFieldE->type;
574,487,296✔
2303
    int32_t       bufLen = 0;
574,488,829✔
2304
    char*         p = NULL;
574,488,829✔
2305
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
574,488,829✔
2306
      continue;
572,473,039✔
2307
    } else {
2308
      bufLen = 64;
2,014,840✔
2309
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
2,014,840✔
2310
      pFieldE->bytes = bufLen;
2,014,840✔
2311
      pField->bytes = bufLen;
2,014,840✔
2312
    }
2313
    if (!p) return terrno;
2,014,840✔
2314
    pResultInfo->convertBuf[i] = p;
2,014,840✔
2315

2316
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
1,509,324,469✔
2317
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
1,507,309,629✔
2318
                                  pFieldE->precision, pFieldE->scale, p, bufLen);
1,507,309,629✔
2319
      p += bufLen;
1,507,309,629✔
2320
      if (TSDB_CODE_SUCCESS != code) {
1,507,309,629✔
UNCOV
2321
        return code;
×
2322
      }
2323
    }
2324
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
2,014,840✔
2325
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
2,014,840✔
2326
  }
2327
  return 0;
125,256,885✔
2328
}
2329

2330
int32_t getVersion1BlockMetaSize(const char* p, int32_t numOfCols) {
382,934✔
2331
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) * 3 + sizeof(uint64_t) +
765,868✔
2332
         numOfCols * (sizeof(int8_t) + sizeof(int32_t));
382,934✔
2333
}
2334

2335
static int32_t estimateJsonLen(SReqResultInfo* pResultInfo) {
191,467✔
2336
  char*   p = (char*)pResultInfo->pData;
191,467✔
2337
  int32_t blockVersion = *(int32_t*)p;
191,467✔
2338

2339
  int32_t numOfRows = pResultInfo->numOfRows;
191,467✔
2340
  int32_t numOfCols = pResultInfo->numOfCols;
191,467✔
2341

2342
  // | version | total length | total rows | total columns | flag seg| block group id | column schema | each column
2343
  // length |
2344
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
191,467✔
2345
  if (numOfCols != cols) {
191,467✔
UNCOV
2346
    tscError("estimateJsonLen error: numOfCols:%d != cols:%d", numOfCols, cols);
×
UNCOV
2347
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2348
  }
2349

2350
  int32_t  len = getVersion1BlockMetaSize(p, numOfCols);
191,467✔
2351
  int32_t* colLength = (int32_t*)(p + len);
191,467✔
2352
  len += sizeof(int32_t) * numOfCols;
191,467✔
2353

2354
  char* pStart = p + len;
191,467✔
2355
  for (int32_t i = 0; i < numOfCols; ++i) {
832,416✔
2356
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
640,949✔
2357

2358
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
640,949✔
2359
      int32_t* offset = (int32_t*)pStart;
226,922✔
2360
      int32_t  lenTmp = numOfRows * sizeof(int32_t);
226,922✔
2361
      len += lenTmp;
226,922✔
2362
      pStart += lenTmp;
226,922✔
2363

2364
      int32_t estimateColLen = 0;
226,922✔
2365
      for (int32_t j = 0; j < numOfRows; ++j) {
1,187,487✔
2366
        if (offset[j] == -1) {
960,565✔
2367
          continue;
48,186✔
2368
        }
2369
        char* data = offset[j] + pStart;
912,379✔
2370

2371
        int32_t jsonInnerType = *data;
912,379✔
2372
        char*   jsonInnerData = data + CHAR_BYTES;
912,379✔
2373
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
912,379✔
2374
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
12,792✔
2375
        } else if (tTagIsJson(data)) {
899,587✔
2376
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
211,186✔
2377
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
688,401✔
2378
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
640,431✔
2379
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
47,970✔
2380
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
35,178✔
2381
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
12,792✔
2382
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
12,792✔
UNCOV
2383
        } else if (IS_STR_DATA_BLOB(jsonInnerType)) {
×
UNCOV
2384
          estimateColLen += (BLOBSTR_HEADER_SIZE + 32);
×
2385
        } else {
UNCOV
2386
          tscError("estimateJsonLen error: invalid type:%d", jsonInnerType);
×
UNCOV
2387
          return -1;
×
2388
        }
2389
      }
2390
      len += TMAX(colLen, estimateColLen);
226,922✔
2391
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
414,027✔
2392
      int32_t lenTmp = numOfRows * sizeof(int32_t);
53,300✔
2393
      len += (lenTmp + colLen);
53,300✔
2394
      pStart += lenTmp;
53,300✔
2395
    } else {
2396
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
360,727✔
2397
      len += (lenTmp + colLen);
360,727✔
2398
      pStart += lenTmp;
360,727✔
2399
    }
2400
    pStart += colLen;
640,949✔
2401
  }
2402

2403
  // Ensure the complete structure of the block, including the blankfill field,
2404
  // even though it is not used on the client side.
2405
  len += sizeof(bool);
191,467✔
2406
  return len;
191,467✔
2407
}
2408

2409
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
126,466,533✔
2410
  int32_t numOfRows = pResultInfo->numOfRows;
126,466,533✔
2411
  int32_t numOfCols = pResultInfo->numOfCols;
126,466,533✔
2412
  bool    needConvert = false;
126,468,804✔
2413
  for (int32_t i = 0; i < numOfCols; ++i) {
707,902,811✔
2414
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
581,626,442✔
2415
      needConvert = true;
191,467✔
2416
      break;
191,467✔
2417
    }
2418
  }
2419

2420
  if (!needConvert) {
126,467,836✔
2421
    return TSDB_CODE_SUCCESS;
126,276,369✔
2422
  }
2423

2424
  tscDebug("start to convert form json format string");
191,467✔
2425

2426
  char*   p = (char*)pResultInfo->pData;
191,467✔
2427
  int32_t blockVersion = *(int32_t*)p;
191,467✔
2428
  int32_t dataLen = estimateJsonLen(pResultInfo);
191,467✔
2429
  if (dataLen <= 0) {
191,467✔
UNCOV
2430
    tscError("doConvertJson error: estimateJsonLen failed");
×
UNCOV
2431
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2432
  }
2433

2434
  taosMemoryFreeClear(pResultInfo->convertJson);
191,467✔
2435
  pResultInfo->convertJson = taosMemoryCalloc(1, dataLen);
191,467✔
2436
  if (pResultInfo->convertJson == NULL) return terrno;
191,467✔
2437
  char* p1 = pResultInfo->convertJson;
191,467✔
2438

2439
  int32_t totalLen = 0;
191,467✔
2440
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
191,467✔
2441
  if (numOfCols != cols) {
191,467✔
UNCOV
2442
    tscError("doConvertJson error: numOfCols:%d != cols:%d", numOfCols, cols);
×
UNCOV
2443
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2444
  }
2445

2446
  int32_t len = getVersion1BlockMetaSize(p, numOfCols);
191,467✔
2447
  (void)memcpy(p1, p, len);
191,467✔
2448

2449
  p += len;
191,467✔
2450
  p1 += len;
191,467✔
2451
  totalLen += len;
191,467✔
2452

2453
  len = sizeof(int32_t) * numOfCols;
191,467✔
2454
  int32_t* colLength = (int32_t*)p;
191,467✔
2455
  int32_t* colLength1 = (int32_t*)p1;
191,467✔
2456
  (void)memcpy(p1, p, len);
191,467✔
2457
  p += len;
191,467✔
2458
  p1 += len;
191,467✔
2459
  totalLen += len;
191,467✔
2460

2461
  char* pStart = p;
191,467✔
2462
  char* pStart1 = p1;
191,467✔
2463
  for (int32_t i = 0; i < numOfCols; ++i) {
832,416✔
2464
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
640,949✔
2465
    int32_t colLen1 = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength1[i]) : colLength1[i];
640,949✔
2466
    if (colLen >= dataLen) {
640,949✔
UNCOV
2467
      tscError("doConvertJson error: colLen:%d >= dataLen:%d", colLen, dataLen);
×
UNCOV
2468
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2469
    }
2470
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
640,949✔
2471
      int32_t* offset = (int32_t*)pStart;
226,922✔
2472
      int32_t* offset1 = (int32_t*)pStart1;
226,922✔
2473
      len = numOfRows * sizeof(int32_t);
226,922✔
2474
      (void)memcpy(pStart1, pStart, len);
226,922✔
2475
      pStart += len;
226,922✔
2476
      pStart1 += len;
226,922✔
2477
      totalLen += len;
226,922✔
2478

2479
      len = 0;
226,922✔
2480
      for (int32_t j = 0; j < numOfRows; ++j) {
1,187,487✔
2481
        if (offset[j] == -1) {
960,565✔
2482
          continue;
48,186✔
2483
        }
2484
        char* data = offset[j] + pStart;
912,379✔
2485

2486
        int32_t jsonInnerType = *data;
912,379✔
2487
        char*   jsonInnerData = data + CHAR_BYTES;
912,379✔
2488
        char    dst[TSDB_MAX_JSON_TAG_LEN] = {0};
912,379✔
2489
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
912,379✔
2490
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s", TSDB_DATA_NULL_STR_L);
12,792✔
2491
          varDataSetLen(dst, strlen(varDataVal(dst)));
12,792✔
2492
        } else if (tTagIsJson(data)) {
899,587✔
2493
          char* jsonString = NULL;
211,186✔
2494
          parseTagDatatoJson(data, &jsonString, pResultInfo->charsetCxt);
211,186✔
2495
          if (jsonString == NULL) {
211,186✔
UNCOV
2496
            tscError("doConvertJson error: parseTagDatatoJson failed");
×
2497
            return terrno;
×
2498
          }
2499
          STR_TO_VARSTR(dst, jsonString);
211,186✔
2500
          taosMemoryFree(jsonString);
211,186✔
2501
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
688,401✔
2502
          *(char*)varDataVal(dst) = '\"';
640,431✔
2503
          char    tmp[TSDB_MAX_JSON_TAG_LEN] = {0};
640,431✔
2504
          int32_t length = taosUcs4ToMbs((TdUcs4*)varDataVal(jsonInnerData), varDataLen(jsonInnerData),
640,431✔
2505
                                         varDataVal(tmp), pResultInfo->charsetCxt);
2506
          if (length <= 0) {
640,431✔
2507
            tscError("charset:%s to %s. convert failed.", DEFAULT_UNICODE_ENCODEC,
533✔
2508
                     pResultInfo->charsetCxt != NULL ? ((SConvInfo*)(pResultInfo->charsetCxt))->charset : tsCharset);
2509
            length = 0;
533✔
2510
          }
2511
          int32_t escapeLength = escapeToPrinted(varDataVal(dst) + CHAR_BYTES, TSDB_MAX_JSON_TAG_LEN - CHAR_BYTES * 2,varDataVal(tmp), length);
640,431✔
2512
          varDataSetLen(dst, escapeLength + CHAR_BYTES * 2);
640,431✔
2513
          *(char*)POINTER_SHIFT(varDataVal(dst), escapeLength + CHAR_BYTES) = '\"';
640,431✔
2514
          tscError("value:%s.", varDataVal(dst));
640,431✔
2515
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
47,970✔
2516
          double jsonVd = *(double*)(jsonInnerData);
35,178✔
2517
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%.9lf", jsonVd);
35,178✔
2518
          varDataSetLen(dst, strlen(varDataVal(dst)));
35,178✔
2519
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
12,792✔
2520
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s",
12,792✔
2521
                         (*((char*)jsonInnerData) == 1) ? "true" : "false");
12,792✔
2522
          varDataSetLen(dst, strlen(varDataVal(dst)));
12,792✔
2523
        } else {
UNCOV
2524
          tscError("doConvertJson error: invalid type:%d", jsonInnerType);
×
UNCOV
2525
          return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2526
        }
2527

2528
        offset1[j] = len;
912,379✔
2529
        (void)memcpy(pStart1 + len, dst, varDataTLen(dst));
912,379✔
2530
        len += varDataTLen(dst);
912,379✔
2531
      }
2532
      colLen1 = len;
226,922✔
2533
      totalLen += colLen1;
226,922✔
2534
      colLength1[i] = (blockVersion == BLOCK_VERSION_1) ? htonl(len) : len;
226,922✔
2535
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
414,027✔
2536
      len = numOfRows * sizeof(int32_t);
53,300✔
2537
      (void)memcpy(pStart1, pStart, len);
53,300✔
2538
      pStart += len;
53,300✔
2539
      pStart1 += len;
53,300✔
2540
      totalLen += len;
53,300✔
2541
      totalLen += colLen;
53,300✔
2542
      (void)memcpy(pStart1, pStart, colLen);
53,300✔
2543
    } else {
2544
      len = BitmapLen(pResultInfo->numOfRows);
360,727✔
2545
      (void)memcpy(pStart1, pStart, len);
360,727✔
2546
      pStart += len;
360,727✔
2547
      pStart1 += len;
360,727✔
2548
      totalLen += len;
360,727✔
2549
      totalLen += colLen;
360,727✔
2550
      (void)memcpy(pStart1, pStart, colLen);
360,727✔
2551
    }
2552
    pStart += colLen;
640,949✔
2553
    pStart1 += colLen1;
640,949✔
2554
  }
2555

2556
  // Ensure the complete structure of the block, including the blankfill field,
2557
  // even though it is not used on the client side.
2558
  // (void)memcpy(pStart1, pStart, sizeof(bool));
2559
  totalLen += sizeof(bool);
191,467✔
2560

2561
  *(int32_t*)(pResultInfo->convertJson + 4) = totalLen;
191,467✔
2562
  pResultInfo->pData = pResultInfo->convertJson;
191,467✔
2563
  return TSDB_CODE_SUCCESS;
191,467✔
2564
}
2565

2566
int32_t setResultDataPtr(SReqResultInfo* pResultInfo, bool convertUcs4, bool isStmt) {
133,634,792✔
2567
  bool convertForDecimal = convertUcs4;
133,634,792✔
2568
  if (pResultInfo == NULL || pResultInfo->numOfCols <= 0 || pResultInfo->fields == NULL) {
133,634,792✔
2569
    tscError("setResultDataPtr paras error");
1,957✔
UNCOV
2570
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2571
  }
2572

2573
  if (pResultInfo->numOfRows == 0) {
133,633,328✔
2574
    return TSDB_CODE_SUCCESS;
7,166,784✔
2575
  }
2576

2577
  if (pResultInfo->pData == NULL) {
126,467,527✔
UNCOV
2578
    tscError("setResultDataPtr error: pData is NULL");
×
UNCOV
2579
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2580
  }
2581

2582
  int32_t code = doPrepareResPtr(pResultInfo);
126,465,653✔
2583
  if (code != TSDB_CODE_SUCCESS) {
126,467,592✔
UNCOV
2584
    return code;
×
2585
  }
2586
  code = doConvertJson(pResultInfo);
126,467,592✔
2587
  if (code != TSDB_CODE_SUCCESS) {
126,467,091✔
UNCOV
2588
    return code;
×
2589
  }
2590

2591
  char* p = (char*)pResultInfo->pData;
126,467,091✔
2592

2593
  // version:
2594
  int32_t blockVersion = *(int32_t*)p;
126,467,177✔
2595
  p += sizeof(int32_t);
126,467,091✔
2596

2597
  int32_t dataLen = *(int32_t*)p;
126,467,263✔
2598
  p += sizeof(int32_t);
126,467,263✔
2599

2600
  int32_t rows = *(int32_t*)p;
126,467,593✔
2601
  p += sizeof(int32_t);
126,467,488✔
2602

2603
  int32_t cols = *(int32_t*)p;
126,467,284✔
2604
  p += sizeof(int32_t);
126,467,284✔
2605

2606
  if (rows != pResultInfo->numOfRows || cols != pResultInfo->numOfCols) {
126,467,374✔
2607
    tscError("setResultDataPtr paras error:rows;%d numOfRows:%" PRId64 " cols:%d numOfCols:%d", rows,
1,230✔
2608
             pResultInfo->numOfRows, cols, pResultInfo->numOfCols);
UNCOV
2609
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2610
  }
2611

2612
  int32_t hasColumnSeg = *(int32_t*)p;
126,466,348✔
2613
  p += sizeof(int32_t);
126,467,371✔
2614

2615
  uint64_t groupId = taosGetUInt64Aligned((uint64_t*)p);
126,466,903✔
2616
  p += sizeof(uint64_t);
126,466,903✔
2617

2618
  // check fields
2619
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
708,144,881✔
2620
    int8_t type = *(int8_t*)p;
581,678,571✔
2621
    p += sizeof(int8_t);
581,676,894✔
2622

2623
    int32_t bytes = *(int32_t*)p;
581,678,267✔
2624
    p += sizeof(int32_t);
581,677,389✔
2625

2626
    if (IS_DECIMAL_TYPE(type) && pResultInfo->fields[i].precision == 0) {
581,677,688✔
2627
      extractDecimalTypeInfoFromBytes(&bytes, &pResultInfo->fields[i].precision, &pResultInfo->fields[i].scale);
310,128✔
2628
    }
2629
  }
2630

2631
  int32_t* colLength = (int32_t*)p;
126,467,601✔
2632
  p += sizeof(int32_t) * pResultInfo->numOfCols;
126,467,601✔
2633

2634
  char* pStart = p;
126,467,764✔
2635
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
708,145,838✔
2636
    if ((pStart - pResultInfo->pData) >= dataLen) {
581,678,659✔
2637
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
UNCOV
2638
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2639
    }
2640
    if (blockVersion == BLOCK_VERSION_1) {
581,676,258✔
2641
      colLength[i] = htonl(colLength[i]);
436,259,229✔
2642
    }
2643
    if (colLength[i] >= dataLen) {
581,677,419✔
UNCOV
2644
      tscError("invalid colLength %d, dataLen %d", colLength[i], dataLen);
×
2645
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2646
    }
2647
    if (IS_INVALID_TYPE(pResultInfo->fields[i].type)) {
581,674,438✔
2648
      tscError("invalid type %d", pResultInfo->fields[i].type);
678✔
UNCOV
2649
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2650
    }
2651
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
581,678,836✔
2652
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
145,256,948✔
2653
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
145,254,998✔
2654
    } else {
2655
      pResultInfo->pCol[i].nullbitmap = pStart;
436,425,250✔
2656
      pStart += BitmapLen(pResultInfo->numOfRows);
436,426,372✔
2657
    }
2658

2659
    pResultInfo->pCol[i].pData = pStart;
581,681,148✔
2660
    pResultInfo->length[i] =
1,163,359,132✔
2661
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
1,106,841,271✔
2662
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
581,678,418✔
2663

2664
    pStart += colLength[i];
581,677,530✔
2665
  }
2666

2667
  p = pStart;
126,467,596✔
2668
  // bool blankFill = *(bool*)p;
2669
  p += sizeof(bool);
126,467,596✔
2670
  int32_t offset = p - pResultInfo->pData;
126,468,094✔
2671
  if (offset > dataLen) {
126,468,027✔
UNCOV
2672
    tscError("invalid offset %d, dataLen %d", offset, dataLen);
×
UNCOV
2673
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2674
  }
2675

2676
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
2677
  if (convertUcs4) {
126,468,027✔
2678
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
125,259,522✔
2679
  }
2680
#endif
2681
  if (TSDB_CODE_SUCCESS == code && convertForDecimal) {
126,466,366✔
2682
    code = convertDecimalType(pResultInfo);
125,258,224✔
2683
  }
2684
  return code;
126,466,313✔
2685
}
2686

2687
char* getDbOfConnection(STscObj* pObj) {
633,902,538✔
2688
  terrno = TSDB_CODE_SUCCESS;
633,902,538✔
2689
  char* p = NULL;
633,906,567✔
2690
  (void)taosThreadMutexLock(&pObj->mutex);
633,906,567✔
2691
  size_t len = strlen(pObj->db);
633,909,704✔
2692
  if (len > 0) {
633,910,194✔
2693
    p = taosStrndup(pObj->db, tListLen(pObj->db));
562,584,118✔
2694
    if (p == NULL) {
562,583,078✔
UNCOV
2695
      tscError("failed to taosStrndup db name");
×
2696
    }
2697
  }
2698

2699
  (void)taosThreadMutexUnlock(&pObj->mutex);
633,909,154✔
2700
  return p;
633,902,546✔
2701
}
2702

2703
void setConnectionDB(STscObj* pTscObj, const char* db) {
2,922,268✔
2704
  if (db == NULL || pTscObj == NULL) {
2,922,268✔
2705
    tscError("setConnectionDB para is NULL");
×
UNCOV
2706
    return;
×
2707
  }
2708

2709
  (void)taosThreadMutexLock(&pTscObj->mutex);
2,922,350✔
2710
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
2,922,607✔
2711
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
2,922,350✔
2712
}
2713

UNCOV
2714
void resetConnectDB(STscObj* pTscObj) {
×
UNCOV
2715
  if (pTscObj == NULL) {
×
2716
    return;
×
2717
  }
2718

UNCOV
2719
  (void)taosThreadMutexLock(&pTscObj->mutex);
×
UNCOV
2720
  pTscObj->db[0] = 0;
×
UNCOV
2721
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
×
2722
}
2723

2724
int32_t setQueryResultFromRsp(SReqResultInfo* pResultInfo, const SRetrieveTableRsp* pRsp, bool convertUcs4,
101,311,755✔
2725
                              bool isStmt) {
2726
  if (pResultInfo == NULL || pRsp == NULL) {
101,311,755✔
2727
    tscError("setQueryResultFromRsp paras is null");
488✔
UNCOV
2728
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2729
  }
2730

2731
  taosMemoryFreeClear(pResultInfo->pRspMsg);
101,311,267✔
2732
  pResultInfo->pRspMsg = (const char*)pRsp;
101,310,774✔
2733
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
101,311,518✔
2734
  pResultInfo->current = 0;
101,311,511✔
2735
  pResultInfo->completed = (pRsp->completed == 1);
101,311,511✔
2736
  pResultInfo->precision = pRsp->precision;
101,311,511✔
2737

2738
  // decompress data if needed
2739
  int32_t payloadLen = htonl(pRsp->payloadLen);
101,311,042✔
2740

2741
  if (pRsp->compressed) {
101,311,511✔
UNCOV
2742
    if (pResultInfo->decompBuf == NULL) {
×
UNCOV
2743
      pResultInfo->decompBuf = taosMemoryMalloc(payloadLen);
×
UNCOV
2744
      if (pResultInfo->decompBuf == NULL) {
×
UNCOV
2745
        tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
UNCOV
2746
        return terrno;
×
2747
      }
UNCOV
2748
      pResultInfo->decompBufSize = payloadLen;
×
2749
    } else {
UNCOV
2750
      if (pResultInfo->decompBufSize < payloadLen) {
×
UNCOV
2751
        char* p = taosMemoryRealloc(pResultInfo->decompBuf, payloadLen);
×
UNCOV
2752
        if (p == NULL) {
×
UNCOV
2753
          tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
UNCOV
2754
          return terrno;
×
2755
        }
2756

UNCOV
2757
        pResultInfo->decompBuf = p;
×
UNCOV
2758
        pResultInfo->decompBufSize = payloadLen;
×
2759
      }
2760
    }
2761
  }
2762

2763
  if (payloadLen > 0) {
101,310,781✔
2764
    int32_t compLen = *(int32_t*)pRsp->data;
94,145,118✔
2765
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
94,145,111✔
2766

2767
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
94,145,111✔
2768

2769
    if (pRsp->compressed && compLen < rawLen) {
94,144,867✔
UNCOV
2770
      int32_t len = tsDecompressString(pStart, compLen, 1, pResultInfo->decompBuf, rawLen, ONE_STAGE_COMP, NULL, 0);
×
UNCOV
2771
      if (len < 0) {
×
2772
        tscError("tsDecompressString failed");
×
2773
        return terrno ? terrno : TSDB_CODE_FAILED;
×
2774
      }
UNCOV
2775
      if (len != rawLen) {
×
UNCOV
2776
        tscError("tsDecompressString failed, len:%d != rawLen:%d", len, rawLen);
×
UNCOV
2777
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2778
      }
UNCOV
2779
      pResultInfo->pData = pResultInfo->decompBuf;
×
UNCOV
2780
      pResultInfo->payloadLen = rawLen;
×
2781
    } else {
2782
      pResultInfo->pData = pStart;
94,145,111✔
2783
      pResultInfo->payloadLen = htonl(pRsp->compLen);
94,145,355✔
2784
      if (pRsp->compLen != pRsp->payloadLen) {
94,145,118✔
UNCOV
2785
        tscError("pRsp->compLen:%d != pRsp->payloadLen:%d", pRsp->compLen, pRsp->payloadLen);
×
2786
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2787
      }
2788
    }
2789
  }
2790

2791
  // TODO handle the compressed case
2792
  pResultInfo->totalRows += pResultInfo->numOfRows;
101,310,537✔
2793

2794
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
101,311,511✔
2795
  return code;
101,310,332✔
2796
}
2797

2798
TSDB_SERVER_STATUS taos_check_server_status(const char* fqdn, int port, char* details, int maxlen) {
885✔
2799
  TSDB_SERVER_STATUS code = TSDB_SRV_STATUS_UNAVAILABLE;
885✔
2800
  void*              clientRpc = NULL;
885✔
2801
  SServerStatusRsp   statusRsp = {0};
885✔
2802
  SEpSet             epSet = {.inUse = 0, .numOfEps = 1};
885✔
2803
  SRpcMsg  rpcMsg = {.info.ahandle = (void*)0x9527, .info.notFreeAhandle = 1, .msgType = TDMT_DND_SERVER_STATUS};
885✔
2804
  SRpcMsg  rpcRsp = {0};
885✔
2805
  SRpcInit rpcInit = {0};
885✔
2806
  char     pass[TSDB_PASSWORD_LEN + 1] = {0};
885✔
2807

2808
  rpcInit.label = "CHK";
885✔
2809
  rpcInit.numOfThreads = 1;
885✔
2810
  rpcInit.cfp = NULL;
885✔
2811
  rpcInit.sessions = 16;
885✔
2812
  rpcInit.connType = TAOS_CONN_CLIENT;
885✔
2813
  rpcInit.idleTime = tsShellActivityTimer * 1000;
885✔
2814
  rpcInit.compressSize = tsCompressMsgSize;
885✔
2815
  rpcInit.user = "_dnd";
885✔
2816

2817
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
885✔
2818
  connLimitNum = TMAX(connLimitNum, 10);
885✔
2819
  connLimitNum = TMIN(connLimitNum, 500);
885✔
2820
  rpcInit.connLimitNum = connLimitNum;
885✔
2821
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
885✔
2822
  rpcInit.readTimeout = tsReadTimeout;
885✔
2823
  rpcInit.ipv6 = tsEnableIpv6;
885✔
2824
  rpcInit.enableSSL = tsEnableTLS;
885✔
2825

2826
  memcpy(rpcInit.caPath, tsTLSCaPath, strlen(tsTLSCaPath));
885✔
2827
  memcpy(rpcInit.certPath, tsTLSSvrCertPath, strlen(tsTLSSvrCertPath));
885✔
2828
  memcpy(rpcInit.keyPath, tsTLSSvrKeyPath, strlen(tsTLSSvrKeyPath));
885✔
2829
  memcpy(rpcInit.cliCertPath, tsTLSCliCertPath, strlen(tsTLSCliCertPath));
885✔
2830
  memcpy(rpcInit.cliKeyPath, tsTLSCliKeyPath, strlen(tsTLSCliKeyPath));
885✔
2831

2832
  if (TSDB_CODE_SUCCESS != taosVersionStrToInt(td_version, &rpcInit.compatibilityVer)) {
885✔
UNCOV
2833
    tscError("faild to convert taos version from str to int, errcode:%s", terrstr());
×
UNCOV
2834
    goto _OVER;
×
2835
  }
2836

2837
  clientRpc = rpcOpen(&rpcInit);
885✔
2838
  if (clientRpc == NULL) {
885✔
2839
    code = terrno;
×
2840
    tscError("failed to init server status client since %s", tstrerror(code));
×
UNCOV
2841
    goto _OVER;
×
2842
  }
2843

2844
  if (fqdn == NULL) {
885✔
2845
    fqdn = tsLocalFqdn;
885✔
2846
  }
2847

2848
  if (port == 0) {
885✔
2849
    port = tsServerPort;
885✔
2850
  }
2851

2852
  tstrncpy(epSet.eps[0].fqdn, fqdn, TSDB_FQDN_LEN);
885✔
2853
  epSet.eps[0].port = (uint16_t)port;
885✔
2854
  int32_t ret = rpcSendRecv(clientRpc, &epSet, &rpcMsg, &rpcRsp);
885✔
2855
  if (TSDB_CODE_SUCCESS != ret) {
885✔
UNCOV
2856
    tscError("failed to send recv since %s", tstrerror(ret));
×
UNCOV
2857
    goto _OVER;
×
2858
  }
2859

2860
  if (rpcRsp.code != 0 || rpcRsp.contLen <= 0 || rpcRsp.pCont == NULL) {
885✔
2861
    tscError("failed to send server status req since %s", terrstr());
128✔
2862
    goto _OVER;
128✔
2863
  }
2864

2865
  if (tDeserializeSServerStatusRsp(rpcRsp.pCont, rpcRsp.contLen, &statusRsp) != 0) {
757✔
UNCOV
2866
    tscError("failed to parse server status rsp since %s", terrstr());
×
UNCOV
2867
    goto _OVER;
×
2868
  }
2869

2870
  code = statusRsp.statusCode;
757✔
2871
  if (details != NULL) {
757✔
2872
    tstrncpy(details, statusRsp.details, maxlen);
757✔
2873
  }
2874

2875
_OVER:
642✔
2876
  if (clientRpc != NULL) {
885✔
2877
    rpcClose(clientRpc);
885✔
2878
  }
2879
  if (rpcRsp.pCont != NULL) {
885✔
2880
    rpcFreeCont(rpcRsp.pCont);
757✔
2881
  }
2882
  return code;
885✔
2883
}
2884

2885
int32_t appendTbToReq(SHashObj* pHash, int32_t pos1, int32_t len1, int32_t pos2, int32_t len2, const char* str,
1,244✔
2886
                      int32_t acctId, char* db) {
2887
  SName name = {0};
1,244✔
2888

2889
  if (len1 <= 0) {
1,244✔
UNCOV
2890
    return -1;
×
2891
  }
2892

2893
  const char* dbName = db;
1,244✔
2894
  const char* tbName = NULL;
1,244✔
2895
  int32_t     dbLen = 0;
1,244✔
2896
  int32_t     tbLen = 0;
1,244✔
2897
  if (len2 > 0) {
1,244✔
UNCOV
2898
    dbName = str + pos1;
×
UNCOV
2899
    dbLen = len1;
×
2900
    tbName = str + pos2;
×
2901
    tbLen = len2;
×
2902
  } else {
2903
    dbLen = strlen(db);
1,244✔
2904
    tbName = str + pos1;
1,244✔
2905
    tbLen = len1;
1,244✔
2906
  }
2907

2908
  if (dbLen <= 0 || tbLen <= 0) {
1,244✔
UNCOV
2909
    return -1;
×
2910
  }
2911

2912
  if (tNameSetDbName(&name, acctId, dbName, dbLen)) {
1,244✔
UNCOV
2913
    return -1;
×
2914
  }
2915

2916
  if (tNameAddTbName(&name, tbName, tbLen)) {
1,244✔
UNCOV
2917
    return -1;
×
2918
  }
2919

2920
  char dbFName[TSDB_DB_FNAME_LEN] = {0};
1,244✔
2921
  (void)snprintf(dbFName, TSDB_DB_FNAME_LEN, "%d.%.*s", acctId, dbLen, dbName);
1,244✔
2922

2923
  STablesReq* pDb = taosHashGet(pHash, dbFName, strlen(dbFName));
1,244✔
2924
  if (pDb) {
1,244✔
UNCOV
2925
    if (NULL == taosArrayPush(pDb->pTables, &name)) {
×
UNCOV
2926
      return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
2927
    }
2928
  } else {
2929
    STablesReq db;
1,244✔
2930
    db.pTables = taosArrayInit(20, sizeof(SName));
1,244✔
2931
    if (NULL == db.pTables) {
1,244✔
UNCOV
2932
      return terrno;
×
2933
    }
2934
    tstrncpy(db.dbFName, dbFName, TSDB_DB_FNAME_LEN);
1,244✔
2935
    if (NULL == taosArrayPush(db.pTables, &name)) {
2,488✔
UNCOV
2936
      return terrno;
×
2937
    }
2938
    TSC_ERR_RET(taosHashPut(pHash, dbFName, strlen(dbFName), &db, sizeof(db)));
1,244✔
2939
  }
2940

2941
  return TSDB_CODE_SUCCESS;
1,244✔
2942
}
2943

2944
int32_t transferTableNameList(const char* tbList, int32_t acctId, char* dbName, SArray** pReq) {
1,244✔
2945
  SHashObj* pHash = taosHashInit(3, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
1,244✔
2946
  if (NULL == pHash) {
1,244✔
UNCOV
2947
    return terrno;
×
2948
  }
2949

2950
  bool    inEscape = false;
1,244✔
2951
  int32_t code = 0;
1,244✔
2952
  void*   pIter = NULL;
1,244✔
2953

2954
  int32_t vIdx = 0;
1,244✔
2955
  int32_t vPos[2];
1,244✔
2956
  int32_t vLen[2];
1,244✔
2957

2958
  (void)memset(vPos, -1, sizeof(vPos));
1,244✔
2959
  (void)memset(vLen, 0, sizeof(vLen));
1,244✔
2960

2961
  for (int32_t i = 0;; ++i) {
6,220✔
2962
    if (0 == *(tbList + i)) {
6,220✔
2963
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
1,244✔
2964
        vLen[vIdx] = i - vPos[vIdx];
1,244✔
2965
      }
2966

2967
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
1,244✔
2968
      if (code) {
1,244✔
UNCOV
2969
        goto _return;
×
2970
      }
2971

2972
      break;
1,244✔
2973
    }
2974

2975
    if ('`' == *(tbList + i)) {
4,976✔
2976
      inEscape = !inEscape;
×
UNCOV
2977
      if (!inEscape) {
×
UNCOV
2978
        if (vPos[vIdx] >= 0) {
×
UNCOV
2979
          vLen[vIdx] = i - vPos[vIdx];
×
2980
        } else {
UNCOV
2981
          goto _return;
×
2982
        }
2983
      }
2984

UNCOV
2985
      continue;
×
2986
    }
2987

2988
    if (inEscape) {
4,976✔
UNCOV
2989
      if (vPos[vIdx] < 0) {
×
UNCOV
2990
        vPos[vIdx] = i;
×
2991
      }
2992
      continue;
×
2993
    }
2994

2995
    if ('.' == *(tbList + i)) {
4,976✔
UNCOV
2996
      if (vPos[vIdx] < 0) {
×
UNCOV
2997
        goto _return;
×
2998
      }
2999
      if (vLen[vIdx] <= 0) {
×
UNCOV
3000
        vLen[vIdx] = i - vPos[vIdx];
×
3001
      }
UNCOV
3002
      vIdx++;
×
3003
      if (vIdx >= 2) {
×
UNCOV
3004
        goto _return;
×
3005
      }
UNCOV
3006
      continue;
×
3007
    }
3008

3009
    if (',' == *(tbList + i)) {
4,976✔
UNCOV
3010
      if (vPos[vIdx] < 0) {
×
UNCOV
3011
        goto _return;
×
3012
      }
UNCOV
3013
      if (vLen[vIdx] <= 0) {
×
3014
        vLen[vIdx] = i - vPos[vIdx];
×
3015
      }
3016

UNCOV
3017
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
×
UNCOV
3018
      if (code) {
×
UNCOV
3019
        goto _return;
×
3020
      }
3021

UNCOV
3022
      (void)memset(vPos, -1, sizeof(vPos));
×
UNCOV
3023
      (void)memset(vLen, 0, sizeof(vLen));
×
UNCOV
3024
      vIdx = 0;
×
UNCOV
3025
      continue;
×
3026
    }
3027

3028
    if (' ' == *(tbList + i) || '\r' == *(tbList + i) || '\t' == *(tbList + i) || '\n' == *(tbList + i)) {
4,976✔
UNCOV
3029
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
×
UNCOV
3030
        vLen[vIdx] = i - vPos[vIdx];
×
3031
      }
UNCOV
3032
      continue;
×
3033
    }
3034

3035
    if (('a' <= *(tbList + i) && 'z' >= *(tbList + i)) || ('A' <= *(tbList + i) && 'Z' >= *(tbList + i)) ||
4,976✔
3036
        ('0' <= *(tbList + i) && '9' >= *(tbList + i)) || ('_' == *(tbList + i))) {
622✔
3037
      if (vLen[vIdx] > 0) {
4,976✔
UNCOV
3038
        goto _return;
×
3039
      }
3040
      if (vPos[vIdx] < 0) {
4,976✔
3041
        vPos[vIdx] = i;
1,244✔
3042
      }
3043
      continue;
4,976✔
3044
    }
3045

3046
    goto _return;
×
3047
  }
3048

3049
  int32_t dbNum = taosHashGetSize(pHash);
1,244✔
3050
  *pReq = taosArrayInit(dbNum, sizeof(STablesReq));
1,244✔
3051
  if (NULL == pReq) {
1,244✔
3052
    TSC_ERR_JRET(terrno);
×
3053
  }
3054
  pIter = taosHashIterate(pHash, NULL);
1,244✔
3055
  while (pIter) {
2,488✔
3056
    STablesReq* pDb = (STablesReq*)pIter;
1,244✔
3057
    if (NULL == taosArrayPush(*pReq, pDb)) {
2,488✔
UNCOV
3058
      TSC_ERR_JRET(terrno);
×
3059
    }
3060
    pIter = taosHashIterate(pHash, pIter);
1,244✔
3061
  }
3062

3063
  taosHashCleanup(pHash);
1,244✔
3064

3065
  return TSDB_CODE_SUCCESS;
1,244✔
3066

3067
_return:
×
3068

3069
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
3070

3071
  pIter = taosHashIterate(pHash, NULL);
×
UNCOV
3072
  while (pIter) {
×
3073
    STablesReq* pDb = (STablesReq*)pIter;
×
UNCOV
3074
    taosArrayDestroy(pDb->pTables);
×
UNCOV
3075
    pIter = taosHashIterate(pHash, pIter);
×
3076
  }
3077

3078
  taosHashCleanup(pHash);
×
3079

3080
  return terrno;
×
3081
}
3082

3083
void syncCatalogFn(SMetaData* pResult, void* param, int32_t code) {
1,244✔
3084
  SSyncQueryParam* pParam = param;
1,244✔
3085
  pParam->pRequest->code = code;
1,244✔
3086

3087
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
1,244✔
UNCOV
3088
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3089
  }
3090
}
1,244✔
3091

3092
void syncQueryFn(void* param, void* res, int32_t code) {
624,831,926✔
3093
  SSyncQueryParam* pParam = param;
624,831,926✔
3094
  pParam->pRequest = res;
624,831,926✔
3095

3096
  if (pParam->pRequest) {
624,837,081✔
3097
    pParam->pRequest->code = code;
624,816,038✔
3098
    clientOperateReport(pParam->pRequest);
624,824,541✔
3099
  }
3100

3101
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
624,827,399✔
UNCOV
3102
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3103
  }
3104
}
624,841,530✔
3105

3106
void taosAsyncQueryImpl(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
624,367,063✔
3107
                        int8_t source) {
3108
  if (sql == NULL || NULL == fp) {
624,367,063✔
3109
    terrno = TSDB_CODE_INVALID_PARA;
1,172✔
UNCOV
3110
    if (fp) {
×
UNCOV
3111
      fp(param, NULL, terrno);
×
3112
    }
3113

UNCOV
3114
    return;
×
3115
  }
3116

3117
  size_t sqlLen = strlen(sql);
624,366,339✔
3118
  if (sqlLen > (size_t)tsMaxSQLLength) {
624,366,339✔
3119
    tscError("conn:0x%" PRIx64 ", sql string exceeds max length:%d", connId, tsMaxSQLLength);
1,236✔
3120
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
1,236✔
3121
    fp(param, NULL, terrno);
1,236✔
3122
    return;
1,236✔
3123
  }
3124

3125
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, sql:%s", connId, sql);
624,365,103✔
3126

3127
  SRequestObj* pRequest = NULL;
624,365,489✔
3128
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
624,369,690✔
3129
  if (code != TSDB_CODE_SUCCESS) {
624,358,010✔
UNCOV
3130
    terrno = code;
×
UNCOV
3131
    fp(param, NULL, terrno);
×
UNCOV
3132
    return;
×
3133
  }
3134

3135
  pRequest->source = source;
624,358,010✔
3136
  pRequest->body.queryFp = fp;
624,365,539✔
3137
  doAsyncQuery(pRequest, false);
624,366,258✔
3138
}
3139

3140
void taosAsyncQueryImplWithReqid(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
6,463✔
3141
                                 int64_t reqid) {
3142
  if (sql == NULL || NULL == fp) {
6,463✔
UNCOV
3143
    terrno = TSDB_CODE_INVALID_PARA;
×
UNCOV
3144
    if (fp) {
×
3145
      fp(param, NULL, terrno);
×
3146
    }
3147

UNCOV
3148
    return;
×
3149
  }
3150

3151
  size_t sqlLen = strlen(sql);
6,463✔
3152
  if (sqlLen > (size_t)tsMaxSQLLength) {
6,463✔
UNCOV
3153
    tscError("conn:0x%" PRIx64 ", QID:0x%" PRIx64 ", sql string exceeds max length:%d", connId, reqid, tsMaxSQLLength);
×
UNCOV
3154
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
3155
    fp(param, NULL, terrno);
×
UNCOV
3156
    return;
×
3157
  }
3158

3159
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, QID:0x%" PRIx64 ", sql:%s", connId, reqid, sql);
6,463✔
3160

3161
  SRequestObj* pRequest = NULL;
6,463✔
3162
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, reqid);
6,463✔
3163
  if (code != TSDB_CODE_SUCCESS) {
6,463✔
UNCOV
3164
    terrno = code;
×
UNCOV
3165
    fp(param, NULL, terrno);
×
UNCOV
3166
    return;
×
3167
  }
3168

3169
  pRequest->body.queryFp = fp;
6,463✔
3170
  doAsyncQuery(pRequest, false);
6,463✔
3171
}
3172

3173
TAOS_RES* taosQueryImpl(TAOS* taos, const char* sql, bool validateOnly, int8_t source) {
624,266,001✔
3174
  if (NULL == taos) {
624,266,001✔
UNCOV
3175
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3176
    return NULL;
×
3177
  }
3178

3179
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
624,266,001✔
3180
  if (NULL == param) {
624,269,227✔
3181
    return NULL;
×
3182
  }
3183
  int32_t code = tsem_init(&param->sem, 0, 0);
624,269,227✔
3184
  if (TSDB_CODE_SUCCESS != code) {
624,264,659✔
UNCOV
3185
    taosMemoryFree(param);
×
UNCOV
3186
    return NULL;
×
3187
  }
3188

3189
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
624,264,659✔
3190
  code = tsem_wait(&param->sem);
624,258,947✔
3191
  if (TSDB_CODE_SUCCESS != code) {
624,272,975✔
UNCOV
3192
    taosMemoryFree(param);
×
UNCOV
3193
    return NULL;
×
3194
  }
3195
  code = tsem_destroy(&param->sem);
624,272,975✔
3196
  if (TSDB_CODE_SUCCESS != code) {
624,275,714✔
3197
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3198
  }
3199

3200
  SRequestObj* pRequest = NULL;
624,275,714✔
3201
  if (param->pRequest != NULL) {
624,275,714✔
3202
    param->pRequest->syncQuery = true;
624,272,087✔
3203
    pRequest = param->pRequest;
624,273,083✔
3204
    param->pRequest->inCallback = false;
624,273,251✔
3205
  }
3206
  taosMemoryFree(param);
624,274,773✔
3207

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

3211
  return pRequest;
624,274,455✔
3212
}
3213

3214
TAOS_RES* taosQueryImplWithReqid(TAOS* taos, const char* sql, bool validateOnly, int64_t reqid) {
6,463✔
3215
  if (NULL == taos) {
6,463✔
UNCOV
3216
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
UNCOV
3217
    return NULL;
×
3218
  }
3219

3220
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
6,463✔
3221
  if (param == NULL) {
6,463✔
3222
    return NULL;
×
3223
  }
3224
  int32_t code = tsem_init(&param->sem, 0, 0);
6,463✔
3225
  if (TSDB_CODE_SUCCESS != code) {
6,463✔
UNCOV
3226
    taosMemoryFree(param);
×
UNCOV
3227
    return NULL;
×
3228
  }
3229

3230
  taosAsyncQueryImplWithReqid(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, reqid);
6,463✔
3231
  code = tsem_wait(&param->sem);
6,463✔
3232
  if (TSDB_CODE_SUCCESS != code) {
6,463✔
3233
    taosMemoryFree(param);
×
UNCOV
3234
    return NULL;
×
3235
  }
3236
  SRequestObj* pRequest = NULL;
6,463✔
3237
  if (param->pRequest != NULL) {
6,463✔
3238
    param->pRequest->syncQuery = true;
6,463✔
3239
    pRequest = param->pRequest;
6,463✔
3240
  }
3241
  taosMemoryFree(param);
6,463✔
3242

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

3246
  return pRequest;
6,463✔
3247
}
3248

3249
static void fetchCallback(void* pResult, void* param, int32_t code) {
98,429,009✔
3250
  SRequestObj* pRequest = (SRequestObj*)param;
98,429,009✔
3251

3252
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
98,429,009✔
3253

3254
  tscDebug("req:0x%" PRIx64 ", enter scheduler fetch cb, code:%d - %s, QID:0x%" PRIx64, pRequest->self, code,
98,429,009✔
3255
           tstrerror(code), pRequest->requestId);
3256

3257
  pResultInfo->pData = pResult;
98,429,009✔
3258
  pResultInfo->numOfRows = 0;
98,429,246✔
3259

3260
  if (code != TSDB_CODE_SUCCESS) {
98,427,801✔
UNCOV
3261
    pRequest->code = code;
×
UNCOV
3262
    taosMemoryFreeClear(pResultInfo->pData);
×
UNCOV
3263
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
×
3264
    return;
×
3265
  }
3266

3267
  if (pRequest->code != TSDB_CODE_SUCCESS) {
98,427,801✔
UNCOV
3268
    taosMemoryFreeClear(pResultInfo->pData);
×
UNCOV
3269
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pRequest->code);
×
UNCOV
3270
    return;
×
3271
  }
3272

3273
  pRequest->code = setQueryResultFromRsp(pResultInfo, (const SRetrieveTableRsp*)pResultInfo->pData,
106,739,141✔
3274
                                         pResultInfo->convertUcs4, pRequest->stmtBindVersion > 0);
98,428,284✔
3275
  if (pRequest->code != TSDB_CODE_SUCCESS) {
98,428,067✔
3276
    pResultInfo->numOfRows = 0;
325✔
3277
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self,
325✔
3278
             tstrerror(pRequest->code), pRequest->requestId);
3279
  } else {
3280
    tscDebug(
98,427,986✔
3281
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
3282
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
3283

3284
    STscObj*            pTscObj = pRequest->pTscObj;
98,428,190✔
3285
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
98,428,921✔
3286
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
98,428,699✔
3287
  }
3288

3289
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
98,428,514✔
3290
}
3291

3292
void taosAsyncFetchImpl(SRequestObj* pRequest, __taos_async_fn_t fp, void* param) {
102,308,021✔
3293
  pRequest->body.fetchFp = fp;
102,308,021✔
3294
  ((SSyncQueryParam*)pRequest->body.interParam)->userParam = param;
102,308,494✔
3295

3296
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
102,308,494✔
3297

3298
  // this query has no results or error exists, return directly
3299
  if (taos_num_fields(pRequest) == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
102,308,494✔
3300
    pResultInfo->numOfRows = 0;
×
3301
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
×
3302
    return;
4,103✔
3303
  }
3304

3305
  // all data has returned to App already, no need to try again
3306
  if (pResultInfo->completed) {
102,308,494✔
3307
    // it is a local executed query, no need to do async fetch
3308
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
3,879,248✔
3309
      if (pResultInfo->localResultFetched) {
1,517,816✔
3310
        pResultInfo->numOfRows = 0;
758,908✔
3311
        pResultInfo->current = 0;
758,908✔
3312
      } else {
3313
        pResultInfo->localResultFetched = true;
758,908✔
3314
      }
3315
    } else {
3316
      pResultInfo->numOfRows = 0;
2,361,432✔
3317
    }
3318

3319
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
3,879,248✔
3320
    return;
3,879,248✔
3321
  }
3322

3323
  SSchedulerReq req = {
98,429,246✔
3324
      .syncReq = false,
3325
      .fetchFp = fetchCallback,
3326
      .cbParam = pRequest,
3327
  };
3328

3329
  int32_t code = schedulerFetchRows(pRequest->body.queryJob, &req);
98,429,246✔
3330
  if (TSDB_CODE_SUCCESS != code) {
98,429,246✔
3331
    tscError("0x%" PRIx64 " failed to schedule fetch rows", pRequest->requestId);
×
3332
    // pRequest->body.fetchFp(param, pRequest, code);
3333
  }
3334
}
3335

3336
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
624,851,185✔
3337
  pRequest->inCallback = true;
624,851,185✔
3338
  int64_t this = pRequest->self;
624,860,646✔
3339
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
624,844,538✔
3340
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
80,100✔
UNCOV
3341
    code = TSDB_CODE_SUCCESS;
×
UNCOV
3342
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3343
  }
3344

3345
  tscDebug("QID:0x%" PRIx64 ", taos_query end, req:0x%" PRIx64 ", res:%p", pRequest->requestId, pRequest->self,
624,844,538✔
3346
           pRequest);
3347

3348
  if (pRequest->body.queryFp != NULL) {
624,846,157✔
3349
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
624,852,927✔
3350
  }
3351

3352
  SRequestObj* pReq = acquireRequest(this);
624,865,494✔
3353
  if (pReq != NULL) {
624,864,572✔
3354
    pReq->inCallback = false;
623,917,093✔
3355
    (void)releaseRequest(this);
623,918,660✔
3356
  }
3357
}
624,867,132✔
3358

3359
int32_t clientParseSql(void* param, const char* dbName, const char* sql, bool parseOnly, const char* effectiveUser,
559,403✔
3360
                       SParseSqlRes* pRes) {
3361
#ifndef TD_ENTERPRISE
3362
  return TSDB_CODE_SUCCESS;
3363
#else
3364
  return clientParseSqlImpl(param, dbName, sql, parseOnly, effectiveUser, pRes);
559,403✔
3365
#endif
3366
}
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