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

taosdata / TDengine / #3558

17 Dec 2024 06:05AM UTC coverage: 59.778% (+1.6%) from 58.204%
#3558

push

travis-ci

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

merge: form main to 3.0 branch

132787 of 287595 branches covered (46.17%)

Branch coverage included in aggregate %.

104 of 191 new or added lines in 5 files covered. (54.45%)

6085 existing lines in 168 files now uncovered.

209348 of 284746 relevant lines covered (73.52%)

8164844.48 hits per line

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

59.7
/source/client/src/clientImpl.c
1
/*
2
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
3
 *
4
 * This program is free software: you can use, redistribute, and/or modify
5
 * it under the terms of the GNU Affero General Public License, version 3
6
 * or later ("AGPL"), as published by the Free Software Foundation.
7
 *
8
 * This program is distributed in the hope that it will be useful, but WITHOUT
9
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10
 * FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * You should have received a copy of the GNU Affero General Public License
13
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14
 */
15

16
#include "cJSON.h"
17
#include "clientInt.h"
18
#include "clientLog.h"
19
#include "clientMonitor.h"
20
#include "command.h"
21
#include "scheduler.h"
22
#include "tdatablock.h"
23
#include "tdataformat.h"
24
#include "tdef.h"
25
#include "tglobal.h"
26
#include "tmsgtype.h"
27
#include "tpagedbuf.h"
28
#include "tref.h"
29
#include "tsched.h"
30
#include "tversion.h"
31
static int32_t initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet);
32
static int32_t buildConnectMsg(SRequestObj* pRequest, SMsgSendInfo** pMsgSendInfo);
33

34
void setQueryRequest(int64_t rId) {
1,291,772✔
35
  SRequestObj* pReq = acquireRequest(rId);
1,291,772✔
36
  if (pReq != NULL) {
1,291,775!
37
    pReq->isQuery = true;
1,291,775✔
38
    (void)releaseRequest(rId);
1,291,775✔
39
  }
40
}
1,291,774✔
41

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

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

52
  return true;
19,497✔
53
}
54

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

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

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

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

67
bool chkRequestKilled(void* param) {
33,083,607✔
68
  bool         killed = false;
33,083,607✔
69
  SRequestObj* pRequest = acquireRequest((int64_t)param);
33,083,607✔
70
  if (NULL == pRequest || pRequest->killed) {
33,698,425!
71
    killed = true;
4✔
72
  }
73

74
  (void)releaseRequest((int64_t)param);
33,698,425✔
75

76
  return killed;
33,632,117✔
77
}
78

79
void cleanupAppInfo() {
×
80
  taosHashCleanup(appInfo.pInstMap);
×
81
  taosHashCleanup(appInfo.pInstMapByClusterId);
×
82
}
×
83

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

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

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

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

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

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

115
  SCorEpSet epSet = {0};
9,736✔
116
  if (ip) {
9,736✔
117
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
7,395✔
118
  } else {
119
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
2,341!
120
  }
121

122
  if (port) {
9,738✔
123
    epSet.epSet.eps[0].port = port;
5,683✔
124
    epSet.epSet.eps[1].port = port;
5,683✔
125
  }
126

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

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

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

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

186
_return:
9,738✔
187

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

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

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

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

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

236
  (void)strntolower((*pRequest)->sqlstr, sql, (int32_t)sqlLen);
10,387,801✔
237
  (*pRequest)->sqlstr[sqlLen] = 0;
10,406,145✔
238
  (*pRequest)->sqlLen = sqlLen;
10,406,145✔
239
  (*pRequest)->validateOnly = validateSql;
10,406,145✔
240
  (*pRequest)->isStmtBind = false;
10,406,145✔
241

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

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

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

267
  tscDebugL("0x%" PRIx64 " SQL: %s,QID:0x%" PRIx64, (*pRequest)->self, (*pRequest)->sqlstr, (*pRequest)->requestId);
10,398,153✔
268
  return TSDB_CODE_SUCCESS;
10,397,329✔
269
}
270

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

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

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

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

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

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

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

330
  return code;
18✔
331
}
332

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

341
  return code;
×
342
}
343

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

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

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

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

364
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
20,133,897✔
365

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

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

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

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

392
  doRequestCallback(pRequest, code);
107,557✔
393
}
394

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

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

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

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

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

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

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

430
  return node1->load > node2->load;
254,928✔
431
}
432

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

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

449
  return TSDB_CODE_SUCCESS;
85,574✔
450
}
451

452
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
10,409,950✔
453
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
10,409,950✔
454
    *required = false;
9,798,505✔
455
    return TSDB_CODE_SUCCESS;
9,798,505✔
456
  }
457

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

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

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

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

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

497
  return code;
×
498
}
499

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

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

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

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

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

543
  for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
4,688,479✔
544
    pResInfo->fields[i].bytes = pSchema[i].bytes;
3,580,447✔
545
    pResInfo->fields[i].type = pSchema[i].type;
3,580,447✔
546

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

550
    if (pSchema[i].type == TSDB_DATA_TYPE_VARCHAR || pSchema[i].type == TSDB_DATA_TYPE_VARBINARY ||
3,580,447✔
551
        pSchema[i].type == TSDB_DATA_TYPE_GEOMETRY) {
2,812,439✔
552
      pResInfo->userFields[i].bytes -= VARSTR_HEADER_SIZE;
768,029✔
553
    } else if (pSchema[i].type == TSDB_DATA_TYPE_NCHAR || pSchema[i].type == TSDB_DATA_TYPE_JSON) {
2,812,418✔
554
      pResInfo->userFields[i].bytes = (pResInfo->userFields[i].bytes - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE;
193,447✔
555
    }
556

557
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
3,580,447✔
558
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
3,580,447✔
559
  }
560
  return TSDB_CODE_SUCCESS;
1,108,032✔
561
}
562

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

569
  pResInfo->precision = precision;
779,229✔
570
}
571

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

579
  int32_t dbNum = taosArrayGetSize(pDbVgList);
451,899✔
580
  for (int32_t i = 0; i < dbNum; ++i) {
900,341✔
581
    SArray* pVg = taosArrayGetP(pDbVgList, i);
448,451✔
582
    if (NULL == pVg) {
448,456!
583
      continue;
×
584
    }
585
    int32_t vgNum = taosArrayGetSize(pVg);
448,456✔
586
    if (vgNum <= 0) {
448,455✔
587
      continue;
477✔
588
    }
589

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

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

607
  int32_t vnodeNum = taosArrayGetSize(nodeList);
451,890✔
608
  if (vnodeNum > 0) {
451,909✔
609
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
447,460✔
610
    goto _return;
447,463✔
611
  }
612

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

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

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

631
_return:
1,358✔
632

633
  *pNodeList = nodeList;
451,905✔
634

635
  return TSDB_CODE_SUCCESS;
451,905✔
636
}
637

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

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

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

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

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

677
_return:
×
678

679
  *pNodeList = nodeList;
277,603✔
680

681
  return TSDB_CODE_SUCCESS;
277,603✔
682
}
683

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

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

695
  switch (tsQueryPolicy) {
728,887!
696
    case QUERY_POLICY_VNODE:
451,313✔
697
    case QUERY_POLICY_CLIENT: {
698
      if (pResultMeta) {
451,313!
699
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
451,321✔
700
        if (NULL == pDbVgList) {
451,318!
701
          code = terrno;
×
702
          goto _return;
×
703
        }
704
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
451,318✔
705
        for (int32_t i = 0; i < dbNum; ++i) {
899,402✔
706
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
448,094✔
707
          if (pRes->code || NULL == pRes->pRes) {
448,085!
708
            continue;
×
709
          }
710

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

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

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

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

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

755
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
451,308✔
756
      break;
451,331✔
757
    }
758
    case QUERY_POLICY_HYBRID:
277,602✔
759
    case QUERY_POLICY_QNODE: {
760
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
282,470!
761
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
4,868✔
762
        if (pRes->code) {
4,868!
763
          pQnodeList = NULL;
×
764
        } else {
765
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
4,868✔
766
          if (NULL == pQnodeList) {
4,868!
767
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
768
            goto _return;
×
769
          }
770
        }
771
      } else {
772
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
272,734✔
773
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
272,734!
774
        if (pInst->pQnodeList) {
272,735!
775
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
272,735✔
776
          if (NULL == pQnodeList) {
272,735!
777
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
778
            goto _return;
×
779
          }
780
        }
781
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
272,735!
782
      }
783

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

792
_return:
728,934✔
793
  taosArrayDestroyEx(pDbVgList, fp);
728,934✔
794
  taosArrayDestroy(pQnodeList);
728,942✔
795

796
  return code;
728,945✔
797
}
798

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

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

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

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

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

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

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

857
_return:
572✔
858

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

862
  return code;
572✔
863
}
864

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

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

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

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

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

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

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

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

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

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

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

934
  return TSDB_CODE_SUCCESS;
42,833✔
935
}
936

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

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

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

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

969
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
573,149✔
970

971
_return:
573,140✔
972

973
  taosArrayDestroy(pArray);
573,140✔
974
  return code;
573,141✔
975
}
976

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

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

985
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
10,152,486✔
986
  if (NULL == pRequest->body.resInfo.execRes.res) {
10,152,486✔
987
    return pRequest->code;
163,957✔
988
  }
989

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

993
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
9,988,211✔
994
  if (code) {
9,993,267!
995
    return code;
×
996
  }
997

998
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
9,993,267✔
999
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
10,021,661✔
1000

1001
  switch (pRes->msgType) {
10,021,661!
1002
    case TDMT_VND_ALTER_TABLE:
154✔
1003
    case TDMT_MND_ALTER_STB: {
1004
      code = handleAlterTbExecRes(pRes->res, pCatalog);
154✔
1005
      break;
154✔
1006
    }
1007
    case TDMT_VND_CREATE_TABLE: {
38,359✔
1008
      SArray* pList = (SArray*)pRes->res;
38,359✔
1009
      int32_t num = taosArrayGetSize(pList);
38,359✔
1010
      for (int32_t i = 0; i < num; ++i) {
109,922✔
1011
        void* res = taosArrayGetP(pList, i);
71,563✔
1012
        // handleCreateTbExecRes will handle res == null
1013
        code = handleCreateTbExecRes(res, pCatalog);
71,563✔
1014
      }
1015
      break;
38,359✔
1016
    }
1017
    case TDMT_MND_CREATE_STB: {
235✔
1018
      code = handleCreateTbExecRes(pRes->res, pCatalog);
235✔
1019
      break;
235✔
1020
    }
1021
    case TDMT_VND_SUBMIT: {
9,409,840✔
1022
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
9,409,840✔
1023

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

1038
  return code;
10,015,943✔
1039
}
1040

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1164
  blockDataDestroy(pBlock);
483✔
1165
}
1166

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

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

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

1190
  pRequest->code = code;
10,106,399✔
1191
  if (pResult) {
10,106,399!
1192
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
10,109,513✔
1193
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
10,122,778✔
1194
  }
1195

1196
  int32_t type = pRequest->type;
10,119,664✔
1197
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
10,119,664✔
1198
    if (pResult) {
9,430,278!
1199
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
9,442,466✔
1200

1201
      // record the insert rows
1202
      if (TDMT_VND_SUBMIT == type) {
9,442,466✔
1203
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
9,362,101✔
1204
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
9,362,101✔
1205
      }
1206
    }
1207
    schedulerFreeJob(&pRequest->body.queryJob, 0);
9,481,201✔
1208
  }
1209

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

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

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

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

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

1243
  if (pRequest->relation.nextRefId) {
10,184,256✔
1244
    handlePostSubQuery(pWrapper);
484✔
1245
  } else {
1246
    destorySqlCallbackWrapper(pWrapper);
10,183,772✔
1247
    pRequest->pWrapper = NULL;
10,187,060✔
1248

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

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

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

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

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

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

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

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

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

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

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

1351
  if (!pRequest->parseOnly) {
10,175,402!
1352
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
10,177,649✔
1353
    if (NULL == pMnodeList) {
10,160,763!
1354
      code = terrno;
×
1355
    }
1356
    SPlanContext cxt = {.queryId = pRequest->requestId,
20,329,572✔
1357
                        .acctId = pRequest->pTscObj->acctId,
10,160,763✔
1358
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
10,160,763✔
1359
                        .pAstRoot = pQuery->pRoot,
10,168,809✔
1360
                        .showRewrite = pQuery->showRewrite,
10,168,809✔
1361
                        .isView = pWrapper->pParseCtx->isView,
10,168,809✔
1362
                        .isAudit = pWrapper->pParseCtx->isAudit,
10,168,809✔
1363
                        .pMsg = pRequest->msgBuf,
10,168,809✔
1364
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1365
                        .pUser = pRequest->pTscObj->user,
10,168,809✔
1366
                        .sysInfo = pRequest->pTscObj->sysInfo,
10,168,809✔
1367
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
10,168,809✔
1368
                        .allocatorId = pRequest->allocatorRefId};
10,168,809✔
1369
    if (TSDB_CODE_SUCCESS == code) {
10,168,809!
1370
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
10,173,392✔
1371
    }
1372
    if (code) {
10,138,043✔
1373
      tscError("0x%" PRIx64 " failed to create query plan, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
889!
1374
               pRequest->requestId);
1375
    } else {
1376
      pRequest->body.subplanNum = pDag->numOfSubplans;
10,137,154✔
1377
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
10,137,154✔
1378
    }
1379
  }
1380

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

1384
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
20,298,160!
1385
    SArray* pNodeList = NULL;
10,151,691✔
1386
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
10,151,691✔
1387
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
728,939✔
1388
    }
1389

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

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

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

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

1431
  return code;
10,155,320✔
1432
}
1433

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

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

1442
  pRequest->body.execMode = pQuery->execMode;
10,252,104✔
1443
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
10,252,104✔
1444
    destorySqlCallbackWrapper(pWrapper);
137,261✔
1445
    pRequest->pWrapper = NULL;
137,261✔
1446
  }
1447

1448
  if (pQuery->pRoot && !pRequest->inRetry) {
10,252,104!
1449
    STscObj*            pTscObj = pRequest->pTscObj;
10,256,395✔
1450
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
10,256,395✔
1451
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
10,256,395✔
1452
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
9,407,743✔
1453
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
9,366,818✔
1454
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
889,577✔
1455
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
639,636✔
1456
    }
1457
  }
1458

1459
  switch (pQuery->execMode) {
10,325,234!
1460
    case QUERY_EXEC_MODE_LOCAL:
107,575✔
1461
      asyncExecLocalCmd(pRequest, pQuery);
107,575✔
1462
      break;
107,575✔
1463
    case QUERY_EXEC_MODE_RPC:
26,947✔
1464
      code = asyncExecDdlQuery(pRequest, pQuery);
26,947✔
1465
      break;
26,947✔
1466
    case QUERY_EXEC_MODE_SCHEDULE: {
10,187,973✔
1467
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
10,187,973✔
1468
      break;
10,145,494✔
1469
    }
1470
    case QUERY_EXEC_MODE_EMPTY_RESULT:
2,739✔
1471
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
2,739✔
1472
      doRequestCallback(pRequest, 0);
2,739✔
1473
      break;
2,739✔
1474
    default:
×
1475
      tscError("0x%" PRIx64 " invalid execMode %d", pRequest->self, pQuery->execMode);
×
1476
      doRequestCallback(pRequest, -1);
×
1477
      break;
×
1478
  }
1479
}
1480

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

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

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

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

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

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

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

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

1521
  return code;
×
1522
}
1523

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

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

1549
  return TSDB_CODE_SUCCESS;
8,680✔
1550
}
1551

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

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

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

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

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

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

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

1608
  return 0;
9,734✔
1609
}
1610

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1727
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
12,918,492✔
1728
  if (NULL == pEpSet) {
12,918,492✔
1729
    return;
11,638,176✔
1730
  }
1731

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

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

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

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

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

1786
  STscObj* pTscObj = NULL;
12,925,408✔
1787

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

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

1795
  if (pSendInfo->requestObjRefId != 0) {
12,925,004✔
1796
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
11,811,689✔
1797
    if (pRequest) {
11,809,169!
1798
      if (pRequest->self != pSendInfo->requestObjRefId) {
11,809,497!
1799
        tscError("doProcessMsgFromServer pRequest->self:%" PRId64 " != pSendInfo->requestObjRefId:%" PRId64,
×
1800
                 pRequest->self, pSendInfo->requestObjRefId);
1801

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

1814
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
12,922,484✔
1815

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

1823
  if (pMsg->contLen > 0) {
12,916,835✔
1824
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
12,836,174!
1825
    if (buf.pData == NULL) {
12,834,910!
1826
      pMsg->code = terrno;
×
1827
    } else {
1828
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
12,834,910✔
1829
    }
1830
  }
1831

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

1834
  if (pTscObj) {
12,908,625✔
1835
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
11,796,347✔
1836
    if (TSDB_CODE_SUCCESS != code) {
11,806,720!
1837
      tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1838
      terrno = code;
×
1839
      pMsg->code = code;
×
1840
    }
1841
  }
1842

1843
  rpcFreeCont(pMsg->pCont);
12,918,998✔
1844
  destroySendMsgInfo(pSendInfo);
12,923,955✔
1845
  return TSDB_CODE_SUCCESS;
12,924,596✔
1846
}
1847
int32_t doProcessMsgFromServer(void* param) {
12,927,684✔
1848
  AsyncArg* arg = (AsyncArg*)param;
12,927,684✔
1849
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
12,927,684✔
1850
  taosMemoryFree(arg);
12,924,113!
1851
  return code;
12,925,843✔
1852
}
1853

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

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

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

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

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

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

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

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

1928
  return NULL;
2✔
1929
}
1930

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

1945
void doSetOneRowPtr(SReqResultInfo* pResultInfo) {
20,640,863✔
1946
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
117,501,023✔
1947
    SResultColumn* pCol = &pResultInfo->pCol[i];
96,860,160✔
1948

1949
    int32_t type = pResultInfo->fields[i].type;
96,860,160✔
1950
    int32_t bytes = pResultInfo->fields[i].bytes;
96,860,160✔
1951

1952
    if (IS_VAR_DATA_TYPE(type)) {
96,860,160✔
1953
      if (!IS_VAR_NULL_TYPE(type, bytes) && pCol->offset[pResultInfo->current] != -1) {
21,801,044!
1954
        char* pStart = pResultInfo->pCol[i].offset[pResultInfo->current] + pResultInfo->pCol[i].pData;
21,123,074✔
1955

1956
        pResultInfo->length[i] = varDataLen(pStart);
21,123,074✔
1957
        pResultInfo->row[i] = varDataVal(pStart);
21,123,074✔
1958
      } else {
1959
        pResultInfo->row[i] = NULL;
677,970✔
1960
        pResultInfo->length[i] = 0;
677,970✔
1961
      }
1962
    } else {
1963
      if (!colDataIsNull_f(pCol->nullbitmap, pResultInfo->current)) {
75,059,116✔
1964
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + bytes * pResultInfo->current;
72,654,321✔
1965
        pResultInfo->length[i] = bytes;
72,654,321✔
1966
      } else {
1967
        pResultInfo->row[i] = NULL;
2,404,795✔
1968
        pResultInfo->length[i] = 0;
2,404,795✔
1969
      }
1970
    }
1971
  }
1972
}
20,640,863✔
1973

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

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

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

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

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

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

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

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

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

2020
  return pResultInfo->row;
×
2021
}
2022

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

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

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

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

2059
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
6,215,755✔
2060
    return NULL;
52,866✔
2061
  } else {
2062
    if (setupOneRowPtr) {
6,162,889✔
2063
      doSetOneRowPtr(pResultInfo);
5,557,156✔
2064
      pResultInfo->current += 1;
5,557,151✔
2065
    }
2066

2067
    return pResultInfo->row;
6,162,884✔
2068
  }
2069
}
2070

2071
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
1,114,432✔
2072
  if (pResInfo->row == NULL) {
1,114,432✔
2073
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
1,002,403!
2074
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
1,002,420!
2075
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
1,002,427!
2076
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
1,002,423!
2077

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

2087
  return TSDB_CODE_SUCCESS;
1,114,460✔
2088
}
2089

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

2095
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
4,764,146✔
2096
    int32_t type = pResultInfo->fields[i].type;
3,649,719✔
2097
    int32_t bytes = pResultInfo->fields[i].bytes;
3,649,719✔
2098

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

2106
      pResultInfo->convertBuf[i] = p;
168,678✔
2107

2108
      SResultColumn* pCol = &pResultInfo->pCol[i];
168,678✔
2109
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
18,669,066✔
2110
        if (pCol->offset[j] != -1) {
18,500,381✔
2111
          char* pStart = pCol->offset[j] + pCol->pData;
18,380,526✔
2112

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

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

2129
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
168,685✔
2130
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
168,685✔
2131
    }
2132
  }
2133
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
1,114,427✔
2134
  return TSDB_CODE_SUCCESS;
1,114,426✔
2135
}
2136

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

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

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

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

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

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

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

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

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

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

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

2225
  if (!needConvert) {
1,114,454✔
2226
    return TSDB_CODE_SUCCESS;
1,114,111✔
2227
  }
2228

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2373
  if (pResultInfo->numOfRows == 0) {
1,172,387✔
2374
    return TSDB_CODE_SUCCESS;
57,948✔
2375
  }
2376

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

2382
  int32_t code = doPrepareResPtr(pResultInfo);
1,114,439✔
2383
  if (code != TSDB_CODE_SUCCESS) {
1,114,460!
2384
    return code;
×
2385
  }
2386
  code = doConvertJson(pResultInfo);
1,114,460✔
2387
  if (code != TSDB_CODE_SUCCESS) {
1,114,450!
2388
    return code;
×
2389
  }
2390

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

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

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

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

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

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

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

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

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

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

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

2430
  char* pStart = p;
1,114,444✔
2431
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
4,764,112✔
2432
    if ((pStart - pResultInfo->pData) >= dataLen) {
3,649,680!
2433
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2434
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2435
    }
2436
    if (blockVersion == BLOCK_VERSION_1) {
3,649,680✔
2437
      colLength[i] = htonl(colLength[i]);
1,838,964✔
2438
    }
2439
    if (colLength[i] >= dataLen) {
3,649,680!
2440
      tscError("invalid colLength %d, dataLen %d", colLength[i], dataLen);
×
2441
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2442
    }
2443
    if (IS_INVALID_TYPE(pResultInfo->fields[i].type)) {
3,649,680!
2444
      tscError("invalid type %d", pResultInfo->fields[i].type);
12!
2445
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2446
    }
2447
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
3,649,668✔
2448
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
959,448✔
2449
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
959,448✔
2450
    } else {
2451
      pResultInfo->pCol[i].nullbitmap = pStart;
2,690,220✔
2452
      pStart += BitmapLen(pResultInfo->numOfRows);
2,690,220✔
2453
    }
2454

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

2459
    pStart += colLength[i];
3,649,668✔
2460
  }
2461

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

2471
  if (convertUcs4) {
1,114,432✔
2472
    code = doConvertUCS4(pResultInfo, colLength);
1,114,416✔
2473
  }
2474

2475
  return code;
1,114,453✔
2476
}
2477

2478
char* getDbOfConnection(STscObj* pObj) {
10,420,219✔
2479
  terrno = TSDB_CODE_SUCCESS;
10,420,219✔
2480
  char* p = NULL;
10,418,857✔
2481
  (void)taosThreadMutexLock(&pObj->mutex);
10,418,857✔
2482
  size_t len = strlen(pObj->db);
10,425,376✔
2483
  if (len > 0) {
10,425,376✔
2484
    p = taosStrndup(pObj->db, tListLen(pObj->db));
10,200,748!
2485
    if (p == NULL) {
10,195,509!
2486
      tscError("failed to taosStrndup db name");
×
2487
    }
2488
  }
2489

2490
  (void)taosThreadMutexUnlock(&pObj->mutex);
10,420,137✔
2491
  return p;
10,427,796✔
2492
}
2493

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

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

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

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

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

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

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

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

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

2553
  if (payloadLen > 0) {
843,593✔
2554
    int32_t compLen = *(int32_t*)pRsp->data;
785,648✔
2555
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
785,648✔
2556

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

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

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

2584
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4);
843,593✔
2585
  return code;
843,604✔
2586
}
2587

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
2722
  return TSDB_CODE_SUCCESS;
×
2723
}
2724

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

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

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

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

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

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

UNCOV
2753
      break;
×
2754
    }
2755

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

2766
      continue;
×
2767
    }
2768

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

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

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

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

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

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

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

2827
    goto _return;
×
2828
  }
2829

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

UNCOV
2844
  taosHashCleanup(pHash);
×
2845

UNCOV
2846
  return TSDB_CODE_SUCCESS;
×
2847

2848
_return:
×
2849

2850
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
2851

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

2859
  taosHashCleanup(pHash);
×
2860

2861
  return terrno;
×
2862
}
2863

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

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

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

2877
  if (pParam->pRequest) {
10,400,054✔
2878
    pParam->pRequest->code = code;
10,398,367✔
2879
    clientOperateReport(pParam->pRequest);
10,398,367✔
2880
  }
2881

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

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

2895
    return;
×
2896
  }
2897

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

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

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

2926
    return;
×
2927
  }
2928

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

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

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

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

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

2957
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
10,390,920!
2958
  if (NULL == param) {
10,401,281!
2959
    return NULL;
×
2960
  }
2961
  int32_t code = tsem_init(&param->sem, 0, 0);
10,401,281✔
2962
  if (TSDB_CODE_SUCCESS != code) {
10,398,943!
2963
    taosMemoryFree(param);
×
2964
    return NULL;
×
2965
  }
2966

2967
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
10,398,943✔
2968
  code = tsem_wait(&param->sem);
10,356,391✔
2969
  if (TSDB_CODE_SUCCESS != code) {
10,403,029!
2970
    taosMemoryFree(param);
×
2971
    return NULL;
×
2972
  }
2973
  code = tsem_destroy(&param->sem);
10,403,029✔
2974
  if (TSDB_CODE_SUCCESS != code) {
10,400,655!
2975
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
2976
  }
2977

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

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

2988
  return pRequest;
10,394,625✔
2989
}
2990

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

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

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

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

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

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

3030
  pResultInfo->pData = pResult;
754,789✔
3031
  pResultInfo->numOfRows = 0;
754,789✔
3032

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

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

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

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

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

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

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

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

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

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

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

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

3109
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
10,400,746✔
3110
  pRequest->inCallback = true;
10,400,746✔
3111
  int64_t this = pRequest->self;
10,400,746✔
3112
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
10,400,746!
3113
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
320!
3114
    code = TSDB_CODE_SUCCESS;
×
3115
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3116
  }
3117
  pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
10,400,746✔
3118
  SRequestObj* pReq = acquireRequest(this);
10,405,634✔
3119
  if (pReq != NULL) {
10,405,771✔
3120
    pReq->inCallback = false;
10,400,472✔
3121
    (void)releaseRequest(this);
10,400,472✔
3122
  }
3123
}
10,401,260✔
3124

3125
int32_t clientParseSql(void* param, const char* dbName, const char* sql, bool parseOnly, const char* effectiveUser,
601✔
3126
                       SParseSqlRes* pRes) {
3127
#ifndef TD_ENTERPRISE
3128
  return TSDB_CODE_SUCCESS;
3129
#else
3130
  return clientParseSqlImpl(param, dbName, sql, parseOnly, effectiveUser, pRes);
601✔
3131
#endif
3132
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc