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

taosdata / TDengine / #3559

18 Dec 2024 12:59AM UTC coverage: 59.805% (+0.03%) from 59.778%
#3559

push

travis-ci

web-flow
Merge pull request #29187 from taosdata/merge/mainto3.0

merge: main to 3.0 branch

132705 of 287544 branches covered (46.15%)

Branch coverage included in aggregate %.

87 of 95 new or added lines in 19 files covered. (91.58%)

1132 existing lines in 133 files now uncovered.

209591 of 284807 relevant lines covered (73.59%)

8125235.78 hits per line

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

59.07
/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,251,204✔
35
  SRequestObj* pReq = acquireRequest(rId);
1,251,204✔
36
  if (pReq != NULL) {
1,251,204!
37
    pReq->isQuery = true;
1,251,204✔
38
    (void)releaseRequest(rId);
1,251,204✔
39
  }
40
}
1,251,201✔
41

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

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

52
  return true;
18,126✔
53
}
54

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

57
static bool validatePassword(const char* passwd) { return stringLengthCheck(passwd, TSDB_PASSWORD_LEN - 1); }
9,050✔
58

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

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

67
bool chkRequestKilled(void* param) {
32,715,010✔
68
  bool         killed = false;
32,715,010✔
69
  SRequestObj* pRequest = acquireRequest((int64_t)param);
32,715,010✔
70
  if (NULL == pRequest || pRequest->killed) {
33,335,061!
71
    killed = true;
2✔
72
  }
73

74
  (void)releaseRequest((int64_t)param);
33,335,061✔
75

76
  return killed;
33,272,210✔
77
}
78

79
void cleanupAppInfo() {
×
80
  taosHashCleanup(appInfo.pInstMap);
×
81
  taosHashCleanup(appInfo.pInstMapByClusterId);
×
82
}
×
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,
9,053✔
88
                              uint16_t port, int connType, STscObj** pObj) {
89
  TSC_ERR_RET(taos_init());
9,053!
90
  if (!validateUserName(user)) {
9,055!
91
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
92
  }
93

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

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

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

110
    taosEncryptPass_c((uint8_t*)pass, strlen(pass), secretEncrypt);
9,054✔
111
  } else {
112
    tstrncpy(secretEncrypt, auth, tListLen(secretEncrypt));
3✔
113
  }
114

115
  SCorEpSet epSet = {0};
9,055✔
116
  if (ip) {
9,055✔
117
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
6,723✔
118
  } else {
119
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
2,332!
120
  }
121

122
  if (port) {
9,053✔
123
    epSet.epSet.eps[0].port = port;
4,952✔
124
    epSet.epSet.eps[1].port = port;
4,952✔
125
  }
126

127
  char* key = getClusterKey(user, secretEncrypt, ip, port);
9,053✔
128
  if (NULL == key) {
9,053!
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,
9,053!
132
          user, db, key);
133
  for (int32_t i = 0; i < epSet.epSet.numOfEps; ++i) {
20,440✔
134
    tscInfo("ep:%d, %s:%u", i, epSet.epSet.eps[i].fqdn, epSet.epSet.eps[i].port);
11,387!
135
  }
136

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

176
    pInst = &p;
2,218✔
177
  } else {
178
    if (NULL == *pInst || NULL == (*pInst)->pAppHbMgr) {
6,835!
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);
6,835✔
184
  }
185

186
_return:
9,053✔
187

188
  if (TSDB_CODE_SUCCESS != code) {
9,053!
189
    (void)taosThreadMutexUnlock(&appInfo.mutex);
×
190
    taosMemoryFreeClear(key);
×
191
    return code;
×
192
  } else {
193
    code = taosThreadMutexUnlock(&appInfo.mutex);
9,053✔
194
    taosMemoryFreeClear(key);
9,053!
195
    if (TSDB_CODE_SUCCESS != code) {
9,053!
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);
9,053✔
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) {
601✔
213
  if (param == NULL) return;
601!
214
  if (TSDB_CODE_SUCCESS != tsem_destroy(&param->sem)) {
601!
215
    tscError("failed to destroy semaphore in freeQueryParam");
×
216
  }
217
  taosMemoryFree(param);
601!
218
}
219

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

228
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
10,328,239!
229
  if ((*pRequest)->sqlstr == NULL) {
10,316,653!
230
    tscError("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);
10,316,653✔
237
  (*pRequest)->sqlstr[sqlLen] = 0;
10,324,937✔
238
  (*pRequest)->sqlLen = sqlLen;
10,324,937✔
239
  (*pRequest)->validateOnly = validateSql;
10,324,937✔
240
  (*pRequest)->isStmtBind = false;
10,324,937✔
241

242
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
10,324,937✔
243

244
  STscObj* pTscObj = (*pRequest)->pTscObj;
10,324,937✔
245
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
10,324,937✔
246
                             sizeof((*pRequest)->self));
247
  if (err) {
10,314,502!
248
    tscError("%" PRId64 " failed to add to request container,QID:0x%" PRIx64 ", conn:%" 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;
10,314,502✔
256
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
10,314,502!
257
    if (TSDB_CODE_SUCCESS !=
929,377!
258
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
929,379✔
259
      tscError("%" PRId64 " failed to create node allocator,QID:0x%" PRIx64 ", conn:%" PRId64 ", %s", (*pRequest)->self,
×
260
               (*pRequest)->requestId, pTscObj->id, sql);
261
      destroyRequest(*pRequest);
×
262
      *pRequest = NULL;
×
263
      return terrno;
×
264
    }
265
  }
266

267
  tscDebugL("0x%" PRIx64 " SQL: %s,QID:0x%" PRIx64, (*pRequest)->self, (*pRequest)->sqlstr, (*pRequest)->requestId);
10,321,608✔
268
  return TSDB_CODE_SUCCESS;
10,320,266✔
269
}
270

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

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

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

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

313
  code = qParseSql(&cxt, pQuery);
22✔
314
  if (TSDB_CODE_SUCCESS == code) {
21✔
315
    if ((*pQuery)->haveResultSet) {
20!
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)) {
21!
322
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
21✔
323
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
21✔
324
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
21✔
325
  }
326

327
  taosArrayDestroy(cxt.pTableMetaPos);
21✔
328
  taosArrayDestroy(cxt.pTableVgroupPos);
22✔
329

330
  return code;
22✔
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) {
334✔
345
  // drop table if exists not_exists_table
346
  if (NULL == pQuery->pCmdMsg) {
334!
347
    return TSDB_CODE_SUCCESS;
×
348
  }
349

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

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

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

364
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
19,980,385✔
365

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

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

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

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

392
  doRequestCallback(pRequest, code);
114,161✔
393
}
394

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

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

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

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

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

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

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

430
  return node1->load > node2->load;
193,290✔
431
}
432

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

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

449
  return TSDB_CODE_SUCCESS;
69,318✔
450
}
451

452
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
10,328,596✔
453
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
10,328,596✔
454
    *required = false;
9,715,893✔
455
    return TSDB_CODE_SUCCESS;
9,715,893✔
456
  }
457

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

462
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
612,703!
463
  *required = (NULL == pInfo->pQnodeList);
612,703✔
464
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
612,703!
465
  return TSDB_CODE_SUCCESS;
612,703✔
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) {
589✔
501
  pRequest->type = pQuery->msgType;
589✔
502
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
589✔
503

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

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

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

524
  pResInfo->numOfCols = numOfCols;
1,072,138✔
525
  if (pResInfo->fields != NULL) {
1,072,138✔
526
    taosMemoryFree(pResInfo->fields);
25!
527
  }
528
  if (pResInfo->userFields != NULL) {
1,072,138✔
529
    taosMemoryFree(pResInfo->userFields);
25!
530
  }
531
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
1,072,138!
532
  if (NULL == pResInfo->fields) return terrno;
1,072,134!
533
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
1,072,134!
534
  if (NULL == pResInfo->userFields) {
1,072,126!
535
    taosMemoryFree(pResInfo->fields);
×
536
    return terrno;
×
537
  }
538
  if (numOfCols != pResInfo->numOfCols) {
1,072,126!
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) {
4,641,280✔
544
    pResInfo->fields[i].bytes = pSchema[i].bytes;
3,569,154✔
545
    pResInfo->fields[i].type = pSchema[i].type;
3,569,154✔
546

547
    pResInfo->userFields[i].bytes = pSchema[i].bytes;
3,569,154✔
548
    pResInfo->userFields[i].type = pSchema[i].type;
3,569,154✔
549

550
    if (pSchema[i].type == TSDB_DATA_TYPE_VARCHAR || pSchema[i].type == TSDB_DATA_TYPE_VARBINARY ||
3,569,154✔
551
        pSchema[i].type == TSDB_DATA_TYPE_GEOMETRY) {
2,787,828✔
552
      pResInfo->userFields[i].bytes -= VARSTR_HEADER_SIZE;
781,354✔
553
    } else if (pSchema[i].type == TSDB_DATA_TYPE_NCHAR || pSchema[i].type == TSDB_DATA_TYPE_JSON) {
2,787,800✔
554
      pResInfo->userFields[i].bytes = (pResInfo->userFields[i].bytes - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE;
192,407✔
555
    }
556

557
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
3,569,154✔
558
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
3,569,154✔
559
  }
560
  return TSDB_CODE_SUCCESS;
1,072,126✔
561
}
562

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

569
  pResInfo->precision = precision;
738,584✔
570
}
571

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

579
  int32_t dbNum = taosArrayGetSize(pDbVgList);
379,298✔
580
  for (int32_t i = 0; i < dbNum; ++i) {
755,176✔
581
    SArray* pVg = taosArrayGetP(pDbVgList, i);
375,867✔
582
    if (NULL == pVg) {
375,865!
583
      continue;
×
584
    }
585
    int32_t vgNum = taosArrayGetSize(pVg);
375,865✔
586
    if (vgNum <= 0) {
375,867✔
587
      continue;
481✔
588
    }
589

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

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

607
  int32_t vnodeNum = taosArrayGetSize(nodeList);
379,309✔
608
  if (vnodeNum > 0) {
379,310✔
609
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
374,878✔
610
    goto _return;
374,879✔
611
  }
612

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

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

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

631
_return:
1,354✔
632

633
  *pNodeList = nodeList;
379,312✔
634

635
  return TSDB_CODE_SUCCESS;
379,312✔
636
}
637

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

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

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

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

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

677
_return:
×
678

679
  *pNodeList = nodeList;
278,720✔
680

681
  return TSDB_CODE_SUCCESS;
278,720✔
682
}
683

684
void freeVgList(void* list) {
366✔
685
  SArray* pList = *(SArray**)list;
366✔
686
  taosArrayDestroy(pList);
366✔
687
}
366✔
688

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

695
  switch (tsQueryPolicy) {
657,423!
696
    case QUERY_POLICY_VNODE:
378,706✔
697
    case QUERY_POLICY_CLIENT: {
698
      if (pResultMeta) {
378,706!
699
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
378,711✔
700
        if (NULL == pDbVgList) {
378,718!
701
          code = terrno;
×
702
          goto _return;
×
703
        }
704
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
378,718✔
705
        for (int32_t i = 0; i < dbNum; ++i) {
754,200✔
706
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
375,505✔
707
          if (pRes->code || NULL == pRes->pRes) {
375,495!
708
            continue;
×
709
          }
710

711
          if (NULL == taosArrayPush(pDbVgList, &pRes->pRes)) {
751,000!
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);
378,695✔
756
      break;
378,721✔
757
    }
758
    case QUERY_POLICY_HYBRID:
278,720✔
759
    case QUERY_POLICY_QNODE: {
760
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
283,640!
761
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
4,920✔
762
        if (pRes->code) {
4,920!
763
          pQnodeList = NULL;
×
764
        } else {
765
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
4,920✔
766
          if (NULL == pQnodeList) {
4,920!
767
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
768
            goto _return;
×
769
          }
770
        }
771
      } else {
772
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
273,800✔
773
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
273,800!
774
        if (pInst->pQnodeList) {
273,800!
775
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
273,800✔
776
          if (NULL == pQnodeList) {
273,800!
777
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
778
            goto _return;
×
779
          }
780
        }
781
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
273,800!
782
      }
783

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

792
_return:
657,441✔
793
  taosArrayDestroyEx(pDbVgList, fp);
657,441✔
794
  taosArrayDestroy(pQnodeList);
657,442✔
795

796
  return code;
657,443✔
797
}
798

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

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

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

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

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

842
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
589✔
843
      break;
589✔
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:
×
853
      tscError("unknown query policy: %d", tsQueryPolicy);
×
854
      return TSDB_CODE_APP_ERROR;
×
855
  }
856

857
_return:
589✔
858

859
  taosArrayDestroyEx(pDbVgList, freeVgList);
589✔
860
  taosArrayDestroy(pQnodeList);
589✔
861

862
  return code;
589✔
863
}
864

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

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

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

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

894
  if (code != TSDB_CODE_SUCCESS) {
589!
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 ||
589!
903
      TDMT_VND_CREATE_TABLE == pRequest->type) {
154✔
904
    pRequest->body.resInfo.numOfRows = res.numOfRows;
566✔
905
    if (TDMT_VND_SUBMIT == pRequest->type) {
566✔
906
      STscObj*            pTscObj = pRequest->pTscObj;
435✔
907
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
435✔
908
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
435✔
909
    }
910

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

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

919
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
9,385,664✔
920
  SArray*      pArray = NULL;
9,385,664✔
921
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
9,385,664✔
922
  if (NULL == pRsp->aCreateTbRsp) {
9,385,664✔
923
    return TSDB_CODE_SUCCESS;
9,345,731✔
924
  }
925

926
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
39,933✔
927
  for (int32_t i = 0; i < tbNum; ++i) {
91,168✔
928
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
48,335✔
929
    if (pTbRsp->pMeta) {
48,335✔
930
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
29,428!
931
    }
932
  }
933

934
  return TSDB_CODE_SUCCESS;
42,833✔
935
}
936

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

946
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
526,006✔
947
  if (NULL == pArray) {
526,009!
948
    return terrno;
×
949
  }
950

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

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

969
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
526,011✔
970

971
_return:
526,006✔
972

973
  taosArrayDestroy(pArray);
526,006✔
974
  return code;
526,007✔
975
}
976

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

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

985
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
10,064,362✔
986
  if (NULL == pRequest->body.resInfo.execRes.res) {
10,064,362✔
987
    return pRequest->code;
139,708✔
988
  }
989

990
  SCatalog*     pCatalog = NULL;
9,924,654✔
991
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
9,924,654✔
992

993
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
9,925,633✔
994
  if (code) {
9,927,218!
995
    return code;
×
996
  }
997

998
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
9,927,218✔
999
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
9,959,971✔
1000

1001
  switch (pRes->msgType) {
9,959,971!
1002
    case TDMT_VND_ALTER_TABLE:
154✔
1003
    case TDMT_MND_ALTER_STB: {
1004
      code = handleAlterTbExecRes(pRes->res, pCatalog);
154✔
1005
      break;
154✔
1006
    }
1007
    case TDMT_VND_CREATE_TABLE: {
38,193✔
1008
      SArray* pList = (SArray*)pRes->res;
38,193✔
1009
      int32_t num = taosArrayGetSize(pList);
38,193✔
1010
      for (int32_t i = 0; i < num; ++i) {
108,443✔
1011
        void* res = taosArrayGetP(pList, i);
70,250✔
1012
        // handleCreateTbExecRes will handle res == null
1013
        code = handleCreateTbExecRes(res, pCatalog);
70,246✔
1014
      }
1015
      break;
38,193✔
1016
    }
1017
    case TDMT_MND_CREATE_STB: {
236✔
1018
      code = handleCreateTbExecRes(pRes->res, pCatalog);
236✔
1019
      break;
236✔
1020
    }
1021
    case TDMT_VND_SUBMIT: {
9,396,817✔
1022
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
9,396,817✔
1023

1024
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
9,397,119✔
1025
      break;
9,386,264✔
1026
    }
1027
    case TDMT_SCH_QUERY:
526,008✔
1028
    case TDMT_SCH_MERGE_QUERY: {
1029
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
526,008✔
1030
      break;
526,003✔
1031
    }
1032
    default:
×
1033
      tscError("0x%" PRIx64 ", invalid exec result for request type %d,QID:0x%" PRIx64, pRequest->self, pRequest->type,
×
1034
               pRequest->requestId);
1035
      code = TSDB_CODE_APP_ERROR;
×
1036
  }
1037

1038
  return code;
9,950,850✔
1039
}
1040

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

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

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

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

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

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

UNCOV
1070
  SRequestObj* pUserReq = acquireRequest(pRequest->relation.userRefId);
×
UNCOV
1071
  if (pUserReq) {
×
UNCOV
1072
    pUserReq->code = pRequest->code;
×
1073
    // return to client
UNCOV
1074
    doRequestCallback(pUserReq, pUserReq->code);
×
UNCOV
1075
    (void)releaseRequest(pRequest->relation.userRefId);
×
UNCOV
1076
    return;
×
1077
  } else {
1078
    tscError("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) {
485✔
1084
  int64_t     lastTs = 0;
485✔
1085
  TAOS_FIELD* pResFields = taos_fetch_fields(pRes);
485✔
1086
  int32_t     numOfFields = taos_num_fields(pRes);
485✔
1087

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

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

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

1108
  for (int32_t i = 0; i < numOfRows; ++i) {
1,486✔
1109
    TAOS_ROW pRow = taos_fetch_row(pRes);
1,001✔
1110
    if (NULL == pRow[0] || NULL == pRow[1] || NULL == pRow[2]) {
1,001!
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,001✔
1116
    if (lastTs < ts) {
1,001✔
1117
      lastTs = ts;
573✔
1118
    }
1119

1120
    for (int32_t j = 0; j < numOfFields; ++j) {
4,004✔
1121
      SColumnInfoData* pColInfoData = taosArrayGet((*pBlock)->pDataBlock, j);
3,003✔
1122
      code = colDataSetVal(pColInfoData, i, pRow[j], false);
3,003✔
1123
      if (TSDB_CODE_SUCCESS != code) {
3,003!
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,001✔
1130
  }
1131

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

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

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

1146
  SSDataBlock* pBlock = NULL;
485✔
1147
  pRequest->code = createResultBlock(res, rowNum, &pBlock);
485✔
1148
  if (TSDB_CODE_SUCCESS != pRequest->code) {
485!
1149
    tscError("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);
485✔
1156
  if (pNextReq) {
485!
1157
    continuePostSubQuery(pNextReq, pBlock);
485✔
1158
    (void)releaseRequest(pRequest->relation.nextRefId);
485✔
1159
  } else {
1160
    tscError("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);
485✔
1165
}
1166

1167
void handlePostSubQuery(SSqlCallbackWrapper* pWrapper) {
485✔
1168
  SRequestObj* pRequest = pWrapper->pRequest;
485✔
1169
  if (TD_RES_QUERY(pRequest)) {
485!
1170
    taosAsyncFetchImpl(pRequest, postSubQueryFetchCb, pWrapper);
485✔
1171
    return;
485✔
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("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) {
10,021,736✔
1186
  SSqlCallbackWrapper* pWrapper = param;
10,021,736✔
1187
  SRequestObj*         pRequest = pWrapper->pRequest;
10,021,736✔
1188
  STscObj*             pTscObj = pRequest->pTscObj;
10,021,736✔
1189

1190
  pRequest->code = code;
10,021,736✔
1191
  if (pResult) {
10,021,736!
1192
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
10,025,613✔
1193
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
10,038,626✔
1194
  }
1195

1196
  int32_t type = pRequest->type;
10,034,749✔
1197
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
10,034,749✔
1198
    if (pResult) {
9,392,368!
1199
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
9,404,773✔
1200

1201
      // record the insert rows
1202
      if (TDMT_VND_SUBMIT == type) {
9,404,773✔
1203
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
9,348,297✔
1204
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
9,348,297✔
1205
      }
1206
    }
1207
    schedulerFreeJob(&pRequest->body.queryJob, 0);
9,443,402✔
1208
  }
1209

1210
  taosMemoryFree(pResult);
10,086,700!
1211
  tscDebug("0x%" PRIx64 " enter scheduler exec cb, code:%s,QID:0x%" PRIx64, pRequest->self, tstrerror(code),
10,098,630✔
1212
           pRequest->requestId);
1213

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

1224
  tscDebug("schedulerExecCb request type %s", TMSG_INFO(pRequest->type));
10,076,801!
1225
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
10,076,801!
1226
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
6,989!
1227
      tscError("0x%" PRIx64 " remove meta failed,QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1228
    }
1229
  }
1230

1231
  pRequest->metric.execCostUs = taosGetTimestampUs() - pRequest->metric.execStart;
10,071,468✔
1232
  int32_t code1 = handleQueryExecRsp(pRequest);
10,071,468✔
1233
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
10,089,851!
1234
    pRequest->code = code1;
×
1235
  }
1236

1237
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
20,184,911!
1238
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
10,095,371✔
1239
    continueInsertFromCsv(pWrapper, pRequest);
×
1240
    return;
×
1241
  }
1242

1243
  if (pRequest->relation.nextRefId) {
10,096,055✔
1244
    handlePostSubQuery(pWrapper);
485✔
1245
  } else {
1246
    destorySqlCallbackWrapper(pWrapper);
10,095,570✔
1247
    pRequest->pWrapper = NULL;
10,100,420✔
1248

1249
    // return to client
1250
    doRequestCallback(pRequest, code);
10,100,420✔
1251
  }
1252
}
1253

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

1258
  if (pQuery->pRoot) {
922✔
1259
    pRequest->stmtType = pQuery->pRoot->type;
589✔
1260
  }
1261

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

1272
  pRequest->body.execMode = pQuery->execMode;
922✔
1273
  switch (pQuery->execMode) {
922!
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:
333✔
1285
      if (!pRequest->validateOnly) {
333!
1286
        code = execDdlQuery(pRequest, pQuery);
333✔
1287
      }
1288
      break;
334✔
1289
    case QUERY_EXEC_MODE_SCHEDULE: {
589✔
1290
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
589✔
1291
      if (NULL == pMnodeList) {
589!
1292
        code = terrno;
×
1293
        break;
×
1294
      }
1295
      SQueryPlan* pDag = NULL;
589✔
1296
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
589✔
1297
      if (TSDB_CODE_SUCCESS == code) {
589!
1298
        pRequest->body.subplanNum = pDag->numOfSubplans;
589✔
1299
        if (!pRequest->validateOnly) {
589!
1300
          SArray* pNodeList = NULL;
589✔
1301
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
589✔
1302
          if (TSDB_CODE_SUCCESS == code) {
589!
1303
            code = scheduleQuery(pRequest, pDag, pNodeList);
589✔
1304
          }
1305
          taosArrayDestroy(pNodeList);
589✔
1306
        }
1307
      }
1308
      taosArrayDestroy(pMnodeList);
589✔
1309
      break;
589✔
1310
    }
1311
    case QUERY_EXEC_MODE_EMPTY_RESULT:
×
1312
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
1313
      break;
×
1314
    default:
×
1315
      break;
×
1316
  }
1317

1318
  if (!keepQuery) {
923!
1319
    qDestroyQuery(pQuery);
×
1320
  }
1321

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

1329
  if (TSDB_CODE_SUCCESS == code) {
923✔
1330
    code = handleQueryExecRsp(pRequest);
922✔
1331
  }
1332

1333
  if (TSDB_CODE_SUCCESS != code) {
923✔
1334
    pRequest->code = code;
37✔
1335
  }
1336

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

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

1351
  if (!pRequest->parseOnly) {
10,085,931!
1352
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
10,088,925✔
1353
    if (NULL == pMnodeList) {
10,076,189!
1354
      code = terrno;
×
1355
    }
1356
    SPlanContext cxt = {.queryId = pRequest->requestId,
20,171,197✔
1357
                        .acctId = pRequest->pTscObj->acctId,
10,076,189✔
1358
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
10,076,189✔
1359
                        .pAstRoot = pQuery->pRoot,
10,095,008✔
1360
                        .showRewrite = pQuery->showRewrite,
10,095,008✔
1361
                        .isView = pWrapper->pParseCtx->isView,
10,095,008✔
1362
                        .isAudit = pWrapper->pParseCtx->isAudit,
10,095,008✔
1363
                        .pMsg = pRequest->msgBuf,
10,095,008✔
1364
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1365
                        .pUser = pRequest->pTscObj->user,
10,095,008✔
1366
                        .sysInfo = pRequest->pTscObj->sysInfo,
10,095,008✔
1367
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
10,095,008✔
1368
                        .allocatorId = pRequest->allocatorRefId};
10,095,008✔
1369
    if (TSDB_CODE_SUCCESS == code) {
10,095,008✔
1370
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
10,094,395✔
1371
    }
1372
    if (code) {
10,052,074✔
1373
      tscError("0x%" PRIx64 " failed to create query plan, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
889!
1374
               pRequest->requestId);
1375
    } else {
1376
      pRequest->body.subplanNum = pDag->numOfSubplans;
10,051,185✔
1377
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
10,051,185✔
1378
    }
1379
  }
1380

1381
  pRequest->metric.execStart = taosGetTimestampUs();
10,036,811✔
1382
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
10,036,811✔
1383

1384
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
20,103,113!
1385
    SArray* pNodeList = NULL;
10,056,155✔
1386
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
10,056,155✔
1387
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
657,437✔
1388
    }
1389

1390
    SRequestConnInfo conn = {.pTrans = getAppInfo(pRequest)->pTransporter,
10,056,160✔
1391
                             .requestId = pRequest->requestId,
10,037,598✔
1392
                             .requestObjRefId = pRequest->self};
10,037,598✔
1393
    SSchedulerReq    req = {
20,066,347✔
1394
           .syncReq = false,
1395
           .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
10,037,598✔
1396
           .pConn = &conn,
1397
           .pNodeList = pNodeList,
1398
           .pDag = pDag,
1399
           .allocatorRefId = pRequest->allocatorRefId,
10,037,598✔
1400
           .sql = pRequest->sqlstr,
10,037,598✔
1401
           .startTs = pRequest->metric.start,
10,037,598✔
1402
           .execFp = schedulerExecCb,
1403
           .cbParam = pWrapper,
1404
           .chkKillFp = chkRequestKilled,
1405
           .chkKillParam = (void*)pRequest->self,
10,037,598✔
1406
           .pExecRes = NULL,
1407
           .source = pRequest->source,
10,037,598✔
1408
           .pWorkerCb = getTaskPoolWorkerCb(),
10,037,598✔
1409
    };
1410
    if (TSDB_CODE_SUCCESS == code) {
10,028,749!
1411
      code = schedulerExecJob(&req, &pRequest->body.queryJob);
10,031,028✔
1412
    }
1413

1414
    taosArrayDestroy(pNodeList);
10,070,476✔
1415
  } else {
1416
    qDestroyQueryPlan(pDag);
×
1417
    tscDebug("0x%" PRIx64 " plan not executed, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
1,030!
1418
             pRequest->requestId);
1419
    destorySqlCallbackWrapper(pWrapper);
1,030✔
1420
    pRequest->pWrapper = NULL;
1,030✔
1421
    if (TSDB_CODE_SUCCESS != code) {
1,030✔
1422
      pRequest->code = terrno;
889✔
1423
    }
1424

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

1428
  // todo not to be released here
1429
  taosArrayDestroy(pMnodeList);
10,067,332✔
1430

1431
  return code;
10,072,745✔
1432
}
1433

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

1437
  if (pRequest->parseOnly) {
10,173,881✔
1438
    doRequestCallback(pRequest, 0);
402✔
1439
    return;
402✔
1440
  }
1441

1442
  pRequest->body.execMode = pQuery->execMode;
10,173,479✔
1443
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
10,173,479✔
1444
    destorySqlCallbackWrapper(pWrapper);
143,984✔
1445
    pRequest->pWrapper = NULL;
143,984✔
1446
  }
1447

1448
  if (pQuery->pRoot && !pRequest->inRetry) {
10,173,479!
1449
    STscObj*            pTscObj = pRequest->pTscObj;
10,178,037✔
1450
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
10,178,037✔
1451
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
10,178,037✔
1452
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
9,396,178✔
1453
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
9,354,076✔
1454
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
823,961✔
1455
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
598,800✔
1456
    }
1457
  }
1458

1459
  switch (pQuery->execMode) {
10,246,104!
1460
    case QUERY_EXEC_MODE_LOCAL:
114,179✔
1461
      asyncExecLocalCmd(pRequest, pQuery);
114,179✔
1462
      break;
114,179✔
1463
    case QUERY_EXEC_MODE_RPC:
27,037✔
1464
      code = asyncExecDdlQuery(pRequest, pQuery);
27,037✔
1465
      break;
27,037✔
1466
    case QUERY_EXEC_MODE_SCHEDULE: {
10,102,120✔
1467
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
10,102,120✔
1468
      break;
10,061,600✔
1469
    }
1470
    case QUERY_EXEC_MODE_EMPTY_RESULT:
2,768✔
1471
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
2,768✔
1472
      doRequestCallback(pRequest, 0);
2,768✔
1473
      break;
2,768✔
1474
    default:
×
1475
      tscError("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) {
12✔
1482
  SCatalog* pCatalog = NULL;
12✔
1483
  int32_t   code = 0;
12✔
1484
  int32_t   dbNum = taosArrayGetSize(pRequest->dbList);
12✔
1485
  int32_t   tblNum = taosArrayGetSize(pRequest->tableList);
12✔
1486

1487
  if (dbNum <= 0 && tblNum <= 0) {
12!
1488
    return TSDB_CODE_APP_ERROR;
12✔
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) {
8,822✔
1525
  SCatalog* pCatalog = NULL;
8,822✔
1526
  int32_t   tbNum = taosArrayGetSize(tbList);
8,822✔
1527
  int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
8,822✔
1528
  if (code != TSDB_CODE_SUCCESS) {
8,822!
1529
    return code;
×
1530
  }
1531

1532
  if (isView) {
8,822✔
1533
    for (int32_t i = 0; i < tbNum; ++i) {
526✔
1534
      SName* pViewName = taosArrayGet(tbList, i);
263✔
1535
      char   dbFName[TSDB_DB_FNAME_LEN];
1536
      if (NULL == pViewName) {
263!
1537
        continue;
×
1538
      }
1539
      (void)tNameGetFullDbName(pViewName, dbFName);
263✔
1540
      TSC_ERR_RET(catalogRemoveViewMeta(pCatalog, dbFName, 0, pViewName->tname, 0));
263!
1541
    }
1542
  } else {
1543
    for (int32_t i = 0; i < tbNum; ++i) {
11,916✔
1544
      SName* pTbName = taosArrayGet(tbList, i);
3,357✔
1545
      TSC_ERR_RET(catalogRemoveTableMeta(pCatalog, pTbName));
3,357!
1546
    }
1547
  }
1548

1549
  return TSDB_CODE_SUCCESS;
8,822✔
1550
}
1551

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

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

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

1566
    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
9,055✔
1567
    if (code != TSDB_CODE_SUCCESS) {
9,055!
1568
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1569
      return terrno;
×
1570
    }
1571
    uint32_t addr = 0;
9,055✔
1572
    code = taosGetIpv4FromFqdn(mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
9,055✔
1573
    if (code) {
9,057✔
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++;
9,053✔
1579
    }
1580
  }
1581

1582
  if (secondEp && secondEp[0] != 0) {
9,055!
1583
    if (strlen(secondEp) >= TSDB_EP_LEN) {
2,334!
1584
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1585
      return terrno;
×
1586
    }
1587

1588
    int32_t code = taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
2,334✔
1589
    if (code != TSDB_CODE_SUCCESS) {
2,334!
1590
      return code;
×
1591
    }
1592
    uint32_t addr = 0;
2,334✔
1593
    code = taosGetIpv4FromFqdn(mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
2,334✔
1594
    if (code) {
2,334!
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++;
2,334✔
1600
    }
1601
  }
1602

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

1608
  return 0;
9,051✔
1609
}
1610

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

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

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

1633
  SMsgSendInfo* body = NULL;
9,053✔
1634
  code = buildConnectMsg(pRequest, &body);
9,053✔
1635
  if (TSDB_CODE_SUCCESS != code) {
9,053!
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);
9,053✔
1642
  if (TSDB_CODE_SUCCESS != code) {
9,053!
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)) {
9,053!
1648
    destroyTscObj(*pTscObj);
×
1649
    tscError("failed to wait sem, code:%s", terrstr());
×
1650
    return terrno;
×
1651
  }
1652
  if (pRequest->code != TSDB_CODE_SUCCESS) {
9,053✔
1653
    const char* errorMsg = (code == TSDB_CODE_RPC_FQDN_ERROR) ? taos_errstr(pRequest) : tstrerror(pRequest->code);
128!
1654
    tscError("failed to connect to server, reason: %s", errorMsg);
128!
1655

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

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

1675
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
9,053✔
1676

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

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

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

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

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

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

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

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

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

1727
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
12,710,992✔
1728
  if (NULL == pEpSet) {
12,710,992✔
1729
    return;
11,430,497✔
1730
  }
1731

1732
  switch (pSendInfo->target.type) {
1,280,495✔
1733
    case TARGET_TYPE_MNODE:
6✔
1734
      if (NULL == pTscObj) {
6!
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;
6✔
1741
      SEp*    pOrigEp = &pOrig->eps[pOrig->inUse];
6✔
1742
      SEp*    pNewEp = &pEpSet->eps[pEpSet->inUse];
6✔
1743
      tscDebug("mnode epset updated from %d/%d=>%s:%d to %d/%d=>%s:%d in client", pOrig->inUse, pOrig->numOfEps,
6!
1744
               pOrigEp->fqdn, pOrigEp->port, pEpSet->inUse, pEpSet->numOfEps, pNewEp->fqdn, pNewEp->port);
1745
      updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
6✔
1746
      break;
6✔
1747
    case TARGET_TYPE_VNODE: {
732,059✔
1748
      if (NULL == pTscObj) {
732,059!
1749
        tscError("vnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1750
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1751
        return;
×
1752
      }
1753

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

1762
      code = catalogUpdateVgEpSet(pCatalog, pSendInfo->target.dbFName, pSendInfo->target.vgId, pEpSet);
732,059✔
1763
      if (code != TSDB_CODE_SUCCESS) {
732,059!
1764
        tscError("fail to update catalog vg epset, clusterId:%" PRIx64 ", error %s", pTscObj->pAppInfo->clusterId,
×
1765
                 tstrerror(code));
1766
        return;
×
1767
      }
1768
      taosMemoryFreeClear(pSendInfo->target.dbFName);
732,059!
1769
      break;
732,056✔
1770
    }
1771
    default:
548,430✔
1772
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
548,430!
1773
      break;
549,456✔
1774
  }
1775
}
1776

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

1786
  STscObj* pTscObj = NULL;
12,718,811✔
1787

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

1792
  tscDebug("processMsgFromServer handle %p, message: %s, size:%d, code: %s,QID:%s", pMsg->info.handle,
12,715,561!
1793
           TMSG_INFO(pMsg->msgType), pMsg->contLen, tstrerror(pMsg->code), tbuf);
1794

1795
  if (pSendInfo->requestObjRefId != 0) {
12,715,620✔
1796
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
11,668,295✔
1797
    if (pRequest) {
11,666,406!
1798
      if (pRequest->self != pSendInfo->requestObjRefId) {
11,667,028!
1799
        tscError("doProcessMsgFromServer pRequest->self:%" PRId64 " != pSendInfo->requestObjRefId:%" 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;
11,667,028✔
1811
    }
1812
  }
1813

1814
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
12,713,731✔
1815

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

1823
  if (pMsg->contLen > 0) {
12,709,701✔
1824
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
12,652,310!
1825
    if (buf.pData == NULL) {
12,651,831!
1826
      pMsg->code = terrno;
×
1827
    } else {
1828
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
12,651,831✔
1829
    }
1830
  }
1831

1832
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
12,709,222✔
1833

1834
  if (pTscObj) {
12,705,753✔
1835
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
11,658,135✔
1836
    if (TSDB_CODE_SUCCESS != code) {
11,666,377!
1837
      tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1838
      terrno = code;
×
1839
      pMsg->code = code;
×
1840
    }
1841
  }
1842

1843
  rpcFreeCont(pMsg->pCont);
12,713,995✔
1844
  destroySendMsgInfo(pSendInfo);
12,716,888✔
1845
  return TSDB_CODE_SUCCESS;
12,718,631✔
1846
}
1847
int32_t doProcessMsgFromServer(void* param) {
12,721,143✔
1848
  AsyncArg* arg = (AsyncArg*)param;
12,721,143✔
1849
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
12,721,143✔
1850
  taosMemoryFree(arg);
12,717,784!
1851
  return code;
12,719,425✔
1852
}
1853

1854
void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
12,694,530✔
1855
  int32_t code = 0;
12,694,530✔
1856
  SEpSet* tEpSet = NULL;
12,694,530✔
1857
  if (pEpSet != NULL) {
12,694,530✔
1858
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
1,281,521!
1859
    if (NULL == tEpSet) {
1,281,520!
1860
      code = terrno;
×
1861
      pMsg->code = terrno;
×
1862
      goto _exit;
×
1863
    }
1864
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
1,281,520✔
1865
  }
1866

1867
  // pMsg is response msg
1868
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
12,694,529✔
1869
    // restore origin code
1870
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
9,053!
1871
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1872
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
9,053!
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) {
12,685,476!
1878
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
1879
    }
1880
  }
1881

1882
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
12,694,529!
1883
  if (NULL == arg) {
12,696,775!
1884
    code = terrno;
×
1885
    pMsg->code = code;
×
1886
    goto _exit;
×
1887
  }
1888

1889
  arg->msg = *pMsg;
12,696,775✔
1890
  arg->pEpset = tEpSet;
12,696,775✔
1891

1892
  if ((code = taosAsyncExec(doProcessMsgFromServer, arg, NULL)) != 0) {
12,696,775✔
1893
    pMsg->code = code;
1,308✔
1894
    taosMemoryFree(arg);
1,308!
1895
    goto _exit;
×
1896
  }
1897
  return;
12,714,518✔
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) {
3✔
1907
  tscDebug("try to connect to %s:%u by auth, user:%s db:%s", ip, port, user, db);
3✔
1908
  if (user == NULL) {
3!
1909
    user = TSDB_DEFAULT_USER;
×
1910
  }
1911

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

1917
  STscObj* pObj = NULL;
3✔
1918
  int32_t  code = taos_connect_internal(ip, user, NULL, auth, db, port, CONN_TYPE__QUERY, &pObj);
3✔
1919
  if (TSDB_CODE_SUCCESS == code) {
3✔
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;
2✔
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) {
20,188,278✔
1946
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
114,392,802✔
1947
    SResultColumn* pCol = &pResultInfo->pCol[i];
94,204,524✔
1948

1949
    int32_t type = pResultInfo->fields[i].type;
94,204,524✔
1950
    int32_t bytes = pResultInfo->fields[i].bytes;
94,204,524✔
1951

1952
    if (IS_VAR_DATA_TYPE(type)) {
94,204,524✔
1953
      if (!IS_VAR_NULL_TYPE(type, bytes) && pCol->offset[pResultInfo->current] != -1) {
21,218,746!
1954
        char* pStart = pResultInfo->pCol[i].offset[pResultInfo->current] + pResultInfo->pCol[i].pData;
20,526,658✔
1955

1956
        pResultInfo->length[i] = varDataLen(pStart);
20,526,658✔
1957
        pResultInfo->row[i] = varDataVal(pStart);
20,526,658✔
1958
      } else {
1959
        pResultInfo->row[i] = NULL;
692,088✔
1960
        pResultInfo->length[i] = 0;
692,088✔
1961
      }
1962
    } else {
1963
      if (!colDataIsNull_f(pCol->nullbitmap, pResultInfo->current)) {
72,985,778✔
1964
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + bytes * pResultInfo->current;
70,423,220✔
1965
        pResultInfo->length[i] = bytes;
70,423,220✔
1966
      } else {
1967
        pResultInfo->row[i] = NULL;
2,562,558✔
1968
        pResultInfo->length[i] = 0;
2,562,558✔
1969
      }
1970
    }
1971
  }
1972
}
20,188,278✔
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("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) {
630,693✔
2024
  tsem_t* sem = param;
630,693✔
2025
  if (TSDB_CODE_SUCCESS != tsem_post(sem)) {
630,693!
2026
    tscError("failed to post sem, code:%s", terrstr());
×
2027
  }
2028
}
630,691✔
2029

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

2035
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
6,713,710✔
2036
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
6,713,710✔
2037
    // All data has returned to App already, no need to try again
2038
    if (pResultInfo->completed) {
1,160,439✔
2039
      pResultInfo->numOfRows = 0;
529,747✔
2040
      return NULL;
529,747✔
2041
    }
2042

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

2059
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
6,183,961!
2060
    return NULL;
53,107✔
2061
  } else {
2062
    if (setupOneRowPtr) {
6,130,854✔
2063
      doSetOneRowPtr(pResultInfo);
5,516,910✔
2064
      pResultInfo->current += 1;
5,516,921✔
2065
    }
2066

2067
    return pResultInfo->row;
6,130,865✔
2068
  }
2069
}
2070

2071
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
1,078,362✔
2072
  if (pResInfo->row == NULL) {
1,078,362✔
2073
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
966,364!
2074
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
966,379!
2075
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
966,377!
2076
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
966,373!
2077

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

2087
  return TSDB_CODE_SUCCESS;
1,078,377✔
2088
}
2089

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

2095
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
4,724,569✔
2096
    int32_t type = pResultInfo->fields[i].type;
3,646,180✔
2097
    int32_t bytes = pResultInfo->fields[i].bytes;
3,646,180✔
2098

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

2106
      pResultInfo->convertBuf[i] = p;
170,607✔
2107

2108
      SResultColumn* pCol = &pResultInfo->pCol[i];
170,607✔
2109
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
18,021,655✔
2110
        if (pCol->offset[j] != -1) {
17,851,006✔
2111
          char* pStart = pCol->offset[j] + pCol->pData;
17,755,300✔
2112

2113
          int32_t len = taosUcs4ToMbsEx((TdUcs4*)varDataVal(pStart), varDataLen(pStart), varDataVal(p), conv);
17,755,300✔
2114
          if (len < 0 || len > bytes || (p + len) >= (pResultInfo->convertBuf[i] + colLength[i])) {
17,755,338!
2115
            tscError(
×
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);
×
2120
            return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2121
          }
2122

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

2129
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
170,649✔
2130
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
170,649✔
2131
    }
2132
  }
2133
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
1,078,389✔
2134
  return TSDB_CODE_SUCCESS;
1,078,362✔
2135
}
2136

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

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

2146
  int32_t numOfRows = pResultInfo->numOfRows;
340✔
2147
  int32_t numOfCols = pResultInfo->numOfCols;
340✔
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);
340✔
2152
  if (numOfCols != cols) {
340!
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);
340✔
2158
  int32_t* colLength = (int32_t*)(p + len);
340✔
2159
  len += sizeof(int32_t) * numOfCols;
340✔
2160

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

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

2171
      int32_t estimateColLen = 0;
416✔
2172
      for (int32_t j = 0; j < numOfRows; ++j) {
2,764✔
2173
        if (offset[j] == -1) {
2,348✔
2174
          continue;
164✔
2175
        }
2176
        char* data = offset[j] + pStart;
2,184✔
2177

2178
        int32_t jsonInnerType = *data;
2,184✔
2179
        char*   jsonInnerData = data + CHAR_BYTES;
2,184✔
2180
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
2,184✔
2181
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
54✔
2182
        } else if (tTagIsJson(data)) {
2,130✔
2183
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
501✔
2184
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
1,629✔
2185
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
1,407✔
2186
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
222✔
2187
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
162✔
2188
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
60!
2189
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
60✔
2190
        } else {
2191
          tscError("estimateJsonLen error: invalid type:%d", jsonInnerType);
×
2192
          return -1;
×
2193
        }
2194
      }
2195
      len += TMAX(colLen, estimateColLen);
416✔
2196
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
902!
2197
      int32_t lenTmp = numOfRows * sizeof(int32_t);
297✔
2198
      len += (lenTmp + colLen);
297✔
2199
      pStart += lenTmp;
297✔
2200
    } else {
2201
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
605✔
2202
      len += (lenTmp + colLen);
605✔
2203
      pStart += lenTmp;
605✔
2204
    }
2205
    pStart += colLen;
1,318✔
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);
340✔
2211
  return len;
340✔
2212
}
2213

2214
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
1,078,383✔
2215
  int32_t numOfRows = pResultInfo->numOfRows;
1,078,383✔
2216
  int32_t numOfCols = pResultInfo->numOfCols;
1,078,383✔
2217
  bool    needConvert = false;
1,078,383✔
2218
  for (int32_t i = 0; i < numOfCols; ++i) {
4,724,296✔
2219
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
3,646,253✔
2220
      needConvert = true;
340✔
2221
      break;
340✔
2222
    }
2223
  }
2224

2225
  if (!needConvert) {
1,078,383✔
2226
    return TSDB_CODE_SUCCESS;
1,078,038✔
2227
  }
2228

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

2231
  char*   p = (char*)pResultInfo->pData;
345✔
2232
  int32_t blockVersion = *(int32_t*)p;
345✔
2233
  int32_t dataLen = estimateJsonLen(pResultInfo);
345✔
2234
  if (dataLen <= 0) {
340!
2235
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2236
  }
2237

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

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

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

2253
  p += len;
340✔
2254
  p1 += len;
340✔
2255
  totalLen += len;
340✔
2256

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

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

2283
      len = 0;
416✔
2284
      for (int32_t j = 0; j < numOfRows; ++j) {
2,764✔
2285
        if (offset[j] == -1) {
2,348✔
2286
          continue;
164✔
2287
        }
2288
        char* data = offset[j] + pStart;
2,184✔
2289

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

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

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

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

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

2373
  if (pResultInfo->numOfRows == 0) {
1,136,422✔
2374
    return TSDB_CODE_SUCCESS;
58,053✔
2375
  }
2376

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

2382
  int32_t code = doPrepareResPtr(pResultInfo);
1,078,369✔
2383
  if (code != TSDB_CODE_SUCCESS) {
1,078,376!
2384
    return code;
×
2385
  }
2386
  code = doConvertJson(pResultInfo);
1,078,376✔
2387
  if (code != TSDB_CODE_SUCCESS) {
1,078,367!
2388
    return code;
×
2389
  }
2390

2391
  char* p = (char*)pResultInfo->pData;
1,078,367✔
2392

2393
  // version:
2394
  int32_t blockVersion = *(int32_t*)p;
1,078,367✔
2395
  p += sizeof(int32_t);
1,078,367✔
2396

2397
  int32_t dataLen = *(int32_t*)p;
1,078,367✔
2398
  p += sizeof(int32_t);
1,078,367✔
2399

2400
  int32_t rows = *(int32_t*)p;
1,078,367✔
2401
  p += sizeof(int32_t);
1,078,367✔
2402

2403
  int32_t cols = *(int32_t*)p;
1,078,367✔
2404
  p += sizeof(int32_t);
1,078,367✔
2405

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

2412
  int32_t hasColumnSeg = *(int32_t*)p;
1,078,371✔
2413
  p += sizeof(int32_t);
1,078,371✔
2414

2415
  uint64_t groupId = *(uint64_t*)p;
1,078,371✔
2416
  p += sizeof(uint64_t);
1,078,371✔
2417

2418
  // check fields
2419
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
4,724,624✔
2420
    int8_t type = *(int8_t*)p;
3,646,253✔
2421
    p += sizeof(int8_t);
3,646,253✔
2422

2423
    int32_t bytes = *(int32_t*)p;
3,646,253✔
2424
    p += sizeof(int32_t);
3,646,253✔
2425
  }
2426

2427
  int32_t* colLength = (int32_t*)p;
1,078,371✔
2428
  p += sizeof(int32_t) * pResultInfo->numOfCols;
1,078,371✔
2429

2430
  char* pStart = p;
1,078,371✔
2431
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
4,724,465✔
2432
    if ((pStart - pResultInfo->pData) >= dataLen) {
3,646,108!
2433
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2434
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2435
    }
2436
    if (blockVersion == BLOCK_VERSION_1) {
3,646,108✔
2437
      colLength[i] = htonl(colLength[i]);
1,800,129✔
2438
    }
2439
    if (colLength[i] >= dataLen) {
3,646,108!
2440
      tscError("invalid colLength %d, dataLen %d", colLength[i], dataLen);
×
2441
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2442
    }
2443
    if (IS_INVALID_TYPE(pResultInfo->fields[i].type)) {
3,646,108!
2444
      tscError("invalid type %d", pResultInfo->fields[i].type);
14!
2445
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2446
    }
2447
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
3,646,094✔
2448
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
972,888✔
2449
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
972,888✔
2450
    } else {
2451
      pResultInfo->pCol[i].nullbitmap = pStart;
2,673,206✔
2452
      pStart += BitmapLen(pResultInfo->numOfRows);
2,673,206✔
2453
    }
2454

2455
    pResultInfo->pCol[i].pData = pStart;
3,646,094✔
2456
    pResultInfo->length[i] = pResultInfo->fields[i].bytes;
3,646,094✔
2457
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
3,646,094✔
2458

2459
    pStart += colLength[i];
3,646,094✔
2460
  }
2461

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

2471
  if (convertUcs4) {
1,078,357✔
2472
    code = doConvertUCS4(pResultInfo, colLength);
1,078,338✔
2473
  }
2474

2475
  return code;
1,078,388✔
2476
}
2477

2478
char* getDbOfConnection(STscObj* pObj) {
10,337,061✔
2479
  terrno = TSDB_CODE_SUCCESS;
10,337,061✔
2480
  char* p = NULL;
10,336,120✔
2481
  (void)taosThreadMutexLock(&pObj->mutex);
10,336,120✔
2482
  size_t len = strlen(pObj->db);
10,345,878✔
2483
  if (len > 0) {
10,345,878✔
2484
    p = taosStrndup(pObj->db, tListLen(pObj->db));
10,118,356!
2485
    if (p == NULL) {
10,112,046!
2486
      tscError("failed to taosStrndup db name");
×
2487
    }
2488
  }
2489

2490
  (void)taosThreadMutexUnlock(&pObj->mutex);
10,339,568✔
2491
  return p;
10,346,792✔
2492
}
2493

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

2500
  (void)taosThreadMutexLock(&pTscObj->mutex);
5,372✔
2501
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
5,372✔
2502
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
5,372✔
2503
}
2504

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

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

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

2521
  taosMemoryFreeClear(pResultInfo->pRspMsg);
802,892!
2522
  pResultInfo->pRspMsg = (const char*)pRsp;
802,892✔
2523
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
802,892✔
2524
  pResultInfo->current = 0;
802,895✔
2525
  pResultInfo->completed = (pRsp->completed == 1);
802,895✔
2526
  pResultInfo->precision = pRsp->precision;
802,895✔
2527

2528
  // decompress data if needed
2529
  int32_t payloadLen = htonl(pRsp->payloadLen);
802,895✔
2530

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

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

2553
  if (payloadLen > 0) {
802,895✔
2554
    int32_t compLen = *(int32_t*)pRsp->data;
744,839✔
2555
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
744,839✔
2556

2557
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
744,839✔
2558

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

2581
  // TODO handle the compressed case
2582
  pResultInfo->totalRows += pResultInfo->numOfRows;
802,895✔
2583

2584
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4);
802,895✔
2585
  return code;
802,895✔
2586
}
2587

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

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

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

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

2625
  if (fqdn == NULL) {
4!
2626
    fqdn = tsLocalFqdn;
4✔
2627
  }
2628

2629
  if (port == 0) {
4!
2630
    port = tsServerPort;
4✔
2631
  }
2632

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

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

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

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

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

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

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

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

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

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

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

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

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

2722
  return TSDB_CODE_SUCCESS;
×
2723
}
2724

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

2731
  bool    inEscape = false;
×
2732
  int32_t code = 0;
×
2733
  void*   pIter = NULL;
×
2734

2735
  int32_t vIdx = 0;
×
2736
  int32_t vPos[2];
2737
  int32_t vLen[2];
2738

2739
  (void)memset(vPos, -1, sizeof(vPos));
×
2740
  (void)memset(vLen, 0, sizeof(vLen));
×
2741

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

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

2753
      break;
×
2754
    }
2755

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

2766
      continue;
×
2767
    }
2768

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

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

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

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

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

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

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

2827
    goto _return;
×
2828
  }
2829

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

2844
  taosHashCleanup(pHash);
×
2845

2846
  return TSDB_CODE_SUCCESS;
×
2847

2848
_return:
×
2849

2850
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
2851

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

2859
  taosHashCleanup(pHash);
×
2860

2861
  return terrno;
×
2862
}
2863

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

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

2873
void syncQueryFn(void* param, void* res, int32_t code) {
10,319,384✔
2874
  SSyncQueryParam* pParam = param;
10,319,384✔
2875
  pParam->pRequest = res;
10,319,384✔
2876

2877
  if (pParam->pRequest) {
10,319,384✔
2878
    pParam->pRequest->code = code;
10,317,340✔
2879
    clientOperateReport(pParam->pRequest);
10,317,340✔
2880
  }
2881

2882
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
10,321,406!
2883
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
2884
  }
2885
}
10,327,101✔
2886

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

2895
    return;
×
2896
  }
2897

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

2906
  SRequestObj* pRequest = NULL;
10,320,766✔
2907
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
10,320,766✔
2908
  if (code != TSDB_CODE_SUCCESS) {
10,315,088!
2909
    terrno = code;
×
2910
    fp(param, NULL, terrno);
×
2911
    return;
×
2912
  }
2913

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

2926
    return;
×
2927
  }
2928

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

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

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

2949
TAOS_RES* taosQueryImpl(TAOS* taos, const char* sql, bool validateOnly, int8_t source) {
10,313,729✔
2950
  if (NULL == taos) {
10,313,729✔
2951
    terrno = TSDB_CODE_TSC_DISCONNECTED;
1✔
2952
    return NULL;
1✔
2953
  }
2954

2955
  tscDebug("taos_query start with sql:%s", sql);
10,313,728✔
2956

2957
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
10,313,728!
2958
  if (NULL == param) {
10,321,833!
2959
    return NULL;
×
2960
  }
2961
  int32_t code = tsem_init(&param->sem, 0, 0);
10,321,833✔
2962
  if (TSDB_CODE_SUCCESS != code) {
10,318,874!
2963
    taosMemoryFree(param);
×
2964
    return NULL;
×
2965
  }
2966

2967
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
10,318,874✔
2968
  code = tsem_wait(&param->sem);
10,275,887✔
2969
  if (TSDB_CODE_SUCCESS != code) {
10,322,957!
2970
    taosMemoryFree(param);
×
2971
    return NULL;
×
2972
  }
2973
  code = tsem_destroy(&param->sem);
10,322,957✔
2974
  if (TSDB_CODE_SUCCESS != code) {
10,320,954!
2975
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
2976
  }
2977

2978
  SRequestObj* pRequest = NULL;
10,321,785✔
2979
  if (param->pRequest != NULL) {
10,321,785!
2980
    param->pRequest->syncQuery = true;
10,321,785✔
2981
    pRequest = param->pRequest;
10,321,785✔
2982
    param->pRequest->inCallback = false;
10,321,785✔
2983
  }
2984
  taosMemoryFree(param);
10,321,785!
2985

2986
  tscDebug("taos_query end with sql:%s", sql);
10,319,457✔
2987

2988
  return pRequest;
10,320,963✔
2989
}
2990

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

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

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

3022
static void fetchCallback(void* pResult, void* param, int32_t code) {
707,775✔
3023
  SRequestObj* pRequest = (SRequestObj*)param;
707,775✔
3024

3025
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
707,775✔
3026

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

3030
  pResultInfo->pData = pResult;
707,773✔
3031
  pResultInfo->numOfRows = 0;
707,773✔
3032

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

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

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

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

3062
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
707,779✔
3063
}
3064

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

3069
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
778,807✔
3070

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

3078
  // all data has returned to App already, no need to try again
3079
  if (pResultInfo->completed) {
778,807✔
3080
    // it is a local executed query, no need to do async fetch
3081
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
71,028✔
3082
      if (pResultInfo->localResultFetched) {
1,696✔
3083
        pResultInfo->numOfRows = 0;
848✔
3084
        pResultInfo->current = 0;
848✔
3085
      } else {
3086
        pResultInfo->localResultFetched = true;
848✔
3087
      }
3088
    } else {
3089
      pResultInfo->numOfRows = 0;
69,332✔
3090
    }
3091

3092
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
71,028✔
3093
    return;
71,028✔
3094
  }
3095

3096
  SSchedulerReq req = {
707,779✔
3097
      .syncReq = false,
3098
      .fetchFp = fetchCallback,
3099
      .cbParam = pRequest,
3100
  };
3101

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

3109
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
10,319,914✔
3110
  pRequest->inCallback = true;
10,319,914✔
3111
  int64_t this = pRequest->self;
10,319,914✔
3112
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
10,319,914!
3113
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
320!
3114
    code = TSDB_CODE_SUCCESS;
×
3115
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3116
  }
3117
  pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
10,319,914✔
3118
  SRequestObj* pReq = acquireRequest(this);
10,327,091✔
3119
  if (pReq != NULL) {
10,324,142✔
3120
    pReq->inCallback = false;
10,316,126✔
3121
    (void)releaseRequest(this);
10,316,126✔
3122
  }
3123
}
10,320,706✔
3124

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