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

taosdata / TDengine / #3824

01 Apr 2025 12:26PM UTC coverage: 34.064% (-0.001%) from 34.065%
#3824

push

travis-ci

happyguoxy
test:alter gcda dir

148483 of 599532 branches covered (24.77%)

Branch coverage included in aggregate %.

222466 of 489445 relevant lines covered (45.45%)

762427.9 hits per line

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

57.3
/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) {
6,909✔
37
  SRequestObj* pReq = acquireRequest(rId);
6,909✔
38
  if (pReq != NULL) {
6,910!
39
    pReq->isQuery = true;
6,910✔
40
    (void)releaseRequest(rId);
6,910✔
41
  }
42
}
6,909✔
43

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

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

54
  return true;
5,884✔
55
}
56

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

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

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

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

69
bool chkRequestKilled(void* param) {
387,862✔
70
  bool         killed = false;
387,862✔
71
  SRequestObj* pRequest = acquireRequest((int64_t)param);
387,862✔
72
  if (NULL == pRequest || pRequest->killed) {
387,962!
73
    killed = true;
×
74
  }
75

76
  (void)releaseRequest((int64_t)param);
387,962✔
77

78
  return killed;
387,938✔
79
}
80

81
void cleanupAppInfo() {
401✔
82
  taosHashCleanup(appInfo.pInstMap);
401✔
83
  taosHashCleanup(appInfo.pInstMapByClusterId);
401✔
84
}
401✔
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,
2,784✔
90
                              uint16_t port, int connType, STscObj** pObj) {
91
  TSC_ERR_RET(taos_init());
2,784!
92
  if (!validateUserName(user)) {
2,784!
93
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
94
  }
95

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

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

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

112
    taosEncryptPass_c((uint8_t*)pass, strlen(pass), secretEncrypt);
2,783✔
113
  } else {
114
    tstrncpy(secretEncrypt, auth, tListLen(secretEncrypt));
1✔
115
  }
116

117
  SCorEpSet epSet = {0};
2,784✔
118
  if (ip) {
2,784✔
119
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
1,849✔
120
  } else {
121
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
935!
122
  }
123

124
  if (port) {
2,783✔
125
    epSet.epSet.eps[0].port = port;
147✔
126
    epSet.epSet.eps[1].port = port;
147✔
127
  }
128

129
  char* key = getClusterKey(user, secretEncrypt, ip, port);
2,783✔
130
  if (NULL == key) {
2,783!
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,
2,783!
134
          user, db, key);
135
  for (int32_t i = 0; i < epSet.epSet.numOfEps; ++i) {
6,501✔
136
    tscInfo("ep:%d, %s:%u", i, epSet.epSet.eps[i].fqdn, epSet.epSet.eps[i].port);
3,718!
137
  }
138

139
  SAppInstInfo** pInst = NULL;
2,783✔
140
  int32_t        code = taosThreadMutexLock(&appInfo.mutex);
2,783✔
141
  if (TSDB_CODE_SUCCESS != code) {
2,783!
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));
2,783✔
147
  SAppInstInfo* p = NULL;
2,783✔
148
  if (pInst == NULL) {
2,783✔
149
    p = taosMemoryCalloc(1, sizeof(struct SAppInstInfo));
433!
150
    if (NULL == p) {
433!
151
      TSC_ERR_JRET(terrno);
×
152
    }
153
    p->mgmtEp = epSet;
433✔
154
    code = taosThreadMutexInit(&p->qnodeMutex, NULL);
433✔
155
    if (TSDB_CODE_SUCCESS != code) {
433!
156
      taosMemoryFree(p);
×
157
      TSC_ERR_JRET(code);
×
158
    }
159
    code = openTransporter(user, secretEncrypt, tsNumOfCores / 2, &p->pTransporter);
433✔
160
    if (TSDB_CODE_SUCCESS != code) {
433!
161
      taosMemoryFree(p);
×
162
      TSC_ERR_JRET(code);
×
163
    }
164
    code = appHbMgrInit(p, key, &p->pAppHbMgr);
433✔
165
    if (TSDB_CODE_SUCCESS != code) {
433!
166
      destroyAppInst(&p);
×
167
      TSC_ERR_JRET(code);
×
168
    }
169
    code = taosHashPut(appInfo.pInstMap, key, strlen(key), &p, POINTER_BYTES);
433✔
170
    if (TSDB_CODE_SUCCESS != code) {
433!
171
      destroyAppInst(&p);
×
172
      TSC_ERR_JRET(code);
×
173
    }
174
    p->instKey = key;
433✔
175
    key = NULL;
433✔
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);
433!
177

178
    pInst = &p;
433✔
179
  } else {
180
    if (NULL == *pInst || NULL == (*pInst)->pAppHbMgr) {
2,350!
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);
2,350✔
186
  }
187

188
_return:
2,783✔
189

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

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

230
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
121,219!
231
  if ((*pRequest)->sqlstr == NULL) {
121,218!
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);
121,218✔
239
  (*pRequest)->sqlstr[sqlLen] = 0;
121,224✔
240
  (*pRequest)->sqlLen = sqlLen;
121,224✔
241
  (*pRequest)->validateOnly = validateSql;
121,224✔
242
  (*pRequest)->isStmtBind = false;
121,224✔
243

244
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
121,224✔
245

246
  STscObj* pTscObj = (*pRequest)->pTscObj;
121,224✔
247
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
121,224✔
248
                             sizeof((*pRequest)->self));
249
  if (err) {
121,223!
250
    tscError("req:0x%" PRId64 ", failed to add to request container, QID:0x%" PRIx64 ", conn:%" 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;
121,223✔
258
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
121,223✔
259
    if (TSDB_CODE_SUCCESS !=
14,166!
260
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
14,166✔
261
      tscError("req:0x%" PRId64 ", failed to create node allocator, QID:0x%" PRIx64 ", conn:%" 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 ", build request, QID:0x%" PRIx64, (*pRequest)->self, (*pRequest)->requestId);
121,224✔
270
  return TSDB_CODE_SUCCESS;
121,222✔
271
}
272

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

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

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

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

315
  code = qParseSql(&cxt, pQuery);
193✔
316
  if (TSDB_CODE_SUCCESS == code) {
193✔
317
    if ((*pQuery)->haveResultSet) {
168!
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)) {
193!
324
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
174✔
325
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
174✔
326
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
174✔
327
  }
328

329
  taosArrayDestroy(cxt.pTableMetaPos);
193✔
330
  taosArrayDestroy(cxt.pTableVgroupPos);
193✔
331

332
  return code;
192✔
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) {
72✔
347
  // drop table if exists not_exists_table
348
  if (NULL == pQuery->pCmdMsg) {
72!
349
    return TSDB_CODE_SUCCESS;
×
350
  }
351

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

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

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

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

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

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

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

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

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

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

403
  // drop table if exists not_exists_table
404
  if (NULL == pQuery->pCmdMsg) {
2,080!
405
    doRequestCallback(pRequest, 0);
×
406
    return TSDB_CODE_SUCCESS;
×
407
  }
408

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

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

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

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

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

432
  return node1->load > node2->load;
×
433
}
434

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

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

451
  return TSDB_CODE_SUCCESS;
22✔
452
}
453

454
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
120,701✔
455
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
120,701!
456
    *required = false;
120,630✔
457
    return TSDB_CODE_SUCCESS;
120,630✔
458
  }
459

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

464
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
71!
465
  *required = (NULL == pInfo->pQnodeList);
71✔
466
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
71!
467
  return TSDB_CODE_SUCCESS;
71✔
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) {
2,647✔
503
  pRequest->type = pQuery->msgType;
2,647✔
504
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
2,647✔
505

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

517
  return qCreateQueryPlan(&cxt, pPlan, pNodeList);
2,647✔
518
}
519

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

526
  pResInfo->numOfCols = numOfCols;
47,175✔
527
  if (pResInfo->fields != NULL) {
47,175✔
528
    taosMemoryFree(pResInfo->fields);
11!
529
  }
530
  if (pResInfo->userFields != NULL) {
47,175✔
531
    taosMemoryFree(pResInfo->userFields);
11!
532
  }
533
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD_E));
47,175!
534
  if (NULL == pResInfo->fields) return terrno;
47,168!
535
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
47,168!
536
  if (NULL == pResInfo->userFields) {
47,171!
537
    taosMemoryFree(pResInfo->fields);
×
538
    return terrno;
×
539
  }
540
  if (numOfCols != pResInfo->numOfCols) {
47,171!
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) {
228,268✔
546
    pResInfo->fields[i].type = pSchema[i].type;
181,083✔
547

548
    pResInfo->userFields[i].type = pSchema[i].type;
181,083✔
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);
181,083✔
551
    pResInfo->fields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, isStmt);
181,092✔
552
    if (IS_DECIMAL_TYPE(pSchema[i].type) && pExtSchema) {
181,097!
553
      decimalFromTypeMod(pExtSchema[i].typeMod, &pResInfo->fields[i].precision, &pResInfo->fields[i].scale);
268✔
554
    }
555

556
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
181,097✔
557
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
181,097✔
558
  }
559
  return TSDB_CODE_SUCCESS;
47,185✔
560
}
561

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

568
  pResInfo->precision = precision;
6,963✔
569
}
570

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

578
  int32_t dbNum = taosArrayGetSize(pDbVgList);
9,364✔
579
  for (int32_t i = 0; i < dbNum; ++i) {
18,263✔
580
    SArray* pVg = taosArrayGetP(pDbVgList, i);
8,889✔
581
    if (NULL == pVg) {
8,891!
582
      continue;
×
583
    }
584
    int32_t vgNum = taosArrayGetSize(pVg);
8,891✔
585
    if (vgNum <= 0) {
8,891✔
586
      continue;
24✔
587
    }
588

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

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

606
  int32_t vnodeNum = taosArrayGetSize(nodeList);
9,374✔
607
  if (vnodeNum > 0) {
9,369✔
608
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
8,772✔
609
    goto _return;
8,772✔
610
  }
611

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

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

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

630
_return:
363✔
631

632
  *pNodeList = nodeList;
9,364✔
633

634
  return TSDB_CODE_SUCCESS;
9,364✔
635
}
636

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

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

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

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

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

676
_return:
×
677

678
  *pNodeList = nodeList;
32✔
679

680
  return TSDB_CODE_SUCCESS;
32✔
681
}
682

683
void freeVgList(void* list) {
2,523✔
684
  SArray* pList = *(SArray**)list;
2,523✔
685
  taosArrayDestroy(pList);
2,523✔
686
}
2,525✔
687

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

694
  switch (tsQueryPolicy) {
6,739!
695
    case QUERY_POLICY_VNODE:
6,716✔
696
    case QUERY_POLICY_CLIENT: {
697
      if (pResultMeta) {
6,716!
698
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
6,720✔
699
        if (NULL == pDbVgList) {
6,709!
700
          code = terrno;
×
701
          goto _return;
×
702
        }
703
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
6,709✔
704
        for (int32_t i = 0; i < dbNum; ++i) {
13,074✔
705
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
6,363✔
706
          if (pRes->code || NULL == pRes->pRes) {
6,362!
707
            continue;
×
708
          }
709

710
          if (NULL == taosArrayPush(pDbVgList, &pRes->pRes)) {
12,729!
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);
6,711✔
755
      break;
6,715✔
756
    }
757
    case QUERY_POLICY_HYBRID:
32✔
758
    case QUERY_POLICY_QNODE: {
759
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
48!
760
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
16✔
761
        if (pRes->code) {
16!
762
          pQnodeList = NULL;
×
763
        } else {
764
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
16✔
765
          if (NULL == pQnodeList) {
16!
766
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
767
            goto _return;
×
768
          }
769
        }
770
      } else {
771
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
16✔
772
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
16!
773
        if (pInst->pQnodeList) {
16!
774
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
16✔
775
          if (NULL == pQnodeList) {
16!
776
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
777
            goto _return;
×
778
          }
779
        }
780
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
16!
781
      }
782

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

791
_return:
6,747✔
792
  taosArrayDestroyEx(pDbVgList, fp);
6,747✔
793
  taosArrayDestroy(pQnodeList);
6,752✔
794

795
  return code;
6,753✔
796
}
797

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

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

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

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

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

841
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
2,648✔
842
      break;
2,646✔
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:
2,646✔
857

858
  taosArrayDestroyEx(pDbVgList, freeVgList);
2,646✔
859
  taosArrayDestroy(pQnodeList);
2,647✔
860

861
  return code;
2,647✔
862
}
863

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

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

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

890
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
2,646✔
891
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
2,647✔
892

893
  if (code != TSDB_CODE_SUCCESS) {
2,647!
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 ||
2,647!
902
      TDMT_VND_CREATE_TABLE == pRequest->type) {
3!
903
    pRequest->body.resInfo.numOfRows = res.numOfRows;
2,644✔
904
    if (TDMT_VND_SUBMIT == pRequest->type) {
2,644✔
905
      STscObj*            pTscObj = pRequest->pTscObj;
2,643✔
906
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
2,643✔
907
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
2,643✔
908
    }
909

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

913
  pRequest->code = res.code;
2,647✔
914
  terrno = res.code;
2,647✔
915
  return pRequest->code;
2,647✔
916
}
917

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

925
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
371✔
926
  for (int32_t i = 0; i < tbNum; ++i) {
953✔
927
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
580✔
928
    if (pTbRsp->pMeta) {
580✔
929
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
305!
930
    }
931
  }
932

933
  return TSDB_CODE_SUCCESS;
373✔
934
}
935

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

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

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

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

968
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
5,568✔
969

970
_return:
5,565✔
971

972
  taosArrayDestroy(pArray);
5,565✔
973
  return code;
5,567✔
974
}
975

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

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

984
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
120,572✔
985
  if (NULL == pRequest->body.resInfo.execRes.res) {
120,572✔
986
    return pRequest->code;
2,121✔
987
  }
988

989
  SCatalog*     pCatalog = NULL;
118,451✔
990
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
118,451✔
991

992
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
118,445✔
993
  if (code) {
118,464!
994
    return code;
×
995
  }
996

997
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
118,464✔
998
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
118,471✔
999

1000
  switch (pRes->msgType) {
118,471✔
1001
    case TDMT_VND_ALTER_TABLE:
19✔
1002
    case TDMT_MND_ALTER_STB: {
1003
      code = handleAlterTbExecRes(pRes->res, pCatalog);
19✔
1004
      break;
19✔
1005
    }
1006
    case TDMT_VND_CREATE_TABLE: {
3,503✔
1007
      SArray* pList = (SArray*)pRes->res;
3,503✔
1008
      int32_t num = taosArrayGetSize(pList);
3,503✔
1009
      for (int32_t i = 0; i < num; ++i) {
8,985✔
1010
        void* res = taosArrayGetP(pList, i);
5,482✔
1011
        // handleCreateTbExecRes will handle res == null
1012
        code = handleCreateTbExecRes(res, pCatalog);
5,482✔
1013
      }
1014
      break;
3,503✔
1015
    }
1016
    case TDMT_MND_CREATE_STB: {
44✔
1017
      code = handleCreateTbExecRes(pRes->res, pCatalog);
44✔
1018
      break;
44✔
1019
    }
1020
    case TDMT_VND_SUBMIT: {
109,326✔
1021
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
109,326✔
1022

1023
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
109,336✔
1024
      break;
109,326✔
1025
    }
1026
    case TDMT_SCH_QUERY:
5,568✔
1027
    case TDMT_SCH_MERGE_QUERY: {
1028
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
5,568✔
1029
      break;
5,566✔
1030
    }
1031
    default:
11✔
1032
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self, pRequest->type,
11!
1033
               pRequest->requestId);
1034
      code = TSDB_CODE_APP_ERROR;
×
1035
  }
1036

1037
  return code;
118,458✔
1038
}
1039

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

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

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

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

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

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

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

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

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

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

1107
  for (int32_t i = 0; i < numOfRows; ++i) {
6✔
1108
    TAOS_ROW pRow = taos_fetch_row(pRes);
4✔
1109
    if (NULL == pRow[0] || NULL == pRow[1] || NULL == pRow[2]) {
4!
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];
4✔
1115
    if (lastTs < ts) {
4✔
1116
      lastTs = ts;
2✔
1117
    }
1118

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

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

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

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

1145
  SSDataBlock* pBlock = NULL;
2✔
1146
  pRequest->code = createResultBlock(res, rowNum, &pBlock);
2✔
1147
  if (TSDB_CODE_SUCCESS != pRequest->code) {
2!
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);
2✔
1155
  if (pNextReq) {
2!
1156
    continuePostSubQuery(pNextReq, pBlock);
2✔
1157
    (void)releaseRequest(pRequest->relation.nextRefId);
2✔
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);
2✔
1164
}
1165

1166
void handlePostSubQuery(SSqlCallbackWrapper* pWrapper) {
2✔
1167
  SRequestObj* pRequest = pWrapper->pRequest;
2✔
1168
  if (TD_RES_QUERY(pRequest)) {
2!
1169
    taosAsyncFetchImpl(pRequest, postSubQueryFetchCb, pWrapper);
2✔
1170
    return;
2✔
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) {
117,887✔
1185
  SSqlCallbackWrapper* pWrapper = param;
117,887✔
1186
  SRequestObj*         pRequest = pWrapper->pRequest;
117,887✔
1187
  STscObj*             pTscObj = pRequest->pTscObj;
117,887✔
1188

1189
  pRequest->code = code;
117,887✔
1190
  if (pResult) {
117,887✔
1191
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
117,880✔
1192
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
117,873✔
1193
  }
1194

1195
  int32_t type = pRequest->type;
117,880✔
1196
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
117,880✔
1197
    if (pResult) {
110,476✔
1198
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
110,469✔
1199

1200
      // record the insert rows
1201
      if (TDMT_VND_SUBMIT == type) {
110,469✔
1202
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
106,687✔
1203
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
106,687✔
1204
      }
1205
    }
1206
    schedulerFreeJob(&pRequest->body.queryJob, 0);
110,491✔
1207
  }
1208

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

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

1223
  tscTrace("req:0x%" PRIx64 ", scheduler exec cb, request type:%s", pRequest->self, TMSG_INFO(pRequest->type));
117,867!
1224
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
117,867!
1225
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
915!
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;
117,869✔
1231
  int32_t code1 = handleQueryExecRsp(pRequest);
117,869✔
1232
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
117,860!
1233
    pRequest->code = code1;
×
1234
  }
1235

1236
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
235,554!
1237
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
117,693✔
1238
    continueInsertFromCsv(pWrapper, pRequest);
×
1239
    return;
×
1240
  }
1241

1242
  if (pRequest->relation.nextRefId) {
117,871✔
1243
    handlePostSubQuery(pWrapper);
2✔
1244
  } else {
1245
    destorySqlCallbackWrapper(pWrapper);
117,869✔
1246
    pRequest->pWrapper = NULL;
117,870✔
1247

1248
    // return to client
1249
    doRequestCallback(pRequest, code);
117,870✔
1250
  }
1251
}
1252

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

1257
  if (pQuery->pRoot) {
2,719✔
1258
    pRequest->stmtType = pQuery->pRoot->type;
2,647✔
1259
  }
1260

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

1271
  pRequest->body.execMode = pQuery->execMode;
2,718✔
1272
  switch (pQuery->execMode) {
2,718!
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:
72✔
1284
      if (!pRequest->validateOnly) {
72!
1285
        code = execDdlQuery(pRequest, pQuery);
72✔
1286
      }
1287
      break;
72✔
1288
    case QUERY_EXEC_MODE_SCHEDULE: {
2,646✔
1289
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
2,646✔
1290
      if (NULL == pMnodeList) {
2,647!
1291
        code = terrno;
×
1292
        break;
×
1293
      }
1294
      SQueryPlan* pDag = NULL;
2,647✔
1295
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
2,647✔
1296
      if (TSDB_CODE_SUCCESS == code) {
2,645!
1297
        pRequest->body.subplanNum = pDag->numOfSubplans;
2,645✔
1298
        if (!pRequest->validateOnly) {
2,645!
1299
          SArray* pNodeList = NULL;
2,645✔
1300
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
2,645✔
1301
          if (TSDB_CODE_SUCCESS == code) {
2,645!
1302
            code = scheduleQuery(pRequest, pDag, pNodeList);
2,646✔
1303
          }
1304
          taosArrayDestroy(pNodeList);
2,645✔
1305
        }
1306
      }
1307
      taosArrayDestroy(pMnodeList);
2,647✔
1308
      break;
2,647✔
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) {
2,719!
1318
    qDestroyQuery(pQuery);
×
1319
  }
1320

1321
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
2,719!
1322
    int ret = removeMeta(pRequest->pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type));
28!
1323
    if (TSDB_CODE_SUCCESS != ret) {
28!
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) {
2,719✔
1329
    code = handleQueryExecRsp(pRequest);
2,717✔
1330
  }
1331

1332
  if (TSDB_CODE_SUCCESS != code) {
2,719✔
1333
    pRequest->code = code;
27✔
1334
  }
1335

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

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

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

1380
  pRequest->metric.execStart = taosGetTimestampUs();
117,874✔
1381
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
117,874✔
1382

1383
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
235,760!
1384
    SArray* pNodeList = NULL;
117,874✔
1385
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
117,874✔
1386
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
6,749✔
1387
    }
1388

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

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

1424
    doRequestCallback(pRequest, code);
×
1425
  }
1426

1427
  // todo not to be released here
1428
  taosArrayDestroy(pMnodeList);
117,886✔
1429

1430
  return code;
117,882✔
1431
}
1432

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

1436
  if (pRequest->parseOnly) {
120,361!
1437
    doRequestCallback(pRequest, 0);
×
1438
    return;
×
1439
  }
1440

1441
  pRequest->body.execMode = pQuery->execMode;
120,361✔
1442
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
120,361✔
1443
    destorySqlCallbackWrapper(pWrapper);
2,484✔
1444
    pRequest->pWrapper = NULL;
2,484✔
1445
  }
1446

1447
  if (pQuery->pRoot && !pRequest->inRetry) {
120,361!
1448
    STscObj*            pTscObj = pRequest->pTscObj;
120,369✔
1449
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
120,369✔
1450
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
120,369✔
1451
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
111,133✔
1452
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
106,694✔
1453
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
13,675✔
1454
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
6,630✔
1455
    }
1456
  }
1457

1458
  switch (pQuery->execMode) {
120,370!
1459
    case QUERY_EXEC_MODE_LOCAL:
396✔
1460
      asyncExecLocalCmd(pRequest, pQuery);
396✔
1461
      break;
396✔
1462
    case QUERY_EXEC_MODE_RPC:
2,080✔
1463
      code = asyncExecDdlQuery(pRequest, pQuery);
2,080✔
1464
      break;
2,080✔
1465
    case QUERY_EXEC_MODE_SCHEDULE: {
117,886✔
1466
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
117,886✔
1467
      break;
117,883✔
1468
    }
1469
    case QUERY_EXEC_MODE_EMPTY_RESULT:
8✔
1470
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
8✔
1471
      doRequestCallback(pRequest, 0);
8✔
1472
      break;
8✔
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) {
2✔
1481
  SCatalog* pCatalog = NULL;
2✔
1482
  int32_t   code = 0;
2✔
1483
  int32_t   dbNum = taosArrayGetSize(pRequest->dbList);
2✔
1484
  int32_t   tblNum = taosArrayGetSize(pRequest->tableList);
2✔
1485

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

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

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

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

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

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

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

1520
  return code;
2✔
1521
}
1522

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

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

1548
  return TSDB_CODE_SUCCESS;
972✔
1549
}
1550

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

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

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

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

1581
  if (secondEp && secondEp[0] != 0) {
2,784!
1582
    if (strlen(secondEp) >= TSDB_EP_LEN) {
935!
1583
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1584
      return terrno;
×
1585
    }
1586

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

1602
  if (mgmtEpSet->numOfEps == 0) {
2,784✔
1603
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
1✔
1604
    return TSDB_CODE_RPC_NETWORK_UNAVAIL;
1✔
1605
  }
1606

1607
  return 0;
2,783✔
1608
}
1609

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

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

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

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

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

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

1674
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
2,783✔
1675

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

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

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

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

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

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

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

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

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

1726
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
160,753✔
1727
  if (NULL == pEpSet) {
160,753✔
1728
    return;
145,173✔
1729
  }
1730

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

1753
      SCatalog* pCatalog = NULL;
15,197✔
1754
      int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
15,197✔
1755
      if (code != TSDB_CODE_SUCCESS) {
15,195!
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);
15,195✔
1762
      if (code != TSDB_CODE_SUCCESS) {
15,199!
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);
15,199!
1768
      break;
15,199✔
1769
    }
1770
    default:
364✔
1771
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
364!
1772
      break;
365✔
1773
  }
1774
}
1775

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

1785
  STscObj* pTscObj = NULL;
160,754✔
1786

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

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

1794
  if (pSendInfo->requestObjRefId != 0) {
160,760✔
1795
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
141,931✔
1796
    if (pRequest) {
141,932✔
1797
      if (pRequest->self != pSendInfo->requestObjRefId) {
141,749!
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;
141,749✔
1810
    }
1811
  }
1812

1813
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
160,761✔
1814

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

1822
  if (pMsg->contLen > 0) {
160,755✔
1823
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
157,004!
1824
    if (buf.pData == NULL) {
157,002!
1825
      pMsg->code = terrno;
×
1826
    } else {
1827
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
157,002✔
1828
    }
1829
  }
1830

1831
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
160,753✔
1832

1833
  if (pTscObj) {
160,751✔
1834
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
141,746✔
1835
    if (TSDB_CODE_SUCCESS != code) {
141,749!
1836
      tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1837
      terrno = code;
×
1838
      pMsg->code = code;
×
1839
    }
1840
  }
1841

1842
  rpcFreeCont(pMsg->pCont);
160,754✔
1843
  destroySendMsgInfo(pSendInfo);
160,757✔
1844
  return TSDB_CODE_SUCCESS;
160,757✔
1845
}
1846
int32_t doProcessMsgFromServer(void* param) {
160,799✔
1847
  AsyncArg* arg = (AsyncArg*)param;
160,799✔
1848
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
160,799✔
1849
  taosMemoryFree(arg);
160,799!
1850
  return code;
160,798✔
1851
}
1852

1853
void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
160,781✔
1854
  int32_t code = 0;
160,781✔
1855
  SEpSet* tEpSet = NULL;
160,781✔
1856

1857
  tscDebug("msg callback, ahandle %p", pMsg->info.ahandle);
160,781✔
1858

1859
  if (pEpSet != NULL) {
160,784✔
1860
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
15,582!
1861
    if (NULL == tEpSet) {
15,582!
1862
      code = terrno;
×
1863
      pMsg->code = terrno;
×
1864
      goto _exit;
×
1865
    }
1866
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
15,582✔
1867
  }
1868

1869
  // pMsg is response msg
1870
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
160,784✔
1871
    // restore origin code
1872
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
2,783!
1873
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1874
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
2,783!
1875
      pMsg->code = TSDB_CODE_RPC_BROKEN_LINK;
×
1876
    }
1877
  } else {
1878
    // uniform to one error code: TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED
1879
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
158,001!
1880
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
1881
    }
1882
  }
1883

1884
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
160,784!
1885
  if (NULL == arg) {
160,780!
1886
    code = terrno;
×
1887
    pMsg->code = code;
×
1888
    goto _exit;
×
1889
  }
1890

1891
  arg->msg = *pMsg;
160,780✔
1892
  arg->pEpset = tEpSet;
160,780✔
1893

1894
  if ((code = taosAsyncExec(doProcessMsgFromServer, arg, NULL)) != 0) {
160,780!
1895
    pMsg->code = code;
×
1896
    taosMemoryFree(arg);
×
1897
    goto _exit;
×
1898
  }
1899
  return;
160,800✔
1900
  
1901
_exit:
×
1902
  tscError("failed to sched msg to tsc since %s", tstrerror(code));
×
1903
  code = doProcessMsgFromServerImpl(pMsg, tEpSet);
×
1904
  if (code != 0) {
×
1905
    tscError("failed to sched msg to tsc, tsc ready quit");
×
1906
  }
1907
}
1908

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

1915
  if (auth == NULL) {
1!
1916
    tscError("No auth info is given, failed to connect to server");
×
1917
    return NULL;
×
1918
  }
1919

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

1931
  return NULL;
1✔
1932
}
1933

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

1948
void doSetOneRowPtr(SReqResultInfo* pResultInfo) {
1,311,470✔
1949
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
17,260,037✔
1950
    SResultColumn* pCol = &pResultInfo->pCol[i];
15,948,625✔
1951

1952
    int32_t type = pResultInfo->fields[i].type;
15,948,625✔
1953
    int32_t schemaBytes = calcSchemaBytesFromTypeBytes(type, pResultInfo->userFields[i].bytes, false);
15,948,625✔
1954

1955
    if (IS_VAR_DATA_TYPE(type)) {
15,948,567✔
1956
      if (!IS_VAR_NULL_TYPE(type, schemaBytes) && pCol->offset[pResultInfo->current] != -1) {
2,047,772✔
1957
        char* pStart = pResultInfo->pCol[i].offset[pResultInfo->current] + pResultInfo->pCol[i].pData;
1,990,540✔
1958

1959
        pResultInfo->length[i] = varDataLen(pStart);
1,990,540✔
1960
        pResultInfo->row[i] = varDataVal(pStart);
1,990,540✔
1961
      } else {
1962
        pResultInfo->row[i] = NULL;
57,232✔
1963
        pResultInfo->length[i] = 0;
57,232✔
1964
      }
1965
    } else {
1966
      if (!colDataIsNull_f(pCol->nullbitmap, pResultInfo->current)) {
13,900,795✔
1967
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + schemaBytes * pResultInfo->current;
13,391,522✔
1968
        pResultInfo->length[i] = schemaBytes;
13,391,522✔
1969
      } else {
1970
        pResultInfo->row[i] = NULL;
509,273✔
1971
        pResultInfo->length[i] = 0;
509,273✔
1972
      }
1973
    }
1974
  }
1975
}
1,311,412✔
1976

1977
void* doFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
×
1978
  if (pRequest == NULL) {
×
1979
    return NULL;
×
1980
  }
1981

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

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

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

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

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

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

2013
    if (pResultInfo->numOfRows == 0) {
×
2014
      return NULL;
×
2015
    }
2016
  }
2017

2018
  if (setupOneRowPtr) {
×
2019
    doSetOneRowPtr(pResultInfo);
×
2020
    pResultInfo->current += 1;
×
2021
  }
2022

2023
  return pResultInfo->row;
×
2024
}
2025

2026
static void syncFetchFn(void* param, TAOS_RES* res, int32_t numOfRows) {
8,539✔
2027
  tsem_t* sem = param;
8,539✔
2028
  if (TSDB_CODE_SUCCESS != tsem_post(sem)) {
8,539!
2029
    tscError("failed to post sem, code:%s", terrstr());
×
2030
  }
2031
}
8,539✔
2032

2033
void* doAsyncFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
1,049,978✔
2034
  if (pRequest == NULL) {
1,049,978!
2035
    return NULL;
×
2036
  }
2037

2038
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
1,049,978✔
2039
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
1,049,978✔
2040
    // All data has returned to App already, no need to try again
2041
    if (pResultInfo->completed) {
13,721✔
2042
      pResultInfo->numOfRows = 0;
5,183✔
2043
      return NULL;
5,183✔
2044
    }
2045

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

2062
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
1,044,795!
2063
    return NULL;
444✔
2064
  } else {
2065
    if (setupOneRowPtr) {
1,044,351✔
2066
      doSetOneRowPtr(pResultInfo);
1,041,366✔
2067
      pResultInfo->current += 1;
1,040,674✔
2068
    }
2069

2070
    return pResultInfo->row;
1,043,659✔
2071
  }
2072
}
2073

2074
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
48,635✔
2075
  if (pResInfo->row == NULL) {
48,635✔
2076
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
46,407!
2077
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
46,409!
2078
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
46,407!
2079
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
46,409!
2080

2081
    if (pResInfo->row == NULL || pResInfo->pCol == NULL || pResInfo->length == NULL || pResInfo->convertBuf == NULL) {
46,408!
2082
      taosMemoryFree(pResInfo->row);
×
2083
      taosMemoryFree(pResInfo->pCol);
×
2084
      taosMemoryFree(pResInfo->length);
×
2085
      taosMemoryFree(pResInfo->convertBuf);
×
2086
      return terrno;
×
2087
    }
2088
  }
2089

2090
  return TSDB_CODE_SUCCESS;
48,638✔
2091
}
2092

2093
static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength, bool isStmt) {
42,753✔
2094
  int32_t idx = -1;
42,753✔
2095
  iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt);
42,753✔
2096
  if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR;
42,754!
2097

2098
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
193,707✔
2099
    int32_t type = pResultInfo->fields[i].type;
150,922✔
2100
    int32_t schemaBytes = calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
150,922✔
2101

2102
    if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) {
150,923✔
2103
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
860!
2104
      if (p == NULL) {
860!
2105
        taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
×
2106
        return terrno;
×
2107
      }
2108

2109
      pResultInfo->convertBuf[i] = p;
860✔
2110

2111
      SResultColumn* pCol = &pResultInfo->pCol[i];
860✔
2112
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
6,050,744✔
2113
        if (pCol->offset[j] != -1) {
6,049,854✔
2114
          char* pStart = pCol->offset[j] + pCol->pData;
5,947,887✔
2115

2116
          int32_t len = taosUcs4ToMbsEx((TdUcs4*)varDataVal(pStart), varDataLen(pStart), varDataVal(p), conv);
5,947,887✔
2117
          if (len < 0 || len > schemaBytes || (p + len) >= (pResultInfo->convertBuf[i] + colLength[i])) {
5,947,918!
2118
            tscError(
1!
2119
                "doConvertUCS4 error, invalid data. len:%d, bytes:%d, (p + len):%p, (pResultInfo->convertBuf[i] + "
2120
                "colLength[i]):%p",
2121
                len, schemaBytes, (p + len), (pResultInfo->convertBuf[i] + colLength[i]));
2122
            taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
1✔
2123
            return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2124
          }
2125

2126
          varDataSetLen(p, len);
5,947,917✔
2127
          pCol->offset[j] = (p - pResultInfo->convertBuf[i]);
5,947,917✔
2128
          p += (len + VARSTR_HEADER_SIZE);
5,947,917✔
2129
        }
2130
      }
2131

2132
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
890✔
2133
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
890✔
2134
    }
2135
  }
2136
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
42,785✔
2137
  return TSDB_CODE_SUCCESS;
42,754✔
2138
}
2139

2140
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
42,753✔
2141
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
193,677✔
2142
    TAOS_FIELD_E* pFieldE = pResultInfo->fields + i;
150,924✔
2143
    TAOS_FIELD* pField = pResultInfo->userFields + i;
150,924✔
2144
    int32_t type = pFieldE->type;
150,924✔
2145
    int32_t bufLen = 0;
150,924✔
2146
    char* p = NULL;
150,924✔
2147
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
150,924!
2148
      continue;
150,914✔
2149
    } else {
2150
      bufLen = 64;
10✔
2151
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
10!
2152
      pFieldE->bytes = bufLen;
10✔
2153
      pField->bytes = bufLen;
10✔
2154
    }
2155
    if (!p) return terrno;
10!
2156
    pResultInfo->convertBuf[i] = p;
10✔
2157

2158
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
8,014✔
2159
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
8,004✔
2160
                                  pFieldE->precision, pFieldE->scale, p, bufLen);
8,004✔
2161
      p += bufLen;
8,004✔
2162
      if (TSDB_CODE_SUCCESS != code) {
8,004!
2163
        return code;
×
2164
      }
2165
    }
2166
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
10✔
2167
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
10✔
2168
  }
2169
  return 0;
42,753✔
2170
}
2171

2172
int32_t getVersion1BlockMetaSize(const char* p, int32_t numOfCols) {
18✔
2173
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) * 3 + sizeof(uint64_t) +
18✔
2174
         numOfCols * (sizeof(int8_t) + sizeof(int32_t));
2175
}
2176

2177
static int32_t estimateJsonLen(SReqResultInfo* pResultInfo) {
9✔
2178
  char*   p = (char*)pResultInfo->pData;
9✔
2179
  int32_t blockVersion = *(int32_t*)p;
9✔
2180

2181
  int32_t numOfRows = pResultInfo->numOfRows;
9✔
2182
  int32_t numOfCols = pResultInfo->numOfCols;
9✔
2183

2184
  // | version | total length | total rows | total columns | flag seg| block group id | column schema | each column
2185
  // length |
2186
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
9✔
2187
  if (numOfCols != cols) {
9!
2188
    tscError("estimateJsonLen error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2189
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2190
  }
2191

2192
  int32_t  len = getVersion1BlockMetaSize(p, numOfCols);
9✔
2193
  int32_t* colLength = (int32_t*)(p + len);
9✔
2194
  len += sizeof(int32_t) * numOfCols;
9✔
2195

2196
  char* pStart = p + len;
9✔
2197
  for (int32_t i = 0; i < numOfCols; ++i) {
20✔
2198
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
11!
2199

2200
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
11✔
2201
      int32_t* offset = (int32_t*)pStart;
9✔
2202
      int32_t  lenTmp = numOfRows * sizeof(int32_t);
9✔
2203
      len += lenTmp;
9✔
2204
      pStart += lenTmp;
9✔
2205

2206
      int32_t estimateColLen = 0;
9✔
2207
      for (int32_t j = 0; j < numOfRows; ++j) {
20✔
2208
        if (offset[j] == -1) {
11✔
2209
          continue;
6✔
2210
        }
2211
        char* data = offset[j] + pStart;
5✔
2212

2213
        int32_t jsonInnerType = *data;
5✔
2214
        char*   jsonInnerData = data + CHAR_BYTES;
5✔
2215
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
5!
2216
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
×
2217
        } else if (tTagIsJson(data)) {
5✔
2218
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
4✔
2219
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
1!
2220
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
1✔
2221
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
×
2222
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
×
2223
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
×
2224
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
×
2225
        } else {
2226
          tscError("estimateJsonLen error: invalid type:%d", jsonInnerType);
×
2227
          return -1;
×
2228
        }
2229
      }
2230
      len += TMAX(colLen, estimateColLen);
9✔
2231
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
2!
2232
      int32_t lenTmp = numOfRows * sizeof(int32_t);
×
2233
      len += (lenTmp + colLen);
×
2234
      pStart += lenTmp;
×
2235
    } else {
2236
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
2✔
2237
      len += (lenTmp + colLen);
2✔
2238
      pStart += lenTmp;
2✔
2239
    }
2240
    pStart += colLen;
11✔
2241
  }
2242

2243
  // Ensure the complete structure of the block, including the blankfill field,
2244
  // even though it is not used on the client side.
2245
  len += sizeof(bool);
9✔
2246
  return len;
9✔
2247
}
2248

2249
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
48,633✔
2250
  int32_t numOfRows = pResultInfo->numOfRows;
48,633✔
2251
  int32_t numOfCols = pResultInfo->numOfCols;
48,633✔
2252
  bool    needConvert = false;
48,633✔
2253
  for (int32_t i = 0; i < numOfCols; ++i) {
234,744✔
2254
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
186,120✔
2255
      needConvert = true;
9✔
2256
      break;
9✔
2257
    }
2258
  }
2259

2260
  if (!needConvert) {
48,633✔
2261
    return TSDB_CODE_SUCCESS;
48,629✔
2262
  }
2263

2264
  tscDebug("start to convert form json format string");
4✔
2265

2266
  char*   p = (char*)pResultInfo->pData;
4✔
2267
  int32_t blockVersion = *(int32_t*)p;
4✔
2268
  int32_t dataLen = estimateJsonLen(pResultInfo);
4✔
2269
  if (dataLen <= 0) {
9!
2270
    tscError("doConvertJson error: estimateJsonLen failed");
×
2271
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2272
  }
2273

2274
  taosMemoryFreeClear(pResultInfo->convertJson);
9!
2275
  pResultInfo->convertJson = taosMemoryCalloc(1, dataLen);
9!
2276
  if (pResultInfo->convertJson == NULL) return terrno;
9!
2277
  char* p1 = pResultInfo->convertJson;
9✔
2278

2279
  int32_t totalLen = 0;
9✔
2280
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
9✔
2281
  if (numOfCols != cols) {
9!
2282
    tscError("doConvertJson error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2283
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2284
  }
2285

2286
  int32_t len = getVersion1BlockMetaSize(p, numOfCols);
9✔
2287
  (void)memcpy(p1, p, len);
9✔
2288

2289
  p += len;
9✔
2290
  p1 += len;
9✔
2291
  totalLen += len;
9✔
2292

2293
  len = sizeof(int32_t) * numOfCols;
9✔
2294
  int32_t* colLength = (int32_t*)p;
9✔
2295
  int32_t* colLength1 = (int32_t*)p1;
9✔
2296
  (void)memcpy(p1, p, len);
9✔
2297
  p += len;
9✔
2298
  p1 += len;
9✔
2299
  totalLen += len;
9✔
2300

2301
  char* pStart = p;
9✔
2302
  char* pStart1 = p1;
9✔
2303
  for (int32_t i = 0; i < numOfCols; ++i) {
20✔
2304
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
11!
2305
    int32_t colLen1 = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength1[i]) : colLength1[i];
11!
2306
    if (colLen >= dataLen) {
11!
2307
      tscError("doConvertJson error: colLen:%d >= dataLen:%d", colLen, dataLen);
×
2308
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2309
    }
2310
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
11✔
2311
      int32_t* offset = (int32_t*)pStart;
9✔
2312
      int32_t* offset1 = (int32_t*)pStart1;
9✔
2313
      len = numOfRows * sizeof(int32_t);
9✔
2314
      (void)memcpy(pStart1, pStart, len);
9✔
2315
      pStart += len;
9✔
2316
      pStart1 += len;
9✔
2317
      totalLen += len;
9✔
2318

2319
      len = 0;
9✔
2320
      for (int32_t j = 0; j < numOfRows; ++j) {
20✔
2321
        if (offset[j] == -1) {
11✔
2322
          continue;
6✔
2323
        }
2324
        char* data = offset[j] + pStart;
5✔
2325

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

2365
        offset1[j] = len;
5✔
2366
        (void)memcpy(pStart1 + len, dst, varDataTLen(dst));
5✔
2367
        len += varDataTLen(dst);
5✔
2368
      }
2369
      colLen1 = len;
9✔
2370
      totalLen += colLen1;
9✔
2371
      colLength1[i] = (blockVersion == BLOCK_VERSION_1) ? htonl(len) : len;
9!
2372
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
2!
2373
      len = numOfRows * sizeof(int32_t);
×
2374
      (void)memcpy(pStart1, pStart, len);
×
2375
      pStart += len;
×
2376
      pStart1 += len;
×
2377
      totalLen += len;
×
2378
      totalLen += colLen;
×
2379
      (void)memcpy(pStart1, pStart, colLen);
×
2380
    } else {
2381
      len = BitmapLen(pResultInfo->numOfRows);
2✔
2382
      (void)memcpy(pStart1, pStart, len);
2✔
2383
      pStart += len;
2✔
2384
      pStart1 += len;
2✔
2385
      totalLen += len;
2✔
2386
      totalLen += colLen;
2✔
2387
      (void)memcpy(pStart1, pStart, colLen);
2✔
2388
    }
2389
    pStart += colLen;
11✔
2390
    pStart1 += colLen1;
11✔
2391
  }
2392

2393
  // Ensure the complete structure of the block, including the blankfill field,
2394
  // even though it is not used on the client side.
2395
  // (void)memcpy(pStart1, pStart, sizeof(bool));
2396
  totalLen += sizeof(bool);
9✔
2397

2398
  *(int32_t*)(pResultInfo->convertJson + 4) = totalLen;
9✔
2399
  pResultInfo->pData = pResultInfo->convertJson;
9✔
2400
  return TSDB_CODE_SUCCESS;
9✔
2401
}
2402

2403
int32_t setResultDataPtr(SReqResultInfo* pResultInfo, bool convertUcs4, bool isStmt) {
49,215✔
2404
  bool convertForDecimal = convertUcs4;
49,215✔
2405
  if (pResultInfo == NULL || pResultInfo->numOfCols <= 0 || pResultInfo->fields == NULL) {
49,215!
2406
    tscError("setResultDataPtr paras error");
2!
2407
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2408
  }
2409

2410
  if (pResultInfo->numOfRows == 0) {
49,213✔
2411
    return TSDB_CODE_SUCCESS;
580✔
2412
  }
2413

2414
  if (pResultInfo->pData == NULL) {
48,633!
2415
    tscError("setResultDataPtr error: pData is NULL");
×
2416
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2417
  }
2418

2419
  int32_t code = doPrepareResPtr(pResultInfo);
48,633✔
2420
  if (code != TSDB_CODE_SUCCESS) {
48,638!
2421
    return code;
×
2422
  }
2423
  code = doConvertJson(pResultInfo);
48,638✔
2424
  if (code != TSDB_CODE_SUCCESS) {
48,637!
2425
    return code;
×
2426
  }
2427

2428
  char* p = (char*)pResultInfo->pData;
48,637✔
2429

2430
  // version:
2431
  int32_t blockVersion = *(int32_t*)p;
48,637✔
2432
  p += sizeof(int32_t);
48,637✔
2433

2434
  int32_t dataLen = *(int32_t*)p;
48,637✔
2435
  p += sizeof(int32_t);
48,637✔
2436

2437
  int32_t rows = *(int32_t*)p;
48,637✔
2438
  p += sizeof(int32_t);
48,637✔
2439

2440
  int32_t cols = *(int32_t*)p;
48,637✔
2441
  p += sizeof(int32_t);
48,637✔
2442

2443
  if (rows != pResultInfo->numOfRows || cols != pResultInfo->numOfCols) {
48,637!
2444
    tscError("setResultDataPtr paras error:rows;%d numOfRows:%" PRId64 " cols:%d numOfCols:%d", rows,
×
2445
             pResultInfo->numOfRows, cols, pResultInfo->numOfCols);
2446
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2447
  }
2448

2449
  int32_t hasColumnSeg = *(int32_t*)p;
48,638✔
2450
  p += sizeof(int32_t);
48,638✔
2451

2452
  uint64_t groupId = taosGetUInt64Aligned((uint64_t*)p);
48,638✔
2453
  p += sizeof(uint64_t);
48,638✔
2454

2455
  // check fields
2456
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
234,763✔
2457
    int8_t type = *(int8_t*)p;
186,123✔
2458
    p += sizeof(int8_t);
186,123✔
2459

2460
    int32_t bytes = *(int32_t*)p;
186,123✔
2461
    p += sizeof(int32_t);
186,123✔
2462

2463
    if (IS_DECIMAL_TYPE(type) && pResultInfo->fields[i].precision == 0) {
186,123!
2464
      extractDecimalTypeInfoFromBytes(&bytes, &pResultInfo->fields[i].precision, &pResultInfo->fields[i].scale);
×
2465
    }
2466
  }
2467

2468
  int32_t* colLength = (int32_t*)p;
48,640✔
2469
  p += sizeof(int32_t) * pResultInfo->numOfCols;
48,640✔
2470

2471
  char* pStart = p;
48,640✔
2472
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
234,754✔
2473
    if ((pStart - pResultInfo->pData) >= dataLen) {
186,116!
2474
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2475
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2476
    }
2477
    if (blockVersion == BLOCK_VERSION_1) {
186,116✔
2478
      colLength[i] = htonl(colLength[i]);
41,484✔
2479
    }
2480
    if (colLength[i] >= dataLen) {
186,116!
2481
      tscError("invalid colLength %d, dataLen %d", colLength[i], dataLen);
×
2482
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2483
    }
2484
    if (IS_INVALID_TYPE(pResultInfo->fields[i].type)) {
186,116✔
2485
      tscError("invalid type %d", pResultInfo->fields[i].type);
4!
2486
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2487
    }
2488
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
186,112✔
2489
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
40,272✔
2490
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
40,272✔
2491
    } else {
2492
      pResultInfo->pCol[i].nullbitmap = pStart;
145,840✔
2493
      pStart += BitmapLen(pResultInfo->numOfRows);
145,840✔
2494
    }
2495

2496
    pResultInfo->pCol[i].pData = pStart;
186,112✔
2497
    pResultInfo->length[i] = calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
186,112✔
2498
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
186,114✔
2499

2500
    pStart += colLength[i];
186,114✔
2501
  }
2502

2503
  p = pStart;
48,638✔
2504
  // bool blankFill = *(bool*)p;
2505
  p += sizeof(bool);
48,638✔
2506
  int32_t offset = p - pResultInfo->pData;
48,638✔
2507
  if (offset > dataLen) {
48,638!
2508
    tscError("invalid offset %d, dataLen %d", offset, dataLen);
×
2509
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2510
  }
2511

2512
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
2513
  if (convertUcs4) {
48,638✔
2514
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
42,753✔
2515
  }
2516
#endif
2517
  if (TSDB_CODE_SUCCESS == code && convertForDecimal) {
48,639!
2518
    code = convertDecimalType(pResultInfo);
42,754✔
2519
  }
2520
  return code;
48,638✔
2521
}
2522

2523
char* getDbOfConnection(STscObj* pObj) {
126,785✔
2524
  terrno = TSDB_CODE_SUCCESS;
126,785✔
2525
  char* p = NULL;
126,785✔
2526
  (void)taosThreadMutexLock(&pObj->mutex);
126,785✔
2527
  size_t len = strlen(pObj->db);
126,788✔
2528
  if (len > 0) {
126,788✔
2529
    p = taosStrndup(pObj->db, tListLen(pObj->db));
113,656!
2530
    if (p == NULL) {
113,651!
2531
      tscError("failed to taosStrndup db name");
×
2532
    }
2533
  }
2534

2535
  (void)taosThreadMutexUnlock(&pObj->mutex);
126,783✔
2536
  return p;
126,784✔
2537
}
2538

2539
void setConnectionDB(STscObj* pTscObj, const char* db) {
614✔
2540
  if (db == NULL || pTscObj == NULL) {
614!
2541
    tscError("setConnectionDB para is NULL");
×
2542
    return;
×
2543
  }
2544

2545
  (void)taosThreadMutexLock(&pTscObj->mutex);
614✔
2546
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
614✔
2547
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
614✔
2548
}
2549

2550
void resetConnectDB(STscObj* pTscObj) {
×
2551
  if (pTscObj == NULL) {
×
2552
    return;
×
2553
  }
2554

2555
  (void)taosThreadMutexLock(&pTscObj->mutex);
×
2556
  pTscObj->db[0] = 0;
×
2557
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
×
2558
}
2559

2560
int32_t setQueryResultFromRsp(SReqResultInfo* pResultInfo, const SRetrieveTableRsp* pRsp, bool convertUcs4, bool isStmt) {
9,009✔
2561
  if (pResultInfo == NULL || pRsp == NULL) {
9,009!
2562
    tscError("setQueryResultFromRsp paras is null");
×
2563
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2564
  }
2565

2566
  taosMemoryFreeClear(pResultInfo->pRspMsg);
9,009!
2567
  pResultInfo->pRspMsg = (const char*)pRsp;
9,009✔
2568
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
9,009✔
2569
  pResultInfo->current = 0;
9,009✔
2570
  pResultInfo->completed = (pRsp->completed == 1);
9,009✔
2571
  pResultInfo->precision = pRsp->precision;
9,009✔
2572

2573
  // decompress data if needed
2574
  int32_t payloadLen = htonl(pRsp->payloadLen);
9,009✔
2575

2576
  if (pRsp->compressed) {
9,009!
2577
    if (pResultInfo->decompBuf == NULL) {
×
2578
      pResultInfo->decompBuf = taosMemoryMalloc(payloadLen);
×
2579
      if (pResultInfo->decompBuf == NULL) {
×
2580
        tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2581
        return terrno;
×
2582
      }
2583
      pResultInfo->decompBufSize = payloadLen;
×
2584
    } else {
2585
      if (pResultInfo->decompBufSize < payloadLen) {
×
2586
        char* p = taosMemoryRealloc(pResultInfo->decompBuf, payloadLen);
×
2587
        if (p == NULL) {
×
2588
          tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2589
          return terrno;
×
2590
        }
2591

2592
        pResultInfo->decompBuf = p;
×
2593
        pResultInfo->decompBufSize = payloadLen;
×
2594
      }
2595
    }
2596
  }
2597

2598
  if (payloadLen > 0) {
9,009✔
2599
    int32_t compLen = *(int32_t*)pRsp->data;
8,429✔
2600
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
8,429✔
2601

2602
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
8,429✔
2603

2604
    if (pRsp->compressed && compLen < rawLen) {
8,429!
2605
      int32_t len = tsDecompressString(pStart, compLen, 1, pResultInfo->decompBuf, rawLen, ONE_STAGE_COMP, NULL, 0);
×
2606
      if (len < 0) {
×
2607
        tscError("tsDecompressString failed");
×
2608
        return terrno ? terrno : TSDB_CODE_FAILED;
×
2609
      }
2610
      if (len != rawLen) {
×
2611
        tscError("tsDecompressString failed, len:%d != rawLen:%d", len, rawLen);
×
2612
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2613
      }
2614
      pResultInfo->pData = pResultInfo->decompBuf;
×
2615
      pResultInfo->payloadLen = rawLen;
×
2616
    } else {
2617
      pResultInfo->pData = pStart;
8,429✔
2618
      pResultInfo->payloadLen = htonl(pRsp->compLen);
8,429✔
2619
      if (pRsp->compLen != pRsp->payloadLen) {
8,429!
2620
        tscError("pRsp->compLen:%d != pRsp->payloadLen:%d", pRsp->compLen, pRsp->payloadLen);
×
2621
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2622
      }
2623
    }
2624
  }
2625

2626
  // TODO handle the compressed case
2627
  pResultInfo->totalRows += pResultInfo->numOfRows;
9,009✔
2628

2629
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
9,009✔
2630
  return code;
9,011✔
2631
}
2632

2633
TSDB_SERVER_STATUS taos_check_server_status(const char* fqdn, int port, char* details, int maxlen) {
1✔
2634
  TSDB_SERVER_STATUS code = TSDB_SRV_STATUS_UNAVAILABLE;
1✔
2635
  void*              clientRpc = NULL;
1✔
2636
  SServerStatusRsp   statusRsp = {0};
1✔
2637
  SEpSet             epSet = {.inUse = 0, .numOfEps = 1};
1✔
2638
  SRpcMsg  rpcMsg = {.info.ahandle = (void*)0x9527, .info.notFreeAhandle = 1, .msgType = TDMT_DND_SERVER_STATUS};
1✔
2639
  SRpcMsg  rpcRsp = {0};
1✔
2640
  SRpcInit rpcInit = {0};
1✔
2641
  char     pass[TSDB_PASSWORD_LEN + 1] = {0};
1✔
2642

2643
  rpcInit.label = "CHK";
1✔
2644
  rpcInit.numOfThreads = 1;
1✔
2645
  rpcInit.cfp = NULL;
1✔
2646
  rpcInit.sessions = 16;
1✔
2647
  rpcInit.connType = TAOS_CONN_CLIENT;
1✔
2648
  rpcInit.idleTime = tsShellActivityTimer * 1000;
1✔
2649
  rpcInit.compressSize = tsCompressMsgSize;
1✔
2650
  rpcInit.user = "_dnd";
1✔
2651

2652
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
1✔
2653
  connLimitNum = TMAX(connLimitNum, 10);
1✔
2654
  connLimitNum = TMIN(connLimitNum, 500);
1✔
2655
  rpcInit.connLimitNum = connLimitNum;
1✔
2656
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
1✔
2657
  rpcInit.readTimeout = tsReadTimeout;
1✔
2658
  if (TSDB_CODE_SUCCESS != taosVersionStrToInt(td_version, &rpcInit.compatibilityVer)) {
1!
2659
    tscError("faild to convert taos version from str to int, errcode:%s", terrstr());
×
2660
    goto _OVER;
×
2661
  }
2662

2663
  clientRpc = rpcOpen(&rpcInit);
1✔
2664
  if (clientRpc == NULL) {
1!
2665
    code = terrno;
×
2666
    tscError("failed to init server status client since %s", tstrerror(code));
×
2667
    goto _OVER;
×
2668
  }
2669

2670
  if (fqdn == NULL) {
1!
2671
    fqdn = tsLocalFqdn;
1✔
2672
  }
2673

2674
  if (port == 0) {
1!
2675
    port = tsServerPort;
1✔
2676
  }
2677

2678
  tstrncpy(epSet.eps[0].fqdn, fqdn, TSDB_FQDN_LEN);
1✔
2679
  epSet.eps[0].port = (uint16_t)port;
1✔
2680
  int32_t ret = rpcSendRecv(clientRpc, &epSet, &rpcMsg, &rpcRsp);
1✔
2681
  if (TSDB_CODE_SUCCESS != ret) {
1!
2682
    tscError("failed to send recv since %s", tstrerror(ret));
×
2683
    goto _OVER;
×
2684
  }
2685

2686
  if (rpcRsp.code != 0 || rpcRsp.contLen <= 0 || rpcRsp.pCont == NULL) {
1!
2687
    tscError("failed to send server status req since %s", terrstr());
×
2688
    goto _OVER;
×
2689
  }
2690

2691
  if (tDeserializeSServerStatusRsp(rpcRsp.pCont, rpcRsp.contLen, &statusRsp) != 0) {
1!
2692
    tscError("failed to parse server status rsp since %s", terrstr());
×
2693
    goto _OVER;
×
2694
  }
2695

2696
  code = statusRsp.statusCode;
1✔
2697
  if (details != NULL) {
1!
2698
    tstrncpy(details, statusRsp.details, maxlen);
1✔
2699
  }
2700

2701
_OVER:
×
2702
  if (clientRpc != NULL) {
1!
2703
    rpcClose(clientRpc);
1✔
2704
  }
2705
  if (rpcRsp.pCont != NULL) {
1!
2706
    rpcFreeCont(rpcRsp.pCont);
1✔
2707
  }
2708
  return code;
1✔
2709
}
2710

2711
int32_t appendTbToReq(SHashObj* pHash, int32_t pos1, int32_t len1, int32_t pos2, int32_t len2, const char* str,
×
2712
                      int32_t acctId, char* db) {
2713
  SName name = {0};
×
2714

2715
  if (len1 <= 0) {
×
2716
    return -1;
×
2717
  }
2718

2719
  const char* dbName = db;
×
2720
  const char* tbName = NULL;
×
2721
  int32_t     dbLen = 0;
×
2722
  int32_t     tbLen = 0;
×
2723
  if (len2 > 0) {
×
2724
    dbName = str + pos1;
×
2725
    dbLen = len1;
×
2726
    tbName = str + pos2;
×
2727
    tbLen = len2;
×
2728
  } else {
2729
    dbLen = strlen(db);
×
2730
    tbName = str + pos1;
×
2731
    tbLen = len1;
×
2732
  }
2733

2734
  if (dbLen <= 0 || tbLen <= 0) {
×
2735
    return -1;
×
2736
  }
2737

2738
  if (tNameSetDbName(&name, acctId, dbName, dbLen)) {
×
2739
    return -1;
×
2740
  }
2741

2742
  if (tNameAddTbName(&name, tbName, tbLen)) {
×
2743
    return -1;
×
2744
  }
2745

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

2749
  STablesReq* pDb = taosHashGet(pHash, dbFName, strlen(dbFName));
×
2750
  if (pDb) {
×
2751
    if (NULL == taosArrayPush(pDb->pTables, &name)) {
×
2752
      return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
2753
    }
2754
  } else {
2755
    STablesReq db;
2756
    db.pTables = taosArrayInit(20, sizeof(SName));
×
2757
    if (NULL == db.pTables) {
×
2758
      return terrno;
×
2759
    }
2760
    tstrncpy(db.dbFName, dbFName, TSDB_DB_FNAME_LEN);
×
2761
    if (NULL == taosArrayPush(db.pTables, &name)) {
×
2762
      return terrno;
×
2763
    }
2764
    TSC_ERR_RET(taosHashPut(pHash, dbFName, strlen(dbFName), &db, sizeof(db)));
×
2765
  }
2766

2767
  return TSDB_CODE_SUCCESS;
×
2768
}
2769

2770
int32_t transferTableNameList(const char* tbList, int32_t acctId, char* dbName, SArray** pReq) {
×
2771
  SHashObj* pHash = taosHashInit(3, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
×
2772
  if (NULL == pHash) {
×
2773
    return terrno;
×
2774
  }
2775

2776
  bool    inEscape = false;
×
2777
  int32_t code = 0;
×
2778
  void*   pIter = NULL;
×
2779

2780
  int32_t vIdx = 0;
×
2781
  int32_t vPos[2];
2782
  int32_t vLen[2];
2783

2784
  (void)memset(vPos, -1, sizeof(vPos));
×
2785
  (void)memset(vLen, 0, sizeof(vLen));
×
2786

2787
  for (int32_t i = 0;; ++i) {
×
2788
    if (0 == *(tbList + i)) {
×
2789
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
×
2790
        vLen[vIdx] = i - vPos[vIdx];
×
2791
      }
2792

2793
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
×
2794
      if (code) {
×
2795
        goto _return;
×
2796
      }
2797

2798
      break;
×
2799
    }
2800

2801
    if ('`' == *(tbList + i)) {
×
2802
      inEscape = !inEscape;
×
2803
      if (!inEscape) {
×
2804
        if (vPos[vIdx] >= 0) {
×
2805
          vLen[vIdx] = i - vPos[vIdx];
×
2806
        } else {
2807
          goto _return;
×
2808
        }
2809
      }
2810

2811
      continue;
×
2812
    }
2813

2814
    if (inEscape) {
×
2815
      if (vPos[vIdx] < 0) {
×
2816
        vPos[vIdx] = i;
×
2817
      }
2818
      continue;
×
2819
    }
2820

2821
    if ('.' == *(tbList + i)) {
×
2822
      if (vPos[vIdx] < 0) {
×
2823
        goto _return;
×
2824
      }
2825
      if (vLen[vIdx] <= 0) {
×
2826
        vLen[vIdx] = i - vPos[vIdx];
×
2827
      }
2828
      vIdx++;
×
2829
      if (vIdx >= 2) {
×
2830
        goto _return;
×
2831
      }
2832
      continue;
×
2833
    }
2834

2835
    if (',' == *(tbList + i)) {
×
2836
      if (vPos[vIdx] < 0) {
×
2837
        goto _return;
×
2838
      }
2839
      if (vLen[vIdx] <= 0) {
×
2840
        vLen[vIdx] = i - vPos[vIdx];
×
2841
      }
2842

2843
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
×
2844
      if (code) {
×
2845
        goto _return;
×
2846
      }
2847

2848
      (void)memset(vPos, -1, sizeof(vPos));
×
2849
      (void)memset(vLen, 0, sizeof(vLen));
×
2850
      vIdx = 0;
×
2851
      continue;
×
2852
    }
2853

2854
    if (' ' == *(tbList + i) || '\r' == *(tbList + i) || '\t' == *(tbList + i) || '\n' == *(tbList + i)) {
×
2855
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
×
2856
        vLen[vIdx] = i - vPos[vIdx];
×
2857
      }
2858
      continue;
×
2859
    }
2860

2861
    if (('a' <= *(tbList + i) && 'z' >= *(tbList + i)) || ('A' <= *(tbList + i) && 'Z' >= *(tbList + i)) ||
×
2862
        ('0' <= *(tbList + i) && '9' >= *(tbList + i)) || ('_' == *(tbList + i))) {
×
2863
      if (vLen[vIdx] > 0) {
×
2864
        goto _return;
×
2865
      }
2866
      if (vPos[vIdx] < 0) {
×
2867
        vPos[vIdx] = i;
×
2868
      }
2869
      continue;
×
2870
    }
2871

2872
    goto _return;
×
2873
  }
2874

2875
  int32_t dbNum = taosHashGetSize(pHash);
×
2876
  *pReq = taosArrayInit(dbNum, sizeof(STablesReq));
×
2877
  if (NULL == pReq) {
×
2878
    TSC_ERR_JRET(terrno);
×
2879
  }
2880
  pIter = taosHashIterate(pHash, NULL);
×
2881
  while (pIter) {
×
2882
    STablesReq* pDb = (STablesReq*)pIter;
×
2883
    if (NULL == taosArrayPush(*pReq, pDb)) {
×
2884
      TSC_ERR_JRET(terrno);
×
2885
    }
2886
    pIter = taosHashIterate(pHash, pIter);
×
2887
  }
2888

2889
  taosHashCleanup(pHash);
×
2890

2891
  return TSDB_CODE_SUCCESS;
×
2892

2893
_return:
×
2894

2895
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
2896

2897
  pIter = taosHashIterate(pHash, NULL);
×
2898
  while (pIter) {
×
2899
    STablesReq* pDb = (STablesReq*)pIter;
×
2900
    taosArrayDestroy(pDb->pTables);
×
2901
    pIter = taosHashIterate(pHash, pIter);
×
2902
  }
2903

2904
  taosHashCleanup(pHash);
×
2905

2906
  return terrno;
×
2907
}
2908

2909
void syncCatalogFn(SMetaData* pResult, void* param, int32_t code) {
×
2910
  SSyncQueryParam* pParam = param;
×
2911
  pParam->pRequest->code = code;
×
2912

2913
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
×
2914
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
2915
  }
2916
}
×
2917

2918
void syncQueryFn(void* param, void* res, int32_t code) {
120,455✔
2919
  SSyncQueryParam* pParam = param;
120,455✔
2920
  pParam->pRequest = res;
120,455✔
2921

2922
  if (pParam->pRequest) {
120,455✔
2923
    pParam->pRequest->code = code;
120,436✔
2924
    clientOperateReport(pParam->pRequest);
120,436✔
2925
  }
2926

2927
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
120,468!
2928
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
2929
  }
2930
}
120,459✔
2931

2932
void taosAsyncQueryImpl(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
120,509✔
2933
                        int8_t source) {
2934
  if (sql == NULL || NULL == fp) {
120,509!
2935
    terrno = TSDB_CODE_INVALID_PARA;
×
2936
    if (fp) {
×
2937
      fp(param, NULL, terrno);
×
2938
    }
2939

2940
    return;
×
2941
  }
2942

2943
  size_t sqlLen = strlen(sql);
120,511✔
2944
  if (sqlLen > (size_t)TSDB_MAX_ALLOWED_SQL_LEN) {
120,511!
2945
    tscError("sql string exceeds max length:%d", TSDB_MAX_ALLOWED_SQL_LEN);
×
2946
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
2947
    fp(param, NULL, terrno);
×
2948
    return;
×
2949
  }
2950

2951
  SRequestObj* pRequest = NULL;
120,511✔
2952
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
120,511✔
2953
  if (code != TSDB_CODE_SUCCESS) {
120,512!
2954
    terrno = code;
×
2955
    fp(param, NULL, terrno);
×
2956
    return;
×
2957
  }
2958

2959
  pRequest->source = source;
120,512✔
2960
  pRequest->body.queryFp = fp;
120,512✔
2961
  doAsyncQuery(pRequest, false);
120,512✔
2962
}
2963
void taosAsyncQueryImplWithReqid(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
31✔
2964
                                 int64_t reqid) {
2965
  if (sql == NULL || NULL == fp) {
31!
2966
    terrno = TSDB_CODE_INVALID_PARA;
×
2967
    if (fp) {
×
2968
      fp(param, NULL, terrno);
×
2969
    }
2970

2971
    return;
×
2972
  }
2973

2974
  size_t sqlLen = strlen(sql);
31✔
2975
  if (sqlLen > (size_t)TSDB_MAX_ALLOWED_SQL_LEN) {
31!
2976
    tscError("sql string exceeds max length:%d", TSDB_MAX_ALLOWED_SQL_LEN);
×
2977
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
2978
    fp(param, NULL, terrno);
×
2979
    return;
×
2980
  }
2981

2982
  SRequestObj* pRequest = NULL;
31✔
2983
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, reqid);
31✔
2984
  if (code != TSDB_CODE_SUCCESS) {
31!
2985
    terrno = code;
×
2986
    fp(param, NULL, terrno);
×
2987
    return;
×
2988
  }
2989

2990
  pRequest->body.queryFp = fp;
31✔
2991
  doAsyncQuery(pRequest, false);
31✔
2992
}
2993

2994
TAOS_RES* taosQueryImpl(TAOS* taos, const char* sql, bool validateOnly, int8_t source) {
120,424✔
2995
  if (NULL == taos) {
120,424!
2996
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
2997
    return NULL;
×
2998
  }
2999

3000
  tscDebug("conn:0x%" PRIx64 ", taos_query execute sql:%s", *(int64_t*)taos, sql);
120,424✔
3001

3002
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
120,424!
3003
  if (NULL == param) {
120,426!
3004
    return NULL;
×
3005
  }
3006
  int32_t code = tsem_init(&param->sem, 0, 0);
120,426✔
3007
  if (TSDB_CODE_SUCCESS != code) {
120,427!
3008
    taosMemoryFree(param);
×
3009
    return NULL;
×
3010
  }
3011

3012
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
120,427✔
3013
  code = tsem_wait(&param->sem);
120,417✔
3014
  if (TSDB_CODE_SUCCESS != code) {
120,427!
3015
    taosMemoryFree(param);
×
3016
    return NULL;
×
3017
  }
3018
  code = tsem_destroy(&param->sem);
120,427✔
3019
  if (TSDB_CODE_SUCCESS != code) {
120,426!
3020
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3021
  }
3022

3023
  SRequestObj* pRequest = NULL;
120,424✔
3024
  if (param->pRequest != NULL) {
120,424!
3025
    param->pRequest->syncQuery = true;
120,424✔
3026
    pRequest = param->pRequest;
120,424✔
3027
    param->pRequest->inCallback = false;
120,424✔
3028
  }
3029
  taosMemoryFree(param);
120,424!
3030

3031
  tscDebug("QID:0x%" PRIx64 ", taos_query end, conn:0x%" PRIx64 " res:%p", pRequest ? pRequest->requestId : 0,
120,425!
3032
           *(int64_t*)taos, pRequest);
3033

3034
  return pRequest;
120,425✔
3035
}
3036

3037
TAOS_RES* taosQueryImplWithReqid(TAOS* taos, const char* sql, bool validateOnly, int64_t reqid) {
31✔
3038
  if (NULL == taos) {
31!
3039
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3040
    return NULL;
×
3041
  }
3042

3043
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
31!
3044
  if (param == NULL) {
31!
3045
    return NULL;
×
3046
  }
3047
  int32_t code = tsem_init(&param->sem, 0, 0);
31✔
3048
  if (TSDB_CODE_SUCCESS != code) {
31!
3049
    taosMemoryFree(param);
×
3050
    return NULL;
×
3051
  }
3052

3053
  taosAsyncQueryImplWithReqid(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, reqid);
31✔
3054
  code = tsem_wait(&param->sem);
31✔
3055
  if (TSDB_CODE_SUCCESS != code) {
31!
3056
    taosMemoryFree(param);
×
3057
    return NULL;
×
3058
  }
3059
  SRequestObj* pRequest = NULL;
31✔
3060
  if (param->pRequest != NULL) {
31!
3061
    param->pRequest->syncQuery = true;
31✔
3062
    pRequest = param->pRequest;
31✔
3063
  }
3064
  taosMemoryFree(param);
31!
3065
  return pRequest;
31✔
3066
}
3067

3068
static void fetchCallback(void* pResult, void* param, int32_t code) {
8,600✔
3069
  SRequestObj* pRequest = (SRequestObj*)param;
8,600✔
3070

3071
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
8,600✔
3072

3073
  tscDebug("req:0x%" PRIx64 ", enter scheduler fetch cb, code:%d - %s, QID:0x%" PRIx64, pRequest->self, code, tstrerror(code),
8,600✔
3074
           pRequest->requestId);
3075

3076
  pResultInfo->pData = pResult;
8,599✔
3077
  pResultInfo->numOfRows = 0;
8,599✔
3078

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

3086
  if (pRequest->code != TSDB_CODE_SUCCESS) {
8,599!
3087
    taosMemoryFreeClear(pResultInfo->pData);
×
3088
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pRequest->code);
×
3089
    return;
×
3090
  }
3091

3092
  pRequest->code =
8,602✔
3093
      setQueryResultFromRsp(pResultInfo, (const SRetrieveTableRsp*)pResultInfo->pData, pResultInfo->convertUcs4, pRequest->isStmtBind);
8,599✔
3094
  if (pRequest->code != TSDB_CODE_SUCCESS) {
8,602!
3095
    pResultInfo->numOfRows = 0;
×
3096
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(pRequest->code),
×
3097
             pRequest->requestId);
3098
  } else {
3099
    tscDebug("req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
8,602✔
3100
             pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed,
3101
             pRequest->requestId);
3102

3103
    STscObj*            pTscObj = pRequest->pTscObj;
8,602✔
3104
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
8,602✔
3105
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
8,602✔
3106
  }
3107

3108
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
8,603✔
3109
}
3110

3111
void taosAsyncFetchImpl(SRequestObj* pRequest, __taos_async_fn_t fp, void* param) {
8,609✔
3112
  pRequest->body.fetchFp = fp;
8,609✔
3113
  ((SSyncQueryParam*)pRequest->body.interParam)->userParam = param;
8,609✔
3114

3115
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
8,609✔
3116

3117
  // this query has no results or error exists, return directly
3118
  if (taos_num_fields(pRequest) == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
8,609!
3119
    pResultInfo->numOfRows = 0;
×
3120
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
×
3121
    return;
6✔
3122
  }
3123

3124
  // all data has returned to App already, no need to try again
3125
  if (pResultInfo->completed) {
8,608✔
3126
    // it is a local executed query, no need to do async fetch
3127
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
6!
3128
      if (pResultInfo->localResultFetched) {
×
3129
        pResultInfo->numOfRows = 0;
×
3130
        pResultInfo->current = 0;
×
3131
      } else {
3132
        pResultInfo->localResultFetched = true;
×
3133
      }
3134
    } else {
3135
      pResultInfo->numOfRows = 0;
6✔
3136
    }
3137

3138
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
6✔
3139
    return;
6✔
3140
  }
3141

3142
  SSchedulerReq req = {
8,602✔
3143
      .syncReq = false,
3144
      .fetchFp = fetchCallback,
3145
      .cbParam = pRequest,
3146
  };
3147

3148
  int32_t code = schedulerFetchRows(pRequest->body.queryJob, &req);
8,602✔
3149
  if (TSDB_CODE_SUCCESS != code) {
8,601!
3150
    tscError("0x%" PRIx64 " failed to schedule fetch rows", pRequest->requestId);
×
3151
    // pRequest->body.fetchFp(param, pRequest, code);
3152
  }
3153
}
3154

3155
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
120,547✔
3156
  pRequest->inCallback = true;
120,547✔
3157
  int64_t this = pRequest->self;
120,547✔
3158
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
120,547!
3159
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
×
3160
    code = TSDB_CODE_SUCCESS;
×
3161
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3162
  }
3163
  if (pRequest->body.queryFp != NULL) {
120,547✔
3164
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
120,537✔
3165
  }
3166
  SRequestObj* pReq = acquireRequest(this);
120,561✔
3167
  if (pReq != NULL) {
120,552✔
3168
    pReq->inCallback = false;
120,425✔
3169
    (void)releaseRequest(this);
120,425✔
3170
  }
3171
}
120,549✔
3172

3173
int32_t clientParseSql(void* param, const char* dbName, const char* sql, bool parseOnly, const char* effectiveUser,
×
3174
                       SParseSqlRes* pRes) {
3175
#ifndef TD_ENTERPRISE
3176
  return TSDB_CODE_SUCCESS;
3177
#else
3178
  return clientParseSqlImpl(param, dbName, sql, parseOnly, effectiveUser, pRes);
×
3179
#endif
3180
}
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