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

taosdata / TDengine / #4877

11 Dec 2025 02:43AM UTC coverage: 64.586% (-0.05%) from 64.632%
#4877

push

travis-ci

guanshengliang
feat(TS-7270): internal dependence

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

673 existing lines in 130 files now uncovered.

163673 of 253417 relevant lines covered (64.59%)

105540806.95 hits per line

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

69.94
/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) {
115,332,300✔
39
  SRequestObj* pReq = acquireRequest(rId);
115,332,300✔
40
  if (pReq != NULL) {
115,332,436✔
41
    pReq->isQuery = true;
115,322,271✔
42
    (void)releaseRequest(rId);
115,322,271✔
43
  }
44
}
115,332,876✔
45

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

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

56
  return true;
7,689,769✔
57
}
58

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

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

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

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

71
static int32_t escapeToPrinted(char* dst, size_t maxDstLength, const char* src, size_t srcLength) {
638,625✔
72
  if (dst == NULL || src == NULL || srcLength == 0) {
638,625✔
73
    return 0;
531✔
74
  }
75
  
76
  size_t escapeLength = 0;
638,094✔
77
  for(size_t i = 0; i < srcLength; ++i) {
18,099,258✔
78
    if( src[i] == '\"' || src[i] == '\\' || src[i] == '\b' || src[i] == '\f' || src[i] == '\n' ||
17,461,164✔
79
        src[i] == '\r' || src[i] == '\t') {
17,461,164✔
80
      escapeLength += 1; 
×
81
    }    
82
  }
83

84
  size_t dstLength = srcLength;
638,094✔
85
  if(escapeLength == 0) {
638,094✔
86
     (void)memcpy(dst, src, srcLength);
638,094✔
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;
638,094✔
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✔
132
    killed = true;
140✔
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,274,152✔
141
  taosHashCleanup(appInfo.pInstMap);
1,274,152✔
142
  taosHashCleanup(appInfo.pInstMapByClusterId);
1,274,152✔
143
  tscInfo("cluster instance map cleaned");
1,274,152✔
144
}
1,274,152✔
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,129,456✔
150
                              uint16_t port, int connType, STscObj** pObj) {
151
  TSC_ERR_RET(taos_init());
3,129,456✔
152
  if (!validateUserName(user)) {
3,129,427✔
153
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
154
  }
155
  int32_t code = 0;
3,129,515✔
156

157
  char localDb[TSDB_DB_NAME_LEN] = {0};
3,129,515✔
158
  if (db != NULL && strlen(db) > 0) {
3,129,456✔
159
    if (!validateDbName(db)) {
1,433,466✔
160
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_DB_LENGTH);
×
161
    }
162

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

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

173
    taosEncryptPass_c((uint8_t*)pass, strlen(pass), secretEncrypt);
3,127,976✔
174
  } else {
175
    tstrncpy(secretEncrypt, auth, tListLen(secretEncrypt));
743✔
176
  }
177

178
  int32_t totpCode = -1;
3,129,220✔
179
  if (totp != NULL) {
3,129,220✔
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,129,220✔
188
  if (ip) {
3,128,307✔
189
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
1,112,615✔
190
  } else {
191
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
2,015,692✔
192
  }
193

194
  if (port) {
3,127,319✔
195
    epSet.epSet.eps[0].port = port;
138,870✔
196
    epSet.epSet.eps[1].port = port;
138,870✔
197
  }
198

199
  char* key = getClusterKey(user, secretEncrypt, ip, port);
3,127,319✔
200
  if (NULL == key) {
3,127,546✔
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,127,546✔
204
          user, db, key);
205
  for (int32_t i = 0; i < epSet.epSet.numOfEps; ++i) {
8,274,591✔
206
    tscInfo("ep:%d, %s:%u", i, epSet.epSet.eps[i].fqdn, epSet.epSet.eps[i].port);
5,145,518✔
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,129,073✔
218
  code = taosThreadMutexLock(&appInfo.mutex);
3,129,073✔
219
  if (TSDB_CODE_SUCCESS != code) {
3,129,073✔
220
    tscError("failed to lock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
221
    TSC_ERR_RET(code);
×
222
  }
223

224
  pInst = taosHashGet(appInfo.pInstMap, key, strlen(key));
3,129,073✔
225
  SAppInstInfo* p = NULL;
3,129,073✔
226
  if (pInst == NULL) {
3,129,073✔
227
    p = taosMemoryCalloc(1, sizeof(struct SAppInstInfo));
1,338,181✔
228
    if (NULL == p) {
1,338,181✔
229
      TSC_ERR_JRET(terrno);
×
230
    }
231
    p->mgmtEp = epSet;
1,338,181✔
232
    code = taosThreadMutexInit(&p->qnodeMutex, NULL);
1,338,181✔
233
    if (TSDB_CODE_SUCCESS != code) {
1,338,181✔
234
      taosMemoryFree(p);
×
235
      TSC_ERR_JRET(code);
×
236
    }
237
    code = openTransporter(user, secretEncrypt, tsNumOfCores / 2, &p->pTransporter);
1,338,181✔
238
    if (TSDB_CODE_SUCCESS != code) {
1,338,181✔
239
      taosMemoryFree(p);
40✔
240
      TSC_ERR_JRET(code);
40✔
241
    }
242
    code = appHbMgrInit(p, key, &p->pAppHbMgr);
1,338,141✔
243
    if (TSDB_CODE_SUCCESS != code) {
1,338,141✔
244
      destroyAppInst(&p);
×
245
      TSC_ERR_JRET(code);
×
246
    }
247
    code = taosHashPut(appInfo.pInstMap, key, strlen(key), &p, POINTER_BYTES);
1,338,141✔
248
    if (TSDB_CODE_SUCCESS != code) {
1,338,141✔
249
      destroyAppInst(&p);
×
250
      TSC_ERR_JRET(code);
×
251
    }
252
    p->instKey = key;
1,338,141✔
253
    key = NULL;
1,338,141✔
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,338,141✔
255

256
    pInst = &p;
1,338,141✔
257
  } else {
258
    if (NULL == *pInst || NULL == (*pInst)->pAppHbMgr) {
1,790,892✔
259
      tscError("*pInst:%p, pAppHgMgr:%p", *pInst, (*pInst) ? (*pInst)->pAppHbMgr : NULL);
×
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,790,892✔
264
  }
265

266
_return:
3,129,073✔
267

268
  if (TSDB_CODE_SUCCESS != code) {
3,129,073✔
269
    (void)taosThreadMutexUnlock(&appInfo.mutex);
40✔
270
    taosMemoryFreeClear(key);
40✔
271
    return code;
40✔
272
  } else {
273
    code = taosThreadMutexUnlock(&appInfo.mutex);
3,129,033✔
274
    taosMemoryFreeClear(key);
3,129,033✔
275
    if (TSDB_CODE_SUCCESS != code) {
3,129,033✔
276
      tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
277
      return code;
×
278
    }
279
    return taosConnectImpl(user, &secretEncrypt[0], totpCode, localDb, NULL, NULL, *pInst, connType, pObj);
3,129,033✔
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) {
556,215✔
293
  if (param == NULL) return;
556,215✔
294
  if (TSDB_CODE_SUCCESS != tsem_destroy(&param->sem)) {
556,215✔
295
    tscError("failed to destroy semaphore in freeQueryParam");
×
296
  }
297
  taosMemoryFree(param);
556,215✔
298
}
299

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

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

316
  (void)strntolower((*pRequest)->sqlstr, sql, (int32_t)sqlLen);
618,884,366✔
317
  (*pRequest)->sqlstr[sqlLen] = 0;
618,892,348✔
318
  (*pRequest)->sqlLen = sqlLen;
618,890,131✔
319
  (*pRequest)->validateOnly = validateSql;
618,892,734✔
320
  (*pRequest)->stmtBindVersion = 0;
618,890,244✔
321

322
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
618,886,926✔
323

324
  STscObj* pTscObj = (*pRequest)->pTscObj;
618,889,983✔
325
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
618,885,467✔
326
                             sizeof((*pRequest)->self));
327
  if (err) {
618,883,533✔
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);
330
    destroyRequest(*pRequest);
×
331
    *pRequest = NULL;
×
332
    return terrno;
×
333
  }
334

335
  (*pRequest)->allocatorRefId = -1;
618,883,533✔
336
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
618,891,072✔
337
    if (TSDB_CODE_SUCCESS !=
176,270,268✔
338
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
176,259,440✔
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);
×
342
      *pRequest = NULL;
×
343
      return terrno;
×
344
    }
345
  }
346

347
  tscDebug("req:0x%" PRIx64 ", build request, QID:0x%" PRIx64, (*pRequest)->self, (*pRequest)->requestId);
618,904,181✔
348
  return TSDB_CODE_SUCCESS;
618,881,642✔
349
}
350

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

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

366
  SParseContext cxt = {
716,313✔
367
      .requestId = pRequest->requestId,
715,989✔
368
      .requestRid = pRequest->self,
716,251✔
369
      .acctId = pTscObj->acctId,
716,406✔
370
      .db = pRequest->pDb,
716,098✔
371
      .topicQuery = topicQuery,
372
      .pSql = pRequest->sqlstr,
716,344✔
373
      .sqlLen = pRequest->sqlLen,
716,375✔
374
      .pMsg = pRequest->msgBuf,
716,313✔
375
      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
376
      .pTransporter = pTscObj->pAppInfo->pTransporter,
715,958✔
377
      .pStmtCb = pStmtCb,
378
      .pUser = pTscObj->user,
716,313✔
379
      .isSuperUser = (0 == strcmp(pTscObj->user, TSDB_DEFAULT_USER)),
716,059✔
380
      .enableSysInfo = pTscObj->sysInfo,
715,766✔
381
      .svrVer = pTscObj->sVer,
715,577✔
382
      .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes),
715,365✔
383
      .stmtBindVersion = pRequest->stmtBindVersion,
716,087✔
384
      .setQueryFp = setQueryRequest,
385
      .timezone = pTscObj->optionInfo.timezone,
715,701✔
386
      .charsetCxt = pTscObj->optionInfo.charsetCxt,
715,740✔
387
  };
388

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

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

404
  if (TSDB_CODE_SUCCESS == code || NEED_CLIENT_HANDLE_ERROR(code)) {
714,901✔
405
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
712,899✔
406
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
714,093✔
407
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
713,292✔
408
  }
409

410
  taosArrayDestroy(cxt.pTableMetaPos);
714,789✔
411
  taosArrayDestroy(cxt.pTableVgroupPos);
714,960✔
412

413
  return code;
716,173✔
414
}
415

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

426
  return code;
×
427
}
428

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

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

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

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

449
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
1,164,964,038✔
450

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

458
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp,
10,420,349✔
459
                              atomic_load_8(&pRequest->pTscObj->biMode), pRequest->pTscObj->optionInfo.charsetCxt);
10,420,349✔
460
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
5,255,444✔
461
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4,
2,740,281✔
462
                                 pRequest->stmtBindVersion > 0);
2,740,281✔
463
  }
464

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

468
  if (pRequest->code != TSDB_CODE_SUCCESS) {
5,255,444✔
469
    pResultInfo->numOfRows = 0;
3,950✔
470
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
3,950✔
471
             pRequest->requestId);
472
  } else {
473
    tscDebug(
5,251,494✔
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,255,444✔
479
}
480

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

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

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

498
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
17,500,597✔
499
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
17,499,691✔
500

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

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

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

516
  return node1->load > node2->load;
319,992✔
517
}
518

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

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

535
  return TSDB_CODE_SUCCESS;
78,064✔
536
}
537

538
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
618,784,278✔
539
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
618,784,278✔
540
    *required = false;
618,306,396✔
541
    return TSDB_CODE_SUCCESS;
618,306,424✔
542
  }
543

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

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

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

558
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
×
559
  if (pInfo->pQnodeList) {
×
560
    *pNodeList = taosArrayDup(pInfo->pQnodeList, NULL);
×
561
  }
562
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
×
563
  if (NULL == *pNodeList) {
×
564
    SCatalog* pCatalog = NULL;
×
565
    code = catalogGetHandle(pRequest->pTscObj->pAppInfo->clusterId, &pCatalog);
×
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) {
×
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,537,072✔
587
  pRequest->type = pQuery->msgType;
11,537,072✔
588
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
11,536,817✔
589

590
  SPlanContext cxt = {.queryId = pRequest->requestId,
17,713,778✔
591
                      .acctId = pRequest->pTscObj->acctId,
11,536,585✔
592
                      .mgmtEpSet = getEpSet_s(&pAppInfo->mgmtEp),
11,536,687✔
593
                      .pAstRoot = pQuery->pRoot,
11,538,812✔
594
                      .showRewrite = pQuery->showRewrite,
11,538,874✔
595
                      .pMsg = pRequest->msgBuf,
11,538,843✔
596
                      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
597
                      .pUser = pRequest->pTscObj->user,
11,538,812✔
598
                      .timezone = pRequest->pTscObj->optionInfo.timezone,
11,538,657✔
599
                      .sysInfo = pRequest->pTscObj->sysInfo};
11,538,781✔
600

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

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

611
  pResInfo->numOfCols = numOfCols;
117,086,718✔
612
  if (pResInfo->fields != NULL) {
117,086,708✔
613
    taosMemoryFree(pResInfo->fields);
17,207✔
614
  }
615
  if (pResInfo->userFields != NULL) {
117,086,420✔
616
    taosMemoryFree(pResInfo->userFields);
17,207✔
617
  }
618
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD_E));
117,083,528✔
619
  if (NULL == pResInfo->fields) return terrno;
117,084,519✔
620
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
117,084,892✔
621
  if (NULL == pResInfo->userFields) {
117,084,656✔
622
    taosMemoryFree(pResInfo->fields);
×
623
    return terrno;
×
624
  }
625
  if (numOfCols != pResInfo->numOfCols) {
117,083,922✔
626
    tscError("numOfCols:%d != pResInfo->numOfCols:%d", numOfCols, pResInfo->numOfCols);
×
627
    return TSDB_CODE_FAILED;
×
628
  }
629

630
  for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
701,834,991✔
631
    pResInfo->fields[i].type = pSchema[i].type;
584,750,398✔
632

633
    pResInfo->userFields[i].type = pSchema[i].type;
584,750,516✔
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);
584,752,947✔
636
    pResInfo->fields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, isStmt);
584,750,095✔
637
    if (IS_DECIMAL_TYPE(pSchema[i].type) && pExtSchema) {
584,748,707✔
638
      decimalFromTypeMod(pExtSchema[i].typeMod, &pResInfo->fields[i].precision, &pResInfo->fields[i].scale);
1,453,037✔
639
    }
640

641
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
584,742,540✔
642
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
584,753,846✔
643
  }
644
  return TSDB_CODE_SUCCESS;
117,088,592✔
645
}
646

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

653
  pResInfo->precision = precision;
84,905,033✔
654
}
655

656
int32_t buildVnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pDbVgList) {
93,861,856✔
657
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
93,861,856✔
658
  if (NULL == nodeList) {
93,868,906✔
659
    return terrno;
×
660
  }
661
  char* policy = (tsQueryPolicy == QUERY_POLICY_VNODE) ? "vnode" : "client";
93,869,529✔
662

663
  int32_t dbNum = taosArrayGetSize(pDbVgList);
93,869,529✔
664
  for (int32_t i = 0; i < dbNum; ++i) {
185,288,995✔
665
    SArray* pVg = taosArrayGetP(pDbVgList, i);
91,411,324✔
666
    if (NULL == pVg) {
91,414,544✔
667
      continue;
×
668
    }
669
    int32_t vgNum = taosArrayGetSize(pVg);
91,414,544✔
670
    if (vgNum <= 0) {
91,414,154✔
671
      continue;
667,097✔
672
    }
673

674
    for (int32_t j = 0; j < vgNum; ++j) {
303,884,170✔
675
      SVgroupInfo* pInfo = taosArrayGet(pVg, j);
213,133,652✔
676
      if (NULL == pInfo) {
213,135,766✔
677
        taosArrayDestroy(nodeList);
×
678
        return TSDB_CODE_OUT_OF_RANGE;
×
679
      }
680
      SQueryNodeLoad load = {0};
213,135,766✔
681
      load.addr.nodeId = pInfo->vgId;
213,134,291✔
682
      load.addr.epSet = pInfo->epSet;
213,135,663✔
683

684
      if (NULL == taosArrayPush(nodeList, &load)) {
213,134,032✔
685
        taosArrayDestroy(nodeList);
×
686
        return terrno;
×
687
      }
688
    }
689
  }
690

691
  int32_t vnodeNum = taosArrayGetSize(nodeList);
93,877,671✔
692
  if (vnodeNum > 0) {
93,874,237✔
693
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
90,444,072✔
694
    goto _return;
90,444,879✔
695
  }
696

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

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

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

715
_return:
105,904✔
716

717
  *pNodeList = nodeList;
93,871,154✔
718

719
  return TSDB_CODE_SUCCESS;
93,869,073✔
720
}
721

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

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

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

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

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

761
_return:
×
762

763
  *pNodeList = nodeList;
381,806✔
764

765
  return TSDB_CODE_SUCCESS;
381,806✔
766
}
767

768
void freeVgList(void* list) {
11,483,542✔
769
  SArray* pList = *(SArray**)list;
11,483,542✔
770
  taosArrayDestroy(pList);
11,484,218✔
771
}
11,489,574✔
772

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

779
  switch (tsQueryPolicy) {
82,714,675✔
780
    case QUERY_POLICY_VNODE:
82,332,825✔
781
    case QUERY_POLICY_CLIENT: {
782
      if (pResultMeta) {
82,332,825✔
783
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
82,334,063✔
784
        if (NULL == pDbVgList) {
82,334,263✔
785
          code = terrno;
×
786
          goto _return;
×
787
        }
788
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
82,334,263✔
789
        for (int32_t i = 0; i < dbNum; ++i) {
162,257,351✔
790
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
79,924,436✔
791
          if (pRes->code || NULL == pRes->pRes) {
79,924,587✔
792
            continue;
1,053✔
793
          }
794

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

803
        int32_t dbNum = taosArrayGetSize(pRequest->dbList);
×
804
        if (dbNum > 0) {
×
805
          SCatalog*     pCtg = NULL;
×
806
          SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
×
807
          code = catalogGetHandle(pInst->clusterId, &pCtg);
×
808
          if (code != TSDB_CODE_SUCCESS) {
×
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) {
×
819
            char*            dbFName = taosArrayGet(pRequest->dbList, i);
×
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;
×
833
              goto _return;
×
834
            }
835
          }
836
        }
837
      }
838

839
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
82,332,915✔
840
      break;
82,334,619✔
841
    }
842
    case QUERY_POLICY_HYBRID:
381,806✔
843
    case QUERY_POLICY_QNODE: {
844
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
474,678✔
845
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
92,872✔
846
        if (pRes->code) {
92,872✔
847
          pQnodeList = NULL;
×
848
        } else {
849
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
92,872✔
850
          if (NULL == pQnodeList) {
92,872✔
851
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
852
            goto _return;
×
853
          }
854
        }
855
      } else {
856
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
288,934✔
857
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
288,934✔
858
        if (pInst->pQnodeList) {
288,934✔
859
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
288,934✔
860
          if (NULL == pQnodeList) {
288,934✔
861
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
862
            goto _return;
×
863
          }
864
        }
865
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
288,934✔
866
      }
867

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

876
_return:
82,716,425✔
877
  taosArrayDestroyEx(pDbVgList, fp);
82,716,425✔
878
  taosArrayDestroy(pQnodeList);
82,714,689✔
879

880
  return code;
82,715,403✔
881
}
882

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

888
  switch (tsQueryPolicy) {
11,529,740✔
889
    case QUERY_POLICY_VNODE:
11,530,170✔
890
    case QUERY_POLICY_CLIENT: {
891
      int32_t dbNum = taosArrayGetSize(pRequest->dbList);
11,530,170✔
892
      if (dbNum > 0) {
11,535,986✔
893
        SCatalog*     pCtg = NULL;
11,488,085✔
894
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
11,487,705✔
895
        code = catalogGetHandle(pInst->clusterId, &pCtg);
11,488,147✔
896
        if (code != TSDB_CODE_SUCCESS) {
11,485,567✔
897
          goto _return;
×
898
        }
899

900
        pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
11,485,567✔
901
        if (NULL == pDbVgList) {
11,488,449✔
902
          code = terrno;
81✔
903
          goto _return;
×
904
        }
905
        SArray* pVgList = NULL;
11,488,368✔
906
        for (int32_t i = 0; i < dbNum; ++i) {
22,977,312✔
907
          char*            dbFName = taosArrayGet(pRequest->dbList, i);
11,482,364✔
908
          SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
11,487,863✔
909
                                   .requestId = pRequest->requestId,
11,488,040✔
910
                                   .requestObjRefId = pRequest->self,
11,487,333✔
911
                                   .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
11,487,911✔
912

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

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

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

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

941
_return:
11,535,420✔
942

943
  taosArrayDestroyEx(pDbVgList, freeVgList);
11,534,346✔
944
  taosArrayDestroy(pQnodeList);
11,534,664✔
945

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

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

952
  SExecResult      res = {0};
11,532,640✔
953
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
11,532,640✔
954
                           .requestId = pRequest->requestId,
11,531,995✔
955
                           .requestObjRefId = pRequest->self};
11,531,225✔
956
  SSchedulerReq    req = {
17,705,751✔
957
         .syncReq = true,
958
         .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
11,531,963✔
959
         .pConn = &conn,
960
         .pNodeList = pNodeList,
961
         .pDag = pDag,
962
         .sql = pRequest->sqlstr,
11,531,963✔
963
         .startTs = pRequest->metric.start,
11,532,250✔
964
         .execFp = NULL,
965
         .cbParam = NULL,
966
         .chkKillFp = chkRequestKilled,
967
         .chkKillParam = (void*)pRequest->self,
11,532,168✔
968
         .pExecRes = &res,
969
         .source = pRequest->source,
11,531,457✔
970
         .pWorkerCb = getTaskPoolWorkerCb(),
11,532,197✔
971
  };
972

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

975
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
11,538,075✔
976
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
11,537,664✔
977

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

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

986
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_DELETE == pRequest->type ||
11,537,369✔
987
      TDMT_VND_CREATE_TABLE == pRequest->type) {
15,026✔
988
    pRequest->body.resInfo.numOfRows = res.numOfRows;
11,526,656✔
989
    if (TDMT_VND_SUBMIT == pRequest->type) {
11,526,402✔
990
      STscObj*            pTscObj = pRequest->pTscObj;
11,522,366✔
991
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
11,522,602✔
992
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
11,522,949✔
993
    }
994

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

998
  pRequest->code = res.code;
11,538,576✔
999
  terrno = res.code;
11,538,830✔
1000
  return pRequest->code;
11,537,414✔
1001
}
1002

1003
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
451,974,458✔
1004
  SArray*      pArray = NULL;
451,974,458✔
1005
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
451,974,458✔
1006
  if (NULL == pRsp->aCreateTbRsp) {
451,974,458✔
1007
    return TSDB_CODE_SUCCESS;
443,274,763✔
1008
  }
1009

1010
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
8,706,192✔
1011
  for (int32_t i = 0; i < tbNum; ++i) {
20,988,437✔
1012
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
12,281,048✔
1013
    if (pTbRsp->pMeta) {
12,281,364✔
1014
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
11,582,845✔
1015
    }
1016
  }
1017

1018
  return TSDB_CODE_SUCCESS;
8,707,389✔
1019
}
1020

1021
int32_t handleQueryExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
68,913,393✔
1022
  int32_t code = 0;
68,913,393✔
1023
  SArray* pArray = NULL;
68,913,393✔
1024
  SArray* pTbArray = (SArray*)res;
68,913,393✔
1025
  int32_t tbNum = taosArrayGetSize(pTbArray);
68,913,393✔
1026
  if (tbNum <= 0) {
68,914,509✔
1027
    return TSDB_CODE_SUCCESS;
×
1028
  }
1029

1030
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
68,914,509✔
1031
  if (NULL == pArray) {
68,913,448✔
1032
    return terrno;
×
1033
  }
1034

1035
  for (int32_t i = 0; i < tbNum; ++i) {
185,866,102✔
1036
    STbVerInfo* tbInfo = taosArrayGet(pTbArray, i);
116,954,169✔
1037
    if (NULL == tbInfo) {
116,954,506✔
1038
      code = terrno;
×
1039
      goto _return;
×
1040
    }
1041
    STbSVersion tbSver = {
116,954,506✔
1042
        .tbFName = tbInfo->tbFName, .sver = tbInfo->sversion, .tver = tbInfo->tversion, .rver = tbInfo->rversion};
116,954,145✔
1043
    if (NULL == taosArrayPush(pArray, &tbSver)) {
116,954,311✔
1044
      code = terrno;
×
1045
      goto _return;
×
1046
    }
1047
  }
1048

1049
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
68,911,933✔
1050
                           .requestId = pRequest->requestId,
68,913,885✔
1051
                           .requestObjRefId = pRequest->self,
68,914,410✔
1052
                           .mgmtEps = *epset};
1053

1054
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
68,912,911✔
1055

1056
_return:
68,914,564✔
1057

1058
  taosArrayDestroy(pArray);
68,914,317✔
1059
  return code;
68,913,833✔
1060
}
1061

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

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

1070
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
586,452,106✔
1071
  if (NULL == pRequest->body.resInfo.execRes.res) {
586,452,106✔
1072
    return pRequest->code;
25,078,228✔
1073
  }
1074

1075
  SCatalog*     pCatalog = NULL;
561,373,679✔
1076
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
561,376,272✔
1077

1078
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
561,385,790✔
1079
  if (code) {
561,377,579✔
1080
    return code;
×
1081
  }
1082

1083
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
561,377,579✔
1084
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
561,386,905✔
1085

1086
  switch (pRes->msgType) {
561,387,517✔
1087
    case TDMT_VND_ALTER_TABLE:
3,769,491✔
1088
    case TDMT_MND_ALTER_STB: {
1089
      code = handleAlterTbExecRes(pRes->res, pCatalog);
3,769,491✔
1090
      break;
3,769,491✔
1091
    }
1092
    case TDMT_VND_CREATE_TABLE: {
36,364,121✔
1093
      SArray* pList = (SArray*)pRes->res;
36,364,121✔
1094
      int32_t num = taosArrayGetSize(pList);
36,373,280✔
1095
      for (int32_t i = 0; i < num; ++i) {
77,206,423✔
1096
        void* res = taosArrayGetP(pList, i);
40,829,824✔
1097
        // handleCreateTbExecRes will handle res == null
1098
        code = handleCreateTbExecRes(res, pCatalog);
40,828,769✔
1099
      }
1100
      break;
36,376,599✔
1101
    }
1102
    case TDMT_MND_CREATE_STB: {
347,943✔
1103
      code = handleCreateTbExecRes(pRes->res, pCatalog);
347,943✔
1104
      break;
347,943✔
1105
    }
1106
    case TDMT_VND_SUBMIT: {
451,973,622✔
1107
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
451,973,622✔
1108

1109
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
451,984,850✔
1110
      break;
451,974,921✔
1111
    }
1112
    case TDMT_SCH_QUERY:
68,914,107✔
1113
    case TDMT_SCH_MERGE_QUERY: {
1114
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
68,914,107✔
1115
      break;
68,913,888✔
1116
    }
1117
    default:
1,849✔
1118
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self,
1,849✔
1119
               pRequest->type, pRequest->requestId);
1120
      code = TSDB_CODE_APP_ERROR;
×
1121
  }
1122

1123
  return code;
561,382,842✔
1124
}
1125

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

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

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

1140
  if (TSDB_CODE_SUCCESS == code) {
×
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,317,204✔
1149
  if (pRequest->relation.userRefId == pRequest->self || 0 == pRequest->relation.userRefId) {
12,317,204✔
1150
    // return to client
1151
    doRequestCallback(pRequest, pRequest->code);
12,317,204✔
1152
    return;
12,317,204✔
1153
  }
1154

1155
  SRequestObj* pUserReq = acquireRequest(pRequest->relation.userRefId);
×
1156
  if (pUserReq) {
×
1157
    pUserReq->code = pRequest->code;
×
1158
    // return to client
1159
    doRequestCallback(pUserReq, pUserReq->code);
×
1160
    (void)releaseRequest(pRequest->relation.userRefId);
×
1161
    return;
×
1162
  } else {
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);
×
1171
  int32_t     numOfFields = taos_num_fields(pRes);
×
1172

1173
  int32_t code = createDataBlock(pBlock);
×
1174
  if (code) {
×
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);
×
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

1193
  for (int32_t i = 0; i < numOfRows; ++i) {
×
1194
    TAOS_ROW pRow = taos_fetch_row(pRes);
×
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
    }
1200
    int64_t ts = *(int64_t*)pRow[0];
×
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);
×
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

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

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

1232
  SSDataBlock* pBlock = NULL;
×
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) {
×
1254
  SRequestObj* pRequest = pWrapper->pRequest;
×
1255
  if (TD_RES_QUERY(pRequest)) {
×
1256
    taosAsyncFetchImpl(pRequest, postSubQueryFetchCb, pWrapper);
×
1257
    return;
×
1258
  }
1259

1260
  SRequestObj* pNextReq = acquireRequest(pRequest->relation.nextRefId);
×
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) {
574,582,738✔
1272
  SSqlCallbackWrapper* pWrapper = param;
574,582,738✔
1273
  SRequestObj*         pRequest = pWrapper->pRequest;
574,582,738✔
1274
  STscObj*             pTscObj = pRequest->pTscObj;
574,590,983✔
1275

1276
  pRequest->code = code;
574,588,639✔
1277
  if (pResult) {
574,592,664✔
1278
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
574,545,664✔
1279
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
574,558,332✔
1280
  }
1281

1282
  int32_t type = pRequest->type;
574,588,408✔
1283
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
574,564,773✔
1284
    if (pResult) {
480,194,686✔
1285
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
480,179,064✔
1286

1287
      // record the insert rows
1288
      if (TDMT_VND_SUBMIT == type) {
480,184,016✔
1289
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
440,594,962✔
1290
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
440,599,449✔
1291
      }
1292
    }
1293
    schedulerFreeJob(&pRequest->body.queryJob, 0);
480,206,101✔
1294
  }
1295

1296
  taosMemoryFree(pResult);
574,590,235✔
1297
  tscDebug("req:0x%" PRIx64 ", enter scheduler exec cb, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
574,584,304✔
1298
           pRequest->requestId);
1299

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

1311
  tscTrace("req:0x%" PRIx64 ", scheduler exec cb, request type:%s", pRequest->self, TMSG_INFO(pRequest->type));
574,540,531✔
1312
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
574,540,531✔
1313
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
2,747,914✔
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;
574,547,627✔
1319
  int32_t code1 = handleQueryExecRsp(pRequest);
574,540,626✔
1320
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
574,542,842✔
1321
    pRequest->code = code1;
×
1322
  }
1323

1324
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
1,148,114,472✔
1325
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
573,565,589✔
1326
    continueInsertFromCsv(pWrapper, pRequest);
12,101✔
1327
    return;
12,029✔
1328
  }
1329

1330
  if (pRequest->relation.nextRefId) {
574,539,529✔
1331
    handlePostSubQuery(pWrapper);
×
1332
  } else {
1333
    destorySqlCallbackWrapper(pWrapper);
574,543,629✔
1334
    pRequest->pWrapper = NULL;
574,529,932✔
1335

1336
    // return to client
1337
    doRequestCallback(pRequest, code);
574,533,953✔
1338
  }
1339
}
1340

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

1345
  if (pQuery->pRoot) {
11,913,702✔
1346
    pRequest->stmtType = pQuery->pRoot->type;
11,536,985✔
1347
  }
1348

1349
  if (pQuery->pRoot && !pRequest->inRetry) {
11,914,554✔
1350
    STscObj*            pTscObj = pRequest->pTscObj;
11,536,848✔
1351
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
11,537,354✔
1352
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type) {
11,537,363✔
1353
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
11,527,225✔
1354
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
10,165✔
1355
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
10,388✔
1356
    }
1357
  }
1358

1359
  pRequest->body.execMode = pQuery->execMode;
11,916,873✔
1360
  switch (pQuery->execMode) {
11,916,634✔
1361
    case QUERY_EXEC_MODE_LOCAL:
×
1362
      if (!pRequest->validateOnly) {
×
1363
        if (NULL == pQuery->pRoot) {
×
1364
          terrno = TSDB_CODE_INVALID_PARA;
×
1365
          code = terrno;
×
1366
        } else {
1367
          code = execLocalCmd(pRequest, pQuery);
×
1368
        }
1369
      }
1370
      break;
×
1371
    case QUERY_EXEC_MODE_RPC:
379,360✔
1372
      if (!pRequest->validateOnly) {
379,360✔
1373
        code = execDdlQuery(pRequest, pQuery);
379,359✔
1374
      }
1375
      break;
379,521✔
1376
    case QUERY_EXEC_MODE_SCHEDULE: {
11,536,955✔
1377
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
11,536,955✔
1378
      if (NULL == pMnodeList) {
11,536,516✔
1379
        code = terrno;
×
1380
        break;
×
1381
      }
1382
      SQueryPlan* pDag = NULL;
11,536,516✔
1383
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
11,536,516✔
1384
      if (TSDB_CODE_SUCCESS == code) {
11,532,770✔
1385
        pRequest->body.subplanNum = pDag->numOfSubplans;
11,533,294✔
1386
        if (!pRequest->validateOnly) {
11,535,471✔
1387
          SArray* pNodeList = NULL;
11,534,893✔
1388
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
11,534,511✔
1389
          if (TSDB_CODE_SUCCESS == code) {
11,535,807✔
1390
            code = scheduleQuery(pRequest, pDag, pNodeList);
11,536,992✔
1391
          }
1392
          taosArrayDestroy(pNodeList);
11,535,804✔
1393
        }
1394
      }
1395
      taosArrayDestroy(pMnodeList);
11,535,305✔
1396
      break;
11,537,332✔
1397
    }
1398
    case QUERY_EXEC_MODE_EMPTY_RESULT:
×
1399
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
1400
      break;
×
1401
    default:
×
1402
      break;
×
1403
  }
1404

1405
  if (!keepQuery) {
11,917,017✔
1406
    qDestroyQuery(pQuery);
×
1407
  }
1408

1409
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
11,917,017✔
1410
    int ret = removeMeta(pRequest->pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type));
31,694✔
1411
    if (TSDB_CODE_SUCCESS != ret) {
31,694✔
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,916,811✔
1418
    code = handleQueryExecRsp(pRequest);
11,915,858✔
1419
  }
1420

1421
  if (TSDB_CODE_SUCCESS != code) {
11,916,523✔
1422
    pRequest->code = code;
26,775✔
1423
  }
1424

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

1431
static int32_t asyncExecSchQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta,
575,045,717✔
1432
                                 SSqlCallbackWrapper* pWrapper) {
1433
  int32_t code = TSDB_CODE_SUCCESS;
575,045,717✔
1434
  pRequest->type = pQuery->msgType;
575,045,717✔
1435
  SArray*     pMnodeList = NULL;
575,061,119✔
1436
  SQueryPlan* pDag = NULL;
575,061,119✔
1437
  int64_t     st = taosGetTimestampUs();
575,037,094✔
1438

1439
  if (!pRequest->parseOnly) {
575,037,094✔
1440
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
575,050,398✔
1441
    if (NULL == pMnodeList) {
575,033,236✔
1442
      code = terrno;
×
1443
    }
1444
    SPlanContext cxt = {.queryId = pRequest->requestId,
617,339,942✔
1445
                        .acctId = pRequest->pTscObj->acctId,
575,064,874✔
1446
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
575,074,132✔
1447
                        .pAstRoot = pQuery->pRoot,
575,082,412✔
1448
                        .showRewrite = pQuery->showRewrite,
575,085,725✔
1449
                        .isView = pWrapper->pParseCtx->isView,
575,066,486✔
1450
                        .isAudit = pWrapper->pParseCtx->isAudit,
575,076,977✔
1451
                        .pMsg = pRequest->msgBuf,
575,063,597✔
1452
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1453
                        .pUser = pRequest->pTscObj->user,
575,073,161✔
1454
                        .sysInfo = pRequest->pTscObj->sysInfo,
575,070,758✔
1455
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
575,073,389✔
1456
                        .allocatorId = pRequest->stmtBindVersion > 0 ? 0 : pRequest->allocatorRefId};
575,061,415✔
1457
    if (TSDB_CODE_SUCCESS == code) {
575,073,130✔
1458
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
575,073,942✔
1459
    }
1460
    if (code) {
575,051,340✔
1461
      tscError("req:0x%" PRIx64 ", failed to create query plan, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
265,458✔
1462
               pRequest->requestId);
1463
    } else {
1464
      pRequest->body.subplanNum = pDag->numOfSubplans;
574,785,882✔
1465
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
574,801,203✔
1466
    }
1467
  }
1468

1469
  pRequest->metric.execStart = taosGetTimestampUs();
575,074,065✔
1470
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
575,073,637✔
1471

1472
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
596,194,051✔
1473
    SArray* pNodeList = NULL;
574,553,048✔
1474
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
574,574,786✔
1475
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
82,714,913✔
1476
    }
1477

1478
    SRequestConnInfo conn = {.pTrans = getAppInfo(pRequest)->pTransporter,
574,574,200✔
1479
                             .requestId = pRequest->requestId,
574,583,083✔
1480
                             .requestObjRefId = pRequest->self};
574,576,667✔
1481
    SSchedulerReq    req = {
595,718,514✔
1482
           .syncReq = false,
1483
           .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
574,565,046✔
1484
           .pConn = &conn,
1485
           .pNodeList = pNodeList,
1486
           .pDag = pDag,
1487
           .allocatorRefId = pRequest->allocatorRefId,
574,565,046✔
1488
           .sql = pRequest->sqlstr,
574,549,952✔
1489
           .startTs = pRequest->metric.start,
574,564,164✔
1490
           .execFp = schedulerExecCb,
1491
           .cbParam = pWrapper,
1492
           .chkKillFp = chkRequestKilled,
1493
           .chkKillParam = (void*)pRequest->self,
574,552,447✔
1494
           .pExecRes = NULL,
1495
           .source = pRequest->source,
574,544,046✔
1496
           .pWorkerCb = getTaskPoolWorkerCb(),
574,543,449✔
1497
    };
1498
    if (TSDB_CODE_SUCCESS == code) {
574,552,984✔
1499
      code = schedulerExecJob(&req, &pRequest->body.queryJob);
574,585,873✔
1500
    }
1501

1502
    taosArrayDestroy(pNodeList);
574,552,734✔
1503
  } else {
1504
    qDestroyQueryPlan(pDag);
511,655✔
1505
    tscDebug("req:0x%" PRIx64 ", plan not executed, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
491,477✔
1506
             pRequest->requestId);
1507
    destorySqlCallbackWrapper(pWrapper);
491,477✔
1508
    pRequest->pWrapper = NULL;
491,477✔
1509
    if (TSDB_CODE_SUCCESS != code) {
491,477✔
1510
      pRequest->code = terrno;
265,458✔
1511
    }
1512

1513
    doRequestCallback(pRequest, code);
491,477✔
1514
  }
1515

1516
  // todo not to be released here
1517
  taosArrayDestroy(pMnodeList);
575,077,367✔
1518

1519
  return code;
575,069,168✔
1520
}
1521

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

1525
  if (pRequest->parseOnly) {
598,453,763✔
1526
    doRequestCallback(pRequest, 0);
286,927✔
1527
    return;
286,927✔
1528
  }
1529

1530
  pRequest->body.execMode = pQuery->execMode;
598,187,332✔
1531
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
598,185,752✔
1532
    destorySqlCallbackWrapper(pWrapper);
23,121,450✔
1533
    pRequest->pWrapper = NULL;
23,121,344✔
1534
  }
1535

1536
  if (pQuery->pRoot && !pRequest->inRetry) {
598,165,893✔
1537
    STscObj*            pTscObj = pRequest->pTscObj;
598,174,421✔
1538
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
598,195,303✔
1539
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
598,185,881✔
1540
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
491,860,364✔
1541
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
440,556,794✔
1542
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
157,618,673✔
1543
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
77,311,348✔
1544
    }
1545
  }
1546

1547
  switch (pQuery->execMode) {
598,188,868✔
1548
    case QUERY_EXEC_MODE_LOCAL:
5,267,513✔
1549
      asyncExecLocalCmd(pRequest, pQuery);
5,267,513✔
1550
      break;
5,267,513✔
1551
    case QUERY_EXEC_MODE_RPC:
17,508,221✔
1552
      code = asyncExecDdlQuery(pRequest, pQuery);
17,508,221✔
1553
      break;
17,508,324✔
1554
    case QUERY_EXEC_MODE_SCHEDULE: {
575,065,322✔
1555
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
575,065,322✔
1556
      break;
575,072,403✔
1557
    }
1558
    case QUERY_EXEC_MODE_EMPTY_RESULT:
345,690✔
1559
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
345,690✔
1560
      doRequestCallback(pRequest, 0);
345,690✔
1561
      break;
345,690✔
1562
    default:
×
1563
      tscError("req:0x%" PRIx64 ", invalid execMode %d", pRequest->self, pQuery->execMode);
×
1564
      doRequestCallback(pRequest, -1);
×
1565
      break;
×
1566
  }
1567
}
1568

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

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

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

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

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

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

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

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

1609
  return code;
316✔
1610
}
1611

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

1620
  if (isView) {
4,046,039✔
1621
    for (int32_t i = 0; i < tbNum; ++i) {
817,282✔
1622
      SName* pViewName = taosArrayGet(tbList, i);
408,641✔
1623
      char   dbFName[TSDB_DB_FNAME_LEN];
399,266✔
1624
      if (NULL == pViewName) {
408,641✔
1625
        continue;
×
1626
      }
1627
      (void)tNameGetFullDbName(pViewName, dbFName);
408,641✔
1628
      TSC_ERR_RET(catalogRemoveViewMeta(pCatalog, dbFName, 0, pViewName->tname, 0));
408,641✔
1629
    }
1630
  } else {
1631
    for (int32_t i = 0; i < tbNum; ++i) {
5,415,626✔
1632
      SName* pTbName = taosArrayGet(tbList, i);
1,778,228✔
1633
      TSC_ERR_RET(catalogRemoveTableMeta(pCatalog, pTbName));
1,778,228✔
1634
    }
1635
  }
1636

1637
  return TSDB_CODE_SUCCESS;
4,046,039✔
1638
}
1639

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

1643
  // init mnode ip set
1644
  SEpSet* mgmtEpSet = &(pEpSet->epSet);
3,127,846✔
1645
  mgmtEpSet->numOfEps = 0;
3,127,844✔
1646
  mgmtEpSet->inUse = 0;
3,128,700✔
1647

1648
  if (firstEp && firstEp[0] != 0) {
3,128,467✔
1649
    if (strlen(firstEp) >= TSDB_EP_LEN) {
3,128,598✔
1650
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1651
      return -1;
×
1652
    }
1653

1654
    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
3,128,598✔
1655
    if (code != TSDB_CODE_SUCCESS) {
3,126,905✔
1656
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1657
      return terrno;
×
1658
    }
1659
    // uint32_t addr = 0;
1660
    SIpAddr addr = {0};
3,126,905✔
1661
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
3,126,292✔
1662
    if (code) {
3,128,719✔
1663
      tscError("failed to resolve firstEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
1,085✔
1664
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1665
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
747✔
1666
    } else {
1667
      mgmtEpSet->numOfEps++;
3,127,634✔
1668
    }
1669
  }
1670

1671
  if (secondEp && secondEp[0] != 0) {
3,127,488✔
1672
    if (strlen(secondEp) >= TSDB_EP_LEN) {
2,015,369✔
1673
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1674
      return terrno;
×
1675
    }
1676

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

1692
  if (mgmtEpSet->numOfEps == 0) {
3,128,283✔
1693
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
747✔
1694
    return TSDB_CODE_RPC_NETWORK_UNAVAIL;
747✔
1695
  }
1696

1697
  return 0;
3,127,044✔
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,129,033✔
1701
                        SAppInstInfo* pAppInfo, int connType, STscObj** pTscObj) {
1702
  *pTscObj = NULL;
3,129,033✔
1703
  int32_t code = createTscObj(user, auth, db, connType, pAppInfo, pTscObj);
3,129,033✔
1704
  if (TSDB_CODE_SUCCESS != code) {
3,129,033✔
1705
    return code;
×
1706
  }
1707

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

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

1722
  SMsgSendInfo* body = NULL;
3,128,634✔
1723
  code = buildConnectMsg(pRequest, &body, totpCode);
3,128,634✔
1724
  if (TSDB_CODE_SUCCESS != code) {
3,127,270✔
1725
    destroyTscObj(*pTscObj);
×
1726
    return code;
×
1727
  }
1728

1729
  // int64_t transporterId = 0;
1730
  SEpSet epset = getEpSet_s(&(*pTscObj)->pAppInfo->mgmtEp);
3,127,270✔
1731
  code = asyncSendMsgToServer((*pTscObj)->pAppInfo->pTransporter, &epset, NULL, body);
3,128,394✔
1732
  if (TSDB_CODE_SUCCESS != code) {
3,128,985✔
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,128,985✔
1738
    destroyTscObj(*pTscObj);
156✔
1739
    tscError("failed to wait sem, code:%s", terrstr());
×
1740
    return terrno;
×
1741
  }
1742
  if (pRequest->code != TSDB_CODE_SUCCESS) {
3,128,877✔
1743
    const char* errorMsg = (code == TSDB_CODE_RPC_FQDN_ERROR) ? taos_errstr(pRequest) : tstrerror(pRequest->code);
20,801✔
1744
    tscError("failed to connect to server, reason: %s", errorMsg);
20,801✔
1745

1746
    terrno = pRequest->code;
20,801✔
1747
    destroyRequest(pRequest);
20,801✔
1748
    taos_close_internal(*pTscObj);
20,801✔
1749
    *pTscObj = NULL;
20,801✔
1750
    return terrno;
20,801✔
1751
  }
1752
  if (connType == CONN_TYPE__AUTH_TEST) {
3,108,076✔
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,108,076✔
1761
          (*pTscObj)->connId, (*pTscObj)->pAppInfo->pTransporter, pRequest->requestId);
1762
  destroyRequest(pRequest);
3,108,076✔
1763
  return code;
3,108,232✔
1764
}
1765

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

1772
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
3,128,956✔
1773

1774
  (*pMsgSendInfo)->requestObjRefId = pRequest->self;
3,128,956✔
1775
  (*pMsgSendInfo)->requestId = pRequest->requestId;
3,128,710✔
1776
  (*pMsgSendInfo)->fp = getMsgRspHandle((*pMsgSendInfo)->msgType);
3,128,956✔
1777
  (*pMsgSendInfo)->param = taosMemoryCalloc(1, sizeof(pRequest->self));
3,128,817✔
1778
  if (NULL == (*pMsgSendInfo)->param) {
3,128,318✔
1779
    taosMemoryFree(*pMsgSendInfo);
×
1780
    return terrno;
×
1781
  }
1782

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

1785
  SConnectReq connectReq = {0};
3,128,072✔
1786
  STscObj*    pObj = pRequest->pTscObj;
3,128,318✔
1787

1788
  char* db = getDbOfConnection(pObj);
3,128,072✔
1789
  if (db != NULL) {
3,128,142✔
1790
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
1,433,011✔
1791
  } else if (terrno) {
1,695,131✔
1792
    taosMemoryFree(*pMsgSendInfo);
×
1793
    return terrno;
×
1794
  }
1795
  taosMemoryFreeClear(db);
3,128,281✔
1796

1797
  connectReq.connType = pObj->connType;
3,128,336✔
1798
  connectReq.pid = appInfo.pid;
3,128,582✔
1799
  connectReq.startTime = appInfo.startTime;
3,128,336✔
1800
  connectReq.totpCode = totpCode;
3,128,336✔
1801

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

1807
  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connectReq);
3,128,336✔
1808
  void*   pReq = taosMemoryMalloc(contLen);
3,127,720✔
1809
  if (NULL == pReq) {
3,128,520✔
1810
    taosMemoryFree(*pMsgSendInfo);
×
1811
    return terrno;
×
1812
  }
1813

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

1820
  (*pMsgSendInfo)->msgInfo.len = contLen;
3,127,310✔
1821
  (*pMsgSendInfo)->msgInfo.pData = pReq;
3,128,008✔
1822
  return TSDB_CODE_SUCCESS;
3,127,338✔
1823
}
1824

1825
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,011,716,550✔
1826
  if (NULL == pEpSet) {
1,011,716,550✔
1827
    return;
1,000,678,004✔
1828
  }
1829

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

1838
      SEpSet  originEpset = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
920✔
1839
      SEpSet* pOrig = &originEpset;
920✔
1840
      SEp*    pOrigEp = &pOrig->eps[pOrig->inUse];
920✔
1841
      SEp*    pNewEp = &pEpSet->eps[pEpSet->inUse];
920✔
1842
      tscDebug("mnode epset updated from %d/%d=>%s:%d to %d/%d=>%s:%d in client", pOrig->inUse, pOrig->numOfEps,
920✔
1843
               pOrigEp->fqdn, pOrigEp->port, pEpSet->inUse, pEpSet->numOfEps, pNewEp->fqdn, pNewEp->port);
1844
      updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
920✔
1845
      break;
7,694,137✔
1846
    case TARGET_TYPE_VNODE: {
10,810,073✔
1847
      if (NULL == pTscObj) {
10,810,073✔
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;
10,810,073✔
1854
      int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
10,810,073✔
1855
      if (code != TSDB_CODE_SUCCESS) {
10,810,067✔
1856
        tscError("fail to get catalog handle, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1857
                 tstrerror(code));
1858
        return;
×
1859
      }
1860

1861
      code = catalogUpdateVgEpSet(pCatalog, pSendInfo->target.dbFName, pSendInfo->target.vgId, pEpSet);
10,810,067✔
1862
      if (code != TSDB_CODE_SUCCESS) {
10,810,692✔
1863
        tscError("fail to update catalog vg epset, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1864
                 tstrerror(code));
1865
        return;
×
1866
      }
1867
      taosMemoryFreeClear(pSendInfo->target.dbFName);
10,810,803✔
1868
      break;
10,811,220✔
1869
    }
1870
    default:
229,018✔
1871
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
229,018✔
1872
      break;
229,513✔
1873
  }
1874
}
1875

1876
int32_t doProcessMsgFromServerImpl(SRpcMsg* pMsg, SEpSet* pEpSet) {
1,012,476,695✔
1877
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
1,012,476,695✔
1878
  if (pMsg->info.ahandle == NULL) {
1,012,478,605✔
1879
    tscError("doProcessMsgFromServer pMsg->info.ahandle == NULL");
758,021✔
1880
    rpcFreeCont(pMsg->pCont);
758,021✔
1881
    taosMemoryFree(pEpSet);
758,021✔
1882
    return TSDB_CODE_TSC_INTERNAL_ERROR;
758,021✔
1883
  }
1884

1885
  STscObj* pTscObj = NULL;
1,011,717,249✔
1886

1887
  STraceId* trace = &pMsg->info.traceId;
1,011,717,249✔
1888
  char      tbuf[40] = {0};
1,011,722,749✔
1889
  TRACE_TO_STR(trace, tbuf);
1,011,721,205✔
1890

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

1894
  if (pSendInfo->requestObjRefId != 0) {
1,011,724,651✔
1895
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
865,888,285✔
1896
    if (pRequest) {
865,887,082✔
1897
      if (pRequest->self != pSendInfo->requestObjRefId) {
865,637,746✔
1898
        tscError("doProcessMsgFromServer req:0x%" PRId64 " != pSendInfo->requestObjRefId:0x%" PRId64, pRequest->self,
×
1899
                 pSendInfo->requestObjRefId);
1900

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

1913
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
1,011,719,802✔
1914

1915
  SDataBuf buf = {.msgType = pMsg->msgType,
1,011,715,973✔
1916
                  .len = pMsg->contLen,
1,011,715,989✔
1917
                  .pData = NULL,
1918
                  .handle = pMsg->info.handle,
1,011,716,692✔
1919
                  .handleRefId = pMsg->info.refId,
1,011,718,520✔
1920
                  .pEpSet = pEpSet};
1921

1922
  if (pMsg->contLen > 0) {
1,011,720,717✔
1923
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
987,554,086✔
1924
    if (buf.pData == NULL) {
987,548,848✔
1925
      pMsg->code = terrno;
×
1926
    } else {
1927
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
987,548,848✔
1928
    }
1929
  }
1930

1931
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
1,011,718,356✔
1932

1933
  if (pTscObj) {
1,011,701,048✔
1934
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
865,621,810✔
1935
    if (TSDB_CODE_SUCCESS != code) {
865,638,362✔
UNCOV
1936
      tscError("doProcessMsgFromServer taosReleaseRef failed");
×
UNCOV
1937
      terrno = code;
×
UNCOV
1938
      pMsg->code = code;
×
1939
    }
1940
  }
1941

1942
  rpcFreeCont(pMsg->pCont);
1,011,717,600✔
1943
  destroySendMsgInfo(pSendInfo);
1,011,704,307✔
1944
  return TSDB_CODE_SUCCESS;
1,011,692,604✔
1945
}
1946

1947
int32_t doProcessMsgFromServer(void* param) {
1,012,479,575✔
1948
  AsyncArg* arg = (AsyncArg*)param;
1,012,479,575✔
1949
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
1,012,479,575✔
1950
  taosMemoryFree(arg);
1,012,448,216✔
1951
  return code;
1,012,459,218✔
1952
}
1953

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

1958
  tscDebug("msg callback, ahandle %p", pMsg->info.ahandle);
1,012,468,696✔
1959

1960
  if (pEpSet != NULL) {
1,012,474,311✔
1961
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
11,040,583✔
1962
    if (NULL == tEpSet) {
11,039,866✔
1963
      code = terrno;
×
1964
      pMsg->code = terrno;
×
1965
      goto _exit;
×
1966
    }
1967
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
11,039,866✔
1968
  }
1969

1970
  // pMsg is response msg
1971
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
1,012,473,594✔
1972
    // restore origin code
1973
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
3,129,033✔
1974
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1975
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
3,129,033✔
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,009,343,303✔
1981
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
1982
    }
1983
  }
1984

1985
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
1,012,476,818✔
1986
  if (NULL == arg) {
1,012,466,632✔
1987
    code = terrno;
×
1988
    pMsg->code = code;
×
1989
    goto _exit;
×
1990
  }
1991

1992
  arg->msg = *pMsg;
1,012,466,632✔
1993
  arg->pEpset = tEpSet;
1,012,471,441✔
1994

1995
  if ((code = taosAsyncExec(doProcessMsgFromServer, arg, NULL)) != 0) {
1,012,470,652✔
1996
    pMsg->code = code;
767✔
1997
    taosMemoryFree(arg);
767✔
1998
    goto _exit;
×
1999
  }
2000
  return;
1,012,473,614✔
2001

2002
_exit:
×
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) {
743✔
2061
  tscInfo("try to connect to %s:%u by auth, user:%s db:%s", ip, port, user, db);
743✔
2062
  if (user == NULL) {
743✔
2063
    user = TSDB_DEFAULT_USER;
×
2064
  }
2065

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

2071
  STscObj* pObj = NULL;
743✔
2072
  int32_t  code = taos_connect_internal(ip, user, NULL, auth, NULL, db, port, CONN_TYPE__QUERY, &pObj);
743✔
2073
  if (TSDB_CODE_SUCCESS == code) {
743✔
2074
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
129✔
2075
    if (NULL == rid) {
129✔
2076
      tscError("out of memory when taos connect to %s:%u, user:%s db:%s", ip, port, user, db);
×
2077
    }
2078
    *rid = pObj->id;
129✔
2079
    return (TAOS*)rid;
129✔
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,138,746,662✔
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,842,075,744✔
2109

2110
        if (IS_STR_DATA_BLOB(type)) {
1,842,494,129✔
UNCOV
2111
          pResultInfo->length[i] = blobDataLen(pStart);
×
2112
          pResultInfo->row[i] = blobDataVal(pStart);
×
2113
        } else {
2114
          pResultInfo->length[i] = varDataLen(pStart);
1,842,722,106✔
2115
          pResultInfo->row[i] = varDataVal(pStart);
1,842,128,484✔
2116
        }
2117
      } else {
2118
        pResultInfo->row[i] = NULL;
23,066,750✔
2119
        pResultInfo->length[i] = 0;
23,529,569✔
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;
143,138,014✔
2127
        pResultInfo->length[i] = 0;
146,985,633✔
2128
      }
2129
    }
2130
  }
2131
}
2,138,731,352✔
2132

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

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

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

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

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

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

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

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

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

2180
  return pResultInfo->row;
×
2181
}
2182

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

2190
void* doAsyncFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
1,051,514,083✔
2191
  if (pRequest == NULL) {
1,051,514,083✔
2192
    return NULL;
×
2193
  }
2194

2195
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
1,051,514,083✔
2196
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
1,051,555,796✔
2197
    // All data has returned to App already, no need to try again
2198
    if (pResultInfo->completed) {
165,555,749✔
2199
      pResultInfo->numOfRows = 0;
71,755,682✔
2200
      return NULL;
71,755,460✔
2201
    }
2202

2203
    // convert ucs4 to native multi-bytes string
2204
    pResultInfo->convertUcs4 = convertUcs4;
93,822,972✔
2205
    tsem_t sem;
86,869,169✔
2206
    if (TSDB_CODE_SUCCESS != tsem_init(&sem, 0, 0)) {
93,823,146✔
2207
      tscError("failed to init sem, code:%s", terrstr());
×
2208
    }
2209
    taos_fetch_rows_a(pRequest, syncFetchFn, &sem);
93,822,896✔
2210
    if (TSDB_CODE_SUCCESS != tsem_wait(&sem)) {
93,823,146✔
2211
      tscError("failed to wait sem, code:%s", terrstr());
×
2212
    }
2213
    if (TSDB_CODE_SUCCESS != tsem_destroy(&sem)) {
93,823,146✔
2214
      tscError("failed to destroy sem, code:%s", terrstr());
×
2215
    }
2216
    pRequest->inCallback = false;
93,823,146✔
2217
  }
2218

2219
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
979,846,966✔
2220
    return NULL;
7,012,324✔
2221
  } else {
2222
    if (setupOneRowPtr) {
972,805,499✔
2223
      doSetOneRowPtr(pResultInfo);
887,716,156✔
2224
      pResultInfo->current += 1;
887,723,890✔
2225
    }
2226

2227
    return pResultInfo->row;
972,813,257✔
2228
  }
2229
}
2230

2231
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
123,151,539✔
2232
  if (pResInfo->row == NULL) {
123,151,539✔
2233
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
106,337,509✔
2234
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
106,337,223✔
2235
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
106,336,547✔
2236
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
106,336,771✔
2237

2238
    if (pResInfo->row == NULL || pResInfo->pCol == NULL || pResInfo->length == NULL || pResInfo->convertBuf == NULL) {
106,336,943✔
2239
      taosMemoryFree(pResInfo->row);
1,386✔
2240
      taosMemoryFree(pResInfo->pCol);
×
2241
      taosMemoryFree(pResInfo->length);
×
2242
      taosMemoryFree(pResInfo->convertBuf);
×
2243
      return terrno;
×
2244
    }
2245
  }
2246

2247
  return TSDB_CODE_SUCCESS;
123,153,010✔
2248
}
2249

2250
static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength, bool isStmt) {
121,858,070✔
2251
  int32_t idx = -1;
121,858,070✔
2252
  iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt);
121,858,316✔
2253
  if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR;
121,856,636✔
2254

2255
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
693,945,211✔
2256
    int32_t type = pResultInfo->fields[i].type;
572,093,440✔
2257
    int32_t schemaBytes =
2258
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
572,093,265✔
2259

2260
    if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) {
572,094,949✔
2261
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
19,534,619✔
2262
      if (p == NULL) {
19,534,619✔
2263
        taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
×
2264
        return terrno;
×
2265
      }
2266

2267
      pResultInfo->convertBuf[i] = p;
19,534,619✔
2268

2269
      SResultColumn* pCol = &pResultInfo->pCol[i];
19,534,619✔
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(
16,484✔
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);
16,484✔
2281
            return TSDB_CODE_TSC_INTERNAL_ERROR;
324✔
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];
19,534,295✔
2291
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
19,534,295✔
2292
    }
2293
  }
2294
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
121,857,924✔
2295
  return TSDB_CODE_SUCCESS;
121,858,184✔
2296
}
2297

2298
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
121,856,980✔
2299
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
693,944,470✔
2300
    TAOS_FIELD_E* pFieldE = pResultInfo->fields + i;
572,090,939✔
2301
    TAOS_FIELD*   pField = pResultInfo->userFields + i;
572,090,011✔
2302
    int32_t       type = pFieldE->type;
572,089,461✔
2303
    int32_t       bufLen = 0;
572,091,551✔
2304
    char*         p = NULL;
572,091,551✔
2305
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
572,091,551✔
2306
      continue;
570,452,991✔
2307
    } else {
2308
      bufLen = 64;
1,637,056✔
2309
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
1,637,056✔
2310
      pFieldE->bytes = bufLen;
1,637,056✔
2311
      pField->bytes = bufLen;
1,637,056✔
2312
    }
2313
    if (!p) return terrno;
1,637,056✔
2314
    pResultInfo->convertBuf[i] = p;
1,637,056✔
2315

2316
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
999,873,907✔
2317
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
998,236,851✔
2318
                                  pFieldE->precision, pFieldE->scale, p, bufLen);
998,236,851✔
2319
      p += bufLen;
998,236,851✔
2320
      if (TSDB_CODE_SUCCESS != code) {
998,236,851✔
2321
        return code;
×
2322
      }
2323
    }
2324
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
1,637,056✔
2325
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
1,637,056✔
2326
  }
2327
  return 0;
121,855,396✔
2328
}
2329

2330
int32_t getVersion1BlockMetaSize(const char* p, int32_t numOfCols) {
379,774✔
2331
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) * 3 + sizeof(uint64_t) +
759,548✔
2332
         numOfCols * (sizeof(int8_t) + sizeof(int32_t));
379,774✔
2333
}
2334

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

2339
  int32_t numOfRows = pResultInfo->numOfRows;
189,887✔
2340
  int32_t numOfCols = pResultInfo->numOfCols;
189,887✔
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);
189,887✔
2345
  if (numOfCols != cols) {
189,887✔
2346
    tscError("estimateJsonLen error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2347
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2348
  }
2349

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

2354
  char* pStart = p + len;
189,887✔
2355
  for (int32_t i = 0; i < numOfCols; ++i) {
825,902✔
2356
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
636,015✔
2357

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

2364
      int32_t estimateColLen = 0;
225,278✔
2365
      for (int32_t j = 0; j < numOfRows; ++j) {
1,181,917✔
2366
        if (offset[j] == -1) {
956,639✔
2367
          continue;
47,970✔
2368
        }
2369
        char* data = offset[j] + pStart;
908,669✔
2370

2371
        int32_t jsonInnerType = *data;
908,669✔
2372
        char*   jsonInnerData = data + CHAR_BYTES;
908,669✔
2373
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
908,669✔
2374
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
12,744✔
2375
        } else if (tTagIsJson(data)) {
895,925✔
2376
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
209,510✔
2377
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
686,415✔
2378
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
638,625✔
2379
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
47,790✔
2380
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
35,046✔
2381
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
12,744✔
2382
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
12,744✔
2383
        } else if (IS_STR_DATA_BLOB(jsonInnerType)) {
×
2384
          estimateColLen += (BLOBSTR_HEADER_SIZE + 32);
×
2385
        } else {
2386
          tscError("estimateJsonLen error: invalid type:%d", jsonInnerType);
×
2387
          return -1;
×
2388
        }
2389
      }
2390
      len += TMAX(colLen, estimateColLen);
225,278✔
2391
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
410,737✔
2392
      int32_t lenTmp = numOfRows * sizeof(int32_t);
53,100✔
2393
      len += (lenTmp + colLen);
53,100✔
2394
      pStart += lenTmp;
53,100✔
2395
    } else {
2396
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
357,637✔
2397
      len += (lenTmp + colLen);
357,637✔
2398
      pStart += lenTmp;
357,637✔
2399
    }
2400
    pStart += colLen;
636,015✔
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);
189,887✔
2406
  return len;
189,887✔
2407
}
2408

2409
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
123,152,704✔
2410
  int32_t numOfRows = pResultInfo->numOfRows;
123,152,704✔
2411
  int32_t numOfCols = pResultInfo->numOfCols;
123,153,048✔
2412
  bool    needConvert = false;
123,153,078✔
2413
  for (int32_t i = 0; i < numOfCols; ++i) {
702,719,948✔
2414
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
579,755,773✔
2415
      needConvert = true;
189,887✔
2416
      break;
189,887✔
2417
    }
2418
  }
2419

2420
  if (!needConvert) {
123,154,062✔
2421
    return TSDB_CODE_SUCCESS;
122,964,175✔
2422
  }
2423

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

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

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

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

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

2449
  p += len;
189,887✔
2450
  p1 += len;
189,887✔
2451
  totalLen += len;
189,887✔
2452

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

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

2479
      len = 0;
225,278✔
2480
      for (int32_t j = 0; j < numOfRows; ++j) {
1,181,917✔
2481
        if (offset[j] == -1) {
956,639✔
2482
          continue;
47,970✔
2483
        }
2484
        char* data = offset[j] + pStart;
908,669✔
2485

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

2528
        offset1[j] = len;
908,669✔
2529
        (void)memcpy(pStart1 + len, dst, varDataTLen(dst));
908,669✔
2530
        len += varDataTLen(dst);
908,669✔
2531
      }
2532
      colLen1 = len;
225,278✔
2533
      totalLen += colLen1;
225,278✔
2534
      colLength1[i] = (blockVersion == BLOCK_VERSION_1) ? htonl(len) : len;
225,278✔
2535
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
410,737✔
2536
      len = numOfRows * sizeof(int32_t);
53,100✔
2537
      (void)memcpy(pStart1, pStart, len);
53,100✔
2538
      pStart += len;
53,100✔
2539
      pStart1 += len;
53,100✔
2540
      totalLen += len;
53,100✔
2541
      totalLen += colLen;
53,100✔
2542
      (void)memcpy(pStart1, pStart, colLen);
53,100✔
2543
    } else {
2544
      len = BitmapLen(pResultInfo->numOfRows);
357,637✔
2545
      (void)memcpy(pStart1, pStart, len);
357,637✔
2546
      pStart += len;
357,637✔
2547
      pStart1 += len;
357,637✔
2548
      totalLen += len;
357,637✔
2549
      totalLen += colLen;
357,637✔
2550
      (void)memcpy(pStart1, pStart, colLen);
357,637✔
2551
    }
2552
    pStart += colLen;
636,015✔
2553
    pStart1 += colLen1;
636,015✔
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);
189,887✔
2560

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

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

2573
  if (pResultInfo->numOfRows == 0) {
130,200,242✔
2574
    return TSDB_CODE_SUCCESS;
7,046,776✔
2575
  }
2576

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

2582
  int32_t code = doPrepareResPtr(pResultInfo);
123,152,895✔
2583
  if (code != TSDB_CODE_SUCCESS) {
123,152,628✔
2584
    return code;
×
2585
  }
2586
  code = doConvertJson(pResultInfo);
123,152,628✔
2587
  if (code != TSDB_CODE_SUCCESS) {
123,152,520✔
2588
    return code;
×
2589
  }
2590

2591
  char* p = (char*)pResultInfo->pData;
123,152,520✔
2592

2593
  // version:
2594
  int32_t blockVersion = *(int32_t*)p;
123,152,434✔
2595
  p += sizeof(int32_t);
123,152,520✔
2596

2597
  int32_t dataLen = *(int32_t*)p;
123,152,852✔
2598
  p += sizeof(int32_t);
123,152,852✔
2599

2600
  int32_t rows = *(int32_t*)p;
123,153,086✔
2601
  p += sizeof(int32_t);
123,153,508✔
2602

2603
  int32_t cols = *(int32_t*)p;
123,153,152✔
2604
  p += sizeof(int32_t);
123,153,852✔
2605

2606
  if (rows != pResultInfo->numOfRows || cols != pResultInfo->numOfCols) {
123,153,208✔
2607
    tscError("setResultDataPtr paras error:rows;%d numOfRows:%" PRId64 " cols:%d numOfCols:%d", rows,
140✔
2608
             pResultInfo->numOfRows, cols, pResultInfo->numOfCols);
2609
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2610
  }
2611

2612
  int32_t hasColumnSeg = *(int32_t*)p;
123,153,270✔
2613
  p += sizeof(int32_t);
123,153,258✔
2614

2615
  uint64_t groupId = taosGetUInt64Aligned((uint64_t*)p);
123,153,766✔
2616
  p += sizeof(uint64_t);
123,153,766✔
2617

2618
  // check fields
2619
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
702,958,390✔
2620
    int8_t type = *(int8_t*)p;
579,806,140✔
2621
    p += sizeof(int8_t);
579,804,566✔
2622

2623
    int32_t bytes = *(int32_t*)p;
579,804,542✔
2624
    p += sizeof(int32_t);
579,805,140✔
2625

2626
    if (IS_DECIMAL_TYPE(type) && pResultInfo->fields[i].precision == 0) {
579,804,238✔
2627
      extractDecimalTypeInfoFromBytes(&bytes, &pResultInfo->fields[i].precision, &pResultInfo->fields[i].scale);
310,664✔
2628
    }
2629
  }
2630

2631
  int32_t* colLength = (int32_t*)p;
123,153,860✔
2632
  p += sizeof(int32_t) * pResultInfo->numOfCols;
123,153,860✔
2633

2634
  char* pStart = p;
123,154,110✔
2635
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
702,960,358✔
2636
    if ((pStart - pResultInfo->pData) >= dataLen) {
579,807,182✔
2637
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2638
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2639
    }
2640
    if (blockVersion == BLOCK_VERSION_1) {
579,804,244✔
2641
      colLength[i] = htonl(colLength[i]);
434,689,060✔
2642
    }
2643
    if (colLength[i] >= dataLen) {
579,803,095✔
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)) {
579,805,118✔
2648
      tscError("invalid type %d", pResultInfo->fields[i].type);
2,846✔
2649
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2650
    }
2651
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
579,805,562✔
2652
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
148,130,409✔
2653
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
148,128,861✔
2654
    } else {
2655
      pResultInfo->pCol[i].nullbitmap = pStart;
431,678,359✔
2656
      pStart += BitmapLen(pResultInfo->numOfRows);
431,680,259✔
2657
    }
2658

2659
    pResultInfo->pCol[i].pData = pStart;
579,809,438✔
2660
    pResultInfo->length[i] =
1,159,615,298✔
2661
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
1,099,760,757✔
2662
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
579,807,632✔
2663

2664
    pStart += colLength[i];
579,807,160✔
2665
  }
2666

2667
  p = pStart;
123,154,298✔
2668
  // bool blankFill = *(bool*)p;
2669
  p += sizeof(bool);
123,154,298✔
2670
  int32_t offset = p - pResultInfo->pData;
123,154,298✔
2671
  if (offset > dataLen) {
123,153,054✔
2672
    tscError("invalid offset %d, dataLen %d", offset, dataLen);
×
2673
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2674
  }
2675

2676
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
2677
  if (convertUcs4) {
123,153,054✔
2678
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
121,858,156✔
2679
  }
2680
#endif
2681
  if (TSDB_CODE_SUCCESS == code && convertForDecimal) {
123,153,652✔
2682
    code = convertDecimalType(pResultInfo);
121,858,602✔
2683
  }
2684
  return code;
123,150,774✔
2685
}
2686

2687
char* getDbOfConnection(STscObj* pObj) {
625,134,393✔
2688
  terrno = TSDB_CODE_SUCCESS;
625,134,393✔
2689
  char* p = NULL;
625,143,649✔
2690
  (void)taosThreadMutexLock(&pObj->mutex);
625,143,649✔
2691
  size_t len = strlen(pObj->db);
625,150,643✔
2692
  if (len > 0) {
625,151,666✔
2693
    p = taosStrndup(pObj->db, tListLen(pObj->db));
559,966,792✔
2694
    if (p == NULL) {
559,964,690✔
2695
      tscError("failed to taosStrndup db name");
×
2696
    }
2697
  }
2698

2699
  (void)taosThreadMutexUnlock(&pObj->mutex);
625,149,564✔
2700
  return p;
625,133,793✔
2701
}
2702

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

2709
  (void)taosThreadMutexLock(&pTscObj->mutex);
2,943,211✔
2710
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
2,942,377✔
2711
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
2,942,313✔
2712
}
2713

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

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

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

2731
  taosMemoryFreeClear(pResultInfo->pRspMsg);
98,018,479✔
2732
  pResultInfo->pRspMsg = (const char*)pRsp;
98,018,028✔
2733
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
98,018,011✔
2734
  pResultInfo->current = 0;
98,018,233✔
2735
  pResultInfo->completed = (pRsp->completed == 1);
98,018,233✔
2736
  pResultInfo->precision = pRsp->precision;
98,018,233✔
2737

2738
  // decompress data if needed
2739
  int32_t payloadLen = htonl(pRsp->payloadLen);
98,018,233✔
2740

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

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

2763
  if (payloadLen > 0) {
98,018,007✔
2764
    int32_t compLen = *(int32_t*)pRsp->data;
90,971,841✔
2765
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
90,972,309✔
2766

2767
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
90,971,841✔
2768

2769
    if (pRsp->compressed && compLen < rawLen) {
90,971,841✔
2770
      int32_t len = tsDecompressString(pStart, compLen, 1, pResultInfo->decompBuf, rawLen, ONE_STAGE_COMP, NULL, 0);
×
2771
      if (len < 0) {
×
2772
        tscError("tsDecompressString failed");
×
2773
        return terrno ? terrno : TSDB_CODE_FAILED;
×
2774
      }
2775
      if (len != rawLen) {
×
2776
        tscError("tsDecompressString failed, len:%d != rawLen:%d", len, rawLen);
×
2777
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2778
      }
2779
      pResultInfo->pData = pResultInfo->decompBuf;
×
2780
      pResultInfo->payloadLen = rawLen;
×
2781
    } else {
2782
      pResultInfo->pData = pStart;
90,971,841✔
2783
      pResultInfo->payloadLen = htonl(pRsp->compLen);
90,972,309✔
2784
      if (pRsp->compLen != pRsp->payloadLen) {
90,972,087✔
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;
98,018,229✔
2793

2794
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
98,018,229✔
2795
  return code;
98,016,371✔
2796
}
2797

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

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

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

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

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

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

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

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

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

2860
  if (rpcRsp.code != 0 || rpcRsp.contLen <= 0 || rpcRsp.pCont == NULL) {
886✔
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) {
758✔
2866
    tscError("failed to parse server status rsp since %s", terrstr());
×
2867
    goto _OVER;
×
2868
  }
2869

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

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

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

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

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

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

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

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

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

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

2941
  return TSDB_CODE_SUCCESS;
1,226✔
2942
}
2943

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

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

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

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

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

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

2972
      break;
1,226✔
2973
    }
2974

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

2985
      continue;
×
2986
    }
2987

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

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

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

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

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

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

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

3046
    goto _return;
×
3047
  }
3048

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

3063
  taosHashCleanup(pHash);
1,226✔
3064

3065
  return TSDB_CODE_SUCCESS;
1,226✔
3066

3067
_return:
×
3068

3069
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
3070

3071
  pIter = taosHashIterate(pHash, NULL);
×
3072
  while (pIter) {
×
3073
    STablesReq* pDb = (STablesReq*)pIter;
×
3074
    taosArrayDestroy(pDb->pTables);
×
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,226✔
3084
  SSyncQueryParam* pParam = param;
1,226✔
3085
  pParam->pRequest->code = code;
1,226✔
3086

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

3092
void syncQueryFn(void* param, void* res, int32_t code) {
616,863,594✔
3093
  SSyncQueryParam* pParam = param;
616,863,594✔
3094
  pParam->pRequest = res;
616,863,594✔
3095

3096
  if (pParam->pRequest) {
616,866,722✔
3097
    pParam->pRequest->code = code;
616,837,711✔
3098
    clientOperateReport(pParam->pRequest);
616,850,641✔
3099
  }
3100

3101
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
616,850,478✔
3102
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3103
  }
3104
}
616,872,180✔
3105

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

3114
    return;
×
3115
  }
3116

3117
  size_t sqlLen = strlen(sql);
616,395,976✔
3118
  if (sqlLen > (size_t)tsMaxSQLLength) {
616,395,976✔
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);
616,394,740✔
3126

3127
  SRequestObj* pRequest = NULL;
616,395,486✔
3128
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
616,400,191✔
3129
  if (code != TSDB_CODE_SUCCESS) {
616,393,748✔
3130
    terrno = code;
×
3131
    fp(param, NULL, terrno);
×
3132
    return;
×
3133
  }
3134

3135
  pRequest->source = source;
616,393,748✔
3136
  pRequest->body.queryFp = fp;
616,400,095✔
3137
  doAsyncQuery(pRequest, false);
616,398,344✔
3138
}
3139

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

3148
    return;
×
3149
  }
3150

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

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

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

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

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

3179
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
616,292,416✔
3180
  if (NULL == param) {
616,299,922✔
3181
    return NULL;
×
3182
  }
3183
  int32_t code = tsem_init(&param->sem, 0, 0);
616,299,922✔
3184
  if (TSDB_CODE_SUCCESS != code) {
616,292,865✔
3185
    taosMemoryFree(param);
×
3186
    return NULL;
×
3187
  }
3188

3189
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
616,292,865✔
3190
  code = tsem_wait(&param->sem);
616,290,755✔
3191
  if (TSDB_CODE_SUCCESS != code) {
616,307,192✔
3192
    taosMemoryFree(param);
×
3193
    return NULL;
×
3194
  }
3195
  code = tsem_destroy(&param->sem);
616,307,192✔
3196
  if (TSDB_CODE_SUCCESS != code) {
616,307,030✔
3197
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3198
  }
3199

3200
  SRequestObj* pRequest = NULL;
616,307,030✔
3201
  if (param->pRequest != NULL) {
616,307,030✔
3202
    param->pRequest->syncQuery = true;
616,306,273✔
3203
    pRequest = param->pRequest;
616,307,577✔
3204
    param->pRequest->inCallback = false;
616,306,256✔
3205
  }
3206
  taosMemoryFree(param);
616,305,028✔
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;
616,304,870✔
3212
}
3213

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

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

3230
  taosAsyncQueryImplWithReqid(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, reqid);
6,806✔
3231
  code = tsem_wait(&param->sem);
6,806✔
3232
  if (TSDB_CODE_SUCCESS != code) {
6,806✔
3233
    taosMemoryFree(param);
×
3234
    return NULL;
×
3235
  }
3236
  SRequestObj* pRequest = NULL;
6,806✔
3237
  if (param->pRequest != NULL) {
6,806✔
3238
    param->pRequest->syncQuery = true;
6,806✔
3239
    pRequest = param->pRequest;
6,806✔
3240
  }
3241
  taosMemoryFree(param);
6,806✔
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,806✔
3247
}
3248

3249
static void fetchCallback(void* pResult, void* param, int32_t code) {
95,175,610✔
3250
  SRequestObj* pRequest = (SRequestObj*)param;
95,175,610✔
3251

3252
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
95,175,610✔
3253

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

3257
  pResultInfo->pData = pResult;
95,175,856✔
3258
  pResultInfo->numOfRows = 0;
95,176,078✔
3259

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

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

3273
  pRequest->code = setQueryResultFromRsp(pResultInfo, (const SRetrieveTableRsp*)pResultInfo->pData,
102,145,338✔
3274
                                         pResultInfo->convertUcs4, pRequest->stmtBindVersion > 0);
95,175,582✔
3275
  if (pRequest->code != TSDB_CODE_SUCCESS) {
95,174,442✔
3276
    pResultInfo->numOfRows = 0;
324✔
3277
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self,
324✔
3278
             tstrerror(pRequest->code), pRequest->requestId);
3279
  } else {
3280
    tscDebug(
95,174,780✔
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;
95,174,780✔
3285
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
95,175,258✔
3286
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
95,175,730✔
3287
  }
3288

3289
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
95,175,856✔
3290
}
3291

3292
void taosAsyncFetchImpl(SRequestObj* pRequest, __taos_async_fn_t fp, void* param) {
98,003,921✔
3293
  pRequest->body.fetchFp = fp;
98,003,921✔
3294
  ((SSyncQueryParam*)pRequest->body.interParam)->userParam = param;
98,003,921✔
3295

3296
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
98,004,171✔
3297

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

3305
  // all data has returned to App already, no need to try again
3306
  if (pResultInfo->completed) {
98,004,171✔
3307
    // it is a local executed query, no need to do async fetch
3308
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
2,827,871✔
3309
      if (pResultInfo->localResultFetched) {
1,509,900✔
3310
        pResultInfo->numOfRows = 0;
754,950✔
3311
        pResultInfo->current = 0;
754,950✔
3312
      } else {
3313
        pResultInfo->localResultFetched = true;
754,950✔
3314
      }
3315
    } else {
3316
      pResultInfo->numOfRows = 0;
1,317,971✔
3317
    }
3318

3319
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
2,827,871✔
3320
    return;
2,827,871✔
3321
  }
3322

3323
  SSchedulerReq req = {
95,176,300✔
3324
      .syncReq = false,
3325
      .fetchFp = fetchCallback,
3326
      .cbParam = pRequest,
3327
  };
3328

3329
  int32_t code = schedulerFetchRows(pRequest->body.queryJob, &req);
95,176,300✔
3330
  if (TSDB_CODE_SUCCESS != code) {
95,176,300✔
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) {
616,879,527✔
3337
  pRequest->inCallback = true;
616,879,527✔
3338
  int64_t this = pRequest->self;
616,887,488✔
3339
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
616,856,667✔
3340
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
80,550✔
3341
    code = TSDB_CODE_SUCCESS;
×
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,
616,856,667✔
3346
           pRequest);
3347

3348
  if (pRequest->body.queryFp != NULL) {
616,857,871✔
3349
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
616,882,680✔
3350
  }
3351

3352
  SRequestObj* pReq = acquireRequest(this);
616,894,002✔
3353
  if (pReq != NULL) {
616,894,766✔
3354
    pReq->inCallback = false;
616,028,800✔
3355
    (void)releaseRequest(this);
616,029,944✔
3356
  }
3357
}
616,896,485✔
3358

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