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

taosdata / TDengine / #3630

06 Mar 2025 11:35AM UTC coverage: 63.629% (-0.06%) from 63.692%
#3630

push

travis-ci

web-flow
Merge pull request #30042 from taosdata/doc/internal

docs: format

149060 of 300532 branches covered (49.6%)

Branch coverage included in aggregate %.

233739 of 301077 relevant lines covered (77.63%)

17473135.72 hits per line

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

63.27
/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 "scheduler.h"
22
#include "tdatablock.h"
23
#include "tdataformat.h"
24
#include "tdef.h"
25
#include "tglobal.h"
26
#include "tmsgtype.h"
27
#include "tpagedbuf.h"
28
#include "tref.h"
29
#include "tsched.h"
30
#include "tversion.h"
31
static int32_t initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet);
32
static int32_t buildConnectMsg(SRequestObj* pRequest, SMsgSendInfo** pMsgSendInfo);
33

34
void setQueryRequest(int64_t rId) {
1,457,304✔
35
  SRequestObj* pReq = acquireRequest(rId);
1,457,304✔
36
  if (pReq != NULL) {
1,457,311✔
37
    pReq->isQuery = true;
1,435,709✔
38
    (void)releaseRequest(rId);
1,435,709✔
39
  }
40
}
1,457,301✔
41

42
static bool stringLengthCheck(const char* str, size_t maxsize) {
30,982✔
43
  if (str == NULL) {
30,982!
44
    return false;
×
45
  }
46

47
  size_t len = strlen(str);
30,982✔
48
  if (len <= 0 || len > maxsize) {
30,982!
49
    return false;
×
50
  }
51

52
  return true;
30,986✔
53
}
54

55
static bool validateUserName(const char* user) { return stringLengthCheck(user, TSDB_USER_LEN - 1); }
15,094✔
56

57
static bool validatePassword(const char* passwd) { return stringLengthCheck(passwd, TSDB_PASSWORD_MAX_LEN); }
15,093✔
58

59
static bool validateDbName(const char* db) { return stringLengthCheck(db, TSDB_DB_NAME_LEN - 1); }
793✔
60

61
static char* getClusterKey(const char* user, const char* auth, const char* ip, int32_t port) {
15,098✔
62
  char key[512] = {0};
15,098✔
63
  (void)snprintf(key, sizeof(key), "%s:%s:%s:%d", user, auth, ip, port);
15,098✔
64
  return taosStrdup(key);
15,098!
65
}
66

67
bool chkRequestKilled(void* param) {
12,742,688✔
68
  bool         killed = false;
12,742,688✔
69
  SRequestObj* pRequest = acquireRequest((int64_t)param);
12,742,688✔
70
  if (NULL == pRequest || pRequest->killed) {
12,747,947!
71
    killed = true;
×
72
  }
73

74
  (void)releaseRequest((int64_t)param);
12,747,947✔
75

76
  return killed;
12,746,531✔
77
}
78

79
void cleanupAppInfo() {
3,208✔
80
  taosHashCleanup(appInfo.pInstMap);
3,208✔
81
  taosHashCleanup(appInfo.pInstMapByClusterId);
3,208✔
82
}
3,208✔
83

84
static int32_t taosConnectImpl(const char* user, const char* auth, const char* db, __taos_async_fn_t fp, void* param,
85
                               SAppInstInfo* pAppInfo, int connType, STscObj** pTscObj);
86

87
int32_t taos_connect_internal(const char* ip, const char* user, const char* pass, const char* auth, const char* db,
15,095✔
88
                              uint16_t port, int connType, STscObj** pObj) {
89
  TSC_ERR_RET(taos_init());
15,095!
90
  if (!validateUserName(user)) {
15,098!
91
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
92
  }
93

94
  char localDb[TSDB_DB_NAME_LEN] = {0};
15,097✔
95
  if (db != NULL && strlen(db) > 0) {
15,097✔
96
    if (!validateDbName(db)) {
793!
97
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_DB_LENGTH);
×
98
    }
99

100
    tstrncpy(localDb, db, sizeof(localDb));
793✔
101
    (void)strdequote(localDb);
793✔
102
  }
103

104
  char secretEncrypt[TSDB_PASSWORD_LEN + 1] = {0};
15,097✔
105
  if (auth == NULL) {
15,097✔
106
    if (!validatePassword(pass)) {
15,093!
107
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_PASS_LENGTH);
×
108
    }
109

110
    taosEncryptPass_c((uint8_t*)pass, strlen(pass), secretEncrypt);
15,097✔
111
  } else {
112
    tstrncpy(secretEncrypt, auth, tListLen(secretEncrypt));
4✔
113
  }
114

115
  SCorEpSet epSet = {0};
15,096✔
116
  if (ip) {
15,096✔
117
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
11,657✔
118
  } else {
119
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
3,439!
120
  }
121

122
  if (port) {
15,098✔
123
    epSet.epSet.eps[0].port = port;
8,813✔
124
    epSet.epSet.eps[1].port = port;
8,813✔
125
  }
126

127
  char* key = getClusterKey(user, secretEncrypt, ip, port);
15,098✔
128
  if (NULL == key) {
15,098!
129
    TSC_ERR_RET(terrno);
×
130
  }
131
  tscInfo("connecting to server, numOfEps:%d inUse:%d user:%s db:%s key:%s", epSet.epSet.numOfEps, epSet.epSet.inUse,
15,098!
132
          user, db, key);
133
  for (int32_t i = 0; i < epSet.epSet.numOfEps; ++i) {
33,641✔
134
    tscInfo("ep:%d, %s:%u", i, epSet.epSet.eps[i].fqdn, epSet.epSet.eps[i].port);
18,543!
135
  }
136

137
  SAppInstInfo** pInst = NULL;
15,098✔
138
  int32_t        code = taosThreadMutexLock(&appInfo.mutex);
15,098✔
139
  if (TSDB_CODE_SUCCESS != code) {
15,098!
140
    tscError("failed to lock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
141
    TSC_ERR_RET(code);
×
142
  }
143

144
  pInst = taosHashGet(appInfo.pInstMap, key, strlen(key));
15,098✔
145
  SAppInstInfo* p = NULL;
15,098✔
146
  if (pInst == NULL) {
15,098✔
147
    p = taosMemoryCalloc(1, sizeof(struct SAppInstInfo));
3,422!
148
    if (NULL == p) {
3,422!
149
      TSC_ERR_JRET(terrno);
×
150
    }
151
    p->mgmtEp = epSet;
3,422✔
152
    code = taosThreadMutexInit(&p->qnodeMutex, NULL);
3,422✔
153
    if (TSDB_CODE_SUCCESS != code) {
3,422!
154
      taosMemoryFree(p);
×
155
      TSC_ERR_JRET(code);
×
156
    }
157
    code = openTransporter(user, secretEncrypt, tsNumOfCores / 2, &p->pTransporter);
3,422✔
158
    if (TSDB_CODE_SUCCESS != code) {
3,422!
159
      taosMemoryFree(p);
×
160
      TSC_ERR_JRET(code);
×
161
    }
162
    code = appHbMgrInit(p, key, &p->pAppHbMgr);
3,422✔
163
    if (TSDB_CODE_SUCCESS != code) {
3,422!
164
      destroyAppInst(&p);
×
165
      TSC_ERR_JRET(code);
×
166
    }
167
    code = taosHashPut(appInfo.pInstMap, key, strlen(key), &p, POINTER_BYTES);
3,422✔
168
    if (TSDB_CODE_SUCCESS != code) {
3,422!
169
      destroyAppInst(&p);
×
170
      TSC_ERR_JRET(code);
×
171
    }
172
    p->instKey = key;
3,422✔
173
    key = NULL;
3,422✔
174
    tscInfo("new app inst mgr:%p, user:%s, ip:%s, port:%d", p, user, epSet.epSet.eps[0].fqdn, epSet.epSet.eps[0].port);
3,422!
175

176
    pInst = &p;
3,422✔
177
  } else {
178
    if (NULL == *pInst || NULL == (*pInst)->pAppHbMgr) {
11,676!
179
      tscError("*pInst:%p, pAppHgMgr:%p", *pInst, (*pInst) ? (*pInst)->pAppHbMgr : NULL);
×
180
      TSC_ERR_JRET(TSDB_CODE_TSC_INTERNAL_ERROR);
×
181
    }
182
    // reset to 0 in case of conn with duplicated user key but its user has ever been dropped.
183
    atomic_store_8(&(*pInst)->pAppHbMgr->connHbFlag, 0);
11,676✔
184
  }
185

186
_return:
15,098✔
187

188
  if (TSDB_CODE_SUCCESS != code) {
15,098!
189
    (void)taosThreadMutexUnlock(&appInfo.mutex);
×
190
    taosMemoryFreeClear(key);
×
191
    return code;
×
192
  } else {
193
    code = taosThreadMutexUnlock(&appInfo.mutex);
15,098✔
194
    taosMemoryFreeClear(key);
15,098!
195
    if (TSDB_CODE_SUCCESS != code) {
15,098!
196
      tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
197
      return code;
×
198
    }
199
    return taosConnectImpl(user, &secretEncrypt[0], localDb, NULL, NULL, *pInst, connType, pObj);
15,098✔
200
  }
201
}
202

203
// SAppInstInfo* getAppInstInfo(const char* clusterKey) {
204
//   SAppInstInfo** ppAppInstInfo = taosHashGet(appInfo.pInstMap, clusterKey, strlen(clusterKey));
205
//   if (ppAppInstInfo != NULL && *ppAppInstInfo != NULL) {
206
//     return *ppAppInstInfo;
207
//   } else {
208
//     return NULL;
209
//   }
210
// }
211

212
void freeQueryParam(SSyncQueryParam* param) {
906✔
213
  if (param == NULL) return;
906!
214
  if (TSDB_CODE_SUCCESS != tsem_destroy(&param->sem)) {
906!
215
    tscError("failed to destroy semaphore in freeQueryParam");
×
216
  }
217
  taosMemoryFree(param);
906!
218
}
219

220
int32_t buildRequest(uint64_t connId, const char* sql, int sqlLen, void* param, bool validateSql,
3,298,623✔
221
                     SRequestObj** pRequest, int64_t reqid) {
222
  int32_t code = createRequest(connId, TSDB_SQL_SELECT, reqid, pRequest);
3,298,623✔
223
  if (TSDB_CODE_SUCCESS != code) {
3,298,782!
224
    tscError("failed to malloc sqlObj, %s", sql);
×
225
    return code;
×
226
  }
227

228
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
3,298,782!
229
  if ((*pRequest)->sqlstr == NULL) {
3,298,850!
230
    tscError("req:0x%" PRIx64 ", failed to prepare sql string buffer, %s", (*pRequest)->self, sql);
×
231
    destroyRequest(*pRequest);
×
232
    *pRequest = NULL;
×
233
    return terrno;
×
234
  }
235

236
  (void)strntolower((*pRequest)->sqlstr, sql, (int32_t)sqlLen);
3,298,850✔
237
  (*pRequest)->sqlstr[sqlLen] = 0;
3,296,020✔
238
  (*pRequest)->sqlLen = sqlLen;
3,296,020✔
239
  (*pRequest)->validateOnly = validateSql;
3,296,020✔
240
  (*pRequest)->isStmtBind = false;
3,296,020✔
241

242
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
3,296,020✔
243

244
  STscObj* pTscObj = (*pRequest)->pTscObj;
3,296,020✔
245
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
3,296,020✔
246
                             sizeof((*pRequest)->self));
247
  if (err) {
3,298,864!
248
    tscError("req:0x%" PRId64 ", failed to add to request container, QID:0x%" PRIx64 ", connObj:%" PRId64 ", %s",
×
249
             (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
250
    destroyRequest(*pRequest);
×
251
    *pRequest = NULL;
×
252
    return terrno;
×
253
  }
254

255
  (*pRequest)->allocatorRefId = -1;
3,298,864✔
256
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
3,298,864✔
257
    if (TSDB_CODE_SUCCESS !=
1,188,620!
258
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
1,188,613✔
259
      tscError("req:0x%" PRId64 ", failed to create node allocator, QID:0x%" PRIx64 ", connObj:%" PRId64 ", %s", (*pRequest)->self,
×
260
               (*pRequest)->requestId, pTscObj->id, sql);
261
      destroyRequest(*pRequest);
×
262
      *pRequest = NULL;
×
263
      return terrno;
×
264
    }
265
  }
266

267
  tscDebugL("req:0x%" PRIx64 ", QID:0x%" PRIx64 ", build request", (*pRequest)->self, (*pRequest)->requestId);
3,298,737✔
268
  return TSDB_CODE_SUCCESS;
3,298,646✔
269
}
270

271
int32_t buildPreviousRequest(SRequestObj* pRequest, const char* sql, SRequestObj** pNewRequest) {
525✔
272
  int32_t code =
273
      buildRequest(pRequest->pTscObj->id, sql, strlen(sql), pRequest, pRequest->validateOnly, pNewRequest, 0);
525✔
274
  if (TSDB_CODE_SUCCESS == code) {
525!
275
    pRequest->relation.prevRefId = (*pNewRequest)->self;
525✔
276
    (*pNewRequest)->relation.nextRefId = pRequest->self;
525✔
277
    (*pNewRequest)->relation.userRefId = pRequest->self;
525✔
278
    (*pNewRequest)->isSubReq = true;
525✔
279
  }
280
  return code;
525✔
281
}
282

283
int32_t parseSql(SRequestObj* pRequest, bool topicQuery, SQuery** pQuery, SStmtCallback* pStmtCb) {
4,026✔
284
  STscObj* pTscObj = pRequest->pTscObj;
4,026✔
285

286
  SParseContext cxt = {.requestId = pRequest->requestId,
4,026✔
287
                       .requestRid = pRequest->self,
4,026✔
288
                       .acctId = pTscObj->acctId,
4,026✔
289
                       .db = pRequest->pDb,
4,026✔
290
                       .topicQuery = topicQuery,
291
                       .pSql = pRequest->sqlstr,
4,026✔
292
                       .sqlLen = pRequest->sqlLen,
4,026✔
293
                       .pMsg = pRequest->msgBuf,
4,026✔
294
                       .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
295
                       .pTransporter = pTscObj->pAppInfo->pTransporter,
4,026✔
296
                       .pStmtCb = pStmtCb,
297
                       .pUser = pTscObj->user,
4,026✔
298
                       .isSuperUser = (0 == strcmp(pTscObj->user, TSDB_DEFAULT_USER)),
4,026✔
299
                       .enableSysInfo = pTscObj->sysInfo,
4,026✔
300
                       .svrVer = pTscObj->sVer,
4,026✔
301
                       .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes),
4,026✔
302
                       .isStmtBind = pRequest->isStmtBind,
4,026✔
303
                       .setQueryFp = setQueryRequest,
304
                       .timezone = pTscObj->optionInfo.timezone,
4,026✔
305
                       .charsetCxt = pTscObj->optionInfo.charsetCxt,};
4,026✔
306

307
  cxt.mgmtEpSet = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
4,026✔
308
  int32_t code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &cxt.pCatalog);
4,030✔
309
  if (code != TSDB_CODE_SUCCESS) {
4,030!
310
    return code;
×
311
  }
312

313
  code = qParseSql(&cxt, pQuery);
4,030✔
314
  if (TSDB_CODE_SUCCESS == code) {
4,023✔
315
    if ((*pQuery)->haveResultSet) {
3,989!
316
      code = setResSchemaInfo(&pRequest->body.resInfo, (*pQuery)->pResSchema, (*pQuery)->numOfResCols);
×
317
      setResPrecision(&pRequest->body.resInfo, (*pQuery)->precision);
×
318
    }
319
  }
320

321
  if (TSDB_CODE_SUCCESS == code || NEED_CLIENT_HANDLE_ERROR(code)) {
4,023!
322
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
4,006✔
323
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
4,006✔
324
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
4,006✔
325
  }
326

327
  taosArrayDestroy(cxt.pTableMetaPos);
4,023✔
328
  taosArrayDestroy(cxt.pTableVgroupPos);
4,027✔
329

330
  return code;
4,027✔
331
}
332

333
int32_t execLocalCmd(SRequestObj* pRequest, SQuery* pQuery) {
×
334
  SRetrieveTableRsp* pRsp = NULL;
×
335
  int8_t             biMode = atomic_load_8(&pRequest->pTscObj->biMode);
×
336
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp, biMode, pRequest->pTscObj->optionInfo.charsetCxt);
×
337
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
×
338
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4);
×
339
  }
340

341
  return code;
×
342
}
343

344
int32_t execDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
670✔
345
  // drop table if exists not_exists_table
346
  if (NULL == pQuery->pCmdMsg) {
670!
347
    return TSDB_CODE_SUCCESS;
×
348
  }
349

350
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
670✔
351
  pRequest->type = pMsgInfo->msgType;
670✔
352
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
670✔
353
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
670✔
354

355
  STscObj*      pTscObj = pRequest->pTscObj;
670✔
356
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
670✔
357

358
  // int64_t transporterId = 0;
359
  TSC_ERR_RET(asyncSendMsgToServer(pTscObj->pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg));
670!
360
  TSC_ERR_RET(tsem_wait(&pRequest->body.rspSem));
671!
361
  return TSDB_CODE_SUCCESS;
671✔
362
}
363

364
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
5,942,944✔
365

366
void asyncExecLocalCmd(SRequestObj* pRequest, SQuery* pQuery) {
118,400✔
367
  SRetrieveTableRsp* pRsp = NULL;
118,400✔
368
  if (pRequest->validateOnly) {
118,400✔
369
    doRequestCallback(pRequest, 0);
27✔
370
    return;
27✔
371
  }
372

373
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp,
118,373✔
374
                              atomic_load_8(&pRequest->pTscObj->biMode), pRequest->pTscObj->optionInfo.charsetCxt);
118,373✔
375
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
118,373✔
376
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4);
96,148✔
377
  }
378

379
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
118,373✔
380
  pRequest->code = code;
118,373✔
381

382
  if (pRequest->code != TSDB_CODE_SUCCESS) {
118,373✔
383
    pResultInfo->numOfRows = 0;
3✔
384
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
3!
385
             pRequest->requestId);
386
  } else {
387
    tscDebug("req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
118,370✔
388
             pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed,
389
             pRequest->requestId);
390
  }
391

392
  doRequestCallback(pRequest, code);
118,373✔
393
}
394

395
int32_t asyncExecDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
32,701✔
396
  if (pRequest->validateOnly) {
32,701!
397
    doRequestCallback(pRequest, 0);
×
398
    return TSDB_CODE_SUCCESS;
×
399
  }
400

401
  // drop table if exists not_exists_table
402
  if (NULL == pQuery->pCmdMsg) {
32,701✔
403
    doRequestCallback(pRequest, 0);
1✔
404
    return TSDB_CODE_SUCCESS;
1✔
405
  }
406

407
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
32,700✔
408
  pRequest->type = pMsgInfo->msgType;
32,700✔
409
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
32,700✔
410
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
32,700✔
411

412
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
32,700✔
413
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
32,700✔
414

415
  int32_t code = asyncSendMsgToServer(pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg);
32,700✔
416
  if (code) {
32,701!
417
    doRequestCallback(pRequest, code);
×
418
  }
419
  return code;
32,701✔
420
}
421

422
int compareQueryNodeLoad(const void* elem1, const void* elem2) {
109,058✔
423
  SQueryNodeLoad* node1 = (SQueryNodeLoad*)elem1;
109,058✔
424
  SQueryNodeLoad* node2 = (SQueryNodeLoad*)elem2;
109,058✔
425

426
  if (node1->load < node2->load) {
109,058!
427
    return -1;
×
428
  }
429

430
  return node1->load > node2->load;
109,058✔
431
}
432

433
int32_t updateQnodeList(SAppInstInfo* pInfo, SArray* pNodeList) {
53,964✔
434
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
53,964!
435
  if (pInfo->pQnodeList) {
53,964✔
436
    taosArrayDestroy(pInfo->pQnodeList);
53,387✔
437
    pInfo->pQnodeList = NULL;
53,387✔
438
    tscDebug("QnodeList cleared in cluster 0x%" PRIx64, pInfo->clusterId);
53,387✔
439
  }
440

441
  if (pNodeList) {
53,964!
442
    pInfo->pQnodeList = taosArrayDup(pNodeList, NULL);
53,964✔
443
    taosArraySort(pInfo->pQnodeList, compareQueryNodeLoad);
53,964✔
444
    tscDebug("QnodeList updated in cluster 0x%" PRIx64 ", num:%ld", pInfo->clusterId,
53,964✔
445
             taosArrayGetSize(pInfo->pQnodeList));
446
  }
447
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
53,964!
448

449
  return TSDB_CODE_SUCCESS;
53,964✔
450
}
451

452
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
3,193,779✔
453
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
3,193,779✔
454
    *required = false;
2,580,237✔
455
    return TSDB_CODE_SUCCESS;
2,580,237✔
456
  }
457

458
  int32_t       code = TSDB_CODE_SUCCESS;
613,542✔
459
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
613,542✔
460
  *required = false;
613,542✔
461

462
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
613,542!
463
  *required = (NULL == pInfo->pQnodeList);
613,542✔
464
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
613,542!
465
  return TSDB_CODE_SUCCESS;
613,542✔
466
}
467

468
int32_t getQnodeList(SRequestObj* pRequest, SArray** pNodeList) {
×
469
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
×
470
  int32_t       code = 0;
×
471

472
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
×
473
  if (pInfo->pQnodeList) {
×
474
    *pNodeList = taosArrayDup(pInfo->pQnodeList, NULL);
×
475
  }
476
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
×
477
  if (NULL == *pNodeList) {
×
478
    SCatalog* pCatalog = NULL;
×
479
    code = catalogGetHandle(pRequest->pTscObj->pAppInfo->clusterId, &pCatalog);
×
480
    if (TSDB_CODE_SUCCESS == code) {
×
481
      *pNodeList = taosArrayInit(5, sizeof(SQueryNodeLoad));
×
482
      if (NULL == pNodeList) {
×
483
        TSC_ERR_RET(terrno);
×
484
      }
485
      SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
×
486
                               .requestId = pRequest->requestId,
×
487
                               .requestObjRefId = pRequest->self,
×
488
                               .mgmtEps = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp)};
×
489
      code = catalogGetQnodeList(pCatalog, &conn, *pNodeList);
×
490
    }
491

492
    if (TSDB_CODE_SUCCESS == code && *pNodeList) {
×
493
      code = updateQnodeList(pInfo, *pNodeList);
×
494
    }
495
  }
496

497
  return code;
×
498
}
499

500
int32_t getPlan(SRequestObj* pRequest, SQuery* pQuery, SQueryPlan** pPlan, SArray* pNodeList) {
115,969✔
501
  pRequest->type = pQuery->msgType;
115,969✔
502
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
115,969✔
503

504
  SPlanContext cxt = {.queryId = pRequest->requestId,
231,945✔
505
                      .acctId = pRequest->pTscObj->acctId,
115,969✔
506
                      .mgmtEpSet = getEpSet_s(&pAppInfo->mgmtEp),
115,969✔
507
                      .pAstRoot = pQuery->pRoot,
115,976✔
508
                      .showRewrite = pQuery->showRewrite,
115,976✔
509
                      .pMsg = pRequest->msgBuf,
115,976✔
510
                      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
511
                      .pUser = pRequest->pTscObj->user,
115,976✔
512
                      .timezone = pRequest->pTscObj->optionInfo.timezone,
115,976✔
513
                      .sysInfo = pRequest->pTscObj->sysInfo};
115,976✔
514

515
  return qCreateQueryPlan(&cxt, pPlan, pNodeList);
115,976✔
516
}
517

518
int32_t setResSchemaInfo(SReqResultInfo* pResInfo, const SSchema* pSchema, int32_t numOfCols) {
1,245,828✔
519
  if (pResInfo == NULL || pSchema == NULL || numOfCols <= 0) {
1,245,828!
520
    tscError("invalid paras, pResInfo == NULL || pSchema == NULL || numOfCols <= 0");
×
521
    return TSDB_CODE_INVALID_PARA;
×
522
  }
523

524
  pResInfo->numOfCols = numOfCols;
1,245,858✔
525
  if (pResInfo->fields != NULL) {
1,245,858✔
526
    taosMemoryFree(pResInfo->fields);
41!
527
  }
528
  if (pResInfo->userFields != NULL) {
1,245,858✔
529
    taosMemoryFree(pResInfo->userFields);
41!
530
  }
531
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
1,245,858!
532
  if (NULL == pResInfo->fields) return terrno;
1,245,831!
533
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
1,245,831!
534
  if (NULL == pResInfo->userFields) {
1,245,823!
535
    taosMemoryFree(pResInfo->fields);
×
536
    return terrno;
×
537
  }
538
  if (numOfCols != pResInfo->numOfCols) {
1,245,823!
539
    tscError("numOfCols:%d != pResInfo->numOfCols:%d", numOfCols, pResInfo->numOfCols);
×
540
    return TSDB_CODE_FAILED;
×
541
  }
542

543
  for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
5,451,096✔
544
    pResInfo->fields[i].bytes = pSchema[i].bytes;
4,205,273✔
545
    pResInfo->fields[i].type = pSchema[i].type;
4,205,273✔
546

547
    pResInfo->userFields[i].bytes = pSchema[i].bytes;
4,205,273✔
548
    pResInfo->userFields[i].type = pSchema[i].type;
4,205,273✔
549

550
    if (pSchema[i].type == TSDB_DATA_TYPE_VARCHAR || pSchema[i].type == TSDB_DATA_TYPE_VARBINARY ||
4,205,273✔
551
        pSchema[i].type == TSDB_DATA_TYPE_GEOMETRY) {
3,338,706✔
552
      pResInfo->userFields[i].bytes -= VARSTR_HEADER_SIZE;
866,583✔
553
    } else if (pSchema[i].type == TSDB_DATA_TYPE_NCHAR || pSchema[i].type == TSDB_DATA_TYPE_JSON) {
3,338,690✔
554
      pResInfo->userFields[i].bytes = (pResInfo->userFields[i].bytes - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE;
222,623✔
555
    }
556

557
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
4,205,273✔
558
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
4,205,273✔
559
  }
560
  return TSDB_CODE_SUCCESS;
1,245,823✔
561
}
562

563
void setResPrecision(SReqResultInfo* pResInfo, int32_t precision) {
908,952✔
564
  if (precision != TSDB_TIME_PRECISION_MILLI && precision != TSDB_TIME_PRECISION_MICRO &&
908,952!
565
      precision != TSDB_TIME_PRECISION_NANO) {
566
    return;
×
567
  }
568

569
  pResInfo->precision = precision;
908,952✔
570
}
571

572
int32_t buildVnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pDbVgList) {
675,274✔
573
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
675,274✔
574
  if (NULL == nodeList) {
675,299!
575
    return terrno;
×
576
  }
577
  char* policy = (tsQueryPolicy == QUERY_POLICY_VNODE) ? "vnode" : "client";
675,302✔
578

579
  int32_t dbNum = taosArrayGetSize(pDbVgList);
675,302✔
580
  for (int32_t i = 0; i < dbNum; ++i) {
1,258,766✔
581
    SArray* pVg = taosArrayGetP(pDbVgList, i);
583,513✔
582
    if (NULL == pVg) {
583,504!
583
      continue;
×
584
    }
585
    int32_t vgNum = taosArrayGetSize(pVg);
583,504✔
586
    if (vgNum <= 0) {
583,516✔
587
      continue;
633✔
588
    }
589

590
    for (int32_t j = 0; j < vgNum; ++j) {
2,894,324✔
591
      SVgroupInfo* pInfo = taosArrayGet(pVg, j);
2,311,498✔
592
      if (NULL == pInfo) {
2,311,302!
593
        taosArrayDestroy(nodeList);
×
594
        return TSDB_CODE_OUT_OF_RANGE;
×
595
      }
596
      SQueryNodeLoad load = {0};
2,311,302✔
597
      load.addr.nodeId = pInfo->vgId;
2,311,302✔
598
      load.addr.epSet = pInfo->epSet;
2,311,302✔
599

600
      if (NULL == taosArrayPush(nodeList, &load)) {
2,311,441!
601
        taosArrayDestroy(nodeList);
×
602
        return terrno;
×
603
      }
604
    }
605
  }
606

607
  int32_t vnodeNum = taosArrayGetSize(nodeList);
675,253✔
608
  if (vnodeNum > 0) {
675,331✔
609
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
582,181✔
610
    goto _return;
582,183✔
611
  }
612

613
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
93,150✔
614
  if (mnodeNum <= 0) {
93,147!
615
    tscDebug("0x%" PRIx64 " %s policy, empty node list", pRequest->requestId, policy);
×
616
    goto _return;
×
617
  }
618

619
  void* pData = taosArrayGet(pMnodeList, 0);
93,147✔
620
  if (NULL == pData) {
93,147!
621
    taosArrayDestroy(nodeList);
×
622
    return TSDB_CODE_OUT_OF_RANGE;
×
623
  }
624
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
93,147!
625
    taosArrayDestroy(nodeList);
×
626
    return terrno;
×
627
  }
628

629
  tscDebug("0x%" PRIx64 " %s policy, use mnode list, num:%d", pRequest->requestId, policy, mnodeNum);
93,147✔
630

631
_return:
89,492✔
632

633
  *pNodeList = nodeList;
675,325✔
634

635
  return TSDB_CODE_SUCCESS;
675,325✔
636
}
637

638
int32_t buildQnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pQnodeList) {
279,198✔
639
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
279,198✔
640
  if (NULL == nodeList) {
279,198!
641
    return terrno;
×
642
  }
643

644
  int32_t qNodeNum = taosArrayGetSize(pQnodeList);
279,198✔
645
  if (qNodeNum > 0) {
279,198✔
646
    void* pData = taosArrayGet(pQnodeList, 0);
278,876✔
647
    if (NULL == pData) {
278,876!
648
      taosArrayDestroy(nodeList);
×
649
      return TSDB_CODE_OUT_OF_RANGE;
×
650
    }
651
    if (NULL == taosArrayAddBatch(nodeList, pData, qNodeNum)) {
278,876!
652
      taosArrayDestroy(nodeList);
×
653
      return terrno;
×
654
    }
655
    tscDebug("0x%" PRIx64 " qnode policy, use qnode list, num:%d", pRequest->requestId, qNodeNum);
278,876✔
656
    goto _return;
278,876✔
657
  }
658

659
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
322✔
660
  if (mnodeNum <= 0) {
322✔
661
    tscDebug("0x%" PRIx64 " qnode policy, empty node list", pRequest->requestId);
4!
662
    goto _return;
4✔
663
  }
664

665
  void* pData = taosArrayGet(pMnodeList, 0);
318✔
666
  if (NULL == pData) {
318!
667
    taosArrayDestroy(nodeList);
×
668
    return TSDB_CODE_OUT_OF_RANGE;
×
669
  }
670
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
318!
671
    taosArrayDestroy(nodeList);
×
672
    return terrno;
×
673
  }
674

675
  tscDebug("0x%" PRIx64 " qnode policy, use mnode list, num:%d", pRequest->requestId, mnodeNum);
318!
676

677
_return:
×
678

679
  *pNodeList = nodeList;
279,198✔
680

681
  return TSDB_CODE_SUCCESS;
279,198✔
682
}
683

684
void freeVgList(void* list) {
27,709✔
685
  SArray* pList = *(SArray**)list;
27,709✔
686
  taosArrayDestroy(pList);
27,709✔
687
}
27,715✔
688

689
int32_t buildAsyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SMetaData* pResultMeta) {
838,463✔
690
  SArray* pDbVgList = NULL;
838,463✔
691
  SArray* pQnodeList = NULL;
838,463✔
692
  FDelete fp = NULL;
838,463✔
693
  int32_t code = 0;
838,463✔
694

695
  switch (tsQueryPolicy) {
838,463!
696
    case QUERY_POLICY_VNODE:
559,305✔
697
    case QUERY_POLICY_CLIENT: {
698
      if (pResultMeta) {
559,305!
699
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
559,340✔
700
        if (NULL == pDbVgList) {
559,341!
701
          code = terrno;
×
702
          goto _return;
×
703
        }
704
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
559,341✔
705
        for (int32_t i = 0; i < dbNum; ++i) {
1,115,114✔
706
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
555,799✔
707
          if (pRes->code || NULL == pRes->pRes) {
555,786!
708
            continue;
×
709
          }
710

711
          if (NULL == taosArrayPush(pDbVgList, &pRes->pRes)) {
1,111,614!
712
            code = terrno;
×
713
            goto _return;
×
714
          }
715
        }
716
      } else {
717
        fp = freeVgList;
×
718

719
        int32_t dbNum = taosArrayGetSize(pRequest->dbList);
×
720
        if (dbNum > 0) {
×
721
          SCatalog*     pCtg = NULL;
×
722
          SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
×
723
          code = catalogGetHandle(pInst->clusterId, &pCtg);
×
724
          if (code != TSDB_CODE_SUCCESS) {
×
725
            goto _return;
×
726
          }
727

728
          pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
×
729
          if (NULL == pDbVgList) {
×
730
            code = terrno;
×
731
            goto _return;
×
732
          }
733
          SArray* pVgList = NULL;
×
734
          for (int32_t i = 0; i < dbNum; ++i) {
×
735
            char*            dbFName = taosArrayGet(pRequest->dbList, i);
×
736
            SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
×
737
                                     .requestId = pRequest->requestId,
×
738
                                     .requestObjRefId = pRequest->self,
×
739
                                     .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
×
740

741
            // catalogGetDBVgList will handle dbFName == null.
742
            code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
×
743
            if (code) {
×
744
              goto _return;
×
745
            }
746

747
            if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
×
748
              code = terrno;
×
749
              goto _return;
×
750
            }
751
          }
752
        }
753
      }
754

755
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
559,315✔
756
      break;
559,349✔
757
    }
758
    case QUERY_POLICY_HYBRID:
279,196✔
759
    case QUERY_POLICY_QNODE: {
760
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
284,421!
761
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
5,225✔
762
        if (pRes->code) {
5,225!
763
          pQnodeList = NULL;
×
764
        } else {
765
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
5,225✔
766
          if (NULL == pQnodeList) {
5,225!
767
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
768
            goto _return;
×
769
          }
770
        }
771
      } else {
772
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
273,972✔
773
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
273,972!
774
        if (pInst->pQnodeList) {
273,973!
775
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
273,973✔
776
          if (NULL == pQnodeList) {
273,973!
777
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
778
            goto _return;
×
779
          }
780
        }
781
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
273,973!
782
      }
783

784
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
279,198✔
785
      break;
279,198✔
786
    }
787
    default:
×
788
      tscError("unknown query policy: %d", tsQueryPolicy);
×
789
      return TSDB_CODE_APP_ERROR;
×
790
  }
791

792
_return:
838,547✔
793
  taosArrayDestroyEx(pDbVgList, fp);
838,547✔
794
  taosArrayDestroy(pQnodeList);
838,560✔
795

796
  return code;
838,562✔
797
}
798

799
int32_t buildSyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList) {
115,970✔
800
  SArray* pDbVgList = NULL;
115,970✔
801
  SArray* pQnodeList = NULL;
115,970✔
802
  int32_t code = 0;
115,970✔
803

804
  switch (tsQueryPolicy) {
115,970!
805
    case QUERY_POLICY_VNODE:
115,969✔
806
    case QUERY_POLICY_CLIENT: {
807
      int32_t dbNum = taosArrayGetSize(pRequest->dbList);
115,969✔
808
      if (dbNum > 0) {
115,971✔
809
        SCatalog*     pCtg = NULL;
27,712✔
810
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
27,712✔
811
        code = catalogGetHandle(pInst->clusterId, &pCtg);
27,712✔
812
        if (code != TSDB_CODE_SUCCESS) {
27,716!
813
          goto _return;
×
814
        }
815

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

829
          // catalogGetDBVgList will handle dbFName == null.
830
          code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
27,716✔
831
          if (code) {
27,715!
832
            goto _return;
×
833
          }
834

835
          if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
27,715!
836
            code = terrno;
×
837
            goto _return;
×
838
          }
839
        }
840
      }
841

842
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
115,977✔
843
      break;
115,973✔
844
    }
845
    case QUERY_POLICY_HYBRID:
×
846
    case QUERY_POLICY_QNODE: {
847
      TSC_ERR_JRET(getQnodeList(pRequest, &pQnodeList));
×
848

849
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
×
850
      break;
×
851
    }
852
    default:
1✔
853
      tscError("unknown query policy: %d", tsQueryPolicy);
1!
854
      return TSDB_CODE_APP_ERROR;
×
855
  }
856

857
_return:
115,973✔
858

859
  taosArrayDestroyEx(pDbVgList, freeVgList);
115,973✔
860
  taosArrayDestroy(pQnodeList);
115,974✔
861

862
  return code;
115,973✔
863
}
864

865
int32_t scheduleQuery(SRequestObj* pRequest, SQueryPlan* pDag, SArray* pNodeList) {
115,969✔
866
  void* pTransporter = pRequest->pTscObj->pAppInfo->pTransporter;
115,969✔
867

868
  SExecResult      res = {0};
115,969✔
869
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
115,969✔
870
                           .requestId = pRequest->requestId,
115,969✔
871
                           .requestObjRefId = pRequest->self};
115,969✔
872
  SSchedulerReq    req = {
231,938✔
873
         .syncReq = true,
874
         .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
115,969✔
875
         .pConn = &conn,
876
         .pNodeList = pNodeList,
877
         .pDag = pDag,
878
         .sql = pRequest->sqlstr,
115,969✔
879
         .startTs = pRequest->metric.start,
115,969✔
880
         .execFp = NULL,
881
         .cbParam = NULL,
882
         .chkKillFp = chkRequestKilled,
883
         .chkKillParam = (void*)pRequest->self,
115,969✔
884
         .pExecRes = &res,
885
         .source = pRequest->source,
115,969✔
886
         .pWorkerCb = getTaskPoolWorkerCb(),
115,969✔
887
  };
888

889
  int32_t code = schedulerExecJob(&req, &pRequest->body.queryJob);
115,969✔
890

891
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
115,975✔
892
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
115,976✔
893

894
  if (code != TSDB_CODE_SUCCESS) {
115,976!
895
    schedulerFreeJob(&pRequest->body.queryJob, 0);
×
896

897
    pRequest->code = code;
×
898
    terrno = code;
×
899
    return pRequest->code;
×
900
  }
901

902
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_DELETE == pRequest->type ||
115,976!
903
      TDMT_VND_CREATE_TABLE == pRequest->type) {
21,720✔
904
    pRequest->body.resInfo.numOfRows = res.numOfRows;
94,392✔
905
    if (TDMT_VND_SUBMIT == pRequest->type) {
94,392✔
906
      STscObj*            pTscObj = pRequest->pTscObj;
94,255✔
907
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
94,255✔
908
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
94,255✔
909
    }
910

911
    schedulerFreeJob(&pRequest->body.queryJob, 0);
94,393✔
912
  }
913

914
  pRequest->code = res.code;
115,976✔
915
  terrno = res.code;
115,976✔
916
  return pRequest->code;
115,976✔
917
}
918

919
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
2,110,010✔
920
  SArray*      pArray = NULL;
2,110,010✔
921
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
2,110,010✔
922
  if (NULL == pRsp->aCreateTbRsp) {
2,110,010✔
923
    return TSDB_CODE_SUCCESS;
2,044,358✔
924
  }
925

926
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
65,652✔
927
  for (int32_t i = 0; i < tbNum; ++i) {
137,583✔
928
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
71,844✔
929
    if (pTbRsp->pMeta) {
71,844✔
930
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
30,992!
931
    }
932
  }
933

934
  return TSDB_CODE_SUCCESS;
65,739✔
935
}
936

937
int32_t handleQueryExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
687,815✔
938
  int32_t code = 0;
687,815✔
939
  SArray* pArray = NULL;
687,815✔
940
  SArray* pTbArray = (SArray*)res;
687,815✔
941
  int32_t tbNum = taosArrayGetSize(pTbArray);
687,815✔
942
  if (tbNum <= 0) {
687,819!
943
    return TSDB_CODE_SUCCESS;
×
944
  }
945

946
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
687,819✔
947
  if (NULL == pArray) {
687,830✔
948
    return terrno;
5✔
949
  }
950

951
  for (int32_t i = 0; i < tbNum; ++i) {
1,890,223✔
952
    STbVerInfo* tbInfo = taosArrayGet(pTbArray, i);
1,202,397✔
953
    if (NULL == tbInfo) {
1,202,395!
954
      code = terrno;
×
955
      goto _return;
×
956
    }
957
    STbSVersion tbSver = {.tbFName = tbInfo->tbFName, .sver = tbInfo->sversion, .tver = tbInfo->tversion};
1,202,395✔
958
    if (NULL == taosArrayPush(pArray, &tbSver)) {
1,202,398!
959
      code = terrno;
×
960
      goto _return;
×
961
    }
962
  }
963

964
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
687,826✔
965
                           .requestId = pRequest->requestId,
687,826✔
966
                           .requestObjRefId = pRequest->self,
687,826✔
967
                           .mgmtEps = *epset};
968

969
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
687,826✔
970

971
_return:
687,812✔
972

973
  taosArrayDestroy(pArray);
687,812✔
974
  return code;
687,826✔
975
}
976

977
int32_t handleAlterTbExecRes(void* res, SCatalog* pCatalog) {
3,290✔
978
  return catalogUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
3,290✔
979
}
980

981
int32_t handleCreateTbExecRes(void* res, SCatalog* pCatalog) {
136,084✔
982
  return catalogAsyncUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
136,084✔
983
}
984

985
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
3,048,455✔
986
  if (NULL == pRequest->body.resInfo.execRes.res) {
3,048,455✔
987
    return pRequest->code;
185,552✔
988
  }
989

990
  SCatalog*     pCatalog = NULL;
2,862,903✔
991
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
2,862,903✔
992

993
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
2,862,961✔
994
  if (code) {
2,863,054!
995
    return code;
×
996
  }
997

998
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
2,863,054✔
999
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
2,863,296✔
1000

1001
  switch (pRes->msgType) {
2,863,296✔
1002
    case TDMT_VND_ALTER_TABLE:
185✔
1003
    case TDMT_MND_ALTER_STB: {
1004
      code = handleAlterTbExecRes(pRes->res, pCatalog);
185✔
1005
      break;
185✔
1006
    }
1007
    case TDMT_VND_CREATE_TABLE: {
64,544✔
1008
      SArray* pList = (SArray*)pRes->res;
64,544✔
1009
      int32_t num = taosArrayGetSize(pList);
64,544✔
1010
      for (int32_t i = 0; i < num; ++i) {
163,725✔
1011
        void* res = taosArrayGetP(pList, i);
99,179✔
1012
        // handleCreateTbExecRes will handle res == null
1013
        code = handleCreateTbExecRes(res, pCatalog);
99,172✔
1014
      }
1015
      break;
64,546✔
1016
    }
1017
    case TDMT_MND_CREATE_STB: {
448✔
1018
      code = handleCreateTbExecRes(pRes->res, pCatalog);
448✔
1019
      break;
448✔
1020
    }
1021
    case TDMT_VND_SUBMIT: {
2,110,097✔
1022
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
2,110,097✔
1023

1024
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
2,110,182✔
1025
      break;
2,110,102✔
1026
    }
1027
    case TDMT_SCH_QUERY:
687,825✔
1028
    case TDMT_SCH_MERGE_QUERY: {
1029
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
687,825✔
1030
      break;
687,811✔
1031
    }
1032
    default:
197✔
1033
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self, pRequest->type,
197!
1034
               pRequest->requestId);
1035
      code = TSDB_CODE_APP_ERROR;
×
1036
  }
1037

1038
  return code;
2,863,092✔
1039
}
1040

1041
static bool incompletaFileParsing(SNode* pStmt) {
2,931,264✔
1042
  return QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pStmt) ? false : ((SVnodeModifyOpStmt*)pStmt)->fileProcessing;
2,931,264!
1043
}
1044

1045
void continuePostSubQuery(SRequestObj* pRequest, SSDataBlock* pBlock) {
502✔
1046
  SSqlCallbackWrapper* pWrapper = pRequest->pWrapper;
502✔
1047

1048
  int32_t code = nodesAcquireAllocator(pWrapper->pParseCtx->allocatorId);
502✔
1049
  if (TSDB_CODE_SUCCESS == code) {
502!
1050
    int64_t analyseStart = taosGetTimestampUs();
502✔
1051
    code = qContinueParsePostQuery(pWrapper->pParseCtx, pRequest->pQuery, pBlock);
502✔
1052
    pRequest->metric.analyseCostUs += taosGetTimestampUs() - analyseStart;
502✔
1053
  }
1054

1055
  if (TSDB_CODE_SUCCESS == code) {
502!
1056
    code = qContinuePlanPostQuery(pRequest->pPostPlan);
502✔
1057
  }
1058

1059
  code = nodesReleaseAllocator(pWrapper->pParseCtx->allocatorId);
502✔
1060
  handleQueryAnslyseRes(pWrapper, NULL, code);
502✔
1061
}
502✔
1062

1063
void returnToUser(SRequestObj* pRequest) {
62,344✔
1064
  if (pRequest->relation.userRefId == pRequest->self || 0 == pRequest->relation.userRefId) {
62,344!
1065
    // return to client
1066
    doRequestCallback(pRequest, pRequest->code);
62,344✔
1067
    return;
62,344✔
1068
  }
1069

1070
  SRequestObj* pUserReq = acquireRequest(pRequest->relation.userRefId);
×
1071
  if (pUserReq) {
×
1072
    pUserReq->code = pRequest->code;
×
1073
    // return to client
1074
    doRequestCallback(pUserReq, pUserReq->code);
×
1075
    (void)releaseRequest(pRequest->relation.userRefId);
×
1076
    return;
×
1077
  } else {
1078
    tscError("req:0x%" PRIx64 ", user ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1079
             pRequest->relation.userRefId, pRequest->requestId);
1080
  }
1081
}
1082

1083
static int32_t createResultBlock(TAOS_RES* pRes, int32_t numOfRows, SSDataBlock** pBlock) {
502✔
1084
  int64_t     lastTs = 0;
502✔
1085
  TAOS_FIELD* pResFields = taos_fetch_fields(pRes);
502✔
1086
  int32_t     numOfFields = taos_num_fields(pRes);
502✔
1087

1088
  int32_t code = createDataBlock(pBlock);
502✔
1089
  if (code) {
502!
1090
    return code;
×
1091
  }
1092

1093
  for (int32_t i = 0; i < numOfFields; ++i) {
2,008✔
1094
    SColumnInfoData colInfoData = createColumnInfoData(pResFields[i].type, pResFields[i].bytes, i + 1);
1,506✔
1095
    code = blockDataAppendColInfo(*pBlock, &colInfoData);
1,506✔
1096
    if (TSDB_CODE_SUCCESS != code) {
1,506!
1097
      blockDataDestroy(*pBlock);
×
1098
      return code;
×
1099
    }
1100
  }
1101

1102
  code = blockDataEnsureCapacity(*pBlock, numOfRows);
502✔
1103
  if (TSDB_CODE_SUCCESS != code) {
502!
1104
    blockDataDestroy(*pBlock);
×
1105
    return code;
×
1106
  }
1107

1108
  for (int32_t i = 0; i < numOfRows; ++i) {
1,510✔
1109
    TAOS_ROW pRow = taos_fetch_row(pRes);
1,008✔
1110
    if (NULL == pRow[0] || NULL == pRow[1] || NULL == pRow[2]) {
1,008!
1111
      tscError("invalid data from vnode");
×
1112
      blockDataDestroy(*pBlock);
×
1113
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1114
    }
1115
    int64_t ts = *(int64_t*)pRow[0];
1,008✔
1116
    if (lastTs < ts) {
1,008✔
1117
      lastTs = ts;
591✔
1118
    }
1119

1120
    for (int32_t j = 0; j < numOfFields; ++j) {
4,032✔
1121
      SColumnInfoData* pColInfoData = taosArrayGet((*pBlock)->pDataBlock, j);
3,024✔
1122
      code = colDataSetVal(pColInfoData, i, pRow[j], false);
3,024✔
1123
      if (TSDB_CODE_SUCCESS != code) {
3,024!
1124
        blockDataDestroy(*pBlock);
×
1125
        return code;
×
1126
      }
1127
    }
1128

1129
    tscDebug("lastKey:%" PRId64 " vgId:%d, vgVer:%" PRId64, ts, *(int32_t*)pRow[1], *(int64_t*)pRow[2]);
1,008✔
1130
  }
1131

1132
  (*pBlock)->info.window.ekey = lastTs;
502✔
1133
  (*pBlock)->info.rows = numOfRows;
502✔
1134

1135
  tscDebug("lastKey:%" PRId64 " numOfRows:%d from all vgroups", lastTs, numOfRows);
502✔
1136
  return TSDB_CODE_SUCCESS;
502✔
1137
}
1138

1139
void postSubQueryFetchCb(void* param, TAOS_RES* res, int32_t rowNum) {
502✔
1140
  SRequestObj* pRequest = (SRequestObj*)res;
502✔
1141
  if (pRequest->code) {
502!
1142
    returnToUser(pRequest);
×
1143
    return;
×
1144
  }
1145

1146
  SSDataBlock* pBlock = NULL;
502✔
1147
  pRequest->code = createResultBlock(res, rowNum, &pBlock);
502✔
1148
  if (TSDB_CODE_SUCCESS != pRequest->code) {
502!
1149
    tscError("req:0x%" PRIx64 ", create result block failed, QID:0x%" PRIx64 " %s", pRequest->self, pRequest->requestId,
×
1150
             tstrerror(pRequest->code));
1151
    returnToUser(pRequest);
×
1152
    return;
×
1153
  }
1154

1155
  SRequestObj* pNextReq = acquireRequest(pRequest->relation.nextRefId);
502✔
1156
  if (pNextReq) {
502!
1157
    continuePostSubQuery(pNextReq, pBlock);
502✔
1158
    (void)releaseRequest(pRequest->relation.nextRefId);
502✔
1159
  } else {
1160
    tscError("req:0x%" PRIx64 ", next req ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1161
             pRequest->relation.nextRefId, pRequest->requestId);
1162
  }
1163

1164
  blockDataDestroy(pBlock);
502✔
1165
}
1166

1167
void handlePostSubQuery(SSqlCallbackWrapper* pWrapper) {
502✔
1168
  SRequestObj* pRequest = pWrapper->pRequest;
502✔
1169
  if (TD_RES_QUERY(pRequest)) {
502!
1170
    taosAsyncFetchImpl(pRequest, postSubQueryFetchCb, pWrapper);
502✔
1171
    return;
502✔
1172
  }
1173

1174
  SRequestObj* pNextReq = acquireRequest(pRequest->relation.nextRefId);
×
1175
  if (pNextReq) {
×
1176
    continuePostSubQuery(pNextReq, NULL);
×
1177
    (void)releaseRequest(pRequest->relation.nextRefId);
×
1178
  } else {
1179
    tscError("req:0x%" PRIx64 ", next req ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1180
             pRequest->relation.nextRefId, pRequest->requestId);
1181
  }
1182
}
1183

1184
// todo refacto the error code  mgmt
1185
void schedulerExecCb(SExecResult* pResult, void* param, int32_t code) {
2,932,123✔
1186
  SSqlCallbackWrapper* pWrapper = param;
2,932,123✔
1187
  SRequestObj*         pRequest = pWrapper->pRequest;
2,932,123✔
1188
  STscObj*             pTscObj = pRequest->pTscObj;
2,932,123✔
1189

1190
  pRequest->code = code;
2,932,123✔
1191
  if (pResult) {
2,932,123!
1192
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
2,932,202✔
1193
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
2,932,119✔
1194
  }
1195

1196
  int32_t type = pRequest->type;
2,932,040✔
1197
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
2,932,040✔
1198
    if (pResult) {
2,141,181!
1199
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
2,141,252✔
1200

1201
      // record the insert rows
1202
      if (TDMT_VND_SUBMIT == type) {
2,141,252✔
1203
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
2,016,616✔
1204
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
2,016,616✔
1205
      }
1206
    }
1207
    schedulerFreeJob(&pRequest->body.queryJob, 0);
2,141,313✔
1208
  }
1209

1210
  taosMemoryFree(pResult);
2,932,381!
1211
  tscDebug("req:0x%" PRIx64 ", enter scheduler exec cb, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
2,932,271✔
1212
           pRequest->requestId);
1213

1214
  if (code != TSDB_CODE_SUCCESS && NEED_CLIENT_HANDLE_ERROR(code) && pRequest->sqlstr != NULL) {
2,932,222!
1215
    tscDebug("req:0x%" PRIx64 ", client retry to handle the error, code:%s, tryCount:%d, QID:0x%" PRIx64, pRequest->self,
267✔
1216
             tstrerror(code), pRequest->retry, pRequest->requestId);
1217
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
267!
1218
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1219
    }
1220
    restartAsyncQuery(pRequest, code);
267✔
1221
    return;
267✔
1222
  }
1223

1224
  tscTrace("req:0x%" PRIx64 ", scheduler exec cb, request type:%s", pRequest->self, TMSG_INFO(pRequest->type));
2,931,955!
1225
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
2,931,955!
1226
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
11,784!
1227
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1228
    }
1229
  }
1230

1231
  pRequest->metric.execCostUs = taosGetTimestampUs() - pRequest->metric.execStart;
2,932,056✔
1232
  int32_t code1 = handleQueryExecRsp(pRequest);
2,932,056✔
1233
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
2,931,952!
1234
    pRequest->code = code1;
×
1235
  }
1236

1237
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
5,863,238!
1238
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
2,931,263✔
1239
    continueInsertFromCsv(pWrapper, pRequest);
×
1240
    return;
×
1241
  }
1242

1243
  if (pRequest->relation.nextRefId) {
2,932,143✔
1244
    handlePostSubQuery(pWrapper);
502✔
1245
  } else {
1246
    destorySqlCallbackWrapper(pWrapper);
2,931,641✔
1247
    pRequest->pWrapper = NULL;
2,931,650✔
1248

1249
    // return to client
1250
    doRequestCallback(pRequest, code);
2,931,650✔
1251
  }
1252
}
1253

1254
void launchQueryImpl(SRequestObj* pRequest, SQuery* pQuery, bool keepQuery, void** res) {
116,690✔
1255
  int32_t code = 0;
116,690✔
1256
  int32_t subplanNum = 0;
116,690✔
1257

1258
  if (pQuery->pRoot) {
116,690✔
1259
    pRequest->stmtType = pQuery->pRoot->type;
116,021✔
1260
  }
1261

1262
  if (pQuery->pRoot && !pRequest->inRetry) {
116,690✔
1263
    STscObj*            pTscObj = pRequest->pTscObj;
116,021✔
1264
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
116,021✔
1265
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type) {
116,021✔
1266
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
94,418✔
1267
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
21,603!
1268
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
21,606✔
1269
    }
1270
  }
1271

1272
  pRequest->body.execMode = pQuery->execMode;
116,692✔
1273
  switch (pQuery->execMode) {
116,692!
1274
    case QUERY_EXEC_MODE_LOCAL:
×
1275
      if (!pRequest->validateOnly) {
×
1276
        if (NULL == pQuery->pRoot) {
×
1277
          terrno = TSDB_CODE_INVALID_PARA;
×
1278
          code = terrno;
×
1279
        } else {
1280
          code = execLocalCmd(pRequest, pQuery);
×
1281
        }
1282
      }
1283
      break;
×
1284
    case QUERY_EXEC_MODE_RPC:
669✔
1285
      if (!pRequest->validateOnly) {
669!
1286
        code = execDdlQuery(pRequest, pQuery);
669✔
1287
      }
1288
      break;
671✔
1289
    case QUERY_EXEC_MODE_SCHEDULE: {
115,973✔
1290
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
115,973✔
1291
      if (NULL == pMnodeList) {
115,972!
1292
        code = terrno;
×
1293
        break;
×
1294
      }
1295
      SQueryPlan* pDag = NULL;
115,972✔
1296
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
115,972✔
1297
      if (TSDB_CODE_SUCCESS == code) {
115,975!
1298
        pRequest->body.subplanNum = pDag->numOfSubplans;
115,975✔
1299
        if (!pRequest->validateOnly) {
115,975✔
1300
          SArray* pNodeList = NULL;
115,974✔
1301
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
115,974✔
1302
          if (TSDB_CODE_SUCCESS == code) {
115,973!
1303
            code = scheduleQuery(pRequest, pDag, pNodeList);
115,973✔
1304
          }
1305
          taosArrayDestroy(pNodeList);
115,976✔
1306
        }
1307
      }
1308
      taosArrayDestroy(pMnodeList);
115,978✔
1309
      break;
115,977✔
1310
    }
1311
    case QUERY_EXEC_MODE_EMPTY_RESULT:
50✔
1312
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
50✔
1313
      break;
50✔
1314
    default:
×
1315
      break;
×
1316
  }
1317

1318
  if (!keepQuery) {
116,698!
1319
    qDestroyQuery(pQuery);
×
1320
  }
1321

1322
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
116,698!
1323
    int ret = removeMeta(pRequest->pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type));
226!
1324
    if (TSDB_CODE_SUCCESS != ret) {
226!
1325
      tscError("req:0x%" PRIx64 ", remove meta failed,code:%d, QID:0x%" PRIx64, pRequest->self, ret, pRequest->requestId);
×
1326
    }
1327
  }
1328

1329
  if (TSDB_CODE_SUCCESS == code) {
116,698✔
1330
    code = handleQueryExecRsp(pRequest);
116,696✔
1331
  }
1332

1333
  if (TSDB_CODE_SUCCESS != code) {
116,696✔
1334
    pRequest->code = code;
137✔
1335
  }
1336

1337
  if (res) {
116,696!
1338
    *res = pRequest->body.resInfo.execRes.res;
×
1339
    pRequest->body.resInfo.execRes.res = NULL;
×
1340
  }
1341
}
116,696✔
1342

1343
static int32_t asyncExecSchQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta,
2,932,948✔
1344
                                 SSqlCallbackWrapper* pWrapper) {
1345
  int32_t code = TSDB_CODE_SUCCESS;
2,932,948✔
1346
  pRequest->type = pQuery->msgType;
2,932,948✔
1347
  SArray*     pMnodeList = NULL;
2,932,948✔
1348
  SQueryPlan* pDag = NULL;
2,932,948✔
1349
  int64_t     st = taosGetTimestampUs();
2,933,154✔
1350

1351
  if (!pRequest->parseOnly) {
2,933,154!
1352
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
2,933,174✔
1353
    if (NULL == pMnodeList) {
2,932,940!
1354
      code = terrno;
×
1355
    }
1356
    SPlanContext cxt = {.queryId = pRequest->requestId,
5,866,191✔
1357
                        .acctId = pRequest->pTscObj->acctId,
2,932,940✔
1358
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
2,932,940✔
1359
                        .pAstRoot = pQuery->pRoot,
2,933,251✔
1360
                        .showRewrite = pQuery->showRewrite,
2,933,251✔
1361
                        .isView = pWrapper->pParseCtx->isView,
2,933,251✔
1362
                        .isAudit = pWrapper->pParseCtx->isAudit,
2,933,251✔
1363
                        .pMsg = pRequest->msgBuf,
2,933,251✔
1364
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1365
                        .pUser = pRequest->pTscObj->user,
2,933,251✔
1366
                        .sysInfo = pRequest->pTscObj->sysInfo,
2,933,251✔
1367
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
2,933,251✔
1368
                        .allocatorId = pRequest->allocatorRefId};
2,933,251✔
1369
    if (TSDB_CODE_SUCCESS == code) {
2,933,251✔
1370
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
2,933,169✔
1371
    }
1372
    if (code) {
2,932,460✔
1373
      tscError("req:0x%" PRIx64 ", failed to create query plan, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
601!
1374
               pRequest->requestId);
1375
    } else {
1376
      pRequest->body.subplanNum = pDag->numOfSubplans;
2,931,859✔
1377
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
2,931,859✔
1378
    }
1379
  }
1380

1381
  pRequest->metric.execStart = taosGetTimestampUs();
2,932,845✔
1382
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
2,932,845✔
1383

1384
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
5,864,857✔
1385
    SArray* pNodeList = NULL;
2,932,106✔
1386
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
2,932,106✔
1387
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
838,505✔
1388
    }
1389

1390
    SRequestConnInfo conn = {.pTrans = getAppInfo(pRequest)->pTransporter,
2,932,162✔
1391
                             .requestId = pRequest->requestId,
2,931,591✔
1392
                             .requestObjRefId = pRequest->self};
2,931,591✔
1393
    SSchedulerReq    req = {
5,863,124✔
1394
           .syncReq = false,
1395
           .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
2,931,591✔
1396
           .pConn = &conn,
1397
           .pNodeList = pNodeList,
1398
           .pDag = pDag,
1399
           .allocatorRefId = pRequest->allocatorRefId,
2,931,591✔
1400
           .sql = pRequest->sqlstr,
2,931,591✔
1401
           .startTs = pRequest->metric.start,
2,931,591✔
1402
           .execFp = schedulerExecCb,
1403
           .cbParam = pWrapper,
1404
           .chkKillFp = chkRequestKilled,
1405
           .chkKillParam = (void*)pRequest->self,
2,931,591✔
1406
           .pExecRes = NULL,
1407
           .source = pRequest->source,
2,931,591✔
1408
           .pWorkerCb = getTaskPoolWorkerCb(),
2,931,591✔
1409
    };
1410
    if (TSDB_CODE_SUCCESS == code) {
2,931,533!
1411
      code = schedulerExecJob(&req, &pRequest->body.queryJob);
2,931,895✔
1412
    }
1413

1414
    taosArrayDestroy(pNodeList);
2,931,563✔
1415
  } else {
1416
    qDestroyQueryPlan(pDag);
739✔
1417
    tscDebug("req:0x%" PRIx64 ", plan not executed, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
816!
1418
             pRequest->requestId);
1419
    destorySqlCallbackWrapper(pWrapper);
816✔
1420
    pRequest->pWrapper = NULL;
816✔
1421
    if (TSDB_CODE_SUCCESS != code) {
816✔
1422
      pRequest->code = terrno;
601✔
1423
    }
1424

1425
    doRequestCallback(pRequest, code);
816✔
1426
  }
1427

1428
  // todo not to be released here
1429
  taosArrayDestroy(pMnodeList);
2,932,828✔
1430

1431
  return code;
2,932,932✔
1432
}
1433

1434
void launchAsyncQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta, SSqlCallbackWrapper* pWrapper) {
3,087,513✔
1435
  int32_t code = 0;
3,087,513✔
1436

1437
  if (pRequest->parseOnly) {
3,087,513✔
1438
    doRequestCallback(pRequest, 0);
604✔
1439
    return;
604✔
1440
  }
1441

1442
  pRequest->body.execMode = pQuery->execMode;
3,086,909✔
1443
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
3,086,909✔
1444
    destorySqlCallbackWrapper(pWrapper);
154,428✔
1445
    pRequest->pWrapper = NULL;
154,430✔
1446
  }
1447

1448
  if (pQuery->pRoot && !pRequest->inRetry) {
3,086,911!
1449
    STscObj*            pTscObj = pRequest->pTscObj;
3,087,346✔
1450
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
3,087,346✔
1451
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
3,087,346✔
1452
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
2,093,742✔
1453
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
2,016,662✔
1454
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
1,070,684✔
1455
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
737,902✔
1456
    }
1457
  }
1458

1459
  switch (pQuery->execMode) {
3,087,654!
1460
    case QUERY_EXEC_MODE_LOCAL:
118,400✔
1461
      asyncExecLocalCmd(pRequest, pQuery);
118,400✔
1462
      break;
118,400✔
1463
    case QUERY_EXEC_MODE_RPC:
32,702✔
1464
      code = asyncExecDdlQuery(pRequest, pQuery);
32,702✔
1465
      break;
32,702✔
1466
    case QUERY_EXEC_MODE_SCHEDULE: {
2,933,224✔
1467
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
2,933,224✔
1468
      break;
2,932,816✔
1469
    }
1470
    case QUERY_EXEC_MODE_EMPTY_RESULT:
3,328✔
1471
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
3,328✔
1472
      doRequestCallback(pRequest, 0);
3,328✔
1473
      break;
3,328✔
1474
    default:
×
1475
      tscError("req:0x%" PRIx64 ", invalid execMode %d", pRequest->self, pQuery->execMode);
×
1476
      doRequestCallback(pRequest, -1);
×
1477
      break;
×
1478
  }
1479
}
1480

1481
int32_t refreshMeta(STscObj* pTscObj, SRequestObj* pRequest) {
15✔
1482
  SCatalog* pCatalog = NULL;
15✔
1483
  int32_t   code = 0;
15✔
1484
  int32_t   dbNum = taosArrayGetSize(pRequest->dbList);
15✔
1485
  int32_t   tblNum = taosArrayGetSize(pRequest->tableList);
15✔
1486

1487
  if (dbNum <= 0 && tblNum <= 0) {
15!
1488
    return TSDB_CODE_APP_ERROR;
15✔
1489
  }
1490

1491
  code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
×
1492
  if (code != TSDB_CODE_SUCCESS) {
×
1493
    return code;
×
1494
  }
1495

1496
  SRequestConnInfo conn = {.pTrans = pTscObj->pAppInfo->pTransporter,
×
1497
                           .requestId = pRequest->requestId,
×
1498
                           .requestObjRefId = pRequest->self,
×
1499
                           .mgmtEps = getEpSet_s(&pTscObj->pAppInfo->mgmtEp)};
×
1500

1501
  for (int32_t i = 0; i < dbNum; ++i) {
×
1502
    char* dbFName = taosArrayGet(pRequest->dbList, i);
×
1503

1504
    // catalogRefreshDBVgInfo will handle dbFName == null.
1505
    code = catalogRefreshDBVgInfo(pCatalog, &conn, dbFName);
×
1506
    if (code != TSDB_CODE_SUCCESS) {
×
1507
      return code;
×
1508
    }
1509
  }
1510

1511
  for (int32_t i = 0; i < tblNum; ++i) {
×
1512
    SName* tableName = taosArrayGet(pRequest->tableList, i);
×
1513

1514
    // catalogRefreshTableMeta will handle tableName == null.
1515
    code = catalogRefreshTableMeta(pCatalog, &conn, tableName, -1);
×
1516
    if (code != TSDB_CODE_SUCCESS) {
×
1517
      return code;
×
1518
    }
1519
  }
1520

1521
  return code;
×
1522
}
1523

1524
int32_t removeMeta(STscObj* pTscObj, SArray* tbList, bool isView) {
14,000✔
1525
  SCatalog* pCatalog = NULL;
14,000✔
1526
  int32_t   tbNum = taosArrayGetSize(tbList);
14,000✔
1527
  int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
14,000✔
1528
  if (code != TSDB_CODE_SUCCESS) {
14,000!
1529
    return code;
×
1530
  }
1531

1532
  if (isView) {
14,000✔
1533
    for (int32_t i = 0; i < tbNum; ++i) {
818✔
1534
      SName* pViewName = taosArrayGet(tbList, i);
409✔
1535
      char   dbFName[TSDB_DB_FNAME_LEN];
1536
      if (NULL == pViewName) {
409!
1537
        continue;
×
1538
      }
1539
      (void)tNameGetFullDbName(pViewName, dbFName);
409✔
1540
      TSC_ERR_RET(catalogRemoveViewMeta(pCatalog, dbFName, 0, pViewName->tname, 0));
409!
1541
    }
1542
  } else {
1543
    for (int32_t i = 0; i < tbNum; ++i) {
17,861✔
1544
      SName* pTbName = taosArrayGet(tbList, i);
4,270✔
1545
      TSC_ERR_RET(catalogRemoveTableMeta(pCatalog, pTbName));
4,270!
1546
    }
1547
  }
1548

1549
  return TSDB_CODE_SUCCESS;
14,000✔
1550
}
1551

1552
int32_t initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet) {
15,094✔
1553
  pEpSet->version = 0;
15,094✔
1554

1555
  // init mnode ip set
1556
  SEpSet* mgmtEpSet = &(pEpSet->epSet);
15,094✔
1557
  mgmtEpSet->numOfEps = 0;
15,094✔
1558
  mgmtEpSet->inUse = 0;
15,094✔
1559

1560
  if (firstEp && firstEp[0] != 0) {
15,094!
1561
    if (strlen(firstEp) >= TSDB_EP_LEN) {
15,097!
1562
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1563
      return -1;
×
1564
    }
1565

1566
    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
15,097✔
1567
    if (code != TSDB_CODE_SUCCESS) {
15,102!
1568
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1569
      return terrno;
×
1570
    }
1571
    uint32_t addr = 0;
15,102✔
1572
    code = taosGetIpv4FromFqdn(mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
15,102✔
1573
    if (code) {
15,102✔
1574
      tscError("failed to resolve firstEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
4!
1575
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1576
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
4✔
1577
    } else {
1578
      mgmtEpSet->numOfEps++;
15,098✔
1579
    }
1580
  }
1581

1582
  if (secondEp && secondEp[0] != 0) {
15,099!
1583
    if (strlen(secondEp) >= TSDB_EP_LEN) {
3,445!
1584
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1585
      return terrno;
×
1586
    }
1587

1588
    int32_t code = taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
3,445✔
1589
    if (code != TSDB_CODE_SUCCESS) {
3,445!
1590
      return code;
×
1591
    }
1592
    uint32_t addr = 0;
3,445✔
1593
    code = taosGetIpv4FromFqdn(mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
3,445✔
1594
    if (code) {
3,445!
1595
      tscError("failed to resolve secondEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
×
1596
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1597
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
×
1598
    } else {
1599
      mgmtEpSet->numOfEps++;
3,445✔
1600
    }
1601
  }
1602

1603
  if (mgmtEpSet->numOfEps == 0) {
15,099✔
1604
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
4✔
1605
    return TSDB_CODE_RPC_NETWORK_UNAVAIL;
4✔
1606
  }
1607

1608
  return 0;
15,095✔
1609
}
1610

1611
int32_t taosConnectImpl(const char* user, const char* auth, const char* db, __taos_async_fn_t fp, void* param,
15,098✔
1612
                        SAppInstInfo* pAppInfo, int connType, STscObj** pTscObj) {
1613
  *pTscObj = NULL;
15,098✔
1614
  int32_t code = createTscObj(user, auth, db, connType, pAppInfo, pTscObj);
15,098✔
1615
  if (TSDB_CODE_SUCCESS != code) {
15,098!
1616
    return code;
×
1617
  }
1618

1619
  SRequestObj* pRequest = NULL;
15,098✔
1620
  code = createRequest((*pTscObj)->id, TDMT_MND_CONNECT, 0, &pRequest);
15,098✔
1621
  if (TSDB_CODE_SUCCESS != code) {
15,098!
1622
    destroyTscObj(*pTscObj);
×
1623
    return code;
×
1624
  }
1625

1626
  pRequest->sqlstr = taosStrdup("taos_connect");
15,098!
1627
  if (pRequest->sqlstr) {
15,098!
1628
    pRequest->sqlLen = strlen(pRequest->sqlstr);
15,098✔
1629
  } else {
1630
    return terrno;
×
1631
  }
1632

1633
  SMsgSendInfo* body = NULL;
15,098✔
1634
  code = buildConnectMsg(pRequest, &body);
15,098✔
1635
  if (TSDB_CODE_SUCCESS != code) {
15,098!
1636
    destroyTscObj(*pTscObj);
×
1637
    return code;
×
1638
  }
1639

1640
  // int64_t transporterId = 0;
1641
  code = asyncSendMsgToServer((*pTscObj)->pAppInfo->pTransporter, &(*pTscObj)->pAppInfo->mgmtEp.epSet, NULL, body);
15,098✔
1642
  if (TSDB_CODE_SUCCESS != code) {
15,098!
1643
    destroyTscObj(*pTscObj);
×
1644
    tscError("failed to send connect msg to server, code:%s", tstrerror(code));
×
1645
    return code;
×
1646
  }
1647
  if (TSDB_CODE_SUCCESS != tsem_wait(&pRequest->body.rspSem)) {
15,098!
1648
    destroyTscObj(*pTscObj);
×
1649
    tscError("failed to wait sem, code:%s", terrstr());
×
1650
    return terrno;
×
1651
  }
1652
  if (pRequest->code != TSDB_CODE_SUCCESS) {
15,098✔
1653
    const char* errorMsg = (code == TSDB_CODE_RPC_FQDN_ERROR) ? taos_errstr(pRequest) : tstrerror(pRequest->code);
50!
1654
    tscError("failed to connect to server, reason: %s", errorMsg);
50!
1655

1656
    terrno = pRequest->code;
50✔
1657
    destroyRequest(pRequest);
50✔
1658
    taos_close_internal(*pTscObj);
50✔
1659
    *pTscObj = NULL;
50✔
1660
    return terrno;
50✔
1661
  } else {
1662
    tscInfo("connObj:0x%" PRIx64 ", connection is opening, connId:%u, dnodeConn:%p, QID:0x%" PRIx64, (*pTscObj)->id,
15,048✔
1663
             (*pTscObj)->connId, (*pTscObj)->pAppInfo->pTransporter, pRequest->requestId);
1664
    destroyRequest(pRequest);
15,049✔
1665
  }
1666
  return code;
15,048✔
1667
}
1668

1669
static int32_t buildConnectMsg(SRequestObj* pRequest, SMsgSendInfo** pMsgSendInfo) {
15,098✔
1670
  *pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
15,098!
1671
  if (*pMsgSendInfo == NULL) {
15,098!
1672
    return terrno;
×
1673
  }
1674

1675
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
15,098✔
1676

1677
  (*pMsgSendInfo)->requestObjRefId = pRequest->self;
15,098✔
1678
  (*pMsgSendInfo)->requestId = pRequest->requestId;
15,098✔
1679
  (*pMsgSendInfo)->fp = getMsgRspHandle((*pMsgSendInfo)->msgType);
15,098✔
1680
  (*pMsgSendInfo)->param = taosMemoryCalloc(1, sizeof(pRequest->self));
15,098!
1681
  if (NULL == (*pMsgSendInfo)->param) {
15,098!
1682
    taosMemoryFree(*pMsgSendInfo);
×
1683
    return terrno;
×
1684
  }
1685

1686
  *(int64_t*)(*pMsgSendInfo)->param = pRequest->self;
15,098✔
1687

1688
  SConnectReq connectReq = {0};
15,098✔
1689
  STscObj*    pObj = pRequest->pTscObj;
15,098✔
1690

1691
  char* db = getDbOfConnection(pObj);
15,098✔
1692
  if (db != NULL) {
15,098✔
1693
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
793✔
1694
  } else if (terrno) {
14,305!
1695
    taosMemoryFree(*pMsgSendInfo);
×
1696
    return terrno;
×
1697
  }
1698
  taosMemoryFreeClear(db);
15,098!
1699

1700
  connectReq.connType = pObj->connType;
15,098✔
1701
  connectReq.pid = appInfo.pid;
15,098✔
1702
  connectReq.startTime = appInfo.startTime;
15,098✔
1703

1704
  tstrncpy(connectReq.app, appInfo.appName, sizeof(connectReq.app));
15,098✔
1705
  tstrncpy(connectReq.user, pObj->user, sizeof(connectReq.user));
15,098✔
1706
  tstrncpy(connectReq.passwd, pObj->pass, sizeof(connectReq.passwd));
15,098✔
1707
  tstrncpy(connectReq.sVer, td_version, sizeof(connectReq.sVer));
15,098✔
1708

1709
  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connectReq);
15,098✔
1710
  void*   pReq = taosMemoryMalloc(contLen);
15,098!
1711
  if (NULL == pReq) {
15,098!
1712
    taosMemoryFree(*pMsgSendInfo);
×
1713
    return terrno;
×
1714
  }
1715

1716
  if (-1 == tSerializeSConnectReq(pReq, contLen, &connectReq)) {
15,098!
1717
    taosMemoryFree(*pMsgSendInfo);
×
1718
    taosMemoryFree(pReq);
×
1719
    return terrno;
×
1720
  }
1721

1722
  (*pMsgSendInfo)->msgInfo.len = contLen;
15,098✔
1723
  (*pMsgSendInfo)->msgInfo.pData = pReq;
15,098✔
1724
  return TSDB_CODE_SUCCESS;
15,098✔
1725
}
1726

1727
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
10,755,463✔
1728
  if (NULL == pEpSet) {
10,755,463✔
1729
    return;
9,454,738✔
1730
  }
1731

1732
  switch (pSendInfo->target.type) {
1,300,725✔
1733
    case TARGET_TYPE_MNODE:
54✔
1734
      if (NULL == pTscObj) {
54!
1735
        tscError("mnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1736
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1737
        return;
×
1738
      }
1739

1740
      SEpSet* pOrig = &pTscObj->pAppInfo->mgmtEp.epSet;
54✔
1741
      SEp*    pOrigEp = &pOrig->eps[pOrig->inUse];
54✔
1742
      SEp*    pNewEp = &pEpSet->eps[pEpSet->inUse];
54✔
1743
      tscDebug("mnode epset updated from %d/%d=>%s:%d to %d/%d=>%s:%d in client", pOrig->inUse, pOrig->numOfEps,
54✔
1744
               pOrigEp->fqdn, pOrigEp->port, pEpSet->inUse, pEpSet->numOfEps, pNewEp->fqdn, pNewEp->port);
1745
      updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
54✔
1746
      break;
54✔
1747
    case TARGET_TYPE_VNODE: {
744,306✔
1748
      if (NULL == pTscObj) {
744,306✔
1749
        tscError("vnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
1!
1750
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1751
        return;
1✔
1752
      }
1753

1754
      SCatalog* pCatalog = NULL;
744,305✔
1755
      int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
744,305✔
1756
      if (code != TSDB_CODE_SUCCESS) {
744,296!
1757
        tscError("fail to get catalog handle, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1758
                 tstrerror(code));
1759
        return;
×
1760
      }
1761

1762
      code = catalogUpdateVgEpSet(pCatalog, pSendInfo->target.dbFName, pSendInfo->target.vgId, pEpSet);
744,296✔
1763
      if (code != TSDB_CODE_SUCCESS) {
744,309✔
1764
        tscError("fail to update catalog vg epset, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
2!
1765
                 tstrerror(code));
1766
        return;
×
1767
      }
1768
      taosMemoryFreeClear(pSendInfo->target.dbFName);
744,307!
1769
      break;
744,306✔
1770
    }
1771
    default:
556,365✔
1772
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
556,365!
1773
      break;
556,448✔
1774
  }
1775
}
1776

1777
int32_t doProcessMsgFromServerImpl(SRpcMsg* pMsg, SEpSet* pEpSet) {
10,755,745✔
1778
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
10,755,745✔
1779
  if (pMsg->info.ahandle == NULL) {
10,755,745✔
1780
    tscError("doProcessMsgFromServer pMsg->info.ahandle == NULL");
184!
1781
    rpcFreeCont(pMsg->pCont);
184✔
1782
    taosMemoryFree(pEpSet);
184!
1783
    return TSDB_CODE_TSC_INTERNAL_ERROR;
184✔
1784
  }
1785

1786
  STscObj* pTscObj = NULL;
10,755,561✔
1787

1788
  STraceId* trace = &pMsg->info.traceId;
10,755,561✔
1789
  char      tbuf[40] = {0};
10,755,561✔
1790
  TRACE_TO_STR(trace, tbuf);
10,755,561!
1791

1792
  tscDebug("QID:%s, process message from server, handle:%p, message:%s, size:%d, code:%s", tbuf, pMsg->info.handle,
10,755,427!
1793
           TMSG_INFO(pMsg->msgType), pMsg->contLen, tstrerror(pMsg->code));
1794

1795
  if (pSendInfo->requestObjRefId != 0) {
10,755,578✔
1796
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
4,918,803✔
1797
    if (pRequest) {
4,918,816✔
1798
      if (pRequest->self != pSendInfo->requestObjRefId) {
4,918,372!
1799
        tscError("doProcessMsgFromServer req:0x%" PRId64 " != pSendInfo->requestObjRefId:0x%" PRId64,
×
1800
                 pRequest->self, pSendInfo->requestObjRefId);
1801

1802
        if (TSDB_CODE_SUCCESS != taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId)) {
×
1803
          tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1804
        }
1805
        rpcFreeCont(pMsg->pCont);
×
1806
        taosMemoryFree(pEpSet);
×
1807
        destroySendMsgInfo(pSendInfo);
×
1808
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1809
      }
1810
      pTscObj = pRequest->pTscObj;
4,918,372✔
1811
    }
1812
  }
1813

1814
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
10,755,591✔
1815

1816
  SDataBuf buf = {.msgType = pMsg->msgType,
10,755,508✔
1817
                  .len = pMsg->contLen,
10,755,508✔
1818
                  .pData = NULL,
1819
                  .handle = pMsg->info.handle,
10,755,508✔
1820
                  .handleRefId = pMsg->info.refId,
10,755,508✔
1821
                  .pEpSet = pEpSet};
1822

1823
  if (pMsg->contLen > 0) {
10,755,508✔
1824
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
9,655,105!
1825
    if (buf.pData == NULL) {
9,654,940!
1826
      pMsg->code = terrno;
×
1827
    } else {
1828
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
9,654,940✔
1829
    }
1830
  }
1831

1832
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
10,755,343✔
1833

1834
  if (pTscObj) {
10,754,775✔
1835
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
4,918,151✔
1836
    if (TSDB_CODE_SUCCESS != code) {
4,918,344!
1837
      tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1838
      terrno = code;
×
1839
      pMsg->code = code;
×
1840
    }
1841
  }
1842

1843
  rpcFreeCont(pMsg->pCont);
10,754,968✔
1844
  destroySendMsgInfo(pSendInfo);
10,755,054✔
1845
  return TSDB_CODE_SUCCESS;
10,755,631✔
1846
}
1847
int32_t doProcessMsgFromServer(void* param) {
10,755,870✔
1848
  AsyncArg* arg = (AsyncArg*)param;
10,755,870✔
1849
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
10,755,870✔
1850
  taosMemoryFree(arg);
10,755,647!
1851
  return code;
10,755,497✔
1852
}
1853

1854
void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
10,753,870✔
1855
  int32_t code = 0;
10,753,870✔
1856
  SEpSet* tEpSet = NULL;
10,753,870✔
1857
  if (pEpSet != NULL) {
10,753,870✔
1858
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
1,300,798!
1859
    if (NULL == tEpSet) {
1,300,800!
1860
      code = terrno;
×
1861
      pMsg->code = terrno;
×
1862
      goto _exit;
×
1863
    }
1864
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
1,300,800✔
1865
  }
1866

1867
  // pMsg is response msg
1868
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
10,753,872✔
1869
    // restore origin code
1870
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
15,098!
1871
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1872
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
15,098!
1873
      pMsg->code = TSDB_CODE_RPC_BROKEN_LINK;
×
1874
    }
1875
  } else {
1876
    // uniform to one error code: TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED
1877
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
10,738,774!
1878
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
1879
    }
1880
  }
1881

1882
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
10,753,872!
1883
  if (NULL == arg) {
10,754,974!
1884
    code = terrno;
×
1885
    pMsg->code = code;
×
1886
    goto _exit;
×
1887
  }
1888

1889
  arg->msg = *pMsg;
10,754,974✔
1890
  arg->pEpset = tEpSet;
10,754,974✔
1891

1892
  if ((code = taosAsyncExec(doProcessMsgFromServer, arg, NULL)) != 0) {
10,754,974✔
1893
    pMsg->code = code;
126✔
1894
    taosMemoryFree(arg);
126!
1895
    goto _exit;
×
1896
  }
1897
  return;
10,755,389✔
1898
_exit:
×
1899
  tscError("failed to sched msg to tsc since %s", tstrerror(code));
×
1900
  code = doProcessMsgFromServerImpl(pMsg, tEpSet);
×
1901
  if (code != 0) {
×
1902
    tscError("failed to sched msg to tsc, tsc ready quit");
×
1903
  }
1904
}
1905

1906
TAOS* taos_connect_auth(const char* ip, const char* user, const char* auth, const char* db, uint16_t port) {
4✔
1907
  tscInfo("try to connect to %s:%u by auth, user:%s db:%s", ip, port, user, db);
4!
1908
  if (user == NULL) {
4!
1909
    user = TSDB_DEFAULT_USER;
×
1910
  }
1911

1912
  if (auth == NULL) {
4!
1913
    tscError("No auth info is given, failed to connect to server");
×
1914
    return NULL;
×
1915
  }
1916

1917
  STscObj* pObj = NULL;
4✔
1918
  int32_t  code = taos_connect_internal(ip, user, NULL, auth, db, port, CONN_TYPE__QUERY, &pObj);
4✔
1919
  if (TSDB_CODE_SUCCESS == code) {
4✔
1920
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
1!
1921
    if (NULL == rid) {
1!
1922
      tscError("out of memory when taos connect to %s:%u, user:%s db:%s", ip, port, user, db);
×
1923
    }
1924
    *rid = pObj->id;
1✔
1925
    return (TAOS*)rid;
1✔
1926
  }
1927

1928
  return NULL;
3✔
1929
}
1930

1931
// TAOS* taos_connect_l(const char* ip, int ipLen, const char* user, int userLen, const char* pass, int passLen,
1932
//                      const char* db, int dbLen, uint16_t port) {
1933
//   char ipStr[TSDB_EP_LEN] = {0};
1934
//   char dbStr[TSDB_DB_NAME_LEN] = {0};
1935
//   char userStr[TSDB_USER_LEN] = {0};
1936
//   char passStr[TSDB_PASSWORD_LEN] = {0};
1937
//
1938
//   tstrncpy(ipStr, ip, TMIN(TSDB_EP_LEN - 1, ipLen));
1939
//   tstrncpy(userStr, user, TMIN(TSDB_USER_LEN - 1, userLen));
1940
//   tstrncpy(passStr, pass, TMIN(TSDB_PASSWORD_LEN - 1, passLen));
1941
//   tstrncpy(dbStr, db, TMIN(TSDB_DB_NAME_LEN - 1, dbLen));
1942
//   return taos_connect(ipStr, userStr, passStr, dbStr, port);
1943
// }
1944

1945
void doSetOneRowPtr(SReqResultInfo* pResultInfo) {
43,454,730✔
1946
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
256,159,136✔
1947
    SResultColumn* pCol = &pResultInfo->pCol[i];
212,704,406✔
1948

1949
    int32_t type = pResultInfo->fields[i].type;
212,704,406✔
1950
    int32_t bytes = pResultInfo->fields[i].bytes;
212,704,406✔
1951

1952
    if (IS_VAR_DATA_TYPE(type)) {
212,704,406!
1953
      if (!IS_VAR_NULL_TYPE(type, bytes) && pCol->offset[pResultInfo->current] != -1) {
30,770,201!
1954
        char* pStart = pResultInfo->pCol[i].offset[pResultInfo->current] + pResultInfo->pCol[i].pData;
29,535,394✔
1955

1956
        pResultInfo->length[i] = varDataLen(pStart);
29,535,394✔
1957
        pResultInfo->row[i] = varDataVal(pStart);
29,535,394✔
1958
      } else {
1959
        pResultInfo->row[i] = NULL;
1,234,807✔
1960
        pResultInfo->length[i] = 0;
1,234,807✔
1961
      }
1962
    } else {
1963
      if (!colDataIsNull_f(pCol->nullbitmap, pResultInfo->current)) {
181,934,205✔
1964
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + bytes * pResultInfo->current;
176,545,283✔
1965
        pResultInfo->length[i] = bytes;
176,545,283✔
1966
      } else {
1967
        pResultInfo->row[i] = NULL;
5,388,922✔
1968
        pResultInfo->length[i] = 0;
5,388,922✔
1969
      }
1970
    }
1971
  }
1972
}
43,454,730✔
1973

1974
void* doFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
×
1975
  if (pRequest == NULL) {
×
1976
    return NULL;
×
1977
  }
1978

1979
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
×
1980
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
×
1981
    // All data has returned to App already, no need to try again
1982
    if (pResultInfo->completed) {
×
1983
      pResultInfo->numOfRows = 0;
×
1984
      return NULL;
×
1985
    }
1986

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

1990
    pRequest->code = schedulerFetchRows(pRequest->body.queryJob, &req);
×
1991
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
1992
      pResultInfo->numOfRows = 0;
×
1993
      return NULL;
×
1994
    }
1995

1996
    pRequest->code =
×
1997
        setQueryResultFromRsp(&pRequest->body.resInfo, (const SRetrieveTableRsp*)pResInfo->pData, convertUcs4);
×
1998
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
1999
      pResultInfo->numOfRows = 0;
×
2000
      return NULL;
×
2001
    }
2002

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

2006
    STscObj*            pTscObj = pRequest->pTscObj;
×
2007
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
×
2008
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
×
2009

2010
    if (pResultInfo->numOfRows == 0) {
×
2011
      return NULL;
×
2012
    }
2013
  }
2014

2015
  if (setupOneRowPtr) {
×
2016
    doSetOneRowPtr(pResultInfo);
×
2017
    pResultInfo->current += 1;
×
2018
  }
2019

2020
  return pResultInfo->row;
×
2021
}
2022

2023
static void syncFetchFn(void* param, TAOS_RES* res, int32_t numOfRows) {
801,219✔
2024
  tsem_t* sem = param;
801,219✔
2025
  if (TSDB_CODE_SUCCESS != tsem_post(sem)) {
801,219!
2026
    tscError("failed to post sem, code:%s", terrstr());
×
2027
  }
2028
}
801,219✔
2029

2030
void* doAsyncFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
29,436,613✔
2031
  if (pRequest == NULL) {
29,436,613!
2032
    return NULL;
×
2033
  }
2034

2035
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
29,436,613✔
2036
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
29,436,613✔
2037
    // All data has returned to App already, no need to try again
2038
    if (pResultInfo->completed) {
1,418,773✔
2039
      pResultInfo->numOfRows = 0;
617,560✔
2040
      return NULL;
617,560✔
2041
    }
2042

2043
    // convert ucs4 to native multi-bytes string
2044
    pResultInfo->convertUcs4 = convertUcs4;
801,213✔
2045
    tsem_t sem;
2046
    if (TSDB_CODE_SUCCESS != tsem_init(&sem, 0, 0)) {
801,213!
2047
      tscError("failed to init sem, code:%s", terrstr());
×
2048
    }
2049
    taos_fetch_rows_a(pRequest, syncFetchFn, &sem);
801,213✔
2050
    if (TSDB_CODE_SUCCESS != tsem_wait(&sem)) {
801,220!
2051
      tscError("failed to wait sem, code:%s", terrstr());
×
2052
    }
2053
    if (TSDB_CODE_SUCCESS != tsem_destroy(&sem)) {
801,216!
2054
      tscError("failed to destroy sem, code:%s", terrstr());
×
2055
    }
2056
    pRequest->inCallback = false;
801,217✔
2057
  }
2058

2059
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
28,819,057!
2060
    return NULL;
67,777✔
2061
  } else {
2062
    if (setupOneRowPtr) {
28,751,280✔
2063
      doSetOneRowPtr(pResultInfo);
28,084,413✔
2064
      pResultInfo->current += 1;
28,077,958✔
2065
    }
2066

2067
    return pResultInfo->row;
28,744,825✔
2068
  }
2069
}
2070

2071
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
1,241,666✔
2072
  if (pResInfo->row == NULL) {
1,241,666✔
2073
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
1,121,005!
2074
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
1,121,031!
2075
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
1,121,035!
2076
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
1,121,028!
2077

2078
    if (pResInfo->row == NULL || pResInfo->pCol == NULL || pResInfo->length == NULL || pResInfo->convertBuf == NULL) {
1,121,036!
2079
      taosMemoryFree(pResInfo->row);
6!
2080
      taosMemoryFree(pResInfo->pCol);
×
2081
      taosMemoryFree(pResInfo->length);
×
2082
      taosMemoryFree(pResInfo->convertBuf);
×
2083
      return terrno;
×
2084
    }
2085
  }
2086

2087
  return TSDB_CODE_SUCCESS;
1,241,691✔
2088
}
2089

2090
static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength) {
1,241,533✔
2091
  int32_t idx = -1;
1,241,533✔
2092
  iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt);
1,241,533✔
2093
  if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR;
1,241,547!
2094

2095
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
5,401,120✔
2096
    int32_t type = pResultInfo->fields[i].type;
4,159,530✔
2097
    int32_t bytes = pResultInfo->fields[i].bytes;
4,159,530✔
2098

2099
    if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) {
4,159,530✔
2100
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
189,692!
2101
      if (p == NULL) {
189,692!
2102
        taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
×
2103
        return terrno;
×
2104
      }
2105

2106
      pResultInfo->convertBuf[i] = p;
189,692✔
2107

2108
      SResultColumn* pCol = &pResultInfo->pCol[i];
189,692✔
2109
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
29,026,992✔
2110
        if (pCol->offset[j] != -1) {
28,837,257✔
2111
          char* pStart = pCol->offset[j] + pCol->pData;
28,468,641✔
2112

2113
          int32_t len = taosUcs4ToMbsEx((TdUcs4*)varDataVal(pStart), varDataLen(pStart), varDataVal(p), conv);
28,468,641✔
2114
          if (len < 0 || len > bytes || (p + len) >= (pResultInfo->convertBuf[i] + colLength[i])) {
28,468,723✔
2115
            tscError(
39!
2116
                "doConvertUCS4 error, invalid data. len:%d, bytes:%d, (p + len):%p, (pResultInfo->convertBuf[i] + "
2117
                "colLength[i]):%p",
2118
                len, bytes, (p + len), (pResultInfo->convertBuf[i] + colLength[i]));
2119
            taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
39✔
2120
            return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2121
          }
2122

2123
          varDataSetLen(p, len);
28,468,684✔
2124
          pCol->offset[j] = (p - pResultInfo->convertBuf[i]);
28,468,684✔
2125
          p += (len + VARSTR_HEADER_SIZE);
28,468,684✔
2126
        }
2127
      }
2128

2129
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
189,735✔
2130
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
189,735✔
2131
    }
2132
  }
2133
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
1,241,590✔
2134
  return TSDB_CODE_SUCCESS;
1,241,556✔
2135
}
2136

2137
int32_t getVersion1BlockMetaSize(const char* p, int32_t numOfCols) {
900✔
2138
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) * 3 + sizeof(uint64_t) +
900✔
2139
         numOfCols * (sizeof(int8_t) + sizeof(int32_t));
2140
}
2141

2142
static int32_t estimateJsonLen(SReqResultInfo* pResultInfo) {
450✔
2143
  char*   p = (char*)pResultInfo->pData;
450✔
2144
  int32_t blockVersion = *(int32_t*)p;
450✔
2145

2146
  int32_t numOfRows = pResultInfo->numOfRows;
450✔
2147
  int32_t numOfCols = pResultInfo->numOfCols;
450✔
2148

2149
  // | version | total length | total rows | total columns | flag seg| block group id | column schema | each column
2150
  // length |
2151
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
450✔
2152
  if (numOfCols != cols) {
450!
2153
    tscError("estimateJsonLen error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2154
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2155
  }
2156

2157
  int32_t  len = getVersion1BlockMetaSize(p, numOfCols);
450✔
2158
  int32_t* colLength = (int32_t*)(p + len);
450✔
2159
  len += sizeof(int32_t) * numOfCols;
450✔
2160

2161
  char* pStart = p + len;
450✔
2162
  for (int32_t i = 0; i < numOfCols; ++i) {
2,149✔
2163
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
1,699!
2164

2165
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
1,699✔
2166
      int32_t* offset = (int32_t*)pStart;
527✔
2167
      int32_t  lenTmp = numOfRows * sizeof(int32_t);
527✔
2168
      len += lenTmp;
527✔
2169
      pStart += lenTmp;
527✔
2170

2171
      int32_t estimateColLen = 0;
527✔
2172
      for (int32_t j = 0; j < numOfRows; ++j) {
3,243✔
2173
        if (offset[j] == -1) {
2,716✔
2174
          continue;
213✔
2175
        }
2176
        char* data = offset[j] + pStart;
2,503✔
2177

2178
        int32_t jsonInnerType = *data;
2,503✔
2179
        char*   jsonInnerData = data + CHAR_BYTES;
2,503✔
2180
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
2,503✔
2181
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
72✔
2182
        } else if (tTagIsJson(data)) {
2,431✔
2183
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
669✔
2184
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
1,762✔
2185
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
1,466✔
2186
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
296✔
2187
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
216✔
2188
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
80!
2189
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
80✔
2190
        } else {
2191
          tscError("estimateJsonLen error: invalid type:%d", jsonInnerType);
×
2192
          return -1;
×
2193
        }
2194
      }
2195
      len += TMAX(colLen, estimateColLen);
527✔
2196
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
1,172!
2197
      int32_t lenTmp = numOfRows * sizeof(int32_t);
396✔
2198
      len += (lenTmp + colLen);
396✔
2199
      pStart += lenTmp;
396✔
2200
    } else {
2201
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
776✔
2202
      len += (lenTmp + colLen);
776✔
2203
      pStart += lenTmp;
776✔
2204
    }
2205
    pStart += colLen;
1,699✔
2206
  }
2207

2208
  // Ensure the complete structure of the block, including the blankfill field,
2209
  // even though it is not used on the client side.
2210
  len += sizeof(bool);
450✔
2211
  return len;
450✔
2212
}
2213

2214
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
1,241,691✔
2215
  int32_t numOfRows = pResultInfo->numOfRows;
1,241,691✔
2216
  int32_t numOfCols = pResultInfo->numOfCols;
1,241,691✔
2217
  bool    needConvert = false;
1,241,691✔
2218
  for (int32_t i = 0; i < numOfCols; ++i) {
5,401,380✔
2219
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
4,160,139✔
2220
      needConvert = true;
450✔
2221
      break;
450✔
2222
    }
2223
  }
2224

2225
  if (!needConvert) {
1,241,691✔
2226
    return TSDB_CODE_SUCCESS;
1,241,239✔
2227
  }
2228

2229
  tscDebug("start to convert form json format string");
452✔
2230

2231
  char*   p = (char*)pResultInfo->pData;
452✔
2232
  int32_t blockVersion = *(int32_t*)p;
452✔
2233
  int32_t dataLen = estimateJsonLen(pResultInfo);
452✔
2234
  if (dataLen <= 0) {
450!
2235
    tscError("doConvertJson error: estimateJsonLen failed");
×
2236
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2237
  }
2238

2239
  taosMemoryFreeClear(pResultInfo->convertJson);
450!
2240
  pResultInfo->convertJson = taosMemoryCalloc(1, dataLen);
450!
2241
  if (pResultInfo->convertJson == NULL) return terrno;
450!
2242
  char* p1 = pResultInfo->convertJson;
450✔
2243

2244
  int32_t totalLen = 0;
450✔
2245
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
450✔
2246
  if (numOfCols != cols) {
450!
2247
    tscError("doConvertJson error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2248
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2249
  }
2250

2251
  int32_t len = getVersion1BlockMetaSize(p, numOfCols);
450✔
2252
  (void)memcpy(p1, p, len);
450✔
2253

2254
  p += len;
450✔
2255
  p1 += len;
450✔
2256
  totalLen += len;
450✔
2257

2258
  len = sizeof(int32_t) * numOfCols;
450✔
2259
  int32_t* colLength = (int32_t*)p;
450✔
2260
  int32_t* colLength1 = (int32_t*)p1;
450✔
2261
  (void)memcpy(p1, p, len);
450✔
2262
  p += len;
450✔
2263
  p1 += len;
450✔
2264
  totalLen += len;
450✔
2265

2266
  char* pStart = p;
450✔
2267
  char* pStart1 = p1;
450✔
2268
  for (int32_t i = 0; i < numOfCols; ++i) {
2,149✔
2269
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
1,699!
2270
    int32_t colLen1 = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength1[i]) : colLength1[i];
1,699!
2271
    if (colLen >= dataLen) {
1,699!
2272
      tscError("doConvertJson error: colLen:%d >= dataLen:%d", colLen, dataLen);
×
2273
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2274
    }
2275
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
1,699✔
2276
      int32_t* offset = (int32_t*)pStart;
527✔
2277
      int32_t* offset1 = (int32_t*)pStart1;
527✔
2278
      len = numOfRows * sizeof(int32_t);
527✔
2279
      (void)memcpy(pStart1, pStart, len);
527✔
2280
      pStart += len;
527✔
2281
      pStart1 += len;
527✔
2282
      totalLen += len;
527✔
2283

2284
      len = 0;
527✔
2285
      for (int32_t j = 0; j < numOfRows; ++j) {
3,243✔
2286
        if (offset[j] == -1) {
2,716✔
2287
          continue;
213✔
2288
        }
2289
        char* data = offset[j] + pStart;
2,503✔
2290

2291
        int32_t jsonInnerType = *data;
2,503✔
2292
        char*   jsonInnerData = data + CHAR_BYTES;
2,503✔
2293
        char    dst[TSDB_MAX_JSON_TAG_LEN] = {0};
2,503✔
2294
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
2,503✔
2295
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s", TSDB_DATA_NULL_STR_L);
72✔
2296
          varDataSetLen(dst, strlen(varDataVal(dst)));
72✔
2297
        } else if (tTagIsJson(data)) {
2,431✔
2298
          char* jsonString = NULL;
669✔
2299
          parseTagDatatoJson(data, &jsonString, pResultInfo->charsetCxt);
669✔
2300
          if (jsonString == NULL) {
669!
2301
            tscError("doConvertJson error: parseTagDatatoJson failed");
×
2302
            return terrno;
×
2303
          }
2304
          STR_TO_VARSTR(dst, jsonString);
669✔
2305
          taosMemoryFree(jsonString);
669!
2306
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
1,762✔
2307
          *(char*)varDataVal(dst) = '\"';
1,466✔
2308
          int32_t length = taosUcs4ToMbs((TdUcs4*)varDataVal(jsonInnerData), varDataLen(jsonInnerData),
1,466✔
2309
                                         varDataVal(dst) + CHAR_BYTES, pResultInfo->charsetCxt);
2310
          if (length <= 0) {
1,466✔
2311
            tscError("charset:%s to %s. convert failed.", DEFAULT_UNICODE_ENCODEC,
4!
2312
              pResultInfo->charsetCxt != NULL ? ((SConvInfo *)(pResultInfo->charsetCxt))->charset : tsCharset);
2313
            length = 0;
4✔
2314
          }
2315
          varDataSetLen(dst, length + CHAR_BYTES * 2);
1,466✔
2316
          *(char*)POINTER_SHIFT(varDataVal(dst), length + CHAR_BYTES) = '\"';
1,466✔
2317
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
296✔
2318
          double jsonVd = *(double*)(jsonInnerData);
216✔
2319
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%.9lf", jsonVd);
216✔
2320
          varDataSetLen(dst, strlen(varDataVal(dst)));
216✔
2321
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
80!
2322
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s",
80✔
2323
                         (*((char*)jsonInnerData) == 1) ? "true" : "false");
80✔
2324
          varDataSetLen(dst, strlen(varDataVal(dst)));
80✔
2325
        } else {
2326
          tscError("doConvertJson error: invalid type:%d", jsonInnerType);
×
2327
          return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2328
        }
2329

2330
        offset1[j] = len;
2,503✔
2331
        (void)memcpy(pStart1 + len, dst, varDataTLen(dst));
2,503✔
2332
        len += varDataTLen(dst);
2,503✔
2333
      }
2334
      colLen1 = len;
527✔
2335
      totalLen += colLen1;
527✔
2336
      colLength1[i] = (blockVersion == BLOCK_VERSION_1) ? htonl(len) : len;
527!
2337
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
1,172!
2338
      len = numOfRows * sizeof(int32_t);
396✔
2339
      (void)memcpy(pStart1, pStart, len);
396✔
2340
      pStart += len;
396✔
2341
      pStart1 += len;
396✔
2342
      totalLen += len;
396✔
2343
      totalLen += colLen;
396✔
2344
      (void)memcpy(pStart1, pStart, colLen);
396✔
2345
    } else {
2346
      len = BitmapLen(pResultInfo->numOfRows);
776✔
2347
      (void)memcpy(pStart1, pStart, len);
776✔
2348
      pStart += len;
776✔
2349
      pStart1 += len;
776✔
2350
      totalLen += len;
776✔
2351
      totalLen += colLen;
776✔
2352
      (void)memcpy(pStart1, pStart, colLen);
776✔
2353
    }
2354
    pStart += colLen;
1,699✔
2355
    pStart1 += colLen1;
1,699✔
2356
  }
2357

2358
  // Ensure the complete structure of the block, including the blankfill field,
2359
  // even though it is not used on the client side.
2360
  // (void)memcpy(pStart1, pStart, sizeof(bool));
2361
  totalLen += sizeof(bool);
450✔
2362

2363
  *(int32_t*)(pResultInfo->convertJson + 4) = totalLen;
450✔
2364
  pResultInfo->pData = pResultInfo->convertJson;
450✔
2365
  return TSDB_CODE_SUCCESS;
450✔
2366
}
2367

2368
int32_t setResultDataPtr(SReqResultInfo* pResultInfo, bool convertUcs4) {
1,314,613✔
2369
  if (pResultInfo == NULL || pResultInfo->numOfCols <= 0 || pResultInfo->fields == NULL) {
1,314,613!
2370
    tscError("setResultDataPtr paras error");
×
2371
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2372
  }
2373

2374
  if (pResultInfo->numOfRows == 0) {
1,314,620✔
2375
    return TSDB_CODE_SUCCESS;
72,944✔
2376
  }
2377

2378
  if (pResultInfo->pData == NULL) {
1,241,676!
2379
    tscError("setResultDataPtr error: pData is NULL");
×
2380
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2381
  }
2382

2383
  int32_t code = doPrepareResPtr(pResultInfo);
1,241,676✔
2384
  if (code != TSDB_CODE_SUCCESS) {
1,241,693!
2385
    return code;
×
2386
  }
2387
  code = doConvertJson(pResultInfo);
1,241,693✔
2388
  if (code != TSDB_CODE_SUCCESS) {
1,241,687!
2389
    return code;
×
2390
  }
2391

2392
  char* p = (char*)pResultInfo->pData;
1,241,687✔
2393

2394
  // version:
2395
  int32_t blockVersion = *(int32_t*)p;
1,241,687✔
2396
  p += sizeof(int32_t);
1,241,687✔
2397

2398
  int32_t dataLen = *(int32_t*)p;
1,241,687✔
2399
  p += sizeof(int32_t);
1,241,687✔
2400

2401
  int32_t rows = *(int32_t*)p;
1,241,687✔
2402
  p += sizeof(int32_t);
1,241,687✔
2403

2404
  int32_t cols = *(int32_t*)p;
1,241,687✔
2405
  p += sizeof(int32_t);
1,241,687✔
2406

2407
  if (rows != pResultInfo->numOfRows || cols != pResultInfo->numOfCols) {
1,241,687!
2408
    tscError("setResultDataPtr paras error:rows;%d numOfRows:%" PRId64 " cols:%d numOfCols:%d", rows,
2!
2409
             pResultInfo->numOfRows, cols, pResultInfo->numOfCols);
2410
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2411
  }
2412

2413
  int32_t hasColumnSeg = *(int32_t*)p;
1,241,685✔
2414
  p += sizeof(int32_t);
1,241,685✔
2415

2416
  uint64_t groupId = *(uint64_t*)p;
1,241,685✔
2417
  p += sizeof(uint64_t);
1,241,685✔
2418

2419
  // check fields
2420
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
5,401,954✔
2421
    int8_t type = *(int8_t*)p;
4,160,269✔
2422
    p += sizeof(int8_t);
4,160,269✔
2423

2424
    int32_t bytes = *(int32_t*)p;
4,160,269✔
2425
    p += sizeof(int32_t);
4,160,269✔
2426
  }
2427

2428
  int32_t* colLength = (int32_t*)p;
1,241,685✔
2429
  p += sizeof(int32_t) * pResultInfo->numOfCols;
1,241,685✔
2430

2431
  char* pStart = p;
1,241,685✔
2432
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
5,401,797✔
2433
    if ((pStart - pResultInfo->pData) >= dataLen) {
4,160,123!
2434
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2435
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2436
    }
2437
    if (blockVersion == BLOCK_VERSION_1) {
4,160,123✔
2438
      colLength[i] = htonl(colLength[i]);
2,324,589✔
2439
    }
2440
    if (colLength[i] >= dataLen) {
4,160,123!
2441
      tscError("invalid colLength %d, dataLen %d", colLength[i], dataLen);
×
2442
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2443
    }
2444
    if (IS_INVALID_TYPE(pResultInfo->fields[i].type)) {
4,160,123!
2445
      tscError("invalid type %d", pResultInfo->fields[i].type);
11!
2446
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2447
    }
2448
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
4,160,112✔
2449
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
1,072,762✔
2450
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
1,072,762✔
2451
    } else {
2452
      pResultInfo->pCol[i].nullbitmap = pStart;
3,087,350✔
2453
      pStart += BitmapLen(pResultInfo->numOfRows);
3,087,350✔
2454
    }
2455

2456
    pResultInfo->pCol[i].pData = pStart;
4,160,112✔
2457
    pResultInfo->length[i] = pResultInfo->fields[i].bytes;
4,160,112✔
2458
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
4,160,112✔
2459

2460
    pStart += colLength[i];
4,160,112✔
2461
  }
2462

2463
  p = pStart;
1,241,674✔
2464
  // bool blankFill = *(bool*)p;
2465
  p += sizeof(bool);
1,241,674✔
2466
  int32_t offset = p - pResultInfo->pData;
1,241,674✔
2467
  if (offset > dataLen) {
1,241,674!
2468
    tscError("invalid offset %d, dataLen %d", offset, dataLen);
×
2469
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2470
  }
2471

2472
  if (convertUcs4) {
1,241,674✔
2473
    code = doConvertUCS4(pResultInfo, colLength);
1,241,543✔
2474
  }
2475

2476
  return code;
1,241,699✔
2477
}
2478

2479
char* getDbOfConnection(STscObj* pObj) {
3,328,803✔
2480
  terrno = TSDB_CODE_SUCCESS;
3,328,803✔
2481
  char* p = NULL;
3,328,880✔
2482
  (void)taosThreadMutexLock(&pObj->mutex);
3,328,880✔
2483
  size_t len = strlen(pObj->db);
3,329,062✔
2484
  if (len > 0) {
3,329,062✔
2485
    p = taosStrndup(pObj->db, tListLen(pObj->db));
3,054,017!
2486
    if (p == NULL) {
3,053,820!
2487
      tscError("failed to taosStrndup db name");
×
2488
    }
2489
  }
2490

2491
  (void)taosThreadMutexUnlock(&pObj->mutex);
3,328,865✔
2492
  return p;
3,329,043✔
2493
}
2494

2495
void setConnectionDB(STscObj* pTscObj, const char* db) {
7,495✔
2496
  if (db == NULL || pTscObj == NULL) {
7,495!
2497
    tscError("setConnectionDB para is NULL");
×
2498
    return;
×
2499
  }
2500

2501
  (void)taosThreadMutexLock(&pTscObj->mutex);
7,495✔
2502
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
7,495✔
2503
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
7,495✔
2504
}
2505

2506
void resetConnectDB(STscObj* pTscObj) {
×
2507
  if (pTscObj == NULL) {
×
2508
    return;
×
2509
  }
2510

2511
  (void)taosThreadMutexLock(&pTscObj->mutex);
×
2512
  pTscObj->db[0] = 0;
×
2513
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
×
2514
}
2515

2516
int32_t setQueryResultFromRsp(SReqResultInfo* pResultInfo, const SRetrieveTableRsp* pRsp, bool convertUcs4) {
977,747✔
2517
  if (pResultInfo == NULL || pRsp == NULL) {
977,747!
2518
    tscError("setQueryResultFromRsp paras is null");
×
2519
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2520
  }
2521

2522
  taosMemoryFreeClear(pResultInfo->pRspMsg);
977,756!
2523
  pResultInfo->pRspMsg = (const char*)pRsp;
977,756✔
2524
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
977,756✔
2525
  pResultInfo->current = 0;
977,750✔
2526
  pResultInfo->completed = (pRsp->completed == 1);
977,750✔
2527
  pResultInfo->precision = pRsp->precision;
977,750✔
2528

2529
  // decompress data if needed
2530
  int32_t payloadLen = htonl(pRsp->payloadLen);
977,750✔
2531

2532
  if (pRsp->compressed) {
977,750✔
2533
    if (pResultInfo->decompBuf == NULL) {
649✔
2534
      pResultInfo->decompBuf = taosMemoryMalloc(payloadLen);
14!
2535
      if (pResultInfo->decompBuf == NULL) {
14!
2536
        tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2537
        return terrno;
×
2538
      }
2539
      pResultInfo->decompBufSize = payloadLen;
14✔
2540
    } else {
2541
      if (pResultInfo->decompBufSize < payloadLen) {
635✔
2542
        char* p = taosMemoryRealloc(pResultInfo->decompBuf, payloadLen);
14!
2543
        if (p == NULL) {
14!
2544
          tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2545
          return terrno;
×
2546
        }
2547

2548
        pResultInfo->decompBuf = p;
14✔
2549
        pResultInfo->decompBufSize = payloadLen;
14✔
2550
      }
2551
    }
2552
  }
2553

2554
  if (payloadLen > 0) {
977,750✔
2555
    int32_t compLen = *(int32_t*)pRsp->data;
904,801✔
2556
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
904,801✔
2557

2558
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
904,801✔
2559

2560
    if (pRsp->compressed && compLen < rawLen) {
904,801!
2561
      int32_t len = tsDecompressString(pStart, compLen, 1, pResultInfo->decompBuf, rawLen, ONE_STAGE_COMP, NULL, 0);
649✔
2562
      if (len < 0) {
649!
2563
        tscError("tsDecompressString failed");
×
2564
        return terrno ? terrno : TSDB_CODE_FAILED;
×
2565
      }
2566
      if (len != rawLen) {
649!
2567
        tscError("tsDecompressString failed, len:%d != rawLen:%d", len, rawLen);
×
2568
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2569
      }
2570
      pResultInfo->pData = pResultInfo->decompBuf;
649✔
2571
      pResultInfo->payloadLen = rawLen;
649✔
2572
    } else {
2573
      pResultInfo->pData = pStart;
904,152✔
2574
      pResultInfo->payloadLen = htonl(pRsp->compLen);
904,152✔
2575
      if (pRsp->compLen != pRsp->payloadLen) {
904,152!
2576
        tscError("pRsp->compLen:%d != pRsp->payloadLen:%d", pRsp->compLen, pRsp->payloadLen);
×
2577
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2578
      }
2579
    }
2580
  }
2581

2582
  // TODO handle the compressed case
2583
  pResultInfo->totalRows += pResultInfo->numOfRows;
977,750✔
2584

2585
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4);
977,750✔
2586
  return code;
977,769✔
2587
}
2588

2589
TSDB_SERVER_STATUS taos_check_server_status(const char* fqdn, int port, char* details, int maxlen) {
5✔
2590
  TSDB_SERVER_STATUS code = TSDB_SRV_STATUS_UNAVAILABLE;
5✔
2591
  void*              clientRpc = NULL;
5✔
2592
  SServerStatusRsp   statusRsp = {0};
5✔
2593
  SEpSet             epSet = {.inUse = 0, .numOfEps = 1};
5✔
2594
  SRpcMsg  rpcMsg = {.info.ahandle = (void*)0x9527, .info.notFreeAhandle = 1, .msgType = TDMT_DND_SERVER_STATUS};
5✔
2595
  SRpcMsg  rpcRsp = {0};
5✔
2596
  SRpcInit rpcInit = {0};
5✔
2597
  char     pass[TSDB_PASSWORD_LEN + 1] = {0};
5✔
2598

2599
  rpcInit.label = "CHK";
5✔
2600
  rpcInit.numOfThreads = 1;
5✔
2601
  rpcInit.cfp = NULL;
5✔
2602
  rpcInit.sessions = 16;
5✔
2603
  rpcInit.connType = TAOS_CONN_CLIENT;
5✔
2604
  rpcInit.idleTime = tsShellActivityTimer * 1000;
5✔
2605
  rpcInit.compressSize = tsCompressMsgSize;
5✔
2606
  rpcInit.user = "_dnd";
5✔
2607

2608
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
5✔
2609
  connLimitNum = TMAX(connLimitNum, 10);
5✔
2610
  connLimitNum = TMIN(connLimitNum, 500);
5✔
2611
  rpcInit.connLimitNum = connLimitNum;
5✔
2612
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
5✔
2613
  rpcInit.readTimeout = tsReadTimeout;
5✔
2614
  if (TSDB_CODE_SUCCESS != taosVersionStrToInt(td_version, &rpcInit.compatibilityVer)) {
5!
2615
    tscError("faild to convert taos version from str to int, errcode:%s", terrstr());
×
2616
    goto _OVER;
×
2617
  }
2618

2619
  clientRpc = rpcOpen(&rpcInit);
5✔
2620
  if (clientRpc == NULL) {
5!
2621
    code = terrno;
×
2622
    tscError("failed to init server status client since %s", tstrerror(code));
×
2623
    goto _OVER;
×
2624
  }
2625

2626
  if (fqdn == NULL) {
5!
2627
    fqdn = tsLocalFqdn;
5✔
2628
  }
2629

2630
  if (port == 0) {
5!
2631
    port = tsServerPort;
5✔
2632
  }
2633

2634
  tstrncpy(epSet.eps[0].fqdn, fqdn, TSDB_FQDN_LEN);
5✔
2635
  epSet.eps[0].port = (uint16_t)port;
5✔
2636
  int32_t ret = rpcSendRecv(clientRpc, &epSet, &rpcMsg, &rpcRsp);
5✔
2637
  if (TSDB_CODE_SUCCESS != ret) {
5!
2638
    tscError("failed to send recv since %s", tstrerror(ret));
×
2639
    goto _OVER;
×
2640
  }
2641

2642
  if (rpcRsp.code != 0 || rpcRsp.contLen <= 0 || rpcRsp.pCont == NULL) {
5!
2643
    tscError("failed to send server status req since %s", terrstr());
1!
2644
    goto _OVER;
1✔
2645
  }
2646

2647
  if (tDeserializeSServerStatusRsp(rpcRsp.pCont, rpcRsp.contLen, &statusRsp) != 0) {
4!
2648
    tscError("failed to parse server status rsp since %s", terrstr());
×
2649
    goto _OVER;
×
2650
  }
2651

2652
  code = statusRsp.statusCode;
4✔
2653
  if (details != NULL) {
4!
2654
    tstrncpy(details, statusRsp.details, maxlen);
4✔
2655
  }
2656

2657
_OVER:
×
2658
  if (clientRpc != NULL) {
5!
2659
    rpcClose(clientRpc);
5✔
2660
  }
2661
  if (rpcRsp.pCont != NULL) {
5✔
2662
    rpcFreeCont(rpcRsp.pCont);
4✔
2663
  }
2664
  return code;
5✔
2665
}
2666

2667
int32_t appendTbToReq(SHashObj* pHash, int32_t pos1, int32_t len1, int32_t pos2, int32_t len2, const char* str,
3✔
2668
                      int32_t acctId, char* db) {
2669
  SName name = {0};
3✔
2670

2671
  if (len1 <= 0) {
3!
2672
    return -1;
×
2673
  }
2674

2675
  const char* dbName = db;
3✔
2676
  const char* tbName = NULL;
3✔
2677
  int32_t     dbLen = 0;
3✔
2678
  int32_t     tbLen = 0;
3✔
2679
  if (len2 > 0) {
3!
2680
    dbName = str + pos1;
×
2681
    dbLen = len1;
×
2682
    tbName = str + pos2;
×
2683
    tbLen = len2;
×
2684
  } else {
2685
    dbLen = strlen(db);
3✔
2686
    tbName = str + pos1;
3✔
2687
    tbLen = len1;
3✔
2688
  }
2689

2690
  if (dbLen <= 0 || tbLen <= 0) {
3!
2691
    return -1;
×
2692
  }
2693

2694
  if (tNameSetDbName(&name, acctId, dbName, dbLen)) {
3!
2695
    return -1;
×
2696
  }
2697

2698
  if (tNameAddTbName(&name, tbName, tbLen)) {
3!
2699
    return -1;
×
2700
  }
2701

2702
  char dbFName[TSDB_DB_FNAME_LEN] = {0};
3✔
2703
  (void)snprintf(dbFName, TSDB_DB_FNAME_LEN, "%d.%.*s", acctId, dbLen, dbName);
3✔
2704

2705
  STablesReq* pDb = taosHashGet(pHash, dbFName, strlen(dbFName));
3✔
2706
  if (pDb) {
3!
2707
    if (NULL == taosArrayPush(pDb->pTables, &name)) {
×
2708
      return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
2709
    }
2710
  } else {
2711
    STablesReq db;
2712
    db.pTables = taosArrayInit(20, sizeof(SName));
3✔
2713
    if (NULL == db.pTables) {
3!
2714
      return terrno;
×
2715
    }
2716
    tstrncpy(db.dbFName, dbFName, TSDB_DB_FNAME_LEN);
3✔
2717
    if (NULL == taosArrayPush(db.pTables, &name)) {
6!
2718
      return terrno;
×
2719
    }
2720
    TSC_ERR_RET(taosHashPut(pHash, dbFName, strlen(dbFName), &db, sizeof(db)));
3!
2721
  }
2722

2723
  return TSDB_CODE_SUCCESS;
3✔
2724
}
2725

2726
int32_t transferTableNameList(const char* tbList, int32_t acctId, char* dbName, SArray** pReq) {
3✔
2727
  SHashObj* pHash = taosHashInit(3, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
3✔
2728
  if (NULL == pHash) {
3!
2729
    return terrno;
×
2730
  }
2731

2732
  bool    inEscape = false;
3✔
2733
  int32_t code = 0;
3✔
2734
  void*   pIter = NULL;
3✔
2735

2736
  int32_t vIdx = 0;
3✔
2737
  int32_t vPos[2];
2738
  int32_t vLen[2];
2739

2740
  (void)memset(vPos, -1, sizeof(vPos));
3✔
2741
  (void)memset(vLen, 0, sizeof(vLen));
3✔
2742

2743
  for (int32_t i = 0;; ++i) {
12✔
2744
    if (0 == *(tbList + i)) {
12✔
2745
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
3!
2746
        vLen[vIdx] = i - vPos[vIdx];
3✔
2747
      }
2748

2749
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
3✔
2750
      if (code) {
3!
2751
        goto _return;
×
2752
      }
2753

2754
      break;
3✔
2755
    }
2756

2757
    if ('`' == *(tbList + i)) {
9!
2758
      inEscape = !inEscape;
×
2759
      if (!inEscape) {
×
2760
        if (vPos[vIdx] >= 0) {
×
2761
          vLen[vIdx] = i - vPos[vIdx];
×
2762
        } else {
2763
          goto _return;
×
2764
        }
2765
      }
2766

2767
      continue;
×
2768
    }
2769

2770
    if (inEscape) {
9!
2771
      if (vPos[vIdx] < 0) {
×
2772
        vPos[vIdx] = i;
×
2773
      }
2774
      continue;
×
2775
    }
2776

2777
    if ('.' == *(tbList + i)) {
9!
2778
      if (vPos[vIdx] < 0) {
×
2779
        goto _return;
×
2780
      }
2781
      if (vLen[vIdx] <= 0) {
×
2782
        vLen[vIdx] = i - vPos[vIdx];
×
2783
      }
2784
      vIdx++;
×
2785
      if (vIdx >= 2) {
×
2786
        goto _return;
×
2787
      }
2788
      continue;
×
2789
    }
2790

2791
    if (',' == *(tbList + i)) {
9!
2792
      if (vPos[vIdx] < 0) {
×
2793
        goto _return;
×
2794
      }
2795
      if (vLen[vIdx] <= 0) {
×
2796
        vLen[vIdx] = i - vPos[vIdx];
×
2797
      }
2798

2799
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
×
2800
      if (code) {
×
2801
        goto _return;
×
2802
      }
2803

2804
      (void)memset(vPos, -1, sizeof(vPos));
×
2805
      (void)memset(vLen, 0, sizeof(vLen));
×
2806
      vIdx = 0;
×
2807
      continue;
×
2808
    }
2809

2810
    if (' ' == *(tbList + i) || '\r' == *(tbList + i) || '\t' == *(tbList + i) || '\n' == *(tbList + i)) {
9!
2811
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
×
2812
        vLen[vIdx] = i - vPos[vIdx];
×
2813
      }
2814
      continue;
×
2815
    }
2816

2817
    if (('a' <= *(tbList + i) && 'z' >= *(tbList + i)) || ('A' <= *(tbList + i) && 'Z' >= *(tbList + i)) ||
9!
2818
        ('0' <= *(tbList + i) && '9' >= *(tbList + i)) || ('_' == *(tbList + i))) {
×
2819
      if (vLen[vIdx] > 0) {
9!
2820
        goto _return;
×
2821
      }
2822
      if (vPos[vIdx] < 0) {
9✔
2823
        vPos[vIdx] = i;
3✔
2824
      }
2825
      continue;
9✔
2826
    }
2827

2828
    goto _return;
×
2829
  }
2830

2831
  int32_t dbNum = taosHashGetSize(pHash);
3✔
2832
  *pReq = taosArrayInit(dbNum, sizeof(STablesReq));
3✔
2833
  if (NULL == pReq) {
3!
2834
    TSC_ERR_JRET(terrno);
×
2835
  }
2836
  pIter = taosHashIterate(pHash, NULL);
3✔
2837
  while (pIter) {
6✔
2838
    STablesReq* pDb = (STablesReq*)pIter;
3✔
2839
    if (NULL == taosArrayPush(*pReq, pDb)) {
6!
2840
      TSC_ERR_JRET(terrno);
×
2841
    }
2842
    pIter = taosHashIterate(pHash, pIter);
3✔
2843
  }
2844

2845
  taosHashCleanup(pHash);
3✔
2846

2847
  return TSDB_CODE_SUCCESS;
3✔
2848

2849
_return:
×
2850

2851
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
2852

2853
  pIter = taosHashIterate(pHash, NULL);
×
2854
  while (pIter) {
×
2855
    STablesReq* pDb = (STablesReq*)pIter;
×
2856
    taosArrayDestroy(pDb->pTables);
×
2857
    pIter = taosHashIterate(pHash, pIter);
×
2858
  }
2859

2860
  taosHashCleanup(pHash);
×
2861

2862
  return terrno;
×
2863
}
2864

2865
void syncCatalogFn(SMetaData* pResult, void* param, int32_t code) {
3✔
2866
  SSyncQueryParam* pParam = param;
3✔
2867
  pParam->pRequest->code = code;
3✔
2868

2869
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
3!
2870
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
2871
  }
2872
}
3✔
2873

2874
void syncQueryFn(void* param, void* res, int32_t code) {
3,182,378✔
2875
  SSyncQueryParam* pParam = param;
3,182,378✔
2876
  pParam->pRequest = res;
3,182,378✔
2877

2878
  if (pParam->pRequest) {
3,182,378!
2879
    pParam->pRequest->code = code;
3,182,398✔
2880
    clientOperateReport(pParam->pRequest);
3,182,398✔
2881
  }
2882

2883
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
3,182,439!
2884
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
2885
  }
2886
}
3,182,507✔
2887

2888
void taosAsyncQueryImpl(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
3,181,931✔
2889
                        int8_t source) {
2890
  if (sql == NULL || NULL == fp) {
3,181,931!
2891
    terrno = TSDB_CODE_INVALID_PARA;
×
2892
    if (fp) {
×
2893
      fp(param, NULL, terrno);
×
2894
    }
2895

2896
    return;
×
2897
  }
2898

2899
  size_t sqlLen = strlen(sql);
3,182,075✔
2900
  if (sqlLen > (size_t)TSDB_MAX_ALLOWED_SQL_LEN) {
3,182,075!
2901
    tscError("sql string exceeds max length:%d", TSDB_MAX_ALLOWED_SQL_LEN);
×
2902
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
2903
    fp(param, NULL, terrno);
×
2904
    return;
×
2905
  }
2906

2907
  SRequestObj* pRequest = NULL;
3,182,075✔
2908
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
3,182,075✔
2909
  if (code != TSDB_CODE_SUCCESS) {
3,181,891!
2910
    terrno = code;
×
2911
    fp(param, NULL, terrno);
×
2912
    return;
×
2913
  }
2914

2915
  pRequest->source = source;
3,181,891✔
2916
  pRequest->body.queryFp = fp;
3,181,891✔
2917
  doAsyncQuery(pRequest, false);
3,181,891✔
2918
}
2919
void taosAsyncQueryImplWithReqid(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
×
2920
                                 int64_t reqid) {
2921
  if (sql == NULL || NULL == fp) {
×
2922
    terrno = TSDB_CODE_INVALID_PARA;
×
2923
    if (fp) {
×
2924
      fp(param, NULL, terrno);
×
2925
    }
2926

2927
    return;
×
2928
  }
2929

2930
  size_t sqlLen = strlen(sql);
×
2931
  if (sqlLen > (size_t)TSDB_MAX_ALLOWED_SQL_LEN) {
×
2932
    tscError("sql string exceeds max length:%d", TSDB_MAX_ALLOWED_SQL_LEN);
×
2933
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
2934
    fp(param, NULL, terrno);
×
2935
    return;
×
2936
  }
2937

2938
  SRequestObj* pRequest = NULL;
×
2939
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, reqid);
×
2940
  if (code != TSDB_CODE_SUCCESS) {
×
2941
    terrno = code;
×
2942
    fp(param, NULL, terrno);
×
2943
    return;
×
2944
  }
2945

2946
  pRequest->body.queryFp = fp;
×
2947
  doAsyncQuery(pRequest, false);
×
2948
}
2949

2950
TAOS_RES* taosQueryImpl(TAOS* taos, const char* sql, bool validateOnly, int8_t source) {
3,181,473✔
2951
  if (NULL == taos) {
3,181,473!
2952
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
2953
    return NULL;
×
2954
  }
2955

2956
  tscDebug("connObj:0x%" PRIx64 ", taos_query start with sql:%s", *(int64_t*)taos, sql);
3,181,473✔
2957

2958
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
3,181,473!
2959
  if (NULL == param) {
3,181,561!
2960
    return NULL;
×
2961
  }
2962
  int32_t code = tsem_init(&param->sem, 0, 0);
3,181,561✔
2963
  if (TSDB_CODE_SUCCESS != code) {
3,181,608!
2964
    taosMemoryFree(param);
×
2965
    return NULL;
×
2966
  }
2967

2968
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
3,181,608✔
2969
  code = tsem_wait(&param->sem);
3,180,997✔
2970
  if (TSDB_CODE_SUCCESS != code) {
3,181,419!
2971
    taosMemoryFree(param);
×
2972
    return NULL;
×
2973
  }
2974
  code = tsem_destroy(&param->sem);
3,181,419✔
2975
  if (TSDB_CODE_SUCCESS != code) {
3,181,430!
2976
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
2977
  }
2978

2979
  SRequestObj* pRequest = NULL;
3,181,514✔
2980
  if (param->pRequest != NULL) {
3,181,514!
2981
    param->pRequest->syncQuery = true;
3,181,514✔
2982
    pRequest = param->pRequest;
3,181,514✔
2983
    param->pRequest->inCallback = false;
3,181,514✔
2984
  }
2985
  taosMemoryFree(param);
3,181,514!
2986

2987
  tscDebug("connObj:0x%" PRIx64 ", res:%p created, taos_query end", *(int64_t*)taos, pRequest);
3,181,450✔
2988

2989
  return pRequest;
3,181,479✔
2990
}
2991

2992
TAOS_RES* taosQueryImplWithReqid(TAOS* taos, const char* sql, bool validateOnly, int64_t reqid) {
×
2993
  if (NULL == taos) {
×
2994
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
2995
    return NULL;
×
2996
  }
2997

2998
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
×
2999
  if (param == NULL) {
×
3000
    return NULL;
×
3001
  }
3002
  int32_t code = tsem_init(&param->sem, 0, 0);
×
3003
  if (TSDB_CODE_SUCCESS != code) {
×
3004
    taosMemoryFree(param);
×
3005
    return NULL;
×
3006
  }
3007

3008
  taosAsyncQueryImplWithReqid(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, reqid);
×
3009
  code = tsem_wait(&param->sem);
×
3010
  if (TSDB_CODE_SUCCESS != code) {
×
3011
    taosMemoryFree(param);
×
3012
    return NULL;
×
3013
  }
3014
  SRequestObj* pRequest = NULL;
×
3015
  if (param->pRequest != NULL) {
×
3016
    param->pRequest->syncQuery = true;
×
3017
    pRequest = param->pRequest;
×
3018
  }
3019
  taosMemoryFree(param);
×
3020
  return pRequest;
×
3021
}
3022

3023
static void fetchCallback(void* pResult, void* param, int32_t code) {
881,471✔
3024
  SRequestObj* pRequest = (SRequestObj*)param;
881,471✔
3025

3026
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
881,471✔
3027

3028
  tscDebug("req:0x%" PRIx64 ", enter scheduler fetch cb, code:%d - %s, QID:0x%" PRIx64, pRequest->self, code, tstrerror(code),
881,471✔
3029
           pRequest->requestId);
3030

3031
  pResultInfo->pData = pResult;
881,462✔
3032
  pResultInfo->numOfRows = 0;
881,462✔
3033

3034
  if (code != TSDB_CODE_SUCCESS) {
881,462!
3035
    pRequest->code = code;
×
3036
    taosMemoryFreeClear(pResultInfo->pData);
×
3037
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
×
3038
    return;
×
3039
  }
3040

3041
  if (pRequest->code != TSDB_CODE_SUCCESS) {
881,462!
3042
    taosMemoryFreeClear(pResultInfo->pData);
×
3043
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pRequest->code);
×
3044
    return;
×
3045
  }
3046

3047
  pRequest->code =
881,480✔
3048
      setQueryResultFromRsp(pResultInfo, (const SRetrieveTableRsp*)pResultInfo->pData, pResultInfo->convertUcs4);
881,462✔
3049
  if (pRequest->code != TSDB_CODE_SUCCESS) {
881,480!
3050
    pResultInfo->numOfRows = 0;
×
3051
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(pRequest->code),
×
3052
             pRequest->requestId);
3053
  } else {
3054
    tscDebug("req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
881,480✔
3055
             pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed,
3056
             pRequest->requestId);
3057

3058
    STscObj*            pTscObj = pRequest->pTscObj;
881,480✔
3059
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
881,480✔
3060
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
881,480✔
3061
  }
3062

3063
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
881,490✔
3064
}
3065

3066
void taosAsyncFetchImpl(SRequestObj* pRequest, __taos_async_fn_t fp, void* param) {
955,655✔
3067
  pRequest->body.fetchFp = fp;
955,655✔
3068
  ((SSyncQueryParam*)pRequest->body.interParam)->userParam = param;
955,655✔
3069

3070
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
955,655✔
3071

3072
  // this query has no results or error exists, return directly
3073
  if (taos_num_fields(pRequest) == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
955,655!
3074
    pResultInfo->numOfRows = 0;
×
3075
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
×
3076
    return;
74,165✔
3077
  }
3078

3079
  // all data has returned to App already, no need to try again
3080
  if (pResultInfo->completed) {
955,654✔
3081
    // it is a local executed query, no need to do async fetch
3082
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
74,165✔
3083
      if (pResultInfo->localResultFetched) {
1,888✔
3084
        pResultInfo->numOfRows = 0;
944✔
3085
        pResultInfo->current = 0;
944✔
3086
      } else {
3087
        pResultInfo->localResultFetched = true;
944✔
3088
      }
3089
    } else {
3090
      pResultInfo->numOfRows = 0;
72,277✔
3091
    }
3092

3093
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
74,165✔
3094
    return;
74,165✔
3095
  }
3096

3097
  SSchedulerReq req = {
881,489✔
3098
      .syncReq = false,
3099
      .fetchFp = fetchCallback,
3100
      .cbParam = pRequest,
3101
  };
3102

3103
  int32_t code = schedulerFetchRows(pRequest->body.queryJob, &req);
881,489✔
3104
  if (TSDB_CODE_SUCCESS != code) {
881,485!
3105
    tscError("0x%" PRIx64 " failed to schedule fetch rows", pRequest->requestId);
×
3106
    // pRequest->body.fetchFp(param, pRequest, code);
3107
  }
3108
}
3109

3110
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
3,182,877✔
3111
  pRequest->inCallback = true;
3,182,877✔
3112
  int64_t this = pRequest->self;
3,182,877✔
3113
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
3,182,877!
3114
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
316!
3115
    code = TSDB_CODE_SUCCESS;
×
3116
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3117
  }
3118
  pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
3,182,877✔
3119
  SRequestObj* pReq = acquireRequest(this);
3,183,030✔
3120
  if (pReq != NULL) {
3,183,081✔
3121
    pReq->inCallback = false;
3,181,799✔
3122
    (void)releaseRequest(this);
3,181,799✔
3123
  }
3124
}
3,183,051✔
3125

3126
int32_t clientParseSql(void* param, const char* dbName, const char* sql, bool parseOnly, const char* effectiveUser,
906✔
3127
                       SParseSqlRes* pRes) {
3128
#ifndef TD_ENTERPRISE
3129
  return TSDB_CODE_SUCCESS;
3130
#else
3131
  return clientParseSqlImpl(param, dbName, sql, parseOnly, effectiveUser, pRes);
906✔
3132
#endif
3133
}
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