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

taosdata / TDengine / #3676

22 Mar 2025 04:46PM UTC coverage: 25.147% (-36.8%) from 61.952%
#3676

push

travis-ci

web-flow
fix: userOperTest in linux (#30363)

Co-authored-by: taos-support <it@taosdata.com>

55963 of 304767 branches covered (18.36%)

Branch coverage included in aggregate %.

96374 of 301020 relevant lines covered (32.02%)

582640.8 hits per line

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

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

16
#include "cJSON.h"
17
#include "clientInt.h"
18
#include "clientLog.h"
19
#include "clientMonitor.h"
20
#include "command.h"
21
#include "scheduler.h"
22
#include "tdatablock.h"
23
#include "tdataformat.h"
24
#include "tdef.h"
25
#include "tglobal.h"
26
#include "tmsgtype.h"
27
#include "tpagedbuf.h"
28
#include "tref.h"
29
#include "tsched.h"
30
#include "tversion.h"
31
#include "decimal.h"
32

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

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

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

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

54
  return true;
182✔
55
}
56

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

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

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

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

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

76
  (void)releaseRequest((int64_t)param);
3,893✔
77

78
  return killed;
3,893✔
79
}
80

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

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

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

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

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

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

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

117
  SCorEpSet epSet = {0};
91✔
118
  if (ip) {
91✔
119
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
86!
120
  } else {
121
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
5!
122
  }
123

124
  if (port) {
91!
125
    epSet.epSet.eps[0].port = port;
×
126
    epSet.epSet.eps[1].port = port;
×
127
  }
128

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

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

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

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

188
_return:
91✔
189

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

332
  return code;
85✔
333
}
334

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

343
  return code;
×
344
}
345

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

451
  return TSDB_CODE_SUCCESS;
×
452
}
453

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

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

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

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

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

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

499
  return code;
×
500
}
501

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

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

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

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

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

545
  for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
470✔
546
    pResInfo->fields[i].type = pSchema[i].type;
298✔
547

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

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

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

568
  pResInfo->precision = precision;
172✔
569
}
570

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

578
  int32_t dbNum = taosArrayGetSize(pDbVgList);
172✔
579
  for (int32_t i = 0; i < dbNum; ++i) {
305✔
580
    SArray* pVg = taosArrayGetP(pDbVgList, i);
133✔
581
    if (NULL == pVg) {
133!
582
      continue;
×
583
    }
584
    int32_t vgNum = taosArrayGetSize(pVg);
133✔
585
    if (vgNum <= 0) {
133!
586
      continue;
×
587
    }
588

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

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

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

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

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

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

630
_return:
39✔
631

632
  *pNodeList = nodeList;
172✔
633

634
  return TSDB_CODE_SUCCESS;
172✔
635
}
636

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

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

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

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

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

676
_return:
×
677

678
  *pNodeList = nodeList;
×
679

680
  return TSDB_CODE_SUCCESS;
×
681
}
682

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

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

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

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

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

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

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

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

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

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

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

795
  return code;
86✔
796
}
797

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

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

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

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

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

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

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

856
_return:
86✔
857

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

861
  return code;
86✔
862
}
863

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

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

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

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

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

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

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

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

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

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

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

933
  return TSDB_CODE_SUCCESS;
48✔
934
}
935

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

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

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

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

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

970
_return:
78✔
971

972
  taosArrayDestroy(pArray);
78✔
973
  return code;
78✔
974
}
975

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

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

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

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

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

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

1000
  switch (pRes->msgType) {
1,111!
1001
    case TDMT_VND_ALTER_TABLE:
×
1002
    case TDMT_MND_ALTER_STB: {
1003
      code = handleAlterTbExecRes(pRes->res, pCatalog);
×
1004
      break;
×
1005
    }
1006
    case TDMT_VND_CREATE_TABLE: {
308✔
1007
      SArray* pList = (SArray*)pRes->res;
308✔
1008
      int32_t num = taosArrayGetSize(pList);
308✔
1009
      for (int32_t i = 0; i < num; ++i) {
866✔
1010
        void* res = taosArrayGetP(pList, i);
558✔
1011
        // handleCreateTbExecRes will handle res == null
1012
        code = handleCreateTbExecRes(res, pCatalog);
558✔
1013
      }
1014
      break;
308✔
1015
    }
1016
    case TDMT_MND_CREATE_STB: {
×
1017
      code = handleCreateTbExecRes(pRes->res, pCatalog);
×
1018
      break;
×
1019
    }
1020
    case TDMT_VND_SUBMIT: {
725✔
1021
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
725✔
1022

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

1037
  return code;
1,111✔
1038
}
1039

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1163
  blockDataDestroy(pBlock);
×
1164
}
1165

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

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

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

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

1195
  int32_t type = pRequest->type;
1,037✔
1196
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
1,037!
1197
    if (pResult) {
951!
1198
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
951✔
1199

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

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

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

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

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

1236
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
2,063!
1237
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
1,026✔
1238
    continueInsertFromCsv(pWrapper, pRequest);
×
1239
    return;
×
1240
  }
1241

1242
  if (pRequest->relation.nextRefId) {
1,037!
1243
    handlePostSubQuery(pWrapper);
×
1244
  } else {
1245
    destorySqlCallbackWrapper(pWrapper);
1,037✔
1246
    pRequest->pWrapper = NULL;
1,037✔
1247

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

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

1257
  if (pQuery->pRoot) {
86!
1258
    pRequest->stmtType = pQuery->pRoot->type;
86✔
1259
  }
1260

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

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

1317
  if (!keepQuery) {
86!
1318
    qDestroyQuery(pQuery);
×
1319
  }
1320

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

1328
  if (TSDB_CODE_SUCCESS == code) {
86!
1329
    code = handleQueryExecRsp(pRequest);
86✔
1330
  }
1331

1332
  if (TSDB_CODE_SUCCESS != code) {
86!
1333
    pRequest->code = code;
×
1334
  }
1335

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

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

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

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

1383
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
2,074!
1384
    SArray* pNodeList = NULL;
1,037✔
1385
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
1,037✔
1386
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
86✔
1387
    }
1388

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

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

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

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

1430
  return code;
1,037✔
1431
}
1432

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

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

1441
  pRequest->body.execMode = pQuery->execMode;
1,311✔
1442
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
1,311✔
1443
    destorySqlCallbackWrapper(pWrapper);
274✔
1444
    pRequest->pWrapper = NULL;
274✔
1445
  }
1446

1447
  if (pQuery->pRoot && !pRequest->inRetry) {
1,311!
1448
    STscObj*            pTscObj = pRequest->pTscObj;
1,311✔
1449
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
1,311✔
1450
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
1,311✔
1451
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
951✔
1452
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
642✔
1453
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
669✔
1454
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
160✔
1455
    }
1456
  }
1457

1458
  switch (pQuery->execMode) {
1,311!
1459
    case QUERY_EXEC_MODE_LOCAL:
85✔
1460
      asyncExecLocalCmd(pRequest, pQuery);
85✔
1461
      break;
85✔
1462
    case QUERY_EXEC_MODE_RPC:
189✔
1463
      code = asyncExecDdlQuery(pRequest, pQuery);
189✔
1464
      break;
189✔
1465
    case QUERY_EXEC_MODE_SCHEDULE: {
1,037✔
1466
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
1,037✔
1467
      break;
1,037✔
1468
    }
1469
    case QUERY_EXEC_MODE_EMPTY_RESULT:
×
1470
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
1471
      doRequestCallback(pRequest, 0);
×
1472
      break;
×
1473
    default:
×
1474
      tscError("req:0x%" PRIx64 ", invalid execMode %d", pRequest->self, pQuery->execMode);
×
1475
      doRequestCallback(pRequest, -1);
×
1476
      break;
×
1477
  }
1478
}
1479

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

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

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

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

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

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

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

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

1520
  return code;
×
1521
}
1522

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

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

1548
  return TSDB_CODE_SUCCESS;
1✔
1549
}
1550

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

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

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

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

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

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

1602
  if (mgmtEpSet->numOfEps == 0) {
91!
1603
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1604
    return TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1605
  }
1606

1607
  return 0;
91✔
1608
}
1609

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

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

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

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

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

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

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

1674
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
91✔
1675

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

1685
  *(int64_t*)(*pMsgSendInfo)->param = pRequest->self;
91✔
1686

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

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

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

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

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

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

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

1726
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,954✔
1727
  if (NULL == pEpSet) {
1,954✔
1728
    return;
1,526✔
1729
  }
1730

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

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

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

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

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

1785
  STscObj* pTscObj = NULL;
1,954✔
1786

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

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

1794
  if (pSendInfo->requestObjRefId != 0) {
1,954✔
1795
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
1,759✔
1796
    if (pRequest) {
1,759✔
1797
      if (pRequest->self != pSendInfo->requestObjRefId) {
1,757!
1798
        tscError("doProcessMsgFromServer req:0x%" PRId64 " != pSendInfo->requestObjRefId:0x%" PRId64,
×
1799
                 pRequest->self, pSendInfo->requestObjRefId);
1800

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

1813
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
1,954✔
1814

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

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

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

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

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

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

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

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

1888
  arg->msg = *pMsg;
1,954✔
1889
  arg->pEpset = tEpSet;
1,954✔
1890

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

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

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

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

1927
  return NULL;
×
1928
}
1929

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

1944
void doSetOneRowPtr(SReqResultInfo* pResultInfo) {
11,833✔
1945
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
47,271✔
1946
    SResultColumn* pCol = &pResultInfo->pCol[i];
35,438✔
1947

1948
    int32_t type = pResultInfo->fields[i].type;
35,438✔
1949
    int32_t schemaBytes = calcSchemaBytesFromTypeBytes(type, pResultInfo->userFields[i].bytes, false);
35,438✔
1950

1951
    if (IS_VAR_DATA_TYPE(type)) {
35,438!
1952
      if (!IS_VAR_NULL_TYPE(type, schemaBytes) && pCol->offset[pResultInfo->current] != -1) {
4,463!
1953
        char* pStart = pResultInfo->pCol[i].offset[pResultInfo->current] + pResultInfo->pCol[i].pData;
4,451✔
1954

1955
        pResultInfo->length[i] = varDataLen(pStart);
4,451✔
1956
        pResultInfo->row[i] = varDataVal(pStart);
4,451✔
1957
      } else {
1958
        pResultInfo->row[i] = NULL;
12✔
1959
        pResultInfo->length[i] = 0;
12✔
1960
      }
1961
    } else {
1962
      if (!colDataIsNull_f(pCol->nullbitmap, pResultInfo->current)) {
30,975✔
1963
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + schemaBytes * pResultInfo->current;
30,969✔
1964
        pResultInfo->length[i] = schemaBytes;
30,969✔
1965
      } else {
1966
        pResultInfo->row[i] = NULL;
6✔
1967
        pResultInfo->length[i] = 0;
6✔
1968
      }
1969
    }
1970
  }
1971
}
11,833✔
1972

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

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

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

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

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

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

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

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

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

2019
  return pResultInfo->row;
×
2020
}
2021

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

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

2034
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
11,997✔
2035
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
11,997✔
2036
    // All data has returned to App already, no need to try again
2037
    if (pResultInfo->completed) {
249✔
2038
      pResultInfo->numOfRows = 0;
164✔
2039
      return NULL;
164✔
2040
    }
2041

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

2058
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
11,833!
2059
    return NULL;
×
2060
  } else {
2061
    if (setupOneRowPtr) {
11,833!
2062
      doSetOneRowPtr(pResultInfo);
11,833✔
2063
      pResultInfo->current += 1;
11,833✔
2064
    }
2065

2066
    return pResultInfo->row;
11,833✔
2067
  }
2068
}
2069

2070
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
170✔
2071
  if (pResInfo->row == NULL) {
170✔
2072
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
167!
2073
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
167!
2074
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
167!
2075
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
167!
2076

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

2086
  return TSDB_CODE_SUCCESS;
170✔
2087
}
2088

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

2094
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
463✔
2095
    int32_t type = pResultInfo->fields[i].type;
295✔
2096
    int32_t schemaBytes = calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
295✔
2097

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

2105
      pResultInfo->convertBuf[i] = p;
12✔
2106

2107
      SResultColumn* pCol = &pResultInfo->pCol[i];
12✔
2108
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
24✔
2109
        if (pCol->offset[j] != -1) {
12!
2110
          char* pStart = pCol->offset[j] + pCol->pData;
12✔
2111

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

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

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

2136
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
168✔
2137
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
463✔
2138
    TAOS_FIELD_E* pFieldE = pResultInfo->fields + i;
295✔
2139
    TAOS_FIELD* pField = pResultInfo->userFields + i;
295✔
2140
    int32_t type = pFieldE->type;
295✔
2141
    int32_t bufLen = 0;
295✔
2142
    char* p = NULL;
295✔
2143
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
295!
2144
      continue;
295✔
2145
    } else {
2146
      bufLen = 64;
×
2147
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
×
2148
      pFieldE->bytes = bufLen;
×
2149
      pField->bytes = bufLen;
×
2150
    }
2151
    if (!p) return terrno;
×
2152
    pResultInfo->convertBuf[i] = p;
×
2153

2154
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
×
2155
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
×
2156
                                  pFieldE->precision, pFieldE->scale, p, bufLen);
×
2157
      p += bufLen;
×
2158
      if (TSDB_CODE_SUCCESS != code) {
×
2159
        return code;
×
2160
      }
2161
    }
2162
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
×
2163
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
×
2164
  }
2165
  return 0;
168✔
2166
}
2167

2168
int32_t getVersion1BlockMetaSize(const char* p, int32_t numOfCols) {
2✔
2169
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) * 3 + sizeof(uint64_t) +
2✔
2170
         numOfCols * (sizeof(int8_t) + sizeof(int32_t));
2171
}
2172

2173
static int32_t estimateJsonLen(SReqResultInfo* pResultInfo) {
1✔
2174
  char*   p = (char*)pResultInfo->pData;
1✔
2175
  int32_t blockVersion = *(int32_t*)p;
1✔
2176

2177
  int32_t numOfRows = pResultInfo->numOfRows;
1✔
2178
  int32_t numOfCols = pResultInfo->numOfCols;
1✔
2179

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

2188
  int32_t  len = getVersion1BlockMetaSize(p, numOfCols);
1✔
2189
  int32_t* colLength = (int32_t*)(p + len);
1✔
2190
  len += sizeof(int32_t) * numOfCols;
1✔
2191

2192
  char* pStart = p + len;
1✔
2193
  for (int32_t i = 0; i < numOfCols; ++i) {
2✔
2194
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
1!
2195

2196
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
1!
2197
      int32_t* offset = (int32_t*)pStart;
1✔
2198
      int32_t  lenTmp = numOfRows * sizeof(int32_t);
1✔
2199
      len += lenTmp;
1✔
2200
      pStart += lenTmp;
1✔
2201

2202
      int32_t estimateColLen = 0;
1✔
2203
      for (int32_t j = 0; j < numOfRows; ++j) {
2✔
2204
        if (offset[j] == -1) {
1!
2205
          continue;
×
2206
        }
2207
        char* data = offset[j] + pStart;
1✔
2208

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

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

2245
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
170✔
2246
  int32_t numOfRows = pResultInfo->numOfRows;
170✔
2247
  int32_t numOfCols = pResultInfo->numOfCols;
170✔
2248
  bool    needConvert = false;
170✔
2249
  for (int32_t i = 0; i < numOfCols; ++i) {
468✔
2250
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
299✔
2251
      needConvert = true;
1✔
2252
      break;
1✔
2253
    }
2254
  }
2255

2256
  if (!needConvert) {
170✔
2257
    return TSDB_CODE_SUCCESS;
169✔
2258
  }
2259

2260
  tscDebug("start to convert form json format string");
1!
2261

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

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

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

2282
  int32_t len = getVersion1BlockMetaSize(p, numOfCols);
1✔
2283
  (void)memcpy(p1, p, len);
1✔
2284

2285
  p += len;
1✔
2286
  p1 += len;
1✔
2287
  totalLen += len;
1✔
2288

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

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

2315
      len = 0;
1✔
2316
      for (int32_t j = 0; j < numOfRows; ++j) {
2✔
2317
        if (offset[j] == -1) {
1!
2318
          continue;
×
2319
        }
2320
        char* data = offset[j] + pStart;
1✔
2321

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

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

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

2394
  *(int32_t*)(pResultInfo->convertJson + 4) = totalLen;
1✔
2395
  pResultInfo->pData = pResultInfo->convertJson;
1✔
2396
  return TSDB_CODE_SUCCESS;
1✔
2397
}
2398

2399
int32_t setResultDataPtr(SReqResultInfo* pResultInfo, bool convertUcs4, bool isStmt) {
170✔
2400
  bool convertForDecimal = convertUcs4;
170✔
2401
  if (pResultInfo == NULL || pResultInfo->numOfCols <= 0 || pResultInfo->fields == NULL) {
170!
2402
    tscError("setResultDataPtr paras error");
×
2403
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2404
  }
2405

2406
  if (pResultInfo->numOfRows == 0) {
170!
2407
    return TSDB_CODE_SUCCESS;
×
2408
  }
2409

2410
  if (pResultInfo->pData == NULL) {
170!
2411
    tscError("setResultDataPtr error: pData is NULL");
×
2412
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2413
  }
2414

2415
  int32_t code = doPrepareResPtr(pResultInfo);
170✔
2416
  if (code != TSDB_CODE_SUCCESS) {
170!
2417
    return code;
×
2418
  }
2419
  code = doConvertJson(pResultInfo);
170✔
2420
  if (code != TSDB_CODE_SUCCESS) {
170!
2421
    return code;
×
2422
  }
2423

2424
  char* p = (char*)pResultInfo->pData;
170✔
2425

2426
  // version:
2427
  int32_t blockVersion = *(int32_t*)p;
170✔
2428
  p += sizeof(int32_t);
170✔
2429

2430
  int32_t dataLen = *(int32_t*)p;
170✔
2431
  p += sizeof(int32_t);
170✔
2432

2433
  int32_t rows = *(int32_t*)p;
170✔
2434
  p += sizeof(int32_t);
170✔
2435

2436
  int32_t cols = *(int32_t*)p;
170✔
2437
  p += sizeof(int32_t);
170✔
2438

2439
  if (rows != pResultInfo->numOfRows || cols != pResultInfo->numOfCols) {
170!
2440
    tscError("setResultDataPtr paras error:rows;%d numOfRows:%" PRId64 " cols:%d numOfCols:%d", rows,
×
2441
             pResultInfo->numOfRows, cols, pResultInfo->numOfCols);
2442
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2443
  }
2444

2445
  int32_t hasColumnSeg = *(int32_t*)p;
170✔
2446
  p += sizeof(int32_t);
170✔
2447

2448
  uint64_t groupId = taosGetUInt64Aligned((uint64_t*)p);
170✔
2449
  p += sizeof(uint64_t);
170✔
2450

2451
  // check fields
2452
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
469✔
2453
    int8_t type = *(int8_t*)p;
299✔
2454
    p += sizeof(int8_t);
299✔
2455

2456
    int32_t bytes = *(int32_t*)p;
299✔
2457
    p += sizeof(int32_t);
299✔
2458

2459
    if (IS_DECIMAL_TYPE(type) && pResultInfo->fields[i].precision == 0) {
299!
2460
      extractDecimalTypeInfoFromBytes(&bytes, &pResultInfo->fields[i].precision, &pResultInfo->fields[i].scale);
×
2461
    }
2462
  }
2463

2464
  int32_t* colLength = (int32_t*)p;
170✔
2465
  p += sizeof(int32_t) * pResultInfo->numOfCols;
170✔
2466

2467
  char* pStart = p;
170✔
2468
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
469✔
2469
    if ((pStart - pResultInfo->pData) >= dataLen) {
299!
2470
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2471
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2472
    }
2473
    if (blockVersion == BLOCK_VERSION_1) {
299!
2474
      colLength[i] = htonl(colLength[i]);
299✔
2475
    }
2476
    if (colLength[i] >= dataLen) {
299!
2477
      tscError("invalid colLength %d, dataLen %d", colLength[i], dataLen);
×
2478
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2479
    }
2480
    if (IS_INVALID_TYPE(pResultInfo->fields[i].type)) {
299!
2481
      tscError("invalid type %d", pResultInfo->fields[i].type);
×
2482
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2483
    }
2484
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
299!
2485
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
124✔
2486
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
124✔
2487
    } else {
2488
      pResultInfo->pCol[i].nullbitmap = pStart;
175✔
2489
      pStart += BitmapLen(pResultInfo->numOfRows);
175✔
2490
    }
2491

2492
    pResultInfo->pCol[i].pData = pStart;
299✔
2493
    pResultInfo->length[i] = calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
299✔
2494
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
299✔
2495

2496
    pStart += colLength[i];
299✔
2497
  }
2498

2499
  p = pStart;
170✔
2500
  // bool blankFill = *(bool*)p;
2501
  p += sizeof(bool);
170✔
2502
  int32_t offset = p - pResultInfo->pData;
170✔
2503
  if (offset > dataLen) {
170!
2504
    tscError("invalid offset %d, dataLen %d", offset, dataLen);
×
2505
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2506
  }
2507

2508
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
2509
  if (convertUcs4) {
170✔
2510
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
168✔
2511
  }
2512
#endif
2513
  if (TSDB_CODE_SUCCESS == code && convertForDecimal) {
170!
2514
    code = convertDecimalType(pResultInfo);
168✔
2515
  }
2516
  return code;
170✔
2517
}
2518

2519
char* getDbOfConnection(STscObj* pObj) {
1,665✔
2520
  terrno = TSDB_CODE_SUCCESS;
1,665✔
2521
  char* p = NULL;
1,665✔
2522
  (void)taosThreadMutexLock(&pObj->mutex);
1,665✔
2523
  size_t len = strlen(pObj->db);
1,665✔
2524
  if (len > 0) {
1,665✔
2525
    p = taosStrndup(pObj->db, tListLen(pObj->db));
962!
2526
    if (p == NULL) {
962!
2527
      tscError("failed to taosStrndup db name");
×
2528
    }
2529
  }
2530

2531
  (void)taosThreadMutexUnlock(&pObj->mutex);
1,665✔
2532
  return p;
1,665✔
2533
}
2534

2535
void setConnectionDB(STscObj* pTscObj, const char* db) {
33✔
2536
  if (db == NULL || pTscObj == NULL) {
33!
2537
    tscError("setConnectionDB para is NULL");
×
2538
    return;
×
2539
  }
2540

2541
  (void)taosThreadMutexLock(&pTscObj->mutex);
33✔
2542
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
33✔
2543
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
33✔
2544
}
2545

2546
void resetConnectDB(STscObj* pTscObj) {
×
2547
  if (pTscObj == NULL) {
×
2548
    return;
×
2549
  }
2550

2551
  (void)taosThreadMutexLock(&pTscObj->mutex);
×
2552
  pTscObj->db[0] = 0;
×
2553
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
×
2554
}
2555

2556
int32_t setQueryResultFromRsp(SReqResultInfo* pResultInfo, const SRetrieveTableRsp* pRsp, bool convertUcs4, bool isStmt) {
170✔
2557
  if (pResultInfo == NULL || pRsp == NULL) {
170!
2558
    tscError("setQueryResultFromRsp paras is null");
×
2559
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2560
  }
2561

2562
  taosMemoryFreeClear(pResultInfo->pRspMsg);
170!
2563
  pResultInfo->pRspMsg = (const char*)pRsp;
170✔
2564
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
170✔
2565
  pResultInfo->current = 0;
170✔
2566
  pResultInfo->completed = (pRsp->completed == 1);
170✔
2567
  pResultInfo->precision = pRsp->precision;
170✔
2568

2569
  // decompress data if needed
2570
  int32_t payloadLen = htonl(pRsp->payloadLen);
170✔
2571

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

2588
        pResultInfo->decompBuf = p;
×
2589
        pResultInfo->decompBufSize = payloadLen;
×
2590
      }
2591
    }
2592
  }
2593

2594
  if (payloadLen > 0) {
170!
2595
    int32_t compLen = *(int32_t*)pRsp->data;
170✔
2596
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
170✔
2597

2598
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
170✔
2599

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

2622
  // TODO handle the compressed case
2623
  pResultInfo->totalRows += pResultInfo->numOfRows;
170✔
2624

2625
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
170✔
2626
  return code;
170✔
2627
}
2628

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

2639
  rpcInit.label = "CHK";
×
2640
  rpcInit.numOfThreads = 1;
×
2641
  rpcInit.cfp = NULL;
×
2642
  rpcInit.sessions = 16;
×
2643
  rpcInit.connType = TAOS_CONN_CLIENT;
×
2644
  rpcInit.idleTime = tsShellActivityTimer * 1000;
×
2645
  rpcInit.compressSize = tsCompressMsgSize;
×
2646
  rpcInit.user = "_dnd";
×
2647

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

2659
  clientRpc = rpcOpen(&rpcInit);
×
2660
  if (clientRpc == NULL) {
×
2661
    code = terrno;
×
2662
    tscError("failed to init server status client since %s", tstrerror(code));
×
2663
    goto _OVER;
×
2664
  }
2665

2666
  if (fqdn == NULL) {
×
2667
    fqdn = tsLocalFqdn;
×
2668
  }
2669

2670
  if (port == 0) {
×
2671
    port = tsServerPort;
×
2672
  }
2673

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

2682
  if (rpcRsp.code != 0 || rpcRsp.contLen <= 0 || rpcRsp.pCont == NULL) {
×
2683
    tscError("failed to send server status req since %s", terrstr());
×
2684
    goto _OVER;
×
2685
  }
2686

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

2692
  code = statusRsp.statusCode;
×
2693
  if (details != NULL) {
×
2694
    tstrncpy(details, statusRsp.details, maxlen);
×
2695
  }
2696

2697
_OVER:
×
2698
  if (clientRpc != NULL) {
×
2699
    rpcClose(clientRpc);
×
2700
  }
2701
  if (rpcRsp.pCont != NULL) {
×
2702
    rpcFreeCont(rpcRsp.pCont);
×
2703
  }
2704
  return code;
×
2705
}
2706

2707
int32_t appendTbToReq(SHashObj* pHash, int32_t pos1, int32_t len1, int32_t pos2, int32_t len2, const char* str,
×
2708
                      int32_t acctId, char* db) {
2709
  SName name = {0};
×
2710

2711
  if (len1 <= 0) {
×
2712
    return -1;
×
2713
  }
2714

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

2730
  if (dbLen <= 0 || tbLen <= 0) {
×
2731
    return -1;
×
2732
  }
2733

2734
  if (tNameSetDbName(&name, acctId, dbName, dbLen)) {
×
2735
    return -1;
×
2736
  }
2737

2738
  if (tNameAddTbName(&name, tbName, tbLen)) {
×
2739
    return -1;
×
2740
  }
2741

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

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

2763
  return TSDB_CODE_SUCCESS;
×
2764
}
2765

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

2772
  bool    inEscape = false;
×
2773
  int32_t code = 0;
×
2774
  void*   pIter = NULL;
×
2775

2776
  int32_t vIdx = 0;
×
2777
  int32_t vPos[2];
2778
  int32_t vLen[2];
2779

2780
  (void)memset(vPos, -1, sizeof(vPos));
×
2781
  (void)memset(vLen, 0, sizeof(vLen));
×
2782

2783
  for (int32_t i = 0;; ++i) {
×
2784
    if (0 == *(tbList + i)) {
×
2785
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
×
2786
        vLen[vIdx] = i - vPos[vIdx];
×
2787
      }
2788

2789
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
×
2790
      if (code) {
×
2791
        goto _return;
×
2792
      }
2793

2794
      break;
×
2795
    }
2796

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

2807
      continue;
×
2808
    }
2809

2810
    if (inEscape) {
×
2811
      if (vPos[vIdx] < 0) {
×
2812
        vPos[vIdx] = i;
×
2813
      }
2814
      continue;
×
2815
    }
2816

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

2831
    if (',' == *(tbList + i)) {
×
2832
      if (vPos[vIdx] < 0) {
×
2833
        goto _return;
×
2834
      }
2835
      if (vLen[vIdx] <= 0) {
×
2836
        vLen[vIdx] = i - vPos[vIdx];
×
2837
      }
2838

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

2844
      (void)memset(vPos, -1, sizeof(vPos));
×
2845
      (void)memset(vLen, 0, sizeof(vLen));
×
2846
      vIdx = 0;
×
2847
      continue;
×
2848
    }
2849

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

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

2868
    goto _return;
×
2869
  }
2870

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

2885
  taosHashCleanup(pHash);
×
2886

2887
  return TSDB_CODE_SUCCESS;
×
2888

2889
_return:
×
2890

2891
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
2892

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

2900
  taosHashCleanup(pHash);
×
2901

2902
  return terrno;
×
2903
}
2904

2905
void syncCatalogFn(SMetaData* pResult, void* param, int32_t code) {
×
2906
  SSyncQueryParam* pParam = param;
×
2907
  pParam->pRequest->code = code;
×
2908

2909
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
×
2910
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
2911
  }
2912
}
×
2913

2914
void syncQueryFn(void* param, void* res, int32_t code) {
1,341✔
2915
  SSyncQueryParam* pParam = param;
1,341✔
2916
  pParam->pRequest = res;
1,341✔
2917

2918
  if (pParam->pRequest) {
1,341!
2919
    pParam->pRequest->code = code;
1,341✔
2920
    clientOperateReport(pParam->pRequest);
1,341✔
2921
  }
2922

2923
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
1,341!
2924
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
2925
  }
2926
}
1,341✔
2927

2928
void taosAsyncQueryImpl(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
1,346✔
2929
                        int8_t source) {
2930
  if (sql == NULL || NULL == fp) {
1,346!
2931
    terrno = TSDB_CODE_INVALID_PARA;
×
2932
    if (fp) {
×
2933
      fp(param, NULL, terrno);
×
2934
    }
2935

2936
    return;
×
2937
  }
2938

2939
  size_t sqlLen = strlen(sql);
1,346✔
2940
  if (sqlLen > (size_t)TSDB_MAX_ALLOWED_SQL_LEN) {
1,346!
2941
    tscError("sql string exceeds max length:%d", TSDB_MAX_ALLOWED_SQL_LEN);
×
2942
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
2943
    fp(param, NULL, terrno);
×
2944
    return;
×
2945
  }
2946

2947
  SRequestObj* pRequest = NULL;
1,346✔
2948
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
1,346✔
2949
  if (code != TSDB_CODE_SUCCESS) {
1,346!
2950
    terrno = code;
×
2951
    fp(param, NULL, terrno);
×
2952
    return;
×
2953
  }
2954

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

2967
    return;
×
2968
  }
2969

2970
  size_t sqlLen = strlen(sql);
×
2971
  if (sqlLen > (size_t)TSDB_MAX_ALLOWED_SQL_LEN) {
×
2972
    tscError("sql string exceeds max length:%d", TSDB_MAX_ALLOWED_SQL_LEN);
×
2973
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
2974
    fp(param, NULL, terrno);
×
2975
    return;
×
2976
  }
2977

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

2986
  pRequest->body.queryFp = fp;
×
2987
  doAsyncQuery(pRequest, false);
×
2988
}
2989

2990
TAOS_RES* taosQueryImpl(TAOS* taos, const char* sql, bool validateOnly, int8_t source) {
1,341✔
2991
  if (NULL == taos) {
1,341!
2992
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
2993
    return NULL;
×
2994
  }
2995

2996
  tscDebug("conn:0x%" PRIx64 ", taos_query execute sql:%s", *(int64_t*)taos, sql);
1,341!
2997

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

3008
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
1,341✔
3009
  code = tsem_wait(&param->sem);
1,341✔
3010
  if (TSDB_CODE_SUCCESS != code) {
1,341!
3011
    taosMemoryFree(param);
×
3012
    return NULL;
×
3013
  }
3014
  code = tsem_destroy(&param->sem);
1,341✔
3015
  if (TSDB_CODE_SUCCESS != code) {
1,341!
3016
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3017
  }
3018

3019
  SRequestObj* pRequest = NULL;
1,341✔
3020
  if (param->pRequest != NULL) {
1,341!
3021
    param->pRequest->syncQuery = true;
1,341✔
3022
    pRequest = param->pRequest;
1,341✔
3023
    param->pRequest->inCallback = false;
1,341✔
3024
  }
3025
  taosMemoryFree(param);
1,341!
3026

3027
  tscDebug("QID:0x%" PRIx64 ", taos_query end, conn:0x%" PRIx64 " res:%p", pRequest ? pRequest->requestId : 0,
1,341!
3028
           *(int64_t*)taos, pRequest);
3029

3030
  return pRequest;
1,341✔
3031
}
3032

3033
TAOS_RES* taosQueryImplWithReqid(TAOS* taos, const char* sql, bool validateOnly, int64_t reqid) {
×
3034
  if (NULL == taos) {
×
3035
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3036
    return NULL;
×
3037
  }
3038

3039
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
×
3040
  if (param == NULL) {
×
3041
    return NULL;
×
3042
  }
3043
  int32_t code = tsem_init(&param->sem, 0, 0);
×
3044
  if (TSDB_CODE_SUCCESS != code) {
×
3045
    taosMemoryFree(param);
×
3046
    return NULL;
×
3047
  }
3048

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

3064
static void fetchCallback(void* pResult, void* param, int32_t code) {
87✔
3065
  SRequestObj* pRequest = (SRequestObj*)param;
87✔
3066

3067
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
87✔
3068

3069
  tscDebug("req:0x%" PRIx64 ", enter scheduler fetch cb, code:%d - %s, QID:0x%" PRIx64, pRequest->self, code, tstrerror(code),
87!
3070
           pRequest->requestId);
3071

3072
  pResultInfo->pData = pResult;
87✔
3073
  pResultInfo->numOfRows = 0;
87✔
3074

3075
  if (code != TSDB_CODE_SUCCESS) {
87!
3076
    pRequest->code = code;
×
3077
    taosMemoryFreeClear(pResultInfo->pData);
×
3078
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
×
3079
    return;
×
3080
  }
3081

3082
  if (pRequest->code != TSDB_CODE_SUCCESS) {
87!
3083
    taosMemoryFreeClear(pResultInfo->pData);
×
3084
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pRequest->code);
×
3085
    return;
×
3086
  }
3087

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

3099
    STscObj*            pTscObj = pRequest->pTscObj;
87✔
3100
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
87✔
3101
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
87✔
3102
  }
3103

3104
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
87✔
3105
}
3106

3107
void taosAsyncFetchImpl(SRequestObj* pRequest, __taos_async_fn_t fp, void* param) {
89✔
3108
  pRequest->body.fetchFp = fp;
89✔
3109
  ((SSyncQueryParam*)pRequest->body.interParam)->userParam = param;
89✔
3110

3111
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
89✔
3112

3113
  // this query has no results or error exists, return directly
3114
  if (taos_num_fields(pRequest) == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
89!
3115
    pResultInfo->numOfRows = 0;
×
3116
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
×
3117
    return;
2✔
3118
  }
3119

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

3134
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
2✔
3135
    return;
2✔
3136
  }
3137

3138
  SSchedulerReq req = {
87✔
3139
      .syncReq = false,
3140
      .fetchFp = fetchCallback,
3141
      .cbParam = pRequest,
3142
  };
3143

3144
  int32_t code = schedulerFetchRows(pRequest->body.queryJob, &req);
87✔
3145
  if (TSDB_CODE_SUCCESS != code) {
87!
3146
    tscError("0x%" PRIx64 " failed to schedule fetch rows", pRequest->requestId);
×
3147
    // pRequest->body.fetchFp(param, pRequest, code);
3148
  }
3149
}
3150

3151
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
1,355✔
3152
  pRequest->inCallback = true;
1,355✔
3153
  int64_t this = pRequest->self;
1,355✔
3154
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
1,355!
3155
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
×
3156
    code = TSDB_CODE_SUCCESS;
×
3157
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3158
  }
3159
  if (pRequest->body.queryFp != NULL) {
1,355!
3160
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
1,355✔
3161
  }
3162
  SRequestObj* pReq = acquireRequest(this);
1,355✔
3163
  if (pReq != NULL) {
1,355✔
3164
    pReq->inCallback = false;
1,347✔
3165
    (void)releaseRequest(this);
1,347✔
3166
  }
3167
}
1,355✔
3168

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