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

taosdata / TDengine / #3661

17 Mar 2025 05:39AM UTC coverage: 62.007% (-0.03%) from 62.039%
#3661

push

travis-ci

web-flow
tests: add tdb ut (#30093)

* fix: compile warnings

* tests: add tdb ut

* test(tdb): fix return code

* test: recover ut

* fix: minor changes

* fix: enable test

* fix: ut errors

---------

Co-authored-by: Minglei Jin <mljin@taosdata.com>

153829 of 317582 branches covered (48.44%)

Branch coverage included in aggregate %.

240310 of 318051 relevant lines covered (75.56%)

19602636.8 hits per line

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

63.98
/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
#include "decimal.h"
32

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

36
void setQueryRequest(int64_t rId) {
1,405,891✔
37
  SRequestObj* pReq = acquireRequest(rId);
1,405,891✔
38
  if (pReq != NULL) {
1,405,894✔
39
    pReq->isQuery = true;
1,405,893✔
40
    (void)releaseRequest(rId);
1,405,893✔
41
  }
42
}
1,405,891✔
43

44
static bool stringLengthCheck(const char* str, size_t maxsize) {
56,692✔
45
  if (str == NULL) {
56,692!
46
    return false;
×
47
  }
48

49
  size_t len = strlen(str);
56,692✔
50
  if (len <= 0 || len > maxsize) {
56,692!
51
    return false;
×
52
  }
53

54
  return true;
56,700✔
55
}
56

57
static bool validateUserName(const char* user) { return stringLengthCheck(user, TSDB_USER_LEN - 1); }
27,949✔
58

59
static bool validatePassword(const char* passwd) { return stringLengthCheck(passwd, TSDB_PASSWORD_MAX_LEN); }
27,946✔
60

61
static bool validateDbName(const char* db) { return stringLengthCheck(db, TSDB_DB_NAME_LEN - 1); }
796✔
62

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

69
bool chkRequestKilled(void* param) {
34,275,126✔
70
  bool         killed = false;
34,275,126✔
71
  SRequestObj* pRequest = acquireRequest((int64_t)param);
34,275,126✔
72
  if (NULL == pRequest || pRequest->killed) {
34,934,134!
73
    killed = true;
1✔
74
  }
75

76
  (void)releaseRequest((int64_t)param);
34,934,134✔
77

78
  return killed;
34,870,606✔
79
}
80

81
void cleanupAppInfo() {
15,721✔
82
  taosHashCleanup(appInfo.pInstMap);
15,721✔
83
  taosHashCleanup(appInfo.pInstMapByClusterId);
15,721✔
84
}
15,721✔
85

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

89
int32_t taos_connect_internal(const char* ip, const char* user, const char* pass, const char* auth, const char* db,
27,949✔
90
                              uint16_t port, int connType, STscObj** pObj) {
91
  TSC_ERR_RET(taos_init());
27,949!
92
  if (!validateUserName(user)) {
27,953!
93
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
94
  }
95

96
  char localDb[TSDB_DB_NAME_LEN] = {0};
27,952✔
97
  if (db != NULL && strlen(db) > 0) {
27,952!
98
    if (!validateDbName(db)) {
796!
99
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_DB_LENGTH);
×
100
    }
101

102
    tstrncpy(localDb, db, sizeof(localDb));
796✔
103
    (void)strdequote(localDb);
796✔
104
  }
105

106
  char secretEncrypt[TSDB_PASSWORD_LEN + 1] = {0};
27,950✔
107
  if (auth == NULL) {
27,950✔
108
    if (!validatePassword(pass)) {
27,946!
109
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_PASS_LENGTH);
×
110
    }
111

112
    taosEncryptPass_c((uint8_t*)pass, strlen(pass), secretEncrypt);
27,951✔
113
  } else {
114
    tstrncpy(secretEncrypt, auth, tListLen(secretEncrypt));
4✔
115
  }
116

117
  SCorEpSet epSet = {0};
27,949✔
118
  if (ip) {
27,949✔
119
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
12,011✔
120
  } else {
121
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
15,938!
122
  }
123

124
  if (port) {
27,950✔
125
    epSet.epSet.eps[0].port = port;
9,225✔
126
    epSet.epSet.eps[1].port = port;
9,225✔
127
  }
128

129
  char* key = getClusterKey(user, secretEncrypt, ip, port);
27,950✔
130
  if (NULL == key) {
27,951!
131
    TSC_ERR_RET(terrno);
×
132
  }
133
  tscInfo("connecting to server, numOfEps:%d inUse:%d user:%s db:%s key:%s", epSet.epSet.numOfEps, epSet.epSet.inUse,
27,951!
134
          user, db, key);
135
  for (int32_t i = 0; i < epSet.epSet.numOfEps; ++i) {
71,845✔
136
    tscInfo("ep:%d, %s:%u", i, epSet.epSet.eps[i].fqdn, epSet.epSet.eps[i].port);
43,894!
137
  }
138

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

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

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

188
_return:
27,951✔
189

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

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

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

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

230
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
10,740,732!
231
  if ((*pRequest)->sqlstr == NULL) {
10,731,290!
232
    tscError("req:0x%" PRIx64 ", failed to prepare sql string buffer, %s", (*pRequest)->self, sql);
×
233
    destroyRequest(*pRequest);
×
234
    *pRequest = NULL;
×
235
    return terrno;
×
236
  }
237

238
  (void)strntolower((*pRequest)->sqlstr, sql, (int32_t)sqlLen);
10,731,290✔
239
  (*pRequest)->sqlstr[sqlLen] = 0;
10,739,394✔
240
  (*pRequest)->sqlLen = sqlLen;
10,739,394✔
241
  (*pRequest)->validateOnly = validateSql;
10,739,394✔
242
  (*pRequest)->isStmtBind = false;
10,739,394✔
243

244
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
10,739,394✔
245

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

257
  (*pRequest)->allocatorRefId = -1;
10,729,808✔
258
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
10,729,808!
259
    if (TSDB_CODE_SUCCESS !=
1,162,707!
260
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
1,162,702✔
261
      tscError("req:0x%" PRId64 ", failed to create node allocator, QID:0x%" PRIx64 ", connObj:%" PRId64 ", %s", (*pRequest)->self,
×
262
               (*pRequest)->requestId, pTscObj->id, sql);
263
      destroyRequest(*pRequest);
×
264
      *pRequest = NULL;
×
265
      return terrno;
×
266
    }
267
  }
268

269
  tscDebugL("req:0x%" PRIx64 ", QID:0x%" PRIx64 ", build request", (*pRequest)->self, (*pRequest)->requestId);
10,731,730✔
270
  return TSDB_CODE_SUCCESS;
10,730,920✔
271
}
272

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

285
int32_t parseSql(SRequestObj* pRequest, bool topicQuery, SQuery** pQuery, SStmtCallback* pStmtCb) {
10,443✔
286
  STscObj* pTscObj = pRequest->pTscObj;
10,443✔
287

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

309
  cxt.mgmtEpSet = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
10,443✔
310
  int32_t code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &cxt.pCatalog);
10,450✔
311
  if (code != TSDB_CODE_SUCCESS) {
10,451!
312
    return code;
×
313
  }
314

315
  code = qParseSql(&cxt, pQuery);
10,451✔
316
  if (TSDB_CODE_SUCCESS == code) {
10,438✔
317
    if ((*pQuery)->haveResultSet) {
10,429!
318
      code = setResSchemaInfo(&pRequest->body.resInfo, (*pQuery)->pResSchema, (*pQuery)->numOfResCols, (*pQuery)->pResExtSchema, pRequest->isStmtBind);
×
319
      setResPrecision(&pRequest->body.resInfo, (*pQuery)->precision);
×
320
    }
321
  }
322

323
  if (TSDB_CODE_SUCCESS == code || NEED_CLIENT_HANDLE_ERROR(code)) {
10,437!
324
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
10,438✔
325
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
10,438✔
326
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
10,438✔
327
  }
328

329
  taosArrayDestroy(cxt.pTableMetaPos);
10,437✔
330
  taosArrayDestroy(cxt.pTableVgroupPos);
10,447✔
331

332
  return code;
10,447✔
333
}
334

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

343
  return code;
×
344
}
345

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

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

357
  STscObj*      pTscObj = pRequest->pTscObj;
548✔
358
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
548✔
359

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

366
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
20,719,959✔
367

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

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

381
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
118,091✔
382
  pRequest->code = code;
118,091✔
383

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

394
  doRequestCallback(pRequest, code);
118,091✔
395
}
396

397
int32_t asyncExecDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
33,394✔
398
  if (pRequest->validateOnly) {
33,394!
399
    doRequestCallback(pRequest, 0);
×
400
    return TSDB_CODE_SUCCESS;
×
401
  }
402

403
  // drop table if exists not_exists_table
404
  if (NULL == pQuery->pCmdMsg) {
33,394✔
405
    doRequestCallback(pRequest, 0);
1✔
406
    return TSDB_CODE_SUCCESS;
1✔
407
  }
408

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

414
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
33,393✔
415
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
33,393✔
416

417
  int32_t code = asyncSendMsgToServer(pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg);
33,393✔
418
  if (code) {
33,393!
419
    doRequestCallback(pRequest, code);
×
420
  }
421
  return code;
33,393✔
422
}
423

424
int compareQueryNodeLoad(const void* elem1, const void* elem2) {
249,688✔
425
  SQueryNodeLoad* node1 = (SQueryNodeLoad*)elem1;
249,688✔
426
  SQueryNodeLoad* node2 = (SQueryNodeLoad*)elem2;
249,688✔
427

428
  if (node1->load < node2->load) {
249,688!
429
    return -1;
×
430
  }
431

432
  return node1->load > node2->load;
249,688✔
433
}
434

435
int32_t updateQnodeList(SAppInstInfo* pInfo, SArray* pNodeList) {
97,430✔
436
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
97,430!
437
  if (pInfo->pQnodeList) {
97,430✔
438
    taosArrayDestroy(pInfo->pQnodeList);
96,814✔
439
    pInfo->pQnodeList = NULL;
96,814✔
440
    tscDebug("QnodeList cleared in cluster 0x%" PRIx64, pInfo->clusterId);
96,814✔
441
  }
442

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

451
  return TSDB_CODE_SUCCESS;
97,430✔
452
}
453

454
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
10,713,579✔
455
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
10,713,579✔
456
    *required = false;
10,087,361✔
457
    return TSDB_CODE_SUCCESS;
10,087,361✔
458
  }
459

460
  int32_t       code = TSDB_CODE_SUCCESS;
626,218✔
461
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
626,218✔
462
  *required = false;
626,218✔
463

464
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
626,218!
465
  *required = (NULL == pInfo->pQnodeList);
626,218✔
466
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
626,218!
467
  return TSDB_CODE_SUCCESS;
626,218✔
468
}
469

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

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

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

499
  return code;
×
500
}
501

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

506
  SPlanContext cxt = {.queryId = pRequest->requestId,
68,231✔
507
                      .acctId = pRequest->pTscObj->acctId,
34,111✔
508
                      .mgmtEpSet = getEpSet_s(&pAppInfo->mgmtEp),
34,111✔
509
                      .pAstRoot = pQuery->pRoot,
34,120✔
510
                      .showRewrite = pQuery->showRewrite,
34,120✔
511
                      .pMsg = pRequest->msgBuf,
34,120✔
512
                      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
513
                      .pUser = pRequest->pTscObj->user,
34,120✔
514
                      .timezone = pRequest->pTscObj->optionInfo.timezone,
34,120✔
515
                      .sysInfo = pRequest->pTscObj->sysInfo};
34,120✔
516

517
  return qCreateQueryPlan(&cxt, pPlan, pNodeList);
34,120✔
518
}
519

520
int32_t setResSchemaInfo(SReqResultInfo* pResInfo, const SSchema* pSchema, int32_t numOfCols, const SExtSchema* pExtSchema, bool isStmt) {
1,212,036✔
521
  if (pResInfo == NULL || pSchema == NULL || numOfCols <= 0) {
1,212,036!
522
    tscError("invalid paras, pResInfo == NULL || pSchema == NULL || numOfCols <= 0");
×
523
    return TSDB_CODE_INVALID_PARA;
×
524
  }
525

526
  pResInfo->numOfCols = numOfCols;
1,212,075✔
527
  if (pResInfo->fields != NULL) {
1,212,075✔
528
    taosMemoryFree(pResInfo->fields);
39!
529
  }
530
  if (pResInfo->userFields != NULL) {
1,212,075✔
531
    taosMemoryFree(pResInfo->userFields);
39!
532
  }
533
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD_E));
1,212,075!
534
  if (NULL == pResInfo->fields) return terrno;
1,212,067!
535
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
1,212,067!
536
  if (NULL == pResInfo->userFields) {
1,212,035!
537
    taosMemoryFree(pResInfo->fields);
×
538
    return terrno;
×
539
  }
540
  if (numOfCols != pResInfo->numOfCols) {
1,212,035!
541
    tscError("numOfCols:%d != pResInfo->numOfCols:%d", numOfCols, pResInfo->numOfCols);
×
542
    return TSDB_CODE_FAILED;
×
543
  }
544

545
  for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
5,020,360✔
546
    pResInfo->fields[i].type = pSchema[i].type;
3,808,316✔
547

548
    pResInfo->userFields[i].type = pSchema[i].type;
3,808,316✔
549
    // userFields must convert to type bytes, no matter isStmt or not
550
    pResInfo->userFields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, false);
3,808,316✔
551
    pResInfo->fields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, isStmt);
3,808,323✔
552
    if (IS_DECIMAL_TYPE(pSchema[i].type) && pExtSchema) {
3,808,344!
553
      decimalFromTypeMod(pExtSchema[i].typeMod, &pResInfo->fields[i].precision, &pResInfo->fields[i].scale);
7,978✔
554
    }
555

556
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
3,808,325✔
557
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
3,808,325✔
558
  }
559
  return TSDB_CODE_SUCCESS;
1,212,044✔
560
}
561

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

568
  pResInfo->precision = precision;
877,770✔
569
}
570

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

578
  int32_t dbNum = taosArrayGetSize(pDbVgList);
596,229✔
579
  for (int32_t i = 0; i < dbNum; ++i) {
1,168,630✔
580
    SArray* pVg = taosArrayGetP(pDbVgList, i);
572,423✔
581
    if (NULL == pVg) {
572,426!
582
      continue;
×
583
    }
584
    int32_t vgNum = taosArrayGetSize(pVg);
572,426✔
585
    if (vgNum <= 0) {
572,427✔
586
      continue;
624✔
587
    }
588

589
    for (int32_t j = 0; j < vgNum; ++j) {
2,973,621✔
590
      SVgroupInfo* pInfo = taosArrayGet(pVg, j);
2,401,846✔
591
      if (NULL == pInfo) {
2,401,821!
592
        taosArrayDestroy(nodeList);
×
593
        return TSDB_CODE_OUT_OF_RANGE;
×
594
      }
595
      SQueryNodeLoad load = {0};
2,401,821✔
596
      load.addr.nodeId = pInfo->vgId;
2,401,821✔
597
      load.addr.epSet = pInfo->epSet;
2,401,821✔
598

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

606
  int32_t vnodeNum = taosArrayGetSize(nodeList);
596,207✔
607
  if (vnodeNum > 0) {
596,235✔
608
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
571,083✔
609
    goto _return;
571,077✔
610
  }
611

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

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

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

630
_return:
21,576✔
631

632
  *pNodeList = nodeList;
596,221✔
633

634
  return TSDB_CODE_SUCCESS;
596,221✔
635
}
636

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

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

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

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

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

676
_return:
×
677

678
  *pNodeList = nodeList;
279,553✔
679

680
  return TSDB_CODE_SUCCESS;
279,553✔
681
}
682

683
void freeVgList(void* list) {
13,793✔
684
  SArray* pList = *(SArray**)list;
13,793✔
685
  taosArrayDestroy(pList);
13,793✔
686
}
13,806✔
687

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

694
  switch (tsQueryPolicy) {
841,588!
695
    case QUERY_POLICY_VNODE:
562,057✔
696
    case QUERY_POLICY_CLIENT: {
697
      if (pResultMeta) {
562,057!
698
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
562,092✔
699
        if (NULL == pDbVgList) {
562,073!
700
          code = terrno;
×
701
          goto _return;
×
702
        }
703
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
562,073✔
704
        for (int32_t i = 0; i < dbNum; ++i) {
1,120,684✔
705
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
558,608✔
706
          if (pRes->code || NULL == pRes->pRes) {
558,592!
707
            continue;
×
708
          }
709

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

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

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

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

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

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

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

791
_return:
841,657✔
792
  taosArrayDestroyEx(pDbVgList, fp);
841,657✔
793
  taosArrayDestroy(pQnodeList);
841,669✔
794

795
  return code;
841,675✔
796
}
797

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

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

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

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

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

841
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
34,123✔
842
      break;
34,114✔
843
    }
844
    case QUERY_POLICY_HYBRID:
×
845
    case QUERY_POLICY_QNODE: {
846
      TSC_ERR_JRET(getQnodeList(pRequest, &pQnodeList));
×
847

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

856
_return:
34,114✔
857

858
  taosArrayDestroyEx(pDbVgList, freeVgList);
34,114✔
859
  taosArrayDestroy(pQnodeList);
34,114✔
860

861
  return code;
34,121✔
862
}
863

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

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

888
  int32_t code = schedulerExecJob(&req, &pRequest->body.queryJob);
34,099✔
889

890
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
34,109✔
891
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
34,111✔
892

893
  if (code != TSDB_CODE_SUCCESS) {
34,111!
894
    schedulerFreeJob(&pRequest->body.queryJob, 0);
×
895

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

901
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_DELETE == pRequest->type ||
34,111!
902
      TDMT_VND_CREATE_TABLE == pRequest->type) {
166✔
903
    pRequest->body.resInfo.numOfRows = res.numOfRows;
34,081✔
904
    if (TDMT_VND_SUBMIT == pRequest->type) {
34,081✔
905
      STscObj*            pTscObj = pRequest->pTscObj;
33,955✔
906
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
33,955✔
907
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
33,955✔
908
    }
909

910
    schedulerFreeJob(&pRequest->body.queryJob, 0);
34,082✔
911
  }
912

913
  pRequest->code = res.code;
34,122✔
914
  terrno = res.code;
34,122✔
915
  return pRequest->code;
34,117✔
916
}
917

918
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
9,572,789✔
919
  SArray*      pArray = NULL;
9,572,789✔
920
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
9,572,789✔
921
  if (NULL == pRsp->aCreateTbRsp) {
9,572,789✔
922
    return TSDB_CODE_SUCCESS;
9,520,304✔
923
  }
924

925
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
52,485✔
926
  for (int32_t i = 0; i < tbNum; ++i) {
117,152✔
927
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
61,401✔
928
    if (pTbRsp->pMeta) {
61,398✔
929
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
40,221!
930
    }
931
  }
932

933
  return TSDB_CODE_SUCCESS;
55,751✔
934
}
935

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

945
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
658,630✔
946
  if (NULL == pArray) {
658,643!
947
    return terrno;
×
948
  }
949

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

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

968
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
658,644✔
969

970
_return:
658,633✔
971

972
  taosArrayDestroy(pArray);
658,633✔
973
  return code;
658,642✔
974
}
975

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

980
int32_t handleCreateTbExecRes(void* res, SCatalog* pCatalog) {
142,456✔
981
  return catalogAsyncUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
142,456✔
982
}
983

984
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
10,469,078✔
985
  if (NULL == pRequest->body.resInfo.execRes.res) {
10,469,078✔
986
    return pRequest->code;
196,828✔
987
  }
988

989
  SCatalog*     pCatalog = NULL;
10,272,250✔
990
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
10,272,250✔
991

992
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
10,271,792✔
993
  if (code) {
10,269,702!
994
    return code;
×
995
  }
996

997
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
10,269,702✔
998
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
10,300,752✔
999

1000
  switch (pRes->msgType) {
10,300,752✔
1001
    case TDMT_VND_ALTER_TABLE:
622✔
1002
    case TDMT_MND_ALTER_STB: {
1003
      code = handleAlterTbExecRes(pRes->res, pCatalog);
622✔
1004
      break;
622✔
1005
    }
1006
    case TDMT_VND_CREATE_TABLE: {
62,298✔
1007
      SArray* pList = (SArray*)pRes->res;
62,298✔
1008
      int32_t num = taosArrayGetSize(pList);
62,298✔
1009
      for (int32_t i = 0; i < num; ++i) {
158,879✔
1010
        void* res = taosArrayGetP(pList, i);
96,581✔
1011
        // handleCreateTbExecRes will handle res == null
1012
        code = handleCreateTbExecRes(res, pCatalog);
96,578✔
1013
      }
1014
      break;
62,298✔
1015
    }
1016
    case TDMT_MND_CREATE_STB: {
331✔
1017
      code = handleCreateTbExecRes(pRes->res, pCatalog);
331✔
1018
      break;
331✔
1019
    }
1020
    case TDMT_VND_SUBMIT: {
9,578,775✔
1021
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
9,578,775✔
1022

1023
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
9,579,803✔
1024
      break;
9,573,721✔
1025
    }
1026
    case TDMT_SCH_QUERY:
658,641✔
1027
    case TDMT_SCH_MERGE_QUERY: {
1028
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
658,641✔
1029
      break;
658,625✔
1030
    }
1031
    default:
85✔
1032
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self, pRequest->type,
85!
1033
               pRequest->requestId);
1034
      code = TSDB_CODE_APP_ERROR;
×
1035
  }
1036

1037
  return code;
10,295,597✔
1038
}
1039

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

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

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

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

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

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

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

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

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

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

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

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

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

1128
    tscInfo("[create stream with histroy] lastKey:%" PRId64 " vgId:%d, vgVer:%" PRId64, ts, *(int32_t*)pRow[1], *(int64_t*)pRow[2]);
1,035!
1129
  }
1130

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

1134
  tscInfo("[create stream with histroy] lastKey:%" PRId64 " numOfRows:%d from all vgroups", lastTs, numOfRows);
489!
1135
  return TSDB_CODE_SUCCESS;
489✔
1136
}
1137

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

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

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

1163
  blockDataDestroy(pBlock);
489✔
1164
}
1165

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

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

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

1189
  pRequest->code = code;
10,401,173✔
1190
  if (pResult) {
10,401,173!
1191
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
10,410,436✔
1192
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
10,422,504✔
1193
  }
1194

1195
  int32_t type = pRequest->type;
10,413,241✔
1196
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
10,413,241✔
1197
    if (pResult) {
9,631,341!
1198
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
9,646,520✔
1199

1200
      // record the insert rows
1201
      if (TDMT_VND_SUBMIT == type) {
9,646,520✔
1202
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
9,514,302✔
1203
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
9,514,302✔
1204
      }
1205
    }
1206
    schedulerFreeJob(&pRequest->body.queryJob, 0);
9,667,020✔
1207
  }
1208

1209
  taosMemoryFree(pResult);
10,454,417!
1210
  tscDebug("req:0x%" PRIx64 ", enter scheduler exec cb, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
10,463,427✔
1211
           pRequest->requestId);
1212

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

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

1230
  pRequest->metric.execCostUs = taosGetTimestampUs() - pRequest->metric.execStart;
10,442,210✔
1231
  int32_t code1 = handleQueryExecRsp(pRequest);
10,442,210✔
1232
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
10,458,035!
1233
    pRequest->code = code1;
×
1234
  }
1235

1236
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
20,919,021!
1237
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
10,460,615✔
1238
    continueInsertFromCsv(pWrapper, pRequest);
×
1239
    return;
×
1240
  }
1241

1242
  if (pRequest->relation.nextRefId) {
10,463,082✔
1243
    handlePostSubQuery(pWrapper);
490✔
1244
  } else {
1245
    destorySqlCallbackWrapper(pWrapper);
10,462,592✔
1246
    pRequest->pWrapper = NULL;
10,464,548✔
1247

1248
    // return to client
1249
    doRequestCallback(pRequest, code);
10,464,548✔
1250
  }
1251
}
1252

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

1257
  if (pQuery->pRoot) {
34,663✔
1258
    pRequest->stmtType = pQuery->pRoot->type;
34,118✔
1259
  }
1260

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

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

1317
  if (!keepQuery) {
34,672!
1318
    qDestroyQuery(pQuery);
×
1319
  }
1320

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

1328
  if (TSDB_CODE_SUCCESS == code) {
34,672✔
1329
    code = handleQueryExecRsp(pRequest);
34,668✔
1330
  }
1331

1332
  if (TSDB_CODE_SUCCESS != code) {
34,672✔
1333
    pRequest->code = code;
138✔
1334
  }
1335

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

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

1350
  if (!pRequest->parseOnly) {
10,422,152!
1351
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
10,427,821✔
1352
    if (NULL == pMnodeList) {
10,437,563!
1353
      code = terrno;
×
1354
    }
1355
    SPlanContext cxt = {.queryId = pRequest->requestId,
20,870,341✔
1356
                        .acctId = pRequest->pTscObj->acctId,
10,437,563✔
1357
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
10,437,563✔
1358
                        .pAstRoot = pQuery->pRoot,
10,432,778✔
1359
                        .showRewrite = pQuery->showRewrite,
10,432,778✔
1360
                        .isView = pWrapper->pParseCtx->isView,
10,432,778✔
1361
                        .isAudit = pWrapper->pParseCtx->isAudit,
10,432,778✔
1362
                        .pMsg = pRequest->msgBuf,
10,432,778✔
1363
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1364
                        .pUser = pRequest->pTscObj->user,
10,432,778✔
1365
                        .sysInfo = pRequest->pTscObj->sysInfo,
10,432,778✔
1366
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
10,432,778✔
1367
                        .allocatorId = pRequest->allocatorRefId};
10,432,778✔
1368
    if (TSDB_CODE_SUCCESS == code) {
10,432,778!
1369
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
10,443,487✔
1370
    }
1371
    if (code) {
10,414,188✔
1372
      tscError("req:0x%" PRIx64 ", failed to create query plan, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
640!
1373
               pRequest->requestId);
1374
    } else {
1375
      pRequest->body.subplanNum = pDag->numOfSubplans;
10,413,548✔
1376
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
10,413,548✔
1377
    }
1378
  }
1379

1380
  pRequest->metric.execStart = taosGetTimestampUs();
10,403,750✔
1381
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
10,403,750✔
1382

1383
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
20,833,656!
1384
    SArray* pNodeList = NULL;
10,432,236✔
1385
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
10,432,236✔
1386
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
841,656✔
1387
    }
1388

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

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

1424
    doRequestCallback(pRequest, code);
860✔
1425
  }
1426

1427
  // todo not to be released here
1428
  taosArrayDestroy(pMnodeList);
10,430,766✔
1429

1430
  return code;
10,439,077✔
1431
}
1432

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

1436
  if (pRequest->parseOnly) {
10,566,236✔
1437
    doRequestCallback(pRequest, 0);
609✔
1438
    return;
609✔
1439
  }
1440

1441
  pRequest->body.execMode = pQuery->execMode;
10,565,627✔
1442
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
10,565,627✔
1443
    destorySqlCallbackWrapper(pWrapper);
154,790✔
1444
    pRequest->pWrapper = NULL;
154,790✔
1445
  }
1446

1447
  if (pQuery->pRoot && !pRequest->inRetry) {
10,565,627!
1448
    STscObj*            pTscObj = pRequest->pTscObj;
10,571,240✔
1449
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
10,571,240✔
1450
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
10,571,240✔
1451
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
9,590,781✔
1452
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
9,520,140✔
1453
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
1,051,100✔
1454
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
731,715✔
1455
    }
1456
  }
1457

1458
  switch (pQuery->execMode) {
10,616,953!
1459
    case QUERY_EXEC_MODE_LOCAL:
118,117✔
1460
      asyncExecLocalCmd(pRequest, pQuery);
118,117✔
1461
      break;
118,118✔
1462
    case QUERY_EXEC_MODE_RPC:
33,394✔
1463
      code = asyncExecDdlQuery(pRequest, pQuery);
33,394✔
1464
      break;
33,394✔
1465
    case QUERY_EXEC_MODE_SCHEDULE: {
10,462,163✔
1466
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
10,462,163✔
1467
      break;
10,427,889✔
1468
    }
1469
    case QUERY_EXEC_MODE_EMPTY_RESULT:
3,279✔
1470
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
3,279✔
1471
      doRequestCallback(pRequest, 0);
3,279✔
1472
      break;
3,279✔
1473
    default:
×
1474
      tscError("req:0x%" PRIx64 ", invalid execMode %d", pRequest->self, pQuery->execMode);
×
1475
      doRequestCallback(pRequest, -1);
×
1476
      break;
×
1477
  }
1478
}
1479

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

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

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

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

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

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

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

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

1520
  return code;
×
1521
}
1522

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

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

1548
  return TSDB_CODE_SUCCESS;
14,691✔
1549
}
1550

1551
int32_t initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet) {
27,950✔
1552
  pEpSet->version = 0;
27,950✔
1553

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

1559
  if (firstEp && firstEp[0] != 0) {
27,950!
1560
    if (strlen(firstEp) >= TSDB_EP_LEN) {
27,955!
1561
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1562
      return -1;
×
1563
    }
1564

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

1581
  if (secondEp && secondEp[0] != 0) {
27,949!
1582
    if (strlen(secondEp) >= TSDB_EP_LEN) {
15,943!
1583
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1584
      return terrno;
×
1585
    }
1586

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

1602
  if (mgmtEpSet->numOfEps == 0) {
27,949✔
1603
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
4✔
1604
    return TSDB_CODE_RPC_NETWORK_UNAVAIL;
4✔
1605
  }
1606

1607
  return 0;
27,945✔
1608
}
1609

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

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

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

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

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

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

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

1674
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
27,951✔
1675

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

1685
  *(int64_t*)(*pMsgSendInfo)->param = pRequest->self;
27,951✔
1686

1687
  SConnectReq connectReq = {0};
27,951✔
1688
  STscObj*    pObj = pRequest->pTscObj;
27,951✔
1689

1690
  char* db = getDbOfConnection(pObj);
27,951✔
1691
  if (db != NULL) {
27,951✔
1692
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
796✔
1693
  } else if (terrno) {
27,155!
1694
    taosMemoryFree(*pMsgSendInfo);
×
1695
    return terrno;
×
1696
  }
1697
  taosMemoryFreeClear(db);
27,951!
1698

1699
  connectReq.connType = pObj->connType;
27,951✔
1700
  connectReq.pid = appInfo.pid;
27,951✔
1701
  connectReq.startTime = appInfo.startTime;
27,951✔
1702

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

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

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

1721
  (*pMsgSendInfo)->msgInfo.len = contLen;
27,951✔
1722
  (*pMsgSendInfo)->msgInfo.pData = pReq;
27,951✔
1723
  return TSDB_CODE_SUCCESS;
27,951✔
1724
}
1725

1726
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
18,064,002✔
1727
  if (NULL == pEpSet) {
18,064,002✔
1728
    return;
16,771,086✔
1729
  }
1730

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

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

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

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

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

1785
  STscObj* pTscObj = NULL;
18,069,657✔
1786

1787
  STraceId* trace = &pMsg->info.traceId;
18,069,657✔
1788
  char      tbuf[40] = {0};
18,069,657✔
1789
  TRACE_TO_STR(trace, tbuf);
18,069,657!
1790

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

1794
  if (pSendInfo->requestObjRefId != 0) {
18,067,235✔
1795
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
12,380,905✔
1796
    if (pRequest) {
12,379,824✔
1797
      if (pRequest->self != pSendInfo->requestObjRefId) {
12,378,027!
1798
        tscError("doProcessMsgFromServer req:0x%" PRId64 " != pSendInfo->requestObjRefId:0x%" PRId64,
×
1799
                 pRequest->self, pSendInfo->requestObjRefId);
1800

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

1813
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
18,066,154✔
1814

1815
  SDataBuf buf = {.msgType = pMsg->msgType,
18,063,281✔
1816
                  .len = pMsg->contLen,
18,063,281✔
1817
                  .pData = NULL,
1818
                  .handle = pMsg->info.handle,
18,063,281✔
1819
                  .handleRefId = pMsg->info.refId,
18,063,281✔
1820
                  .pEpSet = pEpSet};
1821

1822
  if (pMsg->contLen > 0) {
18,063,281✔
1823
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
17,074,809!
1824
    if (buf.pData == NULL) {
17,072,671!
1825
      pMsg->code = terrno;
×
1826
    } else {
1827
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
17,072,671✔
1828
    }
1829
  }
1830

1831
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
18,061,143✔
1832

1833
  if (pTscObj) {
18,055,059✔
1834
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
12,367,719✔
1835
    if (TSDB_CODE_SUCCESS != code) {
12,375,953!
1836
      tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1837
      terrno = code;
×
1838
      pMsg->code = code;
×
1839
    }
1840
  }
1841

1842
  rpcFreeCont(pMsg->pCont);
18,063,293✔
1843
  destroySendMsgInfo(pSendInfo);
18,066,630✔
1844
  return TSDB_CODE_SUCCESS;
18,068,296✔
1845
}
1846
int32_t doProcessMsgFromServer(void* param) {
18,071,246✔
1847
  AsyncArg* arg = (AsyncArg*)param;
18,071,246✔
1848
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
18,071,246✔
1849
  taosMemoryFree(arg);
18,066,024!
1850
  return code;
18,069,552✔
1851
}
1852

1853
void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
18,044,547✔
1854
  int32_t code = 0;
18,044,547✔
1855
  SEpSet* tEpSet = NULL;
18,044,547✔
1856
  if (pEpSet != NULL) {
18,044,547✔
1857
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
1,293,906!
1858
    if (NULL == tEpSet) {
1,293,909!
1859
      code = terrno;
×
1860
      pMsg->code = terrno;
×
1861
      goto _exit;
×
1862
    }
1863
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
1,293,909✔
1864
  }
1865

1866
  // pMsg is response msg
1867
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
18,044,550✔
1868
    // restore origin code
1869
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
27,950!
1870
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1871
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
27,950!
1872
      pMsg->code = TSDB_CODE_RPC_BROKEN_LINK;
×
1873
    }
1874
  } else {
1875
    // uniform to one error code: TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED
1876
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
18,016,600!
1877
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
1878
    }
1879
  }
1880

1881
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
18,044,550!
1882
  if (NULL == arg) {
18,046,755!
1883
    code = terrno;
×
1884
    pMsg->code = code;
×
1885
    goto _exit;
×
1886
  }
1887

1888
  arg->msg = *pMsg;
18,046,755✔
1889
  arg->pEpset = tEpSet;
18,046,755✔
1890

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

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

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

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

1927
  return NULL;
3✔
1928
}
1929

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

1944
void doSetOneRowPtr(SReqResultInfo* pResultInfo, bool isStmt) {
31,434,222✔
1945
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
156,624,141✔
1946
    SResultColumn* pCol = &pResultInfo->pCol[i];
125,224,882✔
1947

1948
    int32_t type = pResultInfo->fields[i].type;
125,224,882✔
1949
    int32_t schemaBytes = calcSchemaBytesFromTypeBytes(type, pResultInfo->fields[i].bytes, isStmt);
125,224,882✔
1950

1951
    if (IS_VAR_DATA_TYPE(type)) {
125,189,919✔
1952
      if (!IS_VAR_NULL_TYPE(type, schemaBytes) && pCol->offset[pResultInfo->current] != -1) {
24,735,989!
1953
        char* pStart = pResultInfo->pCol[i].offset[pResultInfo->current] + pResultInfo->pCol[i].pData;
23,729,131✔
1954

1955
        pResultInfo->length[i] = varDataLen(pStart);
23,729,131✔
1956
        pResultInfo->row[i] = varDataVal(pStart);
23,729,131✔
1957
      } else {
1958
        pResultInfo->row[i] = NULL;
1,006,858✔
1959
        pResultInfo->length[i] = 0;
1,006,858✔
1960
      }
1961
    } else {
1962
      if (!colDataIsNull_f(pCol->nullbitmap, pResultInfo->current)) {
100,453,930✔
1963
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + schemaBytes * pResultInfo->current;
96,727,385✔
1964
        pResultInfo->length[i] = schemaBytes;
96,727,385✔
1965
      } else {
1966
        pResultInfo->row[i] = NULL;
3,726,545✔
1967
        pResultInfo->length[i] = 0;
3,726,545✔
1968
      }
1969
    }
1970
  }
1971
}
31,399,259✔
1972

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

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

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

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

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

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

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

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

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

2019
  return pResultInfo->row;
×
2020
}
2021

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

2029
void* doAsyncFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
17,362,455✔
2030
  if (pRequest == NULL) {
17,362,455!
2031
    return NULL;
×
2032
  }
2033

2034
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
17,362,455✔
2035
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
17,362,455✔
2036
    // All data has returned to App already, no need to try again
2037
    if (pResultInfo->completed) {
1,342,231✔
2038
      pResultInfo->numOfRows = 0;
571,927✔
2039
      return NULL;
571,927✔
2040
    }
2041

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

2058
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
16,790,520!
2059
    return NULL;
58,278✔
2060
  } else {
2061
    if (setupOneRowPtr) {
16,732,242✔
2062
      doSetOneRowPtr(pResultInfo, pRequest->isStmtBind);
16,086,473✔
2063
      pResultInfo->current += 1;
16,071,916✔
2064
    }
2065

2066
    return pResultInfo->row;
16,717,685✔
2067
  }
2068
}
2069

2070
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
1,217,885✔
2071
  if (pResInfo->row == NULL) {
1,217,885✔
2072
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
1,097,544!
2073
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
1,097,577!
2074
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
1,097,568!
2075
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
1,097,577!
2076

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

2086
  return TSDB_CODE_SUCCESS;
1,217,908✔
2087
}
2088

2089
static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength, bool isStmt) {
1,216,600✔
2090
  int32_t idx = -1;
1,216,600✔
2091
  iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt);
1,216,600✔
2092
  if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR;
1,216,618!
2093

2094
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
5,113,435✔
2095
    int32_t type = pResultInfo->fields[i].type;
3,896,885✔
2096
    int32_t schemaBytes = calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
3,896,885✔
2097

2098
    if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) {
3,896,885✔
2099
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
174,283!
2100
      if (p == NULL) {
174,284!
2101
        taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
×
2102
        return terrno;
×
2103
      }
2104

2105
      pResultInfo->convertBuf[i] = p;
174,284✔
2106

2107
      SResultColumn* pCol = &pResultInfo->pCol[i];
174,284✔
2108
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
26,139,355✔
2109
        if (pCol->offset[j] != -1) {
25,965,140✔
2110
          char* pStart = pCol->offset[j] + pCol->pData;
25,624,428✔
2111

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

2122
          varDataSetLen(p, len);
25,624,359✔
2123
          pCol->offset[j] = (p - pResultInfo->convertBuf[i]);
25,624,359✔
2124
          p += (len + VARSTR_HEADER_SIZE);
25,624,359✔
2125
        }
2126
      }
2127

2128
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
174,215✔
2129
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
174,215✔
2130
    }
2131
  }
2132
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
1,216,550✔
2133
  return TSDB_CODE_SUCCESS;
1,216,619✔
2134
}
2135

2136
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
1,216,607✔
2137
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
5,113,693✔
2138
    TAOS_FIELD_E* pField = pResultInfo->fields + i;
3,897,086✔
2139
    int32_t type = pField->type;
3,897,086✔
2140
    int32_t bufLen = 0;
3,897,086✔
2141
    char* p = NULL;
3,897,086✔
2142
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
3,897,086✔
2143
      continue;
3,890,561✔
2144
    } else {
2145
      bufLen = 64;
6,525✔
2146
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
6,525!
2147
      pField->bytes = bufLen;
6,525✔
2148
    }
2149
    if (!p) return terrno;
6,525!
2150
    pResultInfo->convertBuf[i] = p;
6,525✔
2151

2152
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
4,349,017✔
2153
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
4,342,492✔
2154
                                  pField->precision, pField->scale, p, bufLen);
4,342,492✔
2155
      p += bufLen;
4,342,492✔
2156
      if (TSDB_CODE_SUCCESS != code) {
4,342,492!
2157
        return code;
×
2158
      }
2159
    }
2160
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
6,525✔
2161
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
6,525✔
2162
  }
2163
  return 0;
1,216,607✔
2164
}
2165

2166
int32_t getVersion1BlockMetaSize(const char* p, int32_t numOfCols) {
1,244✔
2167
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) * 3 + sizeof(uint64_t) +
1,244✔
2168
         numOfCols * (sizeof(int8_t) + sizeof(int32_t));
2169
}
2170

2171
static int32_t estimateJsonLen(SReqResultInfo* pResultInfo) {
622✔
2172
  char*   p = (char*)pResultInfo->pData;
622✔
2173
  int32_t blockVersion = *(int32_t*)p;
622✔
2174

2175
  int32_t numOfRows = pResultInfo->numOfRows;
622✔
2176
  int32_t numOfCols = pResultInfo->numOfCols;
622✔
2177

2178
  // | version | total length | total rows | total columns | flag seg| block group id | column schema | each column
2179
  // length |
2180
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
622✔
2181
  if (numOfCols != cols) {
622!
2182
    tscError("estimateJsonLen error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2183
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2184
  }
2185

2186
  int32_t  len = getVersion1BlockMetaSize(p, numOfCols);
622✔
2187
  int32_t* colLength = (int32_t*)(p + len);
622✔
2188
  len += sizeof(int32_t) * numOfCols;
622✔
2189

2190
  char* pStart = p + len;
622✔
2191
  for (int32_t i = 0; i < numOfCols; ++i) {
3,141✔
2192
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
2,519!
2193

2194
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
2,519✔
2195
      int32_t* offset = (int32_t*)pStart;
705✔
2196
      int32_t  lenTmp = numOfRows * sizeof(int32_t);
705✔
2197
      len += lenTmp;
705✔
2198
      pStart += lenTmp;
705✔
2199

2200
      int32_t estimateColLen = 0;
705✔
2201
      for (int32_t j = 0; j < numOfRows; ++j) {
3,783✔
2202
        if (offset[j] == -1) {
3,078✔
2203
          continue;
233✔
2204
        }
2205
        char* data = offset[j] + pStart;
2,845✔
2206

2207
        int32_t jsonInnerType = *data;
2,845✔
2208
        char*   jsonInnerData = data + CHAR_BYTES;
2,845✔
2209
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
2,845✔
2210
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
78✔
2211
        } else if (tTagIsJson(data)) {
2,767✔
2212
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
947✔
2213
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
1,820✔
2214
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
1,482✔
2215
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
338✔
2216
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
246✔
2217
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
92!
2218
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
92✔
2219
        } else {
2220
          tscError("estimateJsonLen error: invalid type:%d", jsonInnerType);
×
2221
          return -1;
×
2222
        }
2223
      }
2224
      len += TMAX(colLen, estimateColLen);
705✔
2225
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
1,814!
2226
      int32_t lenTmp = numOfRows * sizeof(int32_t);
658✔
2227
      len += (lenTmp + colLen);
658✔
2228
      pStart += lenTmp;
658✔
2229
    } else {
2230
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
1,156✔
2231
      len += (lenTmp + colLen);
1,156✔
2232
      pStart += lenTmp;
1,156✔
2233
    }
2234
    pStart += colLen;
2,519✔
2235
  }
2236

2237
  // Ensure the complete structure of the block, including the blankfill field,
2238
  // even though it is not used on the client side.
2239
  len += sizeof(bool);
622✔
2240
  return len;
622✔
2241
}
2242

2243
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
1,217,909✔
2244
  int32_t numOfRows = pResultInfo->numOfRows;
1,217,909✔
2245
  int32_t numOfCols = pResultInfo->numOfCols;
1,217,909✔
2246
  bool    needConvert = false;
1,217,909✔
2247
  for (int32_t i = 0; i < numOfCols; ++i) {
5,121,381✔
2248
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
3,904,094✔
2249
      needConvert = true;
622✔
2250
      break;
622✔
2251
    }
2252
  }
2253

2254
  if (!needConvert) {
1,217,909✔
2255
    return TSDB_CODE_SUCCESS;
1,217,288✔
2256
  }
2257

2258
  tscDebug("start to convert form json format string");
621✔
2259

2260
  char*   p = (char*)pResultInfo->pData;
621✔
2261
  int32_t blockVersion = *(int32_t*)p;
621✔
2262
  int32_t dataLen = estimateJsonLen(pResultInfo);
621✔
2263
  if (dataLen <= 0) {
622!
2264
    tscError("doConvertJson error: estimateJsonLen failed");
×
2265
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2266
  }
2267

2268
  taosMemoryFreeClear(pResultInfo->convertJson);
622!
2269
  pResultInfo->convertJson = taosMemoryCalloc(1, dataLen);
622!
2270
  if (pResultInfo->convertJson == NULL) return terrno;
622!
2271
  char* p1 = pResultInfo->convertJson;
622✔
2272

2273
  int32_t totalLen = 0;
622✔
2274
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
622✔
2275
  if (numOfCols != cols) {
622!
2276
    tscError("doConvertJson error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2277
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2278
  }
2279

2280
  int32_t len = getVersion1BlockMetaSize(p, numOfCols);
622✔
2281
  (void)memcpy(p1, p, len);
622✔
2282

2283
  p += len;
622✔
2284
  p1 += len;
622✔
2285
  totalLen += len;
622✔
2286

2287
  len = sizeof(int32_t) * numOfCols;
622✔
2288
  int32_t* colLength = (int32_t*)p;
622✔
2289
  int32_t* colLength1 = (int32_t*)p1;
622✔
2290
  (void)memcpy(p1, p, len);
622✔
2291
  p += len;
622✔
2292
  p1 += len;
622✔
2293
  totalLen += len;
622✔
2294

2295
  char* pStart = p;
622✔
2296
  char* pStart1 = p1;
622✔
2297
  for (int32_t i = 0; i < numOfCols; ++i) {
3,141✔
2298
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
2,519!
2299
    int32_t colLen1 = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength1[i]) : colLength1[i];
2,519!
2300
    if (colLen >= dataLen) {
2,519!
2301
      tscError("doConvertJson error: colLen:%d >= dataLen:%d", colLen, dataLen);
×
2302
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2303
    }
2304
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
2,519✔
2305
      int32_t* offset = (int32_t*)pStart;
705✔
2306
      int32_t* offset1 = (int32_t*)pStart1;
705✔
2307
      len = numOfRows * sizeof(int32_t);
705✔
2308
      (void)memcpy(pStart1, pStart, len);
705✔
2309
      pStart += len;
705✔
2310
      pStart1 += len;
705✔
2311
      totalLen += len;
705✔
2312

2313
      len = 0;
705✔
2314
      for (int32_t j = 0; j < numOfRows; ++j) {
3,783✔
2315
        if (offset[j] == -1) {
3,078✔
2316
          continue;
233✔
2317
        }
2318
        char* data = offset[j] + pStart;
2,845✔
2319

2320
        int32_t jsonInnerType = *data;
2,845✔
2321
        char*   jsonInnerData = data + CHAR_BYTES;
2,845✔
2322
        char    dst[TSDB_MAX_JSON_TAG_LEN] = {0};
2,845✔
2323
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
2,845✔
2324
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s", TSDB_DATA_NULL_STR_L);
78✔
2325
          varDataSetLen(dst, strlen(varDataVal(dst)));
78✔
2326
        } else if (tTagIsJson(data)) {
2,767✔
2327
          char* jsonString = NULL;
947✔
2328
          parseTagDatatoJson(data, &jsonString, pResultInfo->charsetCxt);
947✔
2329
          if (jsonString == NULL) {
947!
2330
            tscError("doConvertJson error: parseTagDatatoJson failed");
×
2331
            return terrno;
×
2332
          }
2333
          STR_TO_VARSTR(dst, jsonString);
947✔
2334
          taosMemoryFree(jsonString);
947!
2335
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
1,820✔
2336
          *(char*)varDataVal(dst) = '\"';
1,482✔
2337
          int32_t length = taosUcs4ToMbs((TdUcs4*)varDataVal(jsonInnerData), varDataLen(jsonInnerData),
1,482✔
2338
                                         varDataVal(dst) + CHAR_BYTES, pResultInfo->charsetCxt);
2339
          if (length <= 0) {
1,482✔
2340
            tscError("charset:%s to %s. convert failed.", DEFAULT_UNICODE_ENCODEC,
6!
2341
              pResultInfo->charsetCxt != NULL ? ((SConvInfo *)(pResultInfo->charsetCxt))->charset : tsCharset);
2342
            length = 0;
6✔
2343
          }
2344
          varDataSetLen(dst, length + CHAR_BYTES * 2);
1,482✔
2345
          *(char*)POINTER_SHIFT(varDataVal(dst), length + CHAR_BYTES) = '\"';
1,482✔
2346
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
338✔
2347
          double jsonVd = *(double*)(jsonInnerData);
246✔
2348
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%.9lf", jsonVd);
246✔
2349
          varDataSetLen(dst, strlen(varDataVal(dst)));
246✔
2350
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
92!
2351
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s",
92✔
2352
                         (*((char*)jsonInnerData) == 1) ? "true" : "false");
92✔
2353
          varDataSetLen(dst, strlen(varDataVal(dst)));
92✔
2354
        } else {
2355
          tscError("doConvertJson error: invalid type:%d", jsonInnerType);
×
2356
          return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2357
        }
2358

2359
        offset1[j] = len;
2,845✔
2360
        (void)memcpy(pStart1 + len, dst, varDataTLen(dst));
2,845✔
2361
        len += varDataTLen(dst);
2,845✔
2362
      }
2363
      colLen1 = len;
705✔
2364
      totalLen += colLen1;
705✔
2365
      colLength1[i] = (blockVersion == BLOCK_VERSION_1) ? htonl(len) : len;
705!
2366
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
1,814!
2367
      len = numOfRows * sizeof(int32_t);
658✔
2368
      (void)memcpy(pStart1, pStart, len);
658✔
2369
      pStart += len;
658✔
2370
      pStart1 += len;
658✔
2371
      totalLen += len;
658✔
2372
      totalLen += colLen;
658✔
2373
      (void)memcpy(pStart1, pStart, colLen);
658✔
2374
    } else {
2375
      len = BitmapLen(pResultInfo->numOfRows);
1,156✔
2376
      (void)memcpy(pStart1, pStart, len);
1,156✔
2377
      pStart += len;
1,156✔
2378
      pStart1 += len;
1,156✔
2379
      totalLen += len;
1,156✔
2380
      totalLen += colLen;
1,156✔
2381
      (void)memcpy(pStart1, pStart, colLen);
1,156✔
2382
    }
2383
    pStart += colLen;
2,519✔
2384
    pStart1 += colLen1;
2,519✔
2385
  }
2386

2387
  // Ensure the complete structure of the block, including the blankfill field,
2388
  // even though it is not used on the client side.
2389
  // (void)memcpy(pStart1, pStart, sizeof(bool));
2390
  totalLen += sizeof(bool);
622✔
2391

2392
  *(int32_t*)(pResultInfo->convertJson + 4) = totalLen;
622✔
2393
  pResultInfo->pData = pResultInfo->convertJson;
622✔
2394
  return TSDB_CODE_SUCCESS;
622✔
2395
}
2396

2397
int32_t setResultDataPtr(SReqResultInfo* pResultInfo, bool convertUcs4, bool isStmt) {
1,281,374✔
2398
  if (pResultInfo == NULL || pResultInfo->numOfCols <= 0 || pResultInfo->fields == NULL) {
1,281,374!
2399
    tscError("setResultDataPtr paras error");
×
2400
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2401
  }
2402

2403
  if (pResultInfo->numOfRows == 0) {
1,281,380✔
2404
    return TSDB_CODE_SUCCESS;
63,486✔
2405
  }
2406

2407
  if (pResultInfo->pData == NULL) {
1,217,894!
2408
    tscError("setResultDataPtr error: pData is NULL");
×
2409
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2410
  }
2411

2412
  int32_t code = doPrepareResPtr(pResultInfo);
1,217,894✔
2413
  if (code != TSDB_CODE_SUCCESS) {
1,217,909!
2414
    return code;
×
2415
  }
2416
  code = doConvertJson(pResultInfo);
1,217,909✔
2417
  if (code != TSDB_CODE_SUCCESS) {
1,217,908!
2418
    return code;
×
2419
  }
2420

2421
  char* p = (char*)pResultInfo->pData;
1,217,908✔
2422

2423
  // version:
2424
  int32_t blockVersion = *(int32_t*)p;
1,217,908✔
2425
  p += sizeof(int32_t);
1,217,908✔
2426

2427
  int32_t dataLen = *(int32_t*)p;
1,217,908✔
2428
  p += sizeof(int32_t);
1,217,908✔
2429

2430
  int32_t rows = *(int32_t*)p;
1,217,908✔
2431
  p += sizeof(int32_t);
1,217,908✔
2432

2433
  int32_t cols = *(int32_t*)p;
1,217,908✔
2434
  p += sizeof(int32_t);
1,217,908✔
2435

2436
  if (rows != pResultInfo->numOfRows || cols != pResultInfo->numOfCols) {
1,217,908!
2437
    tscError("setResultDataPtr paras error:rows;%d numOfRows:%" PRId64 " cols:%d numOfCols:%d", rows,
1!
2438
             pResultInfo->numOfRows, cols, pResultInfo->numOfCols);
2439
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2440
  }
2441

2442
  int32_t hasColumnSeg = *(int32_t*)p;
1,217,907✔
2443
  p += sizeof(int32_t);
1,217,907✔
2444

2445
  uint64_t groupId = taosGetUInt64Aligned((uint64_t*)p);
1,217,907✔
2446
  p += sizeof(uint64_t);
1,217,907✔
2447

2448
  // check fields
2449
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
5,122,063✔
2450
    int8_t type = *(int8_t*)p;
3,904,162✔
2451
    p += sizeof(int8_t);
3,904,162✔
2452

2453
    int32_t bytes = *(int32_t*)p;
3,904,162✔
2454
    p += sizeof(int32_t);
3,904,162✔
2455

2456
    if (IS_DECIMAL_TYPE(type) && pResultInfo->fields[i].precision == 0) {
3,904,162!
2457
      extractDecimalTypeInfoFromBytes(&bytes, &pResultInfo->fields[i].precision, &pResultInfo->fields[i].scale);
×
2458
    }
2459
  }
2460

2461
  int32_t* colLength = (int32_t*)p;
1,217,901✔
2462
  p += sizeof(int32_t) * pResultInfo->numOfCols;
1,217,901✔
2463

2464
  char* pStart = p;
1,217,901✔
2465
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
5,121,900✔
2466
    if ((pStart - pResultInfo->pData) >= dataLen) {
3,904,004!
2467
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2468
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2469
    }
2470
    if (blockVersion == BLOCK_VERSION_1) {
3,904,004✔
2471
      colLength[i] = htonl(colLength[i]);
2,070,715✔
2472
    }
2473
    if (colLength[i] >= dataLen) {
3,904,004!
2474
      tscError("invalid colLength %d, dataLen %d", colLength[i], dataLen);
×
2475
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2476
    }
2477
    if (IS_INVALID_TYPE(pResultInfo->fields[i].type)) {
3,904,004!
2478
      tscError("invalid type %d", pResultInfo->fields[i].type);
24!
2479
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2480
    }
2481
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
3,903,980✔
2482
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
1,037,900✔
2483
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
1,037,900✔
2484
    } else {
2485
      pResultInfo->pCol[i].nullbitmap = pStart;
2,866,080✔
2486
      pStart += BitmapLen(pResultInfo->numOfRows);
2,866,080✔
2487
    }
2488

2489
    pResultInfo->pCol[i].pData = pStart;
3,903,980✔
2490
    pResultInfo->length[i] = calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
3,903,980✔
2491
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
3,903,999✔
2492

2493
    pStart += colLength[i];
3,903,999✔
2494
  }
2495

2496
  p = pStart;
1,217,896✔
2497
  // bool blankFill = *(bool*)p;
2498
  p += sizeof(bool);
1,217,896✔
2499
  int32_t offset = p - pResultInfo->pData;
1,217,896✔
2500
  if (offset > dataLen) {
1,217,896!
2501
    tscError("invalid offset %d, dataLen %d", offset, dataLen);
×
2502
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2503
  }
2504

2505
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
2506
  if (convertUcs4) {
1,217,896✔
2507
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
1,216,599✔
2508
  }
2509
#endif
2510
  if (TSDB_CODE_SUCCESS == code && convertUcs4) {
1,217,917✔
2511
    code = convertDecimalType(pResultInfo);
1,216,620✔
2512
  }
2513
  return code;
1,217,901✔
2514
}
2515

2516
char* getDbOfConnection(STscObj* pObj) {
10,787,982✔
2517
  terrno = TSDB_CODE_SUCCESS;
10,787,982✔
2518
  char* p = NULL;
10,785,411✔
2519
  (void)taosThreadMutexLock(&pObj->mutex);
10,785,411✔
2520
  size_t len = strlen(pObj->db);
10,797,077✔
2521
  if (len > 0) {
10,797,077✔
2522
    p = taosStrndup(pObj->db, tListLen(pObj->db));
10,449,885!
2523
    if (p == NULL) {
10,443,646!
2524
      tscError("failed to taosStrndup db name");
×
2525
    }
2526
  }
2527

2528
  (void)taosThreadMutexUnlock(&pObj->mutex);
10,790,838✔
2529
  return p;
10,799,347✔
2530
}
2531

2532
void setConnectionDB(STscObj* pTscObj, const char* db) {
7,604✔
2533
  if (db == NULL || pTscObj == NULL) {
7,604!
2534
    tscError("setConnectionDB para is NULL");
×
2535
    return;
×
2536
  }
2537

2538
  (void)taosThreadMutexLock(&pTscObj->mutex);
7,604✔
2539
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
7,604✔
2540
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
7,604✔
2541
}
2542

2543
void resetConnectDB(STscObj* pTscObj) {
×
2544
  if (pTscObj == NULL) {
×
2545
    return;
×
2546
  }
2547

2548
  (void)taosThreadMutexLock(&pTscObj->mutex);
×
2549
  pTscObj->db[0] = 0;
×
2550
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
×
2551
}
2552

2553
int32_t setQueryResultFromRsp(SReqResultInfo* pResultInfo, const SRetrieveTableRsp* pRsp, bool convertUcs4, bool isStmt) {
947,123✔
2554
  if (pResultInfo == NULL || pRsp == NULL) {
947,123!
2555
    tscError("setQueryResultFromRsp paras is null");
×
2556
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2557
  }
2558

2559
  taosMemoryFreeClear(pResultInfo->pRspMsg);
947,134!
2560
  pResultInfo->pRspMsg = (const char*)pRsp;
947,134✔
2561
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
947,134✔
2562
  pResultInfo->current = 0;
947,129✔
2563
  pResultInfo->completed = (pRsp->completed == 1);
947,129✔
2564
  pResultInfo->precision = pRsp->precision;
947,129✔
2565

2566
  // decompress data if needed
2567
  int32_t payloadLen = htonl(pRsp->payloadLen);
947,129✔
2568

2569
  if (pRsp->compressed) {
947,129✔
2570
    if (pResultInfo->decompBuf == NULL) {
645✔
2571
      pResultInfo->decompBuf = taosMemoryMalloc(payloadLen);
14!
2572
      if (pResultInfo->decompBuf == NULL) {
14!
2573
        tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2574
        return terrno;
×
2575
      }
2576
      pResultInfo->decompBufSize = payloadLen;
14✔
2577
    } else {
2578
      if (pResultInfo->decompBufSize < payloadLen) {
631✔
2579
        char* p = taosMemoryRealloc(pResultInfo->decompBuf, payloadLen);
24!
2580
        if (p == NULL) {
24!
2581
          tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2582
          return terrno;
×
2583
        }
2584

2585
        pResultInfo->decompBuf = p;
24✔
2586
        pResultInfo->decompBufSize = payloadLen;
24✔
2587
      }
2588
    }
2589
  }
2590

2591
  if (payloadLen > 0) {
947,129✔
2592
    int32_t compLen = *(int32_t*)pRsp->data;
883,635✔
2593
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
883,635✔
2594

2595
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
883,635✔
2596

2597
    if (pRsp->compressed && compLen < rawLen) {
883,635!
2598
      int32_t len = tsDecompressString(pStart, compLen, 1, pResultInfo->decompBuf, rawLen, ONE_STAGE_COMP, NULL, 0);
645✔
2599
      if (len < 0) {
645!
2600
        tscError("tsDecompressString failed");
×
2601
        return terrno ? terrno : TSDB_CODE_FAILED;
×
2602
      }
2603
      if (len != rawLen) {
645!
2604
        tscError("tsDecompressString failed, len:%d != rawLen:%d", len, rawLen);
×
2605
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2606
      }
2607
      pResultInfo->pData = pResultInfo->decompBuf;
645✔
2608
      pResultInfo->payloadLen = rawLen;
645✔
2609
    } else {
2610
      pResultInfo->pData = pStart;
882,990✔
2611
      pResultInfo->payloadLen = htonl(pRsp->compLen);
882,990✔
2612
      if (pRsp->compLen != pRsp->payloadLen) {
882,990!
2613
        tscError("pRsp->compLen:%d != pRsp->payloadLen:%d", pRsp->compLen, pRsp->payloadLen);
×
2614
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2615
      }
2616
    }
2617
  }
2618

2619
  // TODO handle the compressed case
2620
  pResultInfo->totalRows += pResultInfo->numOfRows;
947,129✔
2621

2622
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
947,129✔
2623
  return code;
947,143✔
2624
}
2625

2626
TSDB_SERVER_STATUS taos_check_server_status(const char* fqdn, int port, char* details, int maxlen) {
5✔
2627
  TSDB_SERVER_STATUS code = TSDB_SRV_STATUS_UNAVAILABLE;
5✔
2628
  void*              clientRpc = NULL;
5✔
2629
  SServerStatusRsp   statusRsp = {0};
5✔
2630
  SEpSet             epSet = {.inUse = 0, .numOfEps = 1};
5✔
2631
  SRpcMsg  rpcMsg = {.info.ahandle = (void*)0x9527, .info.notFreeAhandle = 1, .msgType = TDMT_DND_SERVER_STATUS};
5✔
2632
  SRpcMsg  rpcRsp = {0};
5✔
2633
  SRpcInit rpcInit = {0};
5✔
2634
  char     pass[TSDB_PASSWORD_LEN + 1] = {0};
5✔
2635

2636
  rpcInit.label = "CHK";
5✔
2637
  rpcInit.numOfThreads = 1;
5✔
2638
  rpcInit.cfp = NULL;
5✔
2639
  rpcInit.sessions = 16;
5✔
2640
  rpcInit.connType = TAOS_CONN_CLIENT;
5✔
2641
  rpcInit.idleTime = tsShellActivityTimer * 1000;
5✔
2642
  rpcInit.compressSize = tsCompressMsgSize;
5✔
2643
  rpcInit.user = "_dnd";
5✔
2644

2645
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
5✔
2646
  connLimitNum = TMAX(connLimitNum, 10);
5✔
2647
  connLimitNum = TMIN(connLimitNum, 500);
5✔
2648
  rpcInit.connLimitNum = connLimitNum;
5✔
2649
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
5✔
2650
  rpcInit.readTimeout = tsReadTimeout;
5✔
2651
  if (TSDB_CODE_SUCCESS != taosVersionStrToInt(td_version, &rpcInit.compatibilityVer)) {
5!
2652
    tscError("faild to convert taos version from str to int, errcode:%s", terrstr());
×
2653
    goto _OVER;
×
2654
  }
2655

2656
  clientRpc = rpcOpen(&rpcInit);
5✔
2657
  if (clientRpc == NULL) {
5!
2658
    code = terrno;
×
2659
    tscError("failed to init server status client since %s", tstrerror(code));
×
2660
    goto _OVER;
×
2661
  }
2662

2663
  if (fqdn == NULL) {
5!
2664
    fqdn = tsLocalFqdn;
5✔
2665
  }
2666

2667
  if (port == 0) {
5!
2668
    port = tsServerPort;
5✔
2669
  }
2670

2671
  tstrncpy(epSet.eps[0].fqdn, fqdn, TSDB_FQDN_LEN);
5✔
2672
  epSet.eps[0].port = (uint16_t)port;
5✔
2673
  int32_t ret = rpcSendRecv(clientRpc, &epSet, &rpcMsg, &rpcRsp);
5✔
2674
  if (TSDB_CODE_SUCCESS != ret) {
5!
2675
    tscError("failed to send recv since %s", tstrerror(ret));
×
2676
    goto _OVER;
×
2677
  }
2678

2679
  if (rpcRsp.code != 0 || rpcRsp.contLen <= 0 || rpcRsp.pCont == NULL) {
5!
2680
    tscError("failed to send server status req since %s", terrstr());
1!
2681
    goto _OVER;
1✔
2682
  }
2683

2684
  if (tDeserializeSServerStatusRsp(rpcRsp.pCont, rpcRsp.contLen, &statusRsp) != 0) {
4!
2685
    tscError("failed to parse server status rsp since %s", terrstr());
×
2686
    goto _OVER;
×
2687
  }
2688

2689
  code = statusRsp.statusCode;
4✔
2690
  if (details != NULL) {
4!
2691
    tstrncpy(details, statusRsp.details, maxlen);
4✔
2692
  }
2693

2694
_OVER:
×
2695
  if (clientRpc != NULL) {
5!
2696
    rpcClose(clientRpc);
5✔
2697
  }
2698
  if (rpcRsp.pCont != NULL) {
5✔
2699
    rpcFreeCont(rpcRsp.pCont);
4✔
2700
  }
2701
  return code;
5✔
2702
}
2703

2704
int32_t appendTbToReq(SHashObj* pHash, int32_t pos1, int32_t len1, int32_t pos2, int32_t len2, const char* str,
3✔
2705
                      int32_t acctId, char* db) {
2706
  SName name = {0};
3✔
2707

2708
  if (len1 <= 0) {
3!
2709
    return -1;
×
2710
  }
2711

2712
  const char* dbName = db;
3✔
2713
  const char* tbName = NULL;
3✔
2714
  int32_t     dbLen = 0;
3✔
2715
  int32_t     tbLen = 0;
3✔
2716
  if (len2 > 0) {
3!
2717
    dbName = str + pos1;
×
2718
    dbLen = len1;
×
2719
    tbName = str + pos2;
×
2720
    tbLen = len2;
×
2721
  } else {
2722
    dbLen = strlen(db);
3✔
2723
    tbName = str + pos1;
3✔
2724
    tbLen = len1;
3✔
2725
  }
2726

2727
  if (dbLen <= 0 || tbLen <= 0) {
3!
2728
    return -1;
×
2729
  }
2730

2731
  if (tNameSetDbName(&name, acctId, dbName, dbLen)) {
3!
2732
    return -1;
×
2733
  }
2734

2735
  if (tNameAddTbName(&name, tbName, tbLen)) {
3!
2736
    return -1;
×
2737
  }
2738

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

2742
  STablesReq* pDb = taosHashGet(pHash, dbFName, strlen(dbFName));
3✔
2743
  if (pDb) {
3!
2744
    if (NULL == taosArrayPush(pDb->pTables, &name)) {
×
2745
      return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
2746
    }
2747
  } else {
2748
    STablesReq db;
2749
    db.pTables = taosArrayInit(20, sizeof(SName));
3✔
2750
    if (NULL == db.pTables) {
3!
2751
      return terrno;
×
2752
    }
2753
    tstrncpy(db.dbFName, dbFName, TSDB_DB_FNAME_LEN);
3✔
2754
    if (NULL == taosArrayPush(db.pTables, &name)) {
6!
2755
      return terrno;
×
2756
    }
2757
    TSC_ERR_RET(taosHashPut(pHash, dbFName, strlen(dbFName), &db, sizeof(db)));
3!
2758
  }
2759

2760
  return TSDB_CODE_SUCCESS;
3✔
2761
}
2762

2763
int32_t transferTableNameList(const char* tbList, int32_t acctId, char* dbName, SArray** pReq) {
3✔
2764
  SHashObj* pHash = taosHashInit(3, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
3✔
2765
  if (NULL == pHash) {
3!
2766
    return terrno;
×
2767
  }
2768

2769
  bool    inEscape = false;
3✔
2770
  int32_t code = 0;
3✔
2771
  void*   pIter = NULL;
3✔
2772

2773
  int32_t vIdx = 0;
3✔
2774
  int32_t vPos[2];
2775
  int32_t vLen[2];
2776

2777
  (void)memset(vPos, -1, sizeof(vPos));
3✔
2778
  (void)memset(vLen, 0, sizeof(vLen));
3✔
2779

2780
  for (int32_t i = 0;; ++i) {
12✔
2781
    if (0 == *(tbList + i)) {
12✔
2782
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
3!
2783
        vLen[vIdx] = i - vPos[vIdx];
3✔
2784
      }
2785

2786
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
3✔
2787
      if (code) {
3!
2788
        goto _return;
×
2789
      }
2790

2791
      break;
3✔
2792
    }
2793

2794
    if ('`' == *(tbList + i)) {
9!
2795
      inEscape = !inEscape;
×
2796
      if (!inEscape) {
×
2797
        if (vPos[vIdx] >= 0) {
×
2798
          vLen[vIdx] = i - vPos[vIdx];
×
2799
        } else {
2800
          goto _return;
×
2801
        }
2802
      }
2803

2804
      continue;
×
2805
    }
2806

2807
    if (inEscape) {
9!
2808
      if (vPos[vIdx] < 0) {
×
2809
        vPos[vIdx] = i;
×
2810
      }
2811
      continue;
×
2812
    }
2813

2814
    if ('.' == *(tbList + i)) {
9!
2815
      if (vPos[vIdx] < 0) {
×
2816
        goto _return;
×
2817
      }
2818
      if (vLen[vIdx] <= 0) {
×
2819
        vLen[vIdx] = i - vPos[vIdx];
×
2820
      }
2821
      vIdx++;
×
2822
      if (vIdx >= 2) {
×
2823
        goto _return;
×
2824
      }
2825
      continue;
×
2826
    }
2827

2828
    if (',' == *(tbList + i)) {
9!
2829
      if (vPos[vIdx] < 0) {
×
2830
        goto _return;
×
2831
      }
2832
      if (vLen[vIdx] <= 0) {
×
2833
        vLen[vIdx] = i - vPos[vIdx];
×
2834
      }
2835

2836
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
×
2837
      if (code) {
×
2838
        goto _return;
×
2839
      }
2840

2841
      (void)memset(vPos, -1, sizeof(vPos));
×
2842
      (void)memset(vLen, 0, sizeof(vLen));
×
2843
      vIdx = 0;
×
2844
      continue;
×
2845
    }
2846

2847
    if (' ' == *(tbList + i) || '\r' == *(tbList + i) || '\t' == *(tbList + i) || '\n' == *(tbList + i)) {
9!
2848
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
×
2849
        vLen[vIdx] = i - vPos[vIdx];
×
2850
      }
2851
      continue;
×
2852
    }
2853

2854
    if (('a' <= *(tbList + i) && 'z' >= *(tbList + i)) || ('A' <= *(tbList + i) && 'Z' >= *(tbList + i)) ||
9!
2855
        ('0' <= *(tbList + i) && '9' >= *(tbList + i)) || ('_' == *(tbList + i))) {
×
2856
      if (vLen[vIdx] > 0) {
9!
2857
        goto _return;
×
2858
      }
2859
      if (vPos[vIdx] < 0) {
9✔
2860
        vPos[vIdx] = i;
3✔
2861
      }
2862
      continue;
9✔
2863
    }
2864

2865
    goto _return;
×
2866
  }
2867

2868
  int32_t dbNum = taosHashGetSize(pHash);
3✔
2869
  *pReq = taosArrayInit(dbNum, sizeof(STablesReq));
3✔
2870
  if (NULL == pReq) {
3!
2871
    TSC_ERR_JRET(terrno);
×
2872
  }
2873
  pIter = taosHashIterate(pHash, NULL);
3✔
2874
  while (pIter) {
6✔
2875
    STablesReq* pDb = (STablesReq*)pIter;
3✔
2876
    if (NULL == taosArrayPush(*pReq, pDb)) {
6!
2877
      TSC_ERR_JRET(terrno);
×
2878
    }
2879
    pIter = taosHashIterate(pHash, pIter);
3✔
2880
  }
2881

2882
  taosHashCleanup(pHash);
3✔
2883

2884
  return TSDB_CODE_SUCCESS;
3✔
2885

2886
_return:
×
2887

2888
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
2889

2890
  pIter = taosHashIterate(pHash, NULL);
×
2891
  while (pIter) {
×
2892
    STablesReq* pDb = (STablesReq*)pIter;
×
2893
    taosArrayDestroy(pDb->pTables);
×
2894
    pIter = taosHashIterate(pHash, pIter);
×
2895
  }
2896

2897
  taosHashCleanup(pHash);
×
2898

2899
  return terrno;
×
2900
}
2901

2902
void syncCatalogFn(SMetaData* pResult, void* param, int32_t code) {
3✔
2903
  SSyncQueryParam* pParam = param;
3✔
2904
  pParam->pRequest->code = code;
3✔
2905

2906
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
3!
2907
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
2908
  }
2909
}
3✔
2910

2911
void syncQueryFn(void* param, void* res, int32_t code) {
10,702,402✔
2912
  SSyncQueryParam* pParam = param;
10,702,402✔
2913
  pParam->pRequest = res;
10,702,402✔
2914

2915
  if (pParam->pRequest) {
10,702,402✔
2916
    pParam->pRequest->code = code;
10,701,091✔
2917
    clientOperateReport(pParam->pRequest);
10,701,091✔
2918
  }
2919

2920
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
10,703,673!
2921
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
2922
  }
2923
}
10,708,858✔
2924

2925
void taosAsyncQueryImpl(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
10,694,837✔
2926
                        int8_t source) {
2927
  if (sql == NULL || NULL == fp) {
10,694,837!
2928
    terrno = TSDB_CODE_INVALID_PARA;
×
2929
    if (fp) {
×
2930
      fp(param, NULL, terrno);
×
2931
    }
2932

2933
    return;
×
2934
  }
2935

2936
  size_t sqlLen = strlen(sql);
10,702,495✔
2937
  if (sqlLen > (size_t)TSDB_MAX_ALLOWED_SQL_LEN) {
10,702,495!
2938
    tscError("sql string exceeds max length:%d", TSDB_MAX_ALLOWED_SQL_LEN);
×
2939
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
2940
    fp(param, NULL, terrno);
×
2941
    return;
×
2942
  }
2943

2944
  SRequestObj* pRequest = NULL;
10,702,495✔
2945
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
10,702,495✔
2946
  if (code != TSDB_CODE_SUCCESS) {
10,693,525!
2947
    terrno = code;
×
2948
    fp(param, NULL, terrno);
×
2949
    return;
×
2950
  }
2951

2952
  pRequest->source = source;
10,693,525✔
2953
  pRequest->body.queryFp = fp;
10,693,525✔
2954
  doAsyncQuery(pRequest, false);
10,693,525✔
2955
}
2956
void taosAsyncQueryImplWithReqid(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
1✔
2957
                                 int64_t reqid) {
2958
  if (sql == NULL || NULL == fp) {
1!
2959
    terrno = TSDB_CODE_INVALID_PARA;
×
2960
    if (fp) {
×
2961
      fp(param, NULL, terrno);
×
2962
    }
2963

2964
    return;
×
2965
  }
2966

2967
  size_t sqlLen = strlen(sql);
1✔
2968
  if (sqlLen > (size_t)TSDB_MAX_ALLOWED_SQL_LEN) {
1!
2969
    tscError("sql string exceeds max length:%d", TSDB_MAX_ALLOWED_SQL_LEN);
×
2970
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
2971
    fp(param, NULL, terrno);
×
2972
    return;
×
2973
  }
2974

2975
  SRequestObj* pRequest = NULL;
1✔
2976
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, reqid);
1✔
2977
  if (code != TSDB_CODE_SUCCESS) {
1!
2978
    terrno = code;
×
2979
    fp(param, NULL, terrno);
×
2980
    return;
×
2981
  }
2982

2983
  pRequest->body.queryFp = fp;
1✔
2984
  doAsyncQuery(pRequest, false);
1✔
2985
}
2986

2987
TAOS_RES* taosQueryImpl(TAOS* taos, const char* sql, bool validateOnly, int8_t source) {
10,694,091✔
2988
  if (NULL == taos) {
10,694,091!
2989
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
2990
    return NULL;
×
2991
  }
2992

2993
  tscDebug("connObj:0x%" PRIx64 ", taos_query start with sql:%s", *(int64_t*)taos, sql);
10,694,091✔
2994

2995
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
10,694,091!
2996
  if (NULL == param) {
10,703,086!
2997
    return NULL;
×
2998
  }
2999
  int32_t code = tsem_init(&param->sem, 0, 0);
10,703,086✔
3000
  if (TSDB_CODE_SUCCESS != code) {
10,701,232!
3001
    taosMemoryFree(param);
×
3002
    return NULL;
×
3003
  }
3004

3005
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
10,701,232✔
3006
  code = tsem_wait(&param->sem);
10,656,802✔
3007
  if (TSDB_CODE_SUCCESS != code) {
10,704,827!
3008
    taosMemoryFree(param);
×
3009
    return NULL;
×
3010
  }
3011
  code = tsem_destroy(&param->sem);
10,704,827✔
3012
  if (TSDB_CODE_SUCCESS != code) {
10,703,027!
3013
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3014
  }
3015

3016
  SRequestObj* pRequest = NULL;
10,706,063✔
3017
  if (param->pRequest != NULL) {
10,706,063!
3018
    param->pRequest->syncQuery = true;
10,706,063✔
3019
    pRequest = param->pRequest;
10,706,063✔
3020
    param->pRequest->inCallback = false;
10,706,063✔
3021
  }
3022
  taosMemoryFree(param);
10,706,063!
3023

3024
  tscDebug("connObj:0x%" PRIx64 ", res:%p created, taos_query end", *(int64_t*)taos, pRequest);
10,697,994✔
3025

3026
  return pRequest;
10,699,632✔
3027
}
3028

3029
TAOS_RES* taosQueryImplWithReqid(TAOS* taos, const char* sql, bool validateOnly, int64_t reqid) {
1✔
3030
  if (NULL == taos) {
1!
3031
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3032
    return NULL;
×
3033
  }
3034

3035
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
1!
3036
  if (param == NULL) {
1!
3037
    return NULL;
×
3038
  }
3039
  int32_t code = tsem_init(&param->sem, 0, 0);
1✔
3040
  if (TSDB_CODE_SUCCESS != code) {
1!
3041
    taosMemoryFree(param);
×
3042
    return NULL;
×
3043
  }
3044

3045
  taosAsyncQueryImplWithReqid(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, reqid);
1✔
3046
  code = tsem_wait(&param->sem);
1✔
3047
  if (TSDB_CODE_SUCCESS != code) {
1!
3048
    taosMemoryFree(param);
×
3049
    return NULL;
×
3050
  }
3051
  SRequestObj* pRequest = NULL;
1✔
3052
  if (param->pRequest != NULL) {
1!
3053
    param->pRequest->syncQuery = true;
1✔
3054
    pRequest = param->pRequest;
1✔
3055
  }
3056
  taosMemoryFree(param);
1!
3057
  return pRequest;
1✔
3058
}
3059

3060
static void fetchCallback(void* pResult, void* param, int32_t code) {
850,913✔
3061
  SRequestObj* pRequest = (SRequestObj*)param;
850,913✔
3062

3063
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
850,913✔
3064

3065
  tscDebug("req:0x%" PRIx64 ", enter scheduler fetch cb, code:%d - %s, QID:0x%" PRIx64, pRequest->self, code, tstrerror(code),
850,913✔
3066
           pRequest->requestId);
3067

3068
  pResultInfo->pData = pResult;
850,910✔
3069
  pResultInfo->numOfRows = 0;
850,910✔
3070

3071
  if (code != TSDB_CODE_SUCCESS) {
850,910!
3072
    pRequest->code = code;
×
3073
    taosMemoryFreeClear(pResultInfo->pData);
×
3074
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
×
3075
    return;
×
3076
  }
3077

3078
  if (pRequest->code != TSDB_CODE_SUCCESS) {
850,910!
3079
    taosMemoryFreeClear(pResultInfo->pData);
×
3080
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pRequest->code);
×
3081
    return;
×
3082
  }
3083

3084
  pRequest->code =
850,924✔
3085
      setQueryResultFromRsp(pResultInfo, (const SRetrieveTableRsp*)pResultInfo->pData, pResultInfo->convertUcs4, pRequest->isStmtBind);
850,910✔
3086
  if (pRequest->code != TSDB_CODE_SUCCESS) {
850,924!
3087
    pResultInfo->numOfRows = 0;
×
3088
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(pRequest->code),
×
3089
             pRequest->requestId);
3090
  } else {
3091
    tscDebug("req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
850,924✔
3092
             pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed,
3093
             pRequest->requestId);
3094

3095
    STscObj*            pTscObj = pRequest->pTscObj;
850,925✔
3096
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
850,925✔
3097
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
850,925✔
3098
  }
3099

3100
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
850,938✔
3101
}
3102

3103
void taosAsyncFetchImpl(SRequestObj* pRequest, __taos_async_fn_t fp, void* param) {
925,296✔
3104
  pRequest->body.fetchFp = fp;
925,296✔
3105
  ((SSyncQueryParam*)pRequest->body.interParam)->userParam = param;
925,296✔
3106

3107
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
925,296✔
3108

3109
  // this query has no results or error exists, return directly
3110
  if (taos_num_fields(pRequest) == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
925,296!
3111
    pResultInfo->numOfRows = 0;
×
3112
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
×
3113
    return;
74,359✔
3114
  }
3115

3116
  // all data has returned to App already, no need to try again
3117
  if (pResultInfo->completed) {
925,296✔
3118
    // it is a local executed query, no need to do async fetch
3119
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
74,358✔
3120
      if (pResultInfo->localResultFetched) {
2,664✔
3121
        pResultInfo->numOfRows = 0;
1,332✔
3122
        pResultInfo->current = 0;
1,332✔
3123
      } else {
3124
        pResultInfo->localResultFetched = true;
1,332✔
3125
      }
3126
    } else {
3127
      pResultInfo->numOfRows = 0;
71,694✔
3128
    }
3129

3130
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
74,358✔
3131
    return;
74,358✔
3132
  }
3133

3134
  SSchedulerReq req = {
850,938✔
3135
      .syncReq = false,
3136
      .fetchFp = fetchCallback,
3137
      .cbParam = pRequest,
3138
  };
3139

3140
  int32_t code = schedulerFetchRows(pRequest->body.queryJob, &req);
850,938✔
3141
  if (TSDB_CODE_SUCCESS != code) {
850,927!
3142
    tscError("0x%" PRIx64 " failed to schedule fetch rows", pRequest->requestId);
×
3143
    // pRequest->body.fetchFp(param, pRequest, code);
3144
  }
3145
}
3146

3147
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
10,702,090✔
3148
  pRequest->inCallback = true;
10,702,090✔
3149
  int64_t this = pRequest->self;
10,702,090✔
3150
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
10,702,090!
3151
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
316!
3152
    code = TSDB_CODE_SUCCESS;
×
3153
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3154
  }
3155
  if (pRequest->body.queryFp != NULL) {
10,702,090!
3156
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
10,705,078✔
3157
  }
3158
  SRequestObj* pReq = acquireRequest(this);
10,705,063✔
3159
  if (pReq != NULL) {
10,706,956✔
3160
    pReq->inCallback = false;
10,698,501✔
3161
    (void)releaseRequest(this);
10,698,501✔
3162
  }
3163
}
10,702,079✔
3164

3165
int32_t clientParseSql(void* param, const char* dbName, const char* sql, bool parseOnly, const char* effectiveUser,
916✔
3166
                       SParseSqlRes* pRes) {
3167
#ifndef TD_ENTERPRISE
3168
  return TSDB_CODE_SUCCESS;
3169
#else
3170
  return clientParseSqlImpl(param, dbName, sql, parseOnly, effectiveUser, pRes);
916✔
3171
#endif
3172
}
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