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

taosdata / TDengine / #4995

18 Mar 2026 06:26AM UTC coverage: 71.996% (-0.2%) from 72.244%
#4995

push

travis-ci

web-flow
merge: from main to 3.0 branch #34835

2 of 4 new or added lines in 2 files covered. (50.0%)

5312 existing lines in 167 files now uncovered.

244665 of 339830 relevant lines covered (72.0%)

135013613.72 hits per line

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

71.87
/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 "clientSession.h"
21
#include "command.h"
22
#include "decimal.h"
23
#include "scheduler.h"
24
#include "tdatablock.h"
25
#include "tdataformat.h"
26
#include "tdef.h"
27
#include "tglobal.h"
28
#include "tmisce.h"
29
#include "tmsg.h"
30
#include "tmsgtype.h"
31
#include "tpagedbuf.h"
32
#include "tref.h"
33
#include "tsched.h"
34
#include "tversion.h"
35

36
static int32_t initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet);
37
static int32_t buildConnectMsg(SRequestObj* pRequest, SMsgSendInfo** pMsgSendInfo, int32_t totpCode);
38

39
void setQueryRequest(int64_t rId) {
650,757,740✔
40
  SRequestObj* pReq = acquireRequest(rId);
650,757,740✔
41
  if (pReq != NULL) {
650,792,002✔
42
    pReq->isQuery = true;
650,772,218✔
43
    (void)releaseRequest(rId);
650,772,218✔
44
  }
45
}
650,780,374✔
46

47
static bool stringLengthCheck(const char* str, size_t maxsize) {
170,720,857✔
48
  if (str == NULL) {
170,720,857✔
49
    return false;
×
50
  }
51

52
  size_t len = strlen(str);
170,720,857✔
53
  if (len <= 0 || len > maxsize) {
170,720,857✔
54
    return false;
×
55
  }
56

57
  return true;
170,724,233✔
58
}
59

60
static bool validateUserName(const char* user) { return stringLengthCheck(user, TSDB_USER_LEN - 1); }
85,098,469✔
61

62
static bool validatePassword(const char* passwd) { return stringLengthCheck(passwd, TSDB_PASSWORD_MAX_LEN); }
85,097,643✔
63

64
static bool validateDbName(const char* db) { return stringLengthCheck(db, TSDB_DB_NAME_LEN - 1); }
527,159✔
65

66
static char* getClusterKey(const char* user, const char* auth, const char* ip, int32_t port) {
85,099,029✔
67
  char key[512] = {0};
85,099,029✔
68
  if (user == NULL) {
85,099,029✔
69
    (void)snprintf(key, sizeof(key), "%s:%s:%d", auth, ip, port);
2,226✔
70
  } else {
71
    (void)snprintf(key, sizeof(key), "%s:%s:%s:%d", user, auth, ip, port);
85,096,803✔
72
  }
73
  return taosStrdup(key);
85,099,029✔
74
}
75

76
static int32_t escapeToPrinted(char* dst, size_t maxDstLength, const char* src, size_t srcLength) {
559,087✔
77
  if (dst == NULL || src == NULL || srcLength == 0) {
559,087✔
78
    return 0;
465✔
79
  }
80

81
  size_t escapeLength = 0;
558,622✔
82
  for (size_t i = 0; i < srcLength; ++i) {
15,837,290✔
83
    if (src[i] == '\"' || src[i] == '\\' || src[i] == '\b' || src[i] == '\f' || src[i] == '\n' || src[i] == '\r' ||
15,278,668✔
84
        src[i] == '\t') {
15,278,668✔
85
      escapeLength += 1;
×
86
    }
87
  }
88

89
  size_t dstLength = srcLength;
558,622✔
90
  if (escapeLength == 0) {
558,622✔
91
    (void)memcpy(dst, src, srcLength);
558,622✔
92
  } else {
93
    dstLength = 0;
×
94
    for (size_t i = 0; i < srcLength && dstLength <= maxDstLength; i++) {
×
95
      switch (src[i]) {
×
96
        case '\"':
×
97
          dst[dstLength++] = '\\';
×
98
          dst[dstLength++] = '\"';
×
99
          break;
×
100
        case '\\':
×
101
          dst[dstLength++] = '\\';
×
102
          dst[dstLength++] = '\\';
×
103
          break;
×
104
        case '\b':
×
105
          dst[dstLength++] = '\\';
×
106
          dst[dstLength++] = 'b';
×
107
          break;
×
108
        case '\f':
×
109
          dst[dstLength++] = '\\';
×
110
          dst[dstLength++] = 'f';
×
111
          break;
×
112
        case '\n':
×
113
          dst[dstLength++] = '\\';
×
114
          dst[dstLength++] = 'n';
×
115
          break;
×
116
        case '\r':
×
117
          dst[dstLength++] = '\\';
×
118
          dst[dstLength++] = 'r';
×
119
          break;
×
120
        case '\t':
×
121
          dst[dstLength++] = '\\';
×
122
          dst[dstLength++] = 't';
×
123
          break;
×
124
        default:
×
125
          dst[dstLength++] = src[i];
×
126
      }
127
    }
128
  }
129

130
  return dstLength;
558,622✔
131
}
132

133
bool chkRequestKilled(void* param) {
2,147,483,647✔
134
  bool         killed = false;
2,147,483,647✔
135
  SRequestObj* pRequest = acquireRequest((int64_t)param);
2,147,483,647✔
136
  if (NULL == pRequest || pRequest->killed) {
2,147,483,647✔
137
    killed = true;
1,942✔
138
  }
139

140
  (void)releaseRequest((int64_t)param);
2,147,483,647✔
141

142
  return killed;
2,147,483,647✔
143
}
144

145
void cleanupAppInfo() {
1,772,277✔
146
  taosHashCleanup(appInfo.pInstMap);
1,772,277✔
147
  taosHashCleanup(appInfo.pInstMapByClusterId);
1,772,277✔
148
  tscInfo("cluster instance map cleaned");
1,772,277✔
149
}
1,772,277✔
150

151
static int32_t taosConnectImpl(const char* user, const char* auth, int32_t totpCode, const char* db,
152
                               __taos_async_fn_t fp, void* param, SAppInstInfo* pAppInfo, int connType,
153
                               STscObj** pTscObj);
154

155
int32_t taos_connect_by_auth(const char* ip, const char* user, const char* auth, const char* totp,
85,101,537✔
156
                                    const char* db, uint16_t port, int connType, STscObj** pObj) {
157
  TSC_ERR_RET(taos_init());
85,101,537✔
158

159
  if (user == NULL) {
85,099,738✔
160
    if (auth == NULL || strlen(auth) != (TSDB_TOKEN_LEN - 1)) {
2,966✔
161
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_TOKEN);
740✔
162
    }
163
  } else if (!validateUserName(user)) {
85,096,772✔
164
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
165
  }
166
  int32_t code = 0;
85,100,876✔
167

168
  char localDb[TSDB_DB_NAME_LEN] = {0};
85,100,876✔
169
  if (db != NULL && strlen(db) > 0) {
85,100,548✔
170
    if (!validateDbName(db)) {
527,216✔
171
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_DB_LENGTH);
×
172
    }
173

174
    tstrncpy(localDb, db, sizeof(localDb));
527,202✔
175
    (void)strdequote(localDb);
527,202✔
176
  }
177

178
  int32_t totpCode = -1;
85,098,708✔
179
  if (totp != NULL) {
85,098,708✔
180
    char* endptr = NULL;
1,961✔
181
    totpCode = taosStr2Int32(totp, &endptr, 10);
1,961✔
182
    if (endptr == totp || *endptr != '\0' || totpCode < 0 || totpCode > 999999) {
1,961✔
183
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_TOTP_CODE);
×
184
    }
185
  }
186

187
  SCorEpSet epSet = {0};
85,098,708✔
188
  if (ip) {
85,098,708✔
189
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
82,854,473✔
190
  } else {
191
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
2,244,235✔
192
  }
193

194
  if (port) {
85,099,287✔
195
    epSet.epSet.eps[0].port = port;
82,224,304✔
196
    epSet.epSet.eps[1].port = port;
82,224,304✔
197
  }
198

199
  char* key = getClusterKey(user, auth, ip, port);
85,099,287✔
200
  if (NULL == key) {
85,100,254✔
201
    TSC_ERR_RET(terrno);
×
202
  }
203
  tscInfo("connecting to server, numOfEps:%d inUse:%d user:%s db:%s key:%s", epSet.epSet.numOfEps, epSet.epSet.inUse,
85,100,254✔
204
          user ? user : "", db, key);
205
  for (int32_t i = 0; i < epSet.epSet.numOfEps; ++i) {
172,446,500✔
206
    tscInfo("ep:%d, %s:%u", i, epSet.epSet.eps[i].fqdn, epSet.epSet.eps[i].port);
87,343,533✔
207
  }
208

209
  SAppInstInfo** pInst = NULL;
85,102,967✔
210
  code = taosThreadMutexLock(&appInfo.mutex);
85,102,967✔
211
  if (TSDB_CODE_SUCCESS != code) {
85,101,295✔
212
    tscError("failed to lock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
213
    TSC_ERR_RET(code);
×
214
  }
215

216
  pInst = taosHashGet(appInfo.pInstMap, key, strlen(key));
85,101,295✔
217
  SAppInstInfo* p = NULL;
85,101,295✔
218
  if (pInst == NULL) {
85,101,295✔
219
    p = taosMemoryCalloc(1, sizeof(struct SAppInstInfo));
1,847,039✔
220
    if (NULL == p) {
1,847,039✔
221
      TSC_ERR_JRET(terrno);
×
222
    }
223
    p->mgmtEp = epSet;
1,847,039✔
224
    code = taosThreadMutexInit(&p->qnodeMutex, NULL);
1,847,039✔
225
    if (TSDB_CODE_SUCCESS != code) {
1,847,039✔
226
      taosMemoryFree(p);
×
227
      TSC_ERR_JRET(code);
×
228
    }
229
    code = openTransporter(user, auth, tsNumOfCores / 2, &p->pTransporter);
1,847,039✔
230
    if (TSDB_CODE_SUCCESS != code) {
1,847,039✔
231
      taosMemoryFree(p);
×
232
      TSC_ERR_JRET(code);
×
233
    }
234
    code = appHbMgrInit(p, key, &p->pAppHbMgr);
1,847,039✔
235
    if (TSDB_CODE_SUCCESS != code) {
1,847,039✔
236
      destroyAppInst(&p);
×
237
      TSC_ERR_JRET(code);
×
238
    }
239
    code = taosHashPut(appInfo.pInstMap, key, strlen(key), &p, POINTER_BYTES);
1,847,039✔
240
    if (TSDB_CODE_SUCCESS != code) {
1,847,039✔
241
      destroyAppInst(&p);
×
242
      TSC_ERR_JRET(code);
×
243
    }
244
    p->instKey = key;
1,847,039✔
245
    key = NULL;
1,847,039✔
246
    tscInfo("new app inst mgr:%p, user:%s, ip:%s, port:%d", p, user ? user : "", epSet.epSet.eps[0].fqdn,
1,847,039✔
247
            epSet.epSet.eps[0].port);
248

249
    pInst = &p;
1,847,039✔
250
  } else {
251
    if (NULL == *pInst || NULL == (*pInst)->pAppHbMgr) {
83,254,256✔
252
      tscError("*pInst:%p, pAppHgMgr:%p", *pInst, (*pInst) ? (*pInst)->pAppHbMgr : NULL);
×
253
      TSC_ERR_JRET(TSDB_CODE_TSC_INTERNAL_ERROR);
×
254
    }
255
    // reset to 0 in case of conn with duplicated user key but its user has ever been dropped.
256
    atomic_store_8(&(*pInst)->pAppHbMgr->connHbFlag, 0);
83,254,256✔
257
  }
258

259
_return:
85,101,295✔
260

261
  if (TSDB_CODE_SUCCESS != code) {
85,101,295✔
262
    (void)taosThreadMutexUnlock(&appInfo.mutex);
×
263
    taosMemoryFreeClear(key);
×
264
    return code;
×
265
  } else {
266
    code = taosThreadMutexUnlock(&appInfo.mutex);
85,101,295✔
267
    taosMemoryFreeClear(key);
85,101,048✔
268
    if (TSDB_CODE_SUCCESS != code) {
85,100,253✔
269
      tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
270
      return code;
×
271
    }
272
    return taosConnectImpl(user, auth, totpCode, localDb, NULL, NULL, *pInst, connType, pObj);
85,100,253✔
273
  }
274
}
275

276
int32_t taos_connect_internal(const char* ip, const char* user, const char* pass, const char* totp, const char* db,
85,097,052✔
277
                              uint16_t port, int connType, STscObj** pObj) {
278
  char auth[TSDB_PASSWORD_LEN + 1] = {0};
85,097,052✔
279
  if (!validatePassword(pass)) {
85,097,052✔
280
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_PASS_LENGTH);
×
281
  }
282

283
  taosEncryptPass_c((uint8_t*)pass, strlen(pass), auth);
85,098,771✔
284
  return taos_connect_by_auth(ip, user, auth, totp, db, port, connType, pObj);
85,097,838✔
285
}
286

287
// SAppInstInfo* getAppInstInfo(const char* clusterKey) {
288
//   SAppInstInfo** ppAppInstInfo = taosHashGet(appInfo.pInstMap, clusterKey, strlen(clusterKey));
289
//   if (ppAppInstInfo != NULL && *ppAppInstInfo != NULL) {
290
//     return *ppAppInstInfo;
291
//   } else {
292
//     return NULL;
293
//   }
294
// }
295

296
void freeQueryParam(SSyncQueryParam* param) {
587,642✔
297
  if (param == NULL) return;
587,642✔
298
  if (TSDB_CODE_SUCCESS != tsem_destroy(&param->sem)) {
587,642✔
299
    tscError("failed to destroy semaphore in freeQueryParam");
×
300
  }
301
  taosMemoryFree(param);
587,642✔
302
}
303

304
int32_t buildRequest(uint64_t connId, const char* sql, int sqlLen, void* param, bool validateSql,
950,479,235✔
305
                     SRequestObj** pRequest, int64_t reqid) {
306
  int32_t code = createRequest(connId, TSDB_SQL_SELECT, reqid, pRequest);
950,479,235✔
307
  if (TSDB_CODE_SUCCESS != code) {
950,483,478✔
308
    tscError("failed to malloc sqlObj, %s", sql);
×
309
    return code;
×
310
  }
311

312
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
950,483,478✔
313
  if ((*pRequest)->sqlstr == NULL) {
950,485,563✔
314
    tscError("req:0x%" PRIx64 ", failed to prepare sql string buffer, %s", (*pRequest)->self, sql);
×
315
    destroyRequest(*pRequest);
×
316
    *pRequest = NULL;
×
317
    return terrno;
×
318
  }
319

320
  (void)strntolower((*pRequest)->sqlstr, sql, (int32_t)sqlLen);
950,483,474✔
321
  (*pRequest)->sqlstr[sqlLen] = 0;
950,492,633✔
322
  (*pRequest)->sqlLen = sqlLen;
950,490,966✔
323
  (*pRequest)->validateOnly = validateSql;
950,492,557✔
324
  (*pRequest)->stmtBindVersion = 0;
950,490,202✔
325

326
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
950,490,878✔
327

328
  STscObj* pTscObj = (*pRequest)->pTscObj;
950,489,223✔
329
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
950,487,868✔
330
                             sizeof((*pRequest)->self));
331
  if (err) {
950,494,669✔
332
    tscError("req:0x%" PRId64 ", failed to add to request container, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
333
             (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
334
    destroyRequest(*pRequest);
×
335
    *pRequest = NULL;
×
336
    return terrno;
×
337
  }
338

339
  (*pRequest)->allocatorRefId = -1;
950,494,669✔
340
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
950,495,402✔
341
    if (TSDB_CODE_SUCCESS !=
440,241,981✔
342
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
440,239,186✔
343
      tscError("req:0x%" PRId64 ", failed to create node allocator, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
344
               (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
345
      destroyRequest(*pRequest);
×
346
      *pRequest = NULL;
×
347
      return terrno;
×
348
    }
349
  }
350

351
  tscDebug("req:0x%" PRIx64 ", build request, QID:0x%" PRIx64, (*pRequest)->self, (*pRequest)->requestId);
950,500,457✔
352
  return TSDB_CODE_SUCCESS;
950,491,512✔
353
}
354

355
int32_t buildPreviousRequest(SRequestObj* pRequest, const char* sql, SRequestObj** pNewRequest) {
×
356
  int32_t code =
357
      buildRequest(pRequest->pTscObj->id, sql, strlen(sql), pRequest, pRequest->validateOnly, pNewRequest, 0);
×
358
  if (TSDB_CODE_SUCCESS == code) {
×
359
    pRequest->relation.prevRefId = (*pNewRequest)->self;
×
360
    (*pNewRequest)->relation.nextRefId = pRequest->self;
×
361
    (*pNewRequest)->relation.userRefId = pRequest->self;
×
362
    (*pNewRequest)->isSubReq = true;
×
363
  }
364
  return code;
×
365
}
366

367
int32_t parseSql(SRequestObj* pRequest, bool topicQuery, SQuery** pQuery, SStmtCallback* pStmtCb) {
6,938,971✔
368
  STscObj* pTscObj = pRequest->pTscObj;
6,938,971✔
369

370
  SParseContext cxt = {
6,939,655✔
371
      .requestId = pRequest->requestId,
6,938,042✔
372
      .requestRid = pRequest->self,
6,939,990✔
373
      .acctId = pTscObj->acctId,
6,939,684✔
374
      .db = pRequest->pDb,
6,937,610✔
375
      .topicQuery = topicQuery,
376
      .pSql = pRequest->sqlstr,
6,937,059✔
377
      .sqlLen = pRequest->sqlLen,
6,937,358✔
378
      .pMsg = pRequest->msgBuf,
6,936,681✔
379
      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
380
      .pTransporter = pTscObj->pAppInfo->pTransporter,
6,937,639✔
381
      .pStmtCb = pStmtCb,
382
      .pUser = pTscObj->user,
6,937,624✔
383
      .userId = pTscObj->userId,
6,937,581✔
384
      .isSuperUser = (0 == strcmp(pTscObj->user, TSDB_DEFAULT_USER)),
6,937,531✔
385
      .enableSysInfo = pTscObj->sysInfo,
6,936,933✔
386
      .svrVer = pTscObj->sVer,
6,935,529✔
387
      .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes),
6,939,990✔
388
      .stmtBindVersion = pRequest->stmtBindVersion,
6,937,959✔
389
      .setQueryFp = setQueryRequest,
390
      .timezone = pTscObj->optionInfo.timezone,
6,935,291✔
391
      .charsetCxt = pTscObj->optionInfo.charsetCxt,
6,937,232✔
392
  };
393

394
  cxt.mgmtEpSet = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
6,937,588✔
395
  int32_t code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &cxt.pCatalog);
6,939,641✔
396
  if (code != TSDB_CODE_SUCCESS) {
6,938,971✔
397
    return code;
×
398
  }
399

400
  code = qParseSql(&cxt, pQuery);
6,938,971✔
401
  if (TSDB_CODE_SUCCESS == code) {
6,935,294✔
402
    if ((*pQuery)->haveResultSet) {
6,930,170✔
403
      code = setResSchemaInfo(&pRequest->body.resInfo, (*pQuery)->pResSchema, (*pQuery)->numOfResCols,
×
404
                              (*pQuery)->pResExtSchema, pRequest->stmtBindVersion > 0);
×
405
      setResPrecision(&pRequest->body.resInfo, (*pQuery)->precision);
×
406
    }
407
  }
408

409
  if (TSDB_CODE_SUCCESS == code || NEED_CLIENT_HANDLE_ERROR(code)) {
6,933,569✔
410
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
6,928,939✔
411
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
6,934,719✔
412
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
6,932,332✔
413
  }
414

415
  taosArrayDestroy(cxt.pTableMetaPos);
6,933,212✔
416
  taosArrayDestroy(cxt.pTableVgroupPos);
6,926,671✔
417

418
  return code;
6,924,914✔
419
}
420

421
int32_t execLocalCmd(SRequestObj* pRequest, SQuery* pQuery) {
×
422
  SRetrieveTableRsp* pRsp = NULL;
×
423
  int8_t             biMode = atomic_load_8(&pRequest->pTscObj->biMode);
×
424
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp, biMode,
×
425
                              pRequest->pTscObj->optionInfo.charsetCxt);
×
426
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
×
427
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4,
×
428
                                 pRequest->stmtBindVersion > 0);
×
429
  }
430

431
  return code;
×
432
}
433

434
int32_t execDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
372,581✔
435
  // drop table if exists not_exists_table
436
  if (NULL == pQuery->pCmdMsg) {
372,581✔
437
    return TSDB_CODE_SUCCESS;
×
438
  }
439

440
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
372,581✔
441
  pRequest->type = pMsgInfo->msgType;
372,581✔
442
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
372,581✔
443
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
372,581✔
444

445
  STscObj*      pTscObj = pRequest->pTscObj;
372,581✔
446
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
372,581✔
447

448
  // int64_t transporterId = 0;
449
  TSC_ERR_RET(asyncSendMsgToServer(pTscObj->pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg));
372,581✔
450
  TSC_ERR_RET(tsem_wait(&pRequest->body.rspSem));
372,581✔
451
  return TSDB_CODE_SUCCESS;
372,581✔
452
}
453

454
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
1,563,396,563✔
455

456
void asyncExecLocalCmd(SRequestObj* pRequest, SQuery* pQuery) {
5,778,142✔
457
  SRetrieveTableRsp* pRsp = NULL;
5,778,142✔
458
  if (pRequest->validateOnly) {
5,778,142✔
459
    doRequestCallback(pRequest, 0);
10,125✔
460
    return;
10,125✔
461
  }
462

463
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp,
11,507,489✔
464
                              atomic_load_8(&pRequest->pTscObj->biMode), pRequest->pTscObj->optionInfo.charsetCxt);
11,507,489✔
465
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
5,768,017✔
466
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4,
3,182,328✔
467
                                 pRequest->stmtBindVersion > 0);
3,182,328✔
468
  }
469

470
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
5,768,017✔
471
  pRequest->code = code;
5,768,017✔
472

473
  if (pRequest->code != TSDB_CODE_SUCCESS) {
5,768,017✔
474
    pResultInfo->numOfRows = 0;
1,743✔
475
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
1,743✔
476
             pRequest->requestId);
477
  } else {
478
    tscDebug(
5,766,274✔
479
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
480
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
481
  }
482

483
  doRequestCallback(pRequest, code);
5,768,017✔
484
}
485

486
int32_t asyncExecDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
98,424,617✔
487
  if (pRequest->validateOnly) {
98,424,617✔
488
    doRequestCallback(pRequest, 0);
×
489
    return TSDB_CODE_SUCCESS;
×
490
  }
491

492
  // drop table if exists not_exists_table
493
  if (NULL == pQuery->pCmdMsg) {
98,424,706✔
494
    doRequestCallback(pRequest, 0);
6,599✔
495
    return TSDB_CODE_SUCCESS;
6,599✔
496
  }
497

498
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
98,417,688✔
499
  pRequest->type = pMsgInfo->msgType;
98,418,060✔
500
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
98,418,101✔
501
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
98,417,977✔
502

503
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
98,418,019✔
504
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
98,417,104✔
505

506
  int32_t code = asyncSendMsgToServer(pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg);
98,419,763✔
507
  if (code) {
98,423,157✔
508
    doRequestCallback(pRequest, code);
×
509
  }
510
  return code;
98,424,588✔
511
}
512

513
int compareQueryNodeLoad(const void* elem1, const void* elem2) {
128,993✔
514
  SQueryNodeLoad* node1 = (SQueryNodeLoad*)elem1;
128,993✔
515
  SQueryNodeLoad* node2 = (SQueryNodeLoad*)elem2;
128,993✔
516

517
  if (node1->load < node2->load) {
128,993✔
518
    return -1;
×
519
  }
520

521
  return node1->load > node2->load;
128,993✔
522
}
523

524
int32_t updateQnodeList(SAppInstInfo* pInfo, SArray* pNodeList) {
355,004✔
525
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
355,004✔
526
  if (pInfo->pQnodeList) {
355,004✔
527
    taosArrayDestroy(pInfo->pQnodeList);
350,312✔
528
    pInfo->pQnodeList = NULL;
350,312✔
529
    tscDebug("QnodeList cleared in cluster 0x%" PRIx64, pInfo->clusterId);
350,312✔
530
  }
531

532
  if (pNodeList) {
355,004✔
533
    pInfo->pQnodeList = taosArrayDup(pNodeList, NULL);
355,004✔
534
    taosArraySort(pInfo->pQnodeList, compareQueryNodeLoad);
355,004✔
535
    tscDebug("QnodeList updated in cluster 0x%" PRIx64 ", num:%ld", pInfo->clusterId,
355,004✔
536
             taosArrayGetSize(pInfo->pQnodeList));
537
  }
538
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
355,004✔
539

540
  return TSDB_CODE_SUCCESS;
355,004✔
541
}
542

543
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
944,435,733✔
544
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
944,435,733✔
545
    *required = false;
932,336,920✔
546
    return TSDB_CODE_SUCCESS;
932,331,615✔
547
  }
548

549
  int32_t       code = TSDB_CODE_SUCCESS;
12,098,813✔
550
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
12,098,813✔
551
  *required = false;
12,098,813✔
552

553
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
12,098,813✔
554
  *required = (NULL == pInfo->pQnodeList);
12,098,813✔
555
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
12,098,813✔
556
  return TSDB_CODE_SUCCESS;
12,098,813✔
557
}
558

559
int32_t getQnodeList(SRequestObj* pRequest, SArray** pNodeList) {
×
560
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
×
561
  int32_t       code = 0;
×
562

563
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
×
564
  if (pInfo->pQnodeList) {
×
565
    *pNodeList = taosArrayDup(pInfo->pQnodeList, NULL);
×
566
  }
567
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
×
568
  if (NULL == *pNodeList) {
×
569
    SCatalog* pCatalog = NULL;
×
570
    code = catalogGetHandle(pRequest->pTscObj->pAppInfo->clusterId, &pCatalog);
×
571
    if (TSDB_CODE_SUCCESS == code) {
×
572
      *pNodeList = taosArrayInit(5, sizeof(SQueryNodeLoad));
×
573
      if (NULL == pNodeList) {
×
574
        TSC_ERR_RET(terrno);
×
575
      }
576
      SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
×
577
                               .requestId = pRequest->requestId,
×
578
                               .requestObjRefId = pRequest->self,
×
579
                               .mgmtEps = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp)};
×
580
      code = catalogGetQnodeList(pCatalog, &conn, *pNodeList);
×
581
    }
582

583
    if (TSDB_CODE_SUCCESS == code && *pNodeList) {
×
584
      code = updateQnodeList(pInfo, *pNodeList);
×
585
    }
586
  }
587

588
  return code;
×
589
}
590

591
int32_t getPlan(SRequestObj* pRequest, SQuery* pQuery, SQueryPlan** pPlan, SArray* pNodeList) {
8,128,305✔
592
  pRequest->type = pQuery->msgType;
8,128,305✔
593
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
8,126,314✔
594

595
  SPlanContext cxt = {.queryId = pRequest->requestId,
8,527,477✔
596
                      .acctId = pRequest->pTscObj->acctId,
8,129,243✔
597
                      .mgmtEpSet = getEpSet_s(&pAppInfo->mgmtEp),
8,129,229✔
598
                      .pAstRoot = pQuery->pRoot,
8,131,675✔
599
                      .showRewrite = pQuery->showRewrite,
8,131,788✔
600
                      .pMsg = pRequest->msgBuf,
8,130,448✔
601
                      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
602
                      .pUser = pRequest->pTscObj->user,
8,122,588✔
603
                      .userId = pRequest->pTscObj->userId,
8,125,031✔
604
                      .timezone = pRequest->pTscObj->optionInfo.timezone,
8,124,558✔
605
                      .sysInfo = pRequest->pTscObj->sysInfo};
8,125,905✔
606

607
  return qCreateQueryPlan(&cxt, pPlan, pNodeList);
8,125,352✔
608
}
609

610
int32_t setResSchemaInfo(SReqResultInfo* pResInfo, const SSchema* pSchema, int32_t numOfCols,
246,810,446✔
611
                         const SExtSchema* pExtSchema, bool isStmt) {
612
  if (pResInfo == NULL || pSchema == NULL || numOfCols <= 0) {
246,810,446✔
613
    tscError("invalid paras, pResInfo == NULL || pSchema == NULL || numOfCols <= 0");
10✔
614
    return TSDB_CODE_INVALID_PARA;
×
615
  }
616

617
  pResInfo->numOfCols = numOfCols;
246,821,243✔
618
  if (pResInfo->fields != NULL) {
246,820,775✔
619
    taosMemoryFree(pResInfo->fields);
16,404✔
620
  }
621
  if (pResInfo->userFields != NULL) {
246,819,611✔
622
    taosMemoryFree(pResInfo->userFields);
16,404✔
623
  }
624
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD_E));
246,819,922✔
625
  if (NULL == pResInfo->fields) return terrno;
246,808,801✔
626
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
246,811,001✔
627
  if (NULL == pResInfo->userFields) {
246,812,931✔
628
    taosMemoryFree(pResInfo->fields);
×
629
    return terrno;
×
630
  }
631
  if (numOfCols != pResInfo->numOfCols) {
246,813,277✔
632
    tscError("numOfCols:%d != pResInfo->numOfCols:%d", numOfCols, pResInfo->numOfCols);
×
633
    return TSDB_CODE_FAILED;
×
634
  }
635

636
  for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
1,220,778,249✔
637
    pResInfo->fields[i].type = pSchema[i].type;
973,950,034✔
638

639
    pResInfo->userFields[i].type = pSchema[i].type;
973,951,421✔
640
    // userFields must convert to type bytes, no matter isStmt or not
641
    pResInfo->userFields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, false);
973,952,203✔
642
    pResInfo->fields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, isStmt);
973,949,974✔
643
    if (IS_DECIMAL_TYPE(pSchema[i].type) && pExtSchema) {
973,957,078✔
644
      decimalFromTypeMod(pExtSchema[i].typeMod, &pResInfo->fields[i].precision, &pResInfo->fields[i].scale);
1,770,744✔
645
    }
646

647
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
973,964,977✔
648
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
973,965,769✔
649
  }
650
  return TSDB_CODE_SUCCESS;
246,829,530✔
651
}
652

653
void setResPrecision(SReqResultInfo* pResInfo, int32_t precision) {
192,730,976✔
654
  if (precision != TSDB_TIME_PRECISION_MILLI && precision != TSDB_TIME_PRECISION_MICRO &&
192,730,976✔
655
      precision != TSDB_TIME_PRECISION_NANO) {
656
    return;
×
657
  }
658

659
  pResInfo->precision = precision;
192,730,976✔
660
}
661

662
int32_t buildVnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pDbVgList) {
196,826,238✔
663
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
196,826,238✔
664
  if (NULL == nodeList) {
196,833,195✔
665
    return terrno;
×
666
  }
667
  char* policy = (tsQueryPolicy == QUERY_POLICY_VNODE) ? "vnode" : "client";
196,835,327✔
668

669
  int32_t dbNum = taosArrayGetSize(pDbVgList);
196,835,327✔
670
  for (int32_t i = 0; i < dbNum; ++i) {
391,422,160✔
671
    SArray* pVg = taosArrayGetP(pDbVgList, i);
194,559,294✔
672
    if (NULL == pVg) {
194,563,280✔
673
      continue;
×
674
    }
675
    int32_t vgNum = taosArrayGetSize(pVg);
194,563,280✔
676
    if (vgNum <= 0) {
194,565,546✔
677
      continue;
567,209✔
678
    }
679

680
    for (int32_t j = 0; j < vgNum; ++j) {
659,826,079✔
681
      SVgroupInfo* pInfo = taosArrayGet(pVg, j);
465,818,012✔
682
      if (NULL == pInfo) {
465,832,855✔
683
        taosArrayDestroy(nodeList);
×
684
        return TSDB_CODE_OUT_OF_RANGE;
×
685
      }
686
      SQueryNodeLoad load = {0};
465,832,855✔
687
      load.addr.nodeId = pInfo->vgId;
465,831,062✔
688
      load.addr.epSet = pInfo->epSet;
465,846,195✔
689

690
      if (NULL == taosArrayPush(nodeList, &load)) {
465,781,194✔
691
        taosArrayDestroy(nodeList);
×
692
        return terrno;
×
693
      }
694
    }
695
  }
696

697
  int32_t vnodeNum = taosArrayGetSize(nodeList);
196,862,866✔
698
  if (vnodeNum > 0) {
196,858,649✔
699
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
193,695,064✔
700
    goto _return;
193,699,092✔
701
  }
702

703
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
3,163,585✔
704
  if (mnodeNum <= 0) {
3,155,607✔
705
    tscDebug("0x%" PRIx64 " %s policy, empty node list", pRequest->requestId, policy);
×
706
    goto _return;
×
707
  }
708

709
  void* pData = taosArrayGet(pMnodeList, 0);
3,155,607✔
710
  if (NULL == pData) {
3,155,607✔
711
    taosArrayDestroy(nodeList);
×
712
    return TSDB_CODE_OUT_OF_RANGE;
×
713
  }
714
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
3,155,607✔
715
    taosArrayDestroy(nodeList);
×
716
    return terrno;
×
717
  }
718

719
  tscDebug("0x%" PRIx64 " %s policy, use mnode list, num:%d", pRequest->requestId, policy, mnodeNum);
3,155,607✔
720

721
_return:
29,827✔
722

723
  *pNodeList = nodeList;
196,848,273✔
724

725
  return TSDB_CODE_SUCCESS;
196,844,233✔
726
}
727

728
int32_t buildQnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pQnodeList) {
1,527,020✔
729
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
1,527,020✔
730
  if (NULL == nodeList) {
1,527,020✔
731
    return terrno;
×
732
  }
733

734
  int32_t qNodeNum = taosArrayGetSize(pQnodeList);
1,527,020✔
735
  if (qNodeNum > 0) {
1,527,020✔
736
    void* pData = taosArrayGet(pQnodeList, 0);
1,505,856✔
737
    if (NULL == pData) {
1,505,856✔
738
      taosArrayDestroy(nodeList);
×
739
      return TSDB_CODE_OUT_OF_RANGE;
×
740
    }
741
    if (NULL == taosArrayAddBatch(nodeList, pData, qNodeNum)) {
1,505,856✔
742
      taosArrayDestroy(nodeList);
×
743
      return terrno;
×
744
    }
745
    tscDebug("0x%" PRIx64 " qnode policy, use qnode list, num:%d", pRequest->requestId, qNodeNum);
1,505,856✔
746
    goto _return;
1,505,856✔
747
  }
748

749
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
21,164✔
750
  if (mnodeNum <= 0) {
21,164✔
751
    tscDebug("0x%" PRIx64 " qnode policy, empty node list", pRequest->requestId);
×
752
    goto _return;
×
753
  }
754

755
  void* pData = taosArrayGet(pMnodeList, 0);
21,164✔
756
  if (NULL == pData) {
21,164✔
757
    taosArrayDestroy(nodeList);
×
758
    return TSDB_CODE_OUT_OF_RANGE;
×
759
  }
760
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
21,164✔
761
    taosArrayDestroy(nodeList);
×
762
    return terrno;
×
763
  }
764

765
  tscDebug("0x%" PRIx64 " qnode policy, use mnode list, num:%d", pRequest->requestId, mnodeNum);
21,164✔
766

767
_return:
×
768

769
  *pNodeList = nodeList;
1,527,020✔
770

771
  return TSDB_CODE_SUCCESS;
1,527,020✔
772
}
773

774
void freeVgList(void* list) {
8,099,089✔
775
  SArray* pList = *(SArray**)list;
8,099,089✔
776
  taosArrayDestroy(pList);
8,101,799✔
777
}
8,093,223✔
778

779
int32_t buildAsyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SMetaData* pResultMeta) {
190,231,137✔
780
  SArray* pDbVgList = NULL;
190,231,137✔
781
  SArray* pQnodeList = NULL;
190,231,137✔
782
  FDelete fp = NULL;
190,231,137✔
783
  int32_t code = 0;
190,231,137✔
784

785
  switch (tsQueryPolicy) {
190,231,137✔
786
    case QUERY_POLICY_VNODE:
188,712,570✔
787
    case QUERY_POLICY_CLIENT: {
788
      if (pResultMeta) {
188,712,570✔
789
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
188,717,831✔
790
        if (NULL == pDbVgList) {
188,708,280✔
791
          code = terrno;
×
792
          goto _return;
×
793
        }
794
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
188,708,280✔
795
        for (int32_t i = 0; i < dbNum; ++i) {
375,172,111✔
796
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
186,454,660✔
797
          if (pRes->code || NULL == pRes->pRes) {
186,455,117✔
798
            continue;
545✔
799
          }
800

801
          if (NULL == taosArrayPush(pDbVgList, &pRes->pRes)) {
372,919,725✔
802
            code = terrno;
×
803
            goto _return;
×
804
          }
805
        }
806
      } else {
807
        fp = freeVgList;
1,737✔
808

809
        int32_t dbNum = taosArrayGetSize(pRequest->dbList);
1,737✔
810
        if (dbNum > 0) {
1,710✔
811
          SCatalog*     pCtg = NULL;
1,710✔
812
          SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
1,710✔
813
          code = catalogGetHandle(pInst->clusterId, &pCtg);
1,710✔
814
          if (code != TSDB_CODE_SUCCESS) {
1,710✔
815
            goto _return;
×
816
          }
817

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

831
            // catalogGetDBVgList will handle dbFName == null.
832
            code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
1,710✔
833
            if (code) {
1,710✔
834
              goto _return;
×
835
            }
836

837
            if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
1,710✔
838
              code = terrno;
×
839
              goto _return;
×
840
            }
841
          }
842
        }
843
      }
844

845
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
188,719,161✔
846
      break;
188,714,320✔
847
    }
848
    case QUERY_POLICY_HYBRID:
1,527,020✔
849
    case QUERY_POLICY_QNODE: {
850
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
1,559,592✔
851
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
32,572✔
852
        if (pRes->code) {
32,572✔
853
          pQnodeList = NULL;
×
854
        } else {
855
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
32,572✔
856
          if (NULL == pQnodeList) {
32,572✔
857
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
858
            goto _return;
×
859
          }
860
        }
861
      } else {
862
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
1,494,448✔
863
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
1,494,448✔
864
        if (pInst->pQnodeList) {
1,494,448✔
865
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
1,494,448✔
866
          if (NULL == pQnodeList) {
1,494,448✔
867
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
868
            goto _return;
×
869
          }
870
        }
871
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
1,494,448✔
872
      }
873

874
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
1,527,020✔
875
      break;
1,527,020✔
876
    }
877
    default:
523✔
878
      tscError("unknown query policy: %d", tsQueryPolicy);
523✔
879
      return TSDB_CODE_APP_ERROR;
×
880
  }
881

882
_return:
190,241,340✔
883
  taosArrayDestroyEx(pDbVgList, fp);
190,241,340✔
884
  taosArrayDestroy(pQnodeList);
190,241,529✔
885

886
  return code;
190,246,737✔
887
}
888

889
int32_t buildSyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList) {
8,121,163✔
890
  SArray* pDbVgList = NULL;
8,121,163✔
891
  SArray* pQnodeList = NULL;
8,121,163✔
892
  int32_t code = 0;
8,125,515✔
893

894
  switch (tsQueryPolicy) {
8,125,515✔
895
    case QUERY_POLICY_VNODE:
8,111,116✔
896
    case QUERY_POLICY_CLIENT: {
897
      int32_t dbNum = taosArrayGetSize(pRequest->dbList);
8,111,116✔
898
      if (dbNum > 0) {
8,125,521✔
899
        SCatalog*     pCtg = NULL;
8,095,409✔
900
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
8,093,791✔
901
        code = catalogGetHandle(pInst->clusterId, &pCtg);
8,090,977✔
902
        if (code != TSDB_CODE_SUCCESS) {
8,091,713✔
903
          goto _return;
×
904
        }
905

906
        pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
8,091,713✔
907
        if (NULL == pDbVgList) {
8,097,050✔
908
          code = terrno;
156✔
909
          goto _return;
×
910
        }
911
        SArray* pVgList = NULL;
8,096,894✔
912
        for (int32_t i = 0; i < dbNum; ++i) {
16,188,582✔
913
          char*            dbFName = taosArrayGet(pRequest->dbList, i);
8,095,567✔
914
          SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
8,097,460✔
915
                                   .requestId = pRequest->requestId,
8,099,036✔
916
                                   .requestObjRefId = pRequest->self,
8,095,332✔
917
                                   .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
8,090,976✔
918

919
          // catalogGetDBVgList will handle dbFName == null.
920
          code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
8,103,212✔
921
          if (code) {
8,094,404✔
922
            goto _return;
×
923
          }
924

925
          if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
8,100,949✔
926
            code = terrno;
×
927
            goto _return;
×
928
          }
929
        }
930
      }
931

932
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
8,127,451✔
933
      break;
8,126,393✔
934
    }
935
    case QUERY_POLICY_HYBRID:
×
936
    case QUERY_POLICY_QNODE: {
937
      TSC_ERR_JRET(getQnodeList(pRequest, &pQnodeList));
×
938

939
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
×
940
      break;
×
941
    }
942
    default:
14,503✔
943
      tscError("unknown query policy: %d", tsQueryPolicy);
14,503✔
944
      return TSDB_CODE_APP_ERROR;
×
945
  }
946

947
_return:
8,129,834✔
948

949
  taosArrayDestroyEx(pDbVgList, freeVgList);
8,127,083✔
950
  taosArrayDestroy(pQnodeList);
8,122,599✔
951

952
  return code;
8,126,075✔
953
}
954

955
int32_t scheduleQuery(SRequestObj* pRequest, SQueryPlan* pDag, SArray* pNodeList) {
8,125,367✔
956
  void* pTransporter = pRequest->pTscObj->pAppInfo->pTransporter;
8,125,367✔
957

958
  SExecResult      res = {0};
8,131,849✔
959
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
8,127,360✔
960
                           .requestId = pRequest->requestId,
8,129,825✔
961
                           .requestObjRefId = pRequest->self};
8,125,281✔
962
  SSchedulerReq    req = {
8,518,248✔
963
         .syncReq       = true,
964
         .localReq      = (tsQueryPolicy == QUERY_POLICY_CLIENT),
8,124,605✔
965
         .pConn         = &conn,
966
         .pNodeList     = pNodeList,
967
         .pDag          = pDag,
968
         .sql           = pRequest->sqlstr,
8,124,605✔
969
         .startTs       = pRequest->metric.start,
8,128,509✔
970
         .execFp        = NULL,
971
         .cbParam       = NULL,
972
         .chkKillFp     = chkRequestKilled,
973
         .chkKillParam  = (void*)pRequest->self,
8,119,563✔
974
         .pExecRes      = &res,
975
         .source        = pRequest->source,
8,124,637✔
976
         .secureDelete  = pRequest->secureDelete,
8,122,019✔
977
         .pWorkerCb     = getTaskPoolWorkerCb(),
8,127,526✔
978
  };
979

980
  int32_t code = schedulerExecJob(&req, &pRequest->body.queryJob);
8,122,891✔
981

982
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
8,133,568✔
983
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
8,134,014✔
984

985
  if (code != TSDB_CODE_SUCCESS) {
8,132,912✔
986
    schedulerFreeJob(&pRequest->body.queryJob, 0);
×
987

988
    pRequest->code = code;
×
989
    terrno = code;
×
990
    return pRequest->code;
×
991
  }
992

993
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_DELETE == pRequest->type ||
8,132,912✔
994
      TDMT_VND_CREATE_TABLE == pRequest->type) {
26,141✔
995
    pRequest->body.resInfo.numOfRows = res.numOfRows;
8,115,733✔
996
    if (TDMT_VND_SUBMIT == pRequest->type) {
8,116,369✔
997
      STscObj*            pTscObj = pRequest->pTscObj;
8,105,325✔
998
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
8,105,746✔
999
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
8,108,560✔
1000
    }
1001

1002
    schedulerFreeJob(&pRequest->body.queryJob, 0);
8,117,219✔
1003
  }
1004

1005
  pRequest->code = res.code;
8,133,343✔
1006
  terrno = res.code;
8,134,062✔
1007
  return pRequest->code;
8,131,510✔
1008
}
1009

1010
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
510,152,633✔
1011
  SArray*      pArray = NULL;
510,152,633✔
1012
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
510,152,633✔
1013
  if (NULL == pRsp->aCreateTbRsp) {
510,152,633✔
1014
    return TSDB_CODE_SUCCESS;
497,795,284✔
1015
  }
1016

1017
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
12,362,561✔
1018
  for (int32_t i = 0; i < tbNum; ++i) {
27,665,739✔
1019
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
15,302,789✔
1020
    if (pTbRsp->pMeta) {
15,304,136✔
1021
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
15,021,218✔
1022
    }
1023
  }
1024

1025
  return TSDB_CODE_SUCCESS;
12,362,950✔
1026
}
1027

1028
int32_t handleQueryExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
151,400,634✔
1029
  int32_t code = 0;
151,400,634✔
1030
  SArray* pArray = NULL;
151,400,634✔
1031
  SArray* pTbArray = (SArray*)res;
151,400,634✔
1032
  int32_t tbNum = taosArrayGetSize(pTbArray);
151,400,634✔
1033
  if (tbNum <= 0) {
151,401,758✔
1034
    return TSDB_CODE_SUCCESS;
×
1035
  }
1036

1037
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
151,401,758✔
1038
  if (NULL == pArray) {
151,402,223✔
1039
    return terrno;
320✔
1040
  }
1041

1042
  for (int32_t i = 0; i < tbNum; ++i) {
488,195,184✔
1043
    STbVerInfo* tbInfo = taosArrayGet(pTbArray, i);
336,791,240✔
1044
    if (NULL == tbInfo) {
336,791,202✔
1045
      code = terrno;
×
1046
      goto _return;
×
1047
    }
1048
    STbSVersion tbSver = {
336,791,202✔
1049
        .tbFName = tbInfo->tbFName, .sver = tbInfo->sversion, .tver = tbInfo->tversion, .rver = tbInfo->rversion};
336,791,193✔
1050
    if (NULL == taosArrayPush(pArray, &tbSver)) {
336,793,321✔
1051
      code = terrno;
×
1052
      goto _return;
×
1053
    }
1054
  }
1055

1056
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
151,403,944✔
1057
                           .requestId = pRequest->requestId,
151,404,006✔
1058
                           .requestObjRefId = pRequest->self,
151,403,572✔
1059
                           .mgmtEps = *epset};
1060

1061
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
151,403,553✔
1062

1063
_return:
151,401,725✔
1064

1065
  taosArrayDestroy(pArray);
151,401,748✔
1066
  return code;
151,402,480✔
1067
}
1068

1069
int32_t handleAlterTbExecRes(void* res, SCatalog* pCatalog) {
8,354,248✔
1070
  return catalogUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
8,354,248✔
1071
}
1072

1073
int32_t handleCreateTbExecRes(void* res, SCatalog* pCatalog) {
65,402,870✔
1074
  return catalogAsyncUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
65,402,870✔
1075
}
1076

1077
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
758,080,470✔
1078
  if (NULL == pRequest->body.resInfo.execRes.res) {
758,080,470✔
1079
    return pRequest->code;
50,854,569✔
1080
  }
1081

1082
  SCatalog*     pCatalog = NULL;
707,215,059✔
1083
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
707,221,549✔
1084

1085
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
707,233,026✔
1086
  if (code) {
707,228,131✔
1087
    return code;
×
1088
  }
1089

1090
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
707,228,131✔
1091
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
707,234,089✔
1092

1093
  switch (pRes->msgType) {
707,234,401✔
1094
    case TDMT_VND_ALTER_TABLE:
3,773,207✔
1095
    case TDMT_MND_ALTER_STB: {
1096
      code = handleAlterTbExecRes(pRes->res, pCatalog);
3,773,207✔
1097
      break;
3,773,207✔
1098
    }
1099
    case TDMT_VND_CREATE_TABLE: {
41,530,969✔
1100
      SArray* pList = (SArray*)pRes->res;
41,530,969✔
1101
      int32_t num = taosArrayGetSize(pList);
41,533,451✔
1102
      for (int32_t i = 0; i < num; ++i) {
90,052,396✔
1103
        void* res = taosArrayGetP(pList, i);
48,516,471✔
1104
        // handleCreateTbExecRes will handle res == null
1105
        code = handleCreateTbExecRes(res, pCatalog);
48,520,977✔
1106
      }
1107
      break;
41,535,925✔
1108
    }
1109
    case TDMT_MND_CREATE_STB: {
366,987✔
1110
      code = handleCreateTbExecRes(pRes->res, pCatalog);
366,987✔
1111
      break;
366,987✔
1112
    }
1113
    case TDMT_VND_SUBMIT: {
510,153,423✔
1114
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
510,153,423✔
1115

1116
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
510,160,244✔
1117
      break;
510,156,143✔
1118
    }
1119
    case TDMT_SCH_QUERY:
151,401,465✔
1120
    case TDMT_SCH_MERGE_QUERY: {
1121
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
151,401,465✔
1122
      break;
151,400,370✔
1123
    }
1124
    default:
1,663✔
1125
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self,
1,663✔
1126
               pRequest->type, pRequest->requestId);
1127
      code = TSDB_CODE_APP_ERROR;
×
1128
  }
1129

1130
  return code;
707,232,632✔
1131
}
1132

1133
static bool incompletaFileParsing(SNode* pStmt) {
737,209,010✔
1134
  return QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pStmt) ? false : ((SVnodeModifyOpStmt*)pStmt)->fileProcessing;
737,209,010✔
1135
}
1136

1137
void continuePostSubQuery(SRequestObj* pRequest, SSDataBlock* pBlock) {
×
1138
  SSqlCallbackWrapper* pWrapper = pRequest->pWrapper;
×
1139

1140
  int32_t code = nodesAcquireAllocator(pWrapper->pParseCtx->allocatorId);
×
1141
  if (TSDB_CODE_SUCCESS == code) {
×
1142
    int64_t analyseStart = taosGetTimestampUs();
×
1143
    code = qContinueParsePostQuery(pWrapper->pParseCtx, pRequest->pQuery, pBlock);
×
1144
    pRequest->metric.analyseCostUs += taosGetTimestampUs() - analyseStart;
×
1145
  }
1146

1147
  if (TSDB_CODE_SUCCESS == code) {
×
1148
    code = qContinuePlanPostQuery(pRequest->pPostPlan);
×
1149
  }
1150

1151
  code = nodesReleaseAllocator(pWrapper->pParseCtx->allocatorId);
×
1152
  handleQueryAnslyseRes(pWrapper, NULL, code);
×
1153
}
×
1154

1155
void returnToUser(SRequestObj* pRequest) {
72,138,375✔
1156
  if (pRequest->relation.userRefId == pRequest->self || 0 == pRequest->relation.userRefId) {
72,138,375✔
1157
    // return to client
1158
    doRequestCallback(pRequest, pRequest->code);
72,138,375✔
1159
    return;
72,135,985✔
1160
  }
1161

1162
  SRequestObj* pUserReq = acquireRequest(pRequest->relation.userRefId);
×
1163
  if (pUserReq) {
×
1164
    pUserReq->code = pRequest->code;
×
1165
    // return to client
1166
    doRequestCallback(pUserReq, pUserReq->code);
×
1167
    (void)releaseRequest(pRequest->relation.userRefId);
×
1168
    return;
×
1169
  } else {
1170
    tscError("req:0x%" PRIx64 ", user ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1171
             pRequest->relation.userRefId, pRequest->requestId);
1172
  }
1173
}
1174

1175
static int32_t createResultBlock(TAOS_RES* pRes, int32_t numOfRows, SSDataBlock** pBlock) {
×
1176
  int64_t     lastTs = 0;
×
1177
  TAOS_FIELD* pResFields = taos_fetch_fields(pRes);
×
1178
  int32_t     numOfFields = taos_num_fields(pRes);
×
1179

1180
  int32_t code = createDataBlock(pBlock);
×
1181
  if (code) {
×
1182
    return code;
×
1183
  }
1184

1185
  for (int32_t i = 0; i < numOfFields; ++i) {
×
1186
    SColumnInfoData colInfoData = createColumnInfoData(pResFields[i].type, pResFields[i].bytes, i + 1);
×
1187
    code = blockDataAppendColInfo(*pBlock, &colInfoData);
×
1188
    if (TSDB_CODE_SUCCESS != code) {
×
1189
      blockDataDestroy(*pBlock);
×
1190
      return code;
×
1191
    }
1192
  }
1193

1194
  code = blockDataEnsureCapacity(*pBlock, numOfRows);
×
1195
  if (TSDB_CODE_SUCCESS != code) {
×
1196
    blockDataDestroy(*pBlock);
×
1197
    return code;
×
1198
  }
1199

1200
  for (int32_t i = 0; i < numOfRows; ++i) {
×
1201
    TAOS_ROW pRow = taos_fetch_row(pRes);
×
1202
    if (NULL == pRow[0] || NULL == pRow[1] || NULL == pRow[2]) {
×
1203
      tscError("invalid data from vnode");
×
1204
      blockDataDestroy(*pBlock);
×
1205
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1206
    }
1207
    int64_t ts = *(int64_t*)pRow[0];
×
1208
    if (lastTs < ts) {
×
1209
      lastTs = ts;
×
1210
    }
1211

1212
    for (int32_t j = 0; j < numOfFields; ++j) {
×
1213
      SColumnInfoData* pColInfoData = taosArrayGet((*pBlock)->pDataBlock, j);
×
1214
      code = colDataSetVal(pColInfoData, i, pRow[j], false);
×
1215
      if (TSDB_CODE_SUCCESS != code) {
×
1216
        blockDataDestroy(*pBlock);
×
1217
        return code;
×
1218
      }
1219
    }
1220

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

1225
  (*pBlock)->info.window.ekey = lastTs;
×
1226
  (*pBlock)->info.rows = numOfRows;
×
1227

1228
  tscInfo("[create stream with histroy] lastKey:%" PRId64 " numOfRows:%d from all vgroups", lastTs, numOfRows);
×
1229
  return TSDB_CODE_SUCCESS;
×
1230
}
1231

1232
void postSubQueryFetchCb(void* param, TAOS_RES* res, int32_t rowNum) {
×
1233
  SRequestObj* pRequest = (SRequestObj*)res;
×
1234
  if (pRequest->code) {
×
1235
    returnToUser(pRequest);
×
1236
    return;
×
1237
  }
1238

1239
  SSDataBlock* pBlock = NULL;
×
1240
  pRequest->code = createResultBlock(res, rowNum, &pBlock);
×
1241
  if (TSDB_CODE_SUCCESS != pRequest->code) {
×
1242
    tscError("req:0x%" PRIx64 ", create result block failed, QID:0x%" PRIx64 " %s", pRequest->self, pRequest->requestId,
×
1243
             tstrerror(pRequest->code));
1244
    returnToUser(pRequest);
×
1245
    return;
×
1246
  }
1247

1248
  SRequestObj* pNextReq = acquireRequest(pRequest->relation.nextRefId);
×
1249
  if (pNextReq) {
×
1250
    continuePostSubQuery(pNextReq, pBlock);
×
1251
    (void)releaseRequest(pRequest->relation.nextRefId);
×
1252
  } else {
1253
    tscError("req:0x%" PRIx64 ", next req ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1254
             pRequest->relation.nextRefId, pRequest->requestId);
1255
  }
1256

1257
  blockDataDestroy(pBlock);
×
1258
}
1259

1260
void handlePostSubQuery(SSqlCallbackWrapper* pWrapper) {
×
1261
  SRequestObj* pRequest = pWrapper->pRequest;
×
1262
  if (TD_RES_QUERY(pRequest)) {
×
1263
    taosAsyncFetchImpl(pRequest, postSubQueryFetchCb, pWrapper);
×
1264
    return;
×
1265
  }
1266

1267
  SRequestObj* pNextReq = acquireRequest(pRequest->relation.nextRefId);
×
1268
  if (pNextReq) {
×
1269
    continuePostSubQuery(pNextReq, NULL);
×
1270
    (void)releaseRequest(pRequest->relation.nextRefId);
×
1271
  } else {
1272
    tscError("req:0x%" PRIx64 ", next req ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1273
             pRequest->relation.nextRefId, pRequest->requestId);
1274
  }
1275
}
1276

1277
// todo refacto the error code  mgmt
1278
void schedulerExecCb(SExecResult* pResult, void* param, int32_t code) {
749,665,377✔
1279
  SSqlCallbackWrapper* pWrapper = param;
749,665,377✔
1280
  SRequestObj*         pRequest = pWrapper->pRequest;
749,665,377✔
1281
  STscObj*             pTscObj = pRequest->pTscObj;
749,671,680✔
1282

1283
  pRequest->code = code;
749,672,783✔
1284
  if (pResult) {
749,671,554✔
1285
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
749,609,894✔
1286
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
749,613,856✔
1287
  }
1288

1289
  int32_t type = pRequest->type;
749,658,409✔
1290
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
749,646,614✔
1291
    if (pResult) {
547,269,604✔
1292
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
547,234,434✔
1293

1294
      // record the insert rows
1295
      if (TDMT_VND_SUBMIT == type) {
547,239,029✔
1296
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
502,423,572✔
1297
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
502,424,438✔
1298
      }
1299
    }
1300
    schedulerFreeJob(&pRequest->body.queryJob, 0);
547,272,098✔
1301
  }
1302

1303
  taosMemoryFree(pResult);
749,672,400✔
1304
  tscDebug("req:0x%" PRIx64 ", enter scheduler exec cb, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
749,665,356✔
1305
           pRequest->requestId);
1306

1307
  if (code != TSDB_CODE_SUCCESS && NEED_CLIENT_HANDLE_ERROR(code) && pRequest->sqlstr != NULL &&
749,662,961✔
1308
      pRequest->stmtBindVersion == 0) {
87,992✔
1309
    tscDebug("req:0x%" PRIx64 ", client retry to handle the error, code:%s, tryCount:%d, QID:0x%" PRIx64,
87,802✔
1310
             pRequest->self, tstrerror(code), pRequest->retry, pRequest->requestId);
1311
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
87,802✔
1312
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1313
    }
1314
    restartAsyncQuery(pRequest, code);
87,802✔
1315
    return;
87,802✔
1316
  }
1317

1318
  tscTrace("req:0x%" PRIx64 ", scheduler exec cb, request type:%s", pRequest->self, TMSG_INFO(pRequest->type));
749,575,159✔
1319
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
749,575,159✔
1320
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
3,404,161✔
1321
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1322
    }
1323
  }
1324

1325
  pRequest->metric.execCostUs = taosGetTimestampUs() - pRequest->metric.execStart;
749,576,426✔
1326
  int32_t code1 = handleQueryExecRsp(pRequest);
749,582,199✔
1327
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
749,580,952✔
1328
    pRequest->code = code1;
×
1329
  }
1330

1331
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
1,486,793,518✔
1332
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
737,203,305✔
1333
    continueInsertFromCsv(pWrapper, pRequest);
12,149✔
1334
    return;
12,033✔
1335
  }
1336

1337
  if (pRequest->relation.nextRefId) {
749,582,798✔
1338
    handlePostSubQuery(pWrapper);
×
1339
  } else {
1340
    destorySqlCallbackWrapper(pWrapper);
749,578,497✔
1341
    pRequest->pWrapper = NULL;
749,568,569✔
1342

1343
    // return to client
1344
    doRequestCallback(pRequest, code);
749,573,195✔
1345
  }
1346
}
1347

1348
void launchQueryImpl(SRequestObj* pRequest, SQuery* pQuery, bool keepQuery, void** res) {
8,497,024✔
1349
  int32_t code = 0;
8,497,024✔
1350
  int32_t subplanNum = 0;
8,497,024✔
1351

1352
  if (pQuery->pRoot) {
8,497,024✔
1353
    pRequest->stmtType = pQuery->pRoot->type;
8,131,545✔
1354
    if (nodeType(pQuery->pRoot) == QUERY_NODE_DELETE_STMT) {
8,129,495✔
1355
      pRequest->secureDelete = ((SDeleteStmt*)pQuery->pRoot)->secureDelete;
×
1356
    }
1357
  }
1358

1359
  if (pQuery->pRoot && !pRequest->inRetry) {
8,496,976✔
1360
    STscObj*            pTscObj = pRequest->pTscObj;
8,126,006✔
1361
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
8,129,983✔
1362
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type) {
8,132,313✔
1363
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
8,114,561✔
1364
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
15,007✔
1365
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
14,969✔
1366
    }
1367
  }
1368

1369
  pRequest->body.execMode = pQuery->execMode;
8,505,545✔
1370
  switch (pQuery->execMode) {
8,505,163✔
1371
    case QUERY_EXEC_MODE_LOCAL:
×
1372
      if (!pRequest->validateOnly) {
×
1373
        if (NULL == pQuery->pRoot) {
×
1374
          terrno = TSDB_CODE_INVALID_PARA;
×
1375
          code = terrno;
×
1376
        } else {
1377
          code = execLocalCmd(pRequest, pQuery);
×
1378
        }
1379
      }
1380
      break;
×
1381
    case QUERY_EXEC_MODE_RPC:
372,581✔
1382
      if (!pRequest->validateOnly) {
372,581✔
1383
        code = execDdlQuery(pRequest, pQuery);
372,581✔
1384
      }
1385
      break;
372,581✔
1386
    case QUERY_EXEC_MODE_SCHEDULE: {
8,121,505✔
1387
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
8,121,505✔
1388
      if (NULL == pMnodeList) {
8,119,250✔
1389
        code = terrno;
×
1390
        break;
×
1391
      }
1392
      SQueryPlan* pDag = NULL;
8,119,250✔
1393
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
8,118,523✔
1394
      if (TSDB_CODE_SUCCESS == code) {
8,123,467✔
1395
        pRequest->body.subplanNum = pDag->numOfSubplans;
8,122,447✔
1396
        if (!pRequest->validateOnly) {
8,118,763✔
1397
          SArray* pNodeList = NULL;
8,120,425✔
1398
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
8,122,833✔
1399

1400
          if (TSDB_CODE_SUCCESS == code) {
8,125,223✔
1401
            code = sessMetricCheckValue((SSessMetric*)pRequest->pTscObj->pSessMetric, SESSION_MAX_CALL_VNODE_NUM,
8,129,514✔
1402
                                        taosArrayGetSize(pNodeList));
8,126,170✔
1403
          }
1404

1405
          if (TSDB_CODE_SUCCESS == code) {
8,123,387✔
1406
            code = scheduleQuery(pRequest, pDag, pNodeList);
8,123,387✔
1407
          }
1408
          taosArrayDestroy(pNodeList);
8,130,494✔
1409
        }
1410
      }
1411
      taosArrayDestroy(pMnodeList);
8,129,833✔
1412
      break;
8,131,998✔
1413
    }
1414
    case QUERY_EXEC_MODE_EMPTY_RESULT:
×
1415
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
1416
      break;
×
1417
    default:
×
1418
      break;
×
1419
  }
1420

1421
  if (!keepQuery) {
8,504,881✔
1422
    qDestroyQuery(pQuery);
×
1423
  }
1424

1425
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
8,504,881✔
1426
    int ret = removeMeta(pRequest->pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type));
5,594✔
1427
    if (TSDB_CODE_SUCCESS != ret) {
5,594✔
1428
      tscError("req:0x%" PRIx64 ", remove meta failed,code:%d, QID:0x%" PRIx64, pRequest->self, ret,
×
1429
               pRequest->requestId);
1430
    }
1431
  }
1432

1433
  if (TSDB_CODE_SUCCESS == code) {
8,505,512✔
1434
    code = handleQueryExecRsp(pRequest);
8,504,431✔
1435
  }
1436

1437
  if (TSDB_CODE_SUCCESS != code) {
8,506,198✔
1438
    pRequest->code = code;
6,204✔
1439
  }
1440

1441
  if (res) {
8,506,198✔
1442
    *res = pRequest->body.resInfo.execRes.res;
×
1443
    pRequest->body.resInfo.execRes.res = NULL;
×
1444
  }
1445
}
8,506,198✔
1446

1447
static int32_t asyncExecSchQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta,
750,144,497✔
1448
                                 SSqlCallbackWrapper* pWrapper) {
1449
  int32_t code = TSDB_CODE_SUCCESS;
750,144,497✔
1450
  pRequest->type = pQuery->msgType;
750,144,497✔
1451
  SArray*     pMnodeList = NULL;
750,139,612✔
1452
  SArray*     pNodeList = NULL;
750,139,612✔
1453
  SQueryPlan* pDag = NULL;
750,122,905✔
1454
  int64_t     st = taosGetTimestampUs();
750,158,201✔
1455

1456
  if (!pRequest->parseOnly) {
750,158,201✔
1457
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
750,152,800✔
1458
    if (NULL == pMnodeList) {
750,142,395✔
1459
      code = terrno;
×
1460
    }
1461
    SPlanContext cxt = {.queryId = pRequest->requestId,
834,223,643✔
1462
                        .acctId = pRequest->pTscObj->acctId,
750,158,997✔
1463
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
750,165,710✔
1464
                        .pAstRoot = pQuery->pRoot,
750,174,171✔
1465
                        .showRewrite = pQuery->showRewrite,
750,162,840✔
1466
                        .isView = pWrapper->pParseCtx->isView,
750,172,111✔
1467
                        .isAudit = pWrapper->pParseCtx->isAudit,
750,169,485✔
1468
                        .privInfo = pWrapper->pParseCtx->privInfo,
750,161,488✔
1469
                        .pMsg = pRequest->msgBuf,
750,155,009✔
1470
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1471
                        .pUser = pRequest->pTscObj->user,
750,166,580✔
1472
                        .userId = pRequest->pTscObj->userId,
750,158,664✔
1473
                        .sysInfo = pRequest->pTscObj->sysInfo,
750,151,799✔
1474
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
750,158,101✔
1475
                        .allocatorId = pRequest->stmtBindVersion > 0 ? 0 : pRequest->allocatorRefId};
750,162,909✔
1476
    if (TSDB_CODE_SUCCESS == code) {
750,157,793✔
1477
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
750,154,776✔
1478
    }
1479
    if (code) {
750,159,354✔
1480
      tscError("req:0x%" PRIx64 " requestId:0x%" PRIx64 ", failed to create query plan, code:%s msg:%s", pRequest->self,
242,553✔
1481
               pRequest->requestId, tstrerror(code), cxt.pMsg);
1482
    } else {
1483
      pRequest->body.subplanNum = pDag->numOfSubplans;
749,916,801✔
1484
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
749,924,566✔
1485
    }
1486
  }
1487

1488
  pRequest->metric.execStart = taosGetTimestampUs();
750,154,014✔
1489
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
750,150,966✔
1490

1491
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
750,138,056✔
1492
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
749,652,401✔
1493
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
190,248,111✔
1494
    }
1495

1496
    if (code == TSDB_CODE_SUCCESS) {
749,663,235✔
1497
      code = sessMetricCheckValue((SSessMetric*)pRequest->pTscObj->pSessMetric, SESSION_MAX_CALL_VNODE_NUM,
749,648,389✔
1498
                                  taosArrayGetSize(pNodeList));
749,659,452✔
1499
    }
1500

1501
    if (code == TSDB_CODE_SUCCESS) {
749,652,239✔
1502
      SRequestConnInfo conn = {.pTrans = getAppInfo(pRequest)->pTransporter,
749,649,219✔
1503
                               .requestId = pRequest->requestId,
749,656,131✔
1504
                               .requestObjRefId = pRequest->self};
749,651,511✔
1505
      SSchedulerReq    req = {
791,662,664✔
1506
             .syncReq       = false,
1507
             .localReq      = (tsQueryPolicy == QUERY_POLICY_CLIENT),
749,641,579✔
1508
             .pConn         = &conn,
1509
             .pNodeList     = pNodeList,
1510
             .pDag          = pDag,
1511
             .allocatorRefId = pRequest->allocatorRefId,
749,641,579✔
1512
             .sql           = pRequest->sqlstr,
749,629,446✔
1513
             .startTs       = pRequest->metric.start,
749,623,014✔
1514
             .execFp        = schedulerExecCb,
1515
             .cbParam       = pWrapper,
1516
             .chkKillFp     = chkRequestKilled,
1517
             .chkKillParam  = (void*)pRequest->self,
749,625,723✔
1518
             .pExecRes      = NULL,
1519
             .source        = pRequest->source,
749,647,122✔
1520
             .secureDelete  = pRequest->secureDelete,
749,643,971✔
1521
             .pWorkerCb     = getTaskPoolWorkerCb(),
749,638,905✔
1522
      };
1523

1524
      if (TSDB_CODE_SUCCESS == code) {
749,640,334✔
1525
        code = schedulerExecJob(&req, &pRequest->body.queryJob);
749,668,526✔
1526
      }
1527
      taosArrayDestroy(pNodeList);
749,637,871✔
1528
      taosArrayDestroy(pMnodeList);
749,668,690✔
1529
      return code;
749,667,724✔
1530
    }
1531
  }
1532

1533
  qDestroyQueryPlan(pDag);
498,771✔
1534
  tscDebug("req:0x%" PRIx64 ", plan not executed, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
505,509✔
1535
           pRequest->requestId);
1536
  destorySqlCallbackWrapper(pWrapper);
505,509✔
1537
  pRequest->pWrapper = NULL;
505,509✔
1538
  if (TSDB_CODE_SUCCESS != code) {
505,509✔
1539
    pRequest->code = code;
245,573✔
1540
  }
1541

1542
  doRequestCallback(pRequest, code);
505,509✔
1543

1544
  // todo not to be released here
1545
  taosArrayDestroy(pMnodeList);
505,509✔
1546
  taosArrayDestroy(pNodeList);
505,509✔
1547

1548
  return code;
504,756✔
1549
}
1550

1551
void launchAsyncQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta, SSqlCallbackWrapper* pWrapper) {
855,211,397✔
1552
  int32_t code = 0;
855,211,397✔
1553

1554
  if (pRequest->parseOnly) {
855,211,397✔
1555
    doRequestCallback(pRequest, 0);
288,244✔
1556
    return;
288,244✔
1557
  }
1558

1559
  pRequest->body.execMode = pQuery->execMode;
854,933,734✔
1560
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
854,922,887✔
1561
    destorySqlCallbackWrapper(pWrapper);
104,789,252✔
1562
    pRequest->pWrapper = NULL;
104,787,291✔
1563
  }
1564

1565
  if (pQuery->pRoot && !pRequest->inRetry) {
854,906,772✔
1566
    STscObj*            pTscObj = pRequest->pTscObj;
854,937,284✔
1567
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
854,947,324✔
1568
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
854,940,073✔
1569
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
559,411,800✔
1570
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
502,190,252✔
1571
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
352,735,584✔
1572
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
141,922,110✔
1573
    }
1574
  }
1575

1576
  switch (pQuery->execMode) {
854,950,904✔
1577
    case QUERY_EXEC_MODE_LOCAL:
5,778,142✔
1578
      asyncExecLocalCmd(pRequest, pQuery);
5,778,142✔
1579
      break;
5,778,142✔
1580
    case QUERY_EXEC_MODE_RPC:
98,430,186✔
1581
      code = asyncExecDdlQuery(pRequest, pQuery);
98,430,186✔
1582
      break;
98,429,657✔
1583
    case QUERY_EXEC_MODE_SCHEDULE: {
750,145,431✔
1584
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
750,145,431✔
1585
      break;
750,171,643✔
1586
    }
1587
    case QUERY_EXEC_MODE_EMPTY_RESULT:
580,016✔
1588
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
580,016✔
1589
      doRequestCallback(pRequest, 0);
580,016✔
1590
      break;
580,016✔
1591
    default:
×
1592
      tscError("req:0x%" PRIx64 ", invalid execMode %d", pRequest->self, pQuery->execMode);
×
1593
      doRequestCallback(pRequest, -1);
×
1594
      break;
×
1595
  }
1596
}
1597

1598
int32_t refreshMeta(STscObj* pTscObj, SRequestObj* pRequest) {
12,551✔
1599
  SCatalog* pCatalog = NULL;
12,551✔
1600
  int32_t   code = 0;
12,551✔
1601
  int32_t   dbNum = taosArrayGetSize(pRequest->dbList);
12,551✔
1602
  int32_t   tblNum = taosArrayGetSize(pRequest->tableList);
12,551✔
1603

1604
  if (dbNum <= 0 && tblNum <= 0) {
12,551✔
1605
    return TSDB_CODE_APP_ERROR;
12,455✔
1606
  }
1607

1608
  code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
96✔
1609
  if (code != TSDB_CODE_SUCCESS) {
96✔
1610
    return code;
×
1611
  }
1612

1613
  SRequestConnInfo conn = {.pTrans = pTscObj->pAppInfo->pTransporter,
96✔
1614
                           .requestId = pRequest->requestId,
96✔
1615
                           .requestObjRefId = pRequest->self,
96✔
1616
                           .mgmtEps = getEpSet_s(&pTscObj->pAppInfo->mgmtEp)};
96✔
1617

1618
  for (int32_t i = 0; i < dbNum; ++i) {
288✔
1619
    char* dbFName = taosArrayGet(pRequest->dbList, i);
192✔
1620

1621
    // catalogRefreshDBVgInfo will handle dbFName == null.
1622
    code = catalogRefreshDBVgInfo(pCatalog, &conn, dbFName);
192✔
1623
    if (code != TSDB_CODE_SUCCESS) {
192✔
1624
      return code;
×
1625
    }
1626
  }
1627

1628
  for (int32_t i = 0; i < tblNum; ++i) {
288✔
1629
    SName* tableName = taosArrayGet(pRequest->tableList, i);
192✔
1630

1631
    // catalogRefreshTableMeta will handle tableName == null.
1632
    code = catalogRefreshTableMeta(pCatalog, &conn, tableName, -1);
192✔
1633
    if (code != TSDB_CODE_SUCCESS) {
192✔
1634
      return code;
×
1635
    }
1636
  }
1637

1638
  return code;
96✔
1639
}
1640

1641
int32_t removeMeta(STscObj* pTscObj, SArray* tbList, bool isView) {
4,826,619✔
1642
  SCatalog* pCatalog = NULL;
4,826,619✔
1643
  int32_t   tbNum = taosArrayGetSize(tbList);
4,826,619✔
1644
  int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
4,826,619✔
1645
  if (code != TSDB_CODE_SUCCESS) {
4,826,619✔
1646
    return code;
×
1647
  }
1648

1649
  if (isView) {
4,826,619✔
1650
    for (int32_t i = 0; i < tbNum; ++i) {
971,684✔
1651
      SName* pViewName = taosArrayGet(tbList, i);
485,842✔
1652
      char   dbFName[TSDB_DB_FNAME_LEN];
482,414✔
1653
      if (NULL == pViewName) {
485,842✔
1654
        continue;
×
1655
      }
1656
      (void)tNameGetFullDbName(pViewName, dbFName);
485,842✔
1657
      TSC_ERR_RET(catalogRemoveViewMeta(pCatalog, dbFName, 0, pViewName->tname, 0));
485,842✔
1658
    }
1659
  } else {
1660
    for (int32_t i = 0; i < tbNum; ++i) {
6,777,932✔
1661
      SName* pTbName = taosArrayGet(tbList, i);
2,437,155✔
1662
      TSC_ERR_RET(catalogRemoveTableMeta(pCatalog, pTbName));
2,437,155✔
1663
    }
1664
  }
1665

1666
  return TSDB_CODE_SUCCESS;
4,826,619✔
1667
}
1668

1669
int32_t initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet) {
85,098,544✔
1670
  pEpSet->version = 0;
85,098,544✔
1671

1672
  // init mnode ip set
1673
  SEpSet* mgmtEpSet = &(pEpSet->epSet);
85,098,983✔
1674
  mgmtEpSet->numOfEps = 0;
85,098,236✔
1675
  mgmtEpSet->inUse = 0;
85,098,983✔
1676

1677
  if (firstEp && firstEp[0] != 0) {
85,098,910✔
1678
    if (strlen(firstEp) >= TSDB_EP_LEN) {
85,100,710✔
1679
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1680
      return -1;
×
1681
    }
1682

1683
    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
85,100,710✔
1684
    if (code != TSDB_CODE_SUCCESS) {
85,100,159✔
1685
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1686
      return terrno;
×
1687
    }
1688
    // uint32_t addr = 0;
1689
    SIpAddr addr = {0};
85,100,159✔
1690
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
85,100,530✔
1691
    if (code) {
85,099,564✔
1692
      tscError("failed to resolve firstEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
1,099✔
1693
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1694
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
143✔
1695
    } else {
1696
      mgmtEpSet->numOfEps++;
85,098,465✔
1697
    }
1698
  }
1699

1700
  if (secondEp && secondEp[0] != 0) {
85,096,839✔
1701
    if (strlen(secondEp) >= TSDB_EP_LEN) {
2,244,275✔
1702
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1703
      return terrno;
×
1704
    }
1705

1706
    int32_t code = taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
2,244,275✔
1707
    if (code != TSDB_CODE_SUCCESS) {
2,244,421✔
1708
      return code;
×
1709
    }
1710
    SIpAddr addr = {0};
2,244,421✔
1711
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
2,244,421✔
1712
    if (code) {
2,244,563✔
1713
      tscError("failed to resolve secondEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
×
1714
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1715
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
×
1716
    } else {
1717
      mgmtEpSet->numOfEps++;
2,244,563✔
1718
    }
1719
  }
1720

1721
  if (mgmtEpSet->numOfEps == 0) {
85,097,415✔
1722
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
143✔
1723
    return TSDB_CODE_RPC_NETWORK_UNAVAIL;
143✔
1724
  }
1725

1726
  return 0;
85,096,980✔
1727
}
1728

1729
int32_t taosConnectImpl(const char* user, const char* auth, int32_t totpCode, const char* db, __taos_async_fn_t fp,
85,098,906✔
1730
                        void* param, SAppInstInfo* pAppInfo, int connType, STscObj** pTscObj) {
1731
  *pTscObj = NULL;
85,098,906✔
1732
  int32_t code = createTscObj(user, auth, db, connType, pAppInfo, pTscObj);
85,098,906✔
1733
  if (TSDB_CODE_SUCCESS != code) {
85,100,943✔
1734
    return code;
×
1735
  }
1736

1737
  SRequestObj* pRequest = NULL;
85,100,943✔
1738
  code = createRequest((*pTscObj)->id, TDMT_MND_CONNECT, 0, &pRequest);
85,100,943✔
1739
  if (TSDB_CODE_SUCCESS != code) {
85,100,708✔
1740
    destroyTscObj(*pTscObj);
×
1741
    return code;
×
1742
  }
1743

1744
  pRequest->sqlstr = taosStrdup("taos_connect");
85,100,708✔
1745
  if (pRequest->sqlstr) {
85,101,164✔
1746
    pRequest->sqlLen = strlen(pRequest->sqlstr);
85,101,164✔
1747
  } else {
1748
    return terrno;
×
1749
  }
1750

1751
  SMsgSendInfo* body = NULL;
85,101,164✔
1752
  code = buildConnectMsg(pRequest, &body, totpCode);
85,101,164✔
1753
  if (TSDB_CODE_SUCCESS != code) {
85,095,603✔
1754
    destroyTscObj(*pTscObj);
×
1755
    return code;
×
1756
  }
1757

1758
  // int64_t transporterId = 0;
1759
  SEpSet epset = getEpSet_s(&(*pTscObj)->pAppInfo->mgmtEp);
85,095,603✔
1760
  code = asyncSendMsgToServer((*pTscObj)->pAppInfo->pTransporter, &epset, NULL, body);
85,100,260✔
1761
  if (TSDB_CODE_SUCCESS != code) {
85,097,304✔
1762
    destroyTscObj(*pTscObj);
×
1763
    tscError("failed to send connect msg to server, code:%s", tstrerror(code));
×
1764
    return code;
×
1765
  }
1766
  if (TSDB_CODE_SUCCESS != tsem_wait(&pRequest->body.rspSem)) {
85,097,304✔
UNCOV
1767
    destroyTscObj(*pTscObj);
×
1768
    tscError("failed to wait sem, code:%s", terrstr());
×
1769
    return terrno;
×
1770
  }
1771
  if (pRequest->code != TSDB_CODE_SUCCESS) {
85,099,602✔
1772
    const char* errorMsg = (code == TSDB_CODE_RPC_FQDN_ERROR) ? taos_errstr(pRequest) : tstrerror(pRequest->code);
13,713✔
1773
    tscError("failed to connect to server, reason: %s", errorMsg);
13,713✔
1774

1775
    terrno = pRequest->code;
13,713✔
1776
    destroyRequest(pRequest);
13,713✔
1777
    taos_close_internal(*pTscObj);
13,713✔
1778
    *pTscObj = NULL;
13,713✔
1779
    return terrno;
13,713✔
1780
  }
1781
  if (connType == CONN_TYPE__AUTH_TEST) {
85,085,889✔
UNCOV
1782
    terrno = TSDB_CODE_SUCCESS;
×
UNCOV
1783
    destroyRequest(pRequest);
×
UNCOV
1784
    taos_close_internal(*pTscObj);
×
1785
    *pTscObj = NULL;
3,823✔
1786
    return TSDB_CODE_SUCCESS;
3,823✔
1787
  }
1788

1789
  tscInfo("conn:0x%" PRIx64 ", connection is opening, connId:%u, dnodeConn:%p, QID:0x%" PRIx64, (*pTscObj)->id,
85,085,889✔
1790
          (*pTscObj)->connId, (*pTscObj)->pAppInfo->pTransporter, pRequest->requestId);
1791
  destroyRequest(pRequest);
85,087,514✔
1792
  return code;
85,079,868✔
1793
}
1794

1795
static int32_t buildConnectMsg(SRequestObj* pRequest, SMsgSendInfo** pMsgSendInfo, int32_t totpCode) {
85,099,211✔
1796
  *pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
85,099,211✔
1797
  if (*pMsgSendInfo == NULL) {
85,099,614✔
1798
    return terrno;
×
1799
  }
1800

1801
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
85,099,614✔
1802

1803
  (*pMsgSendInfo)->requestObjRefId = pRequest->self;
85,099,614✔
1804
  (*pMsgSendInfo)->requestId = pRequest->requestId;
85,099,614✔
1805
  (*pMsgSendInfo)->fp = getMsgRspHandle((*pMsgSendInfo)->msgType);
85,099,614✔
1806
  (*pMsgSendInfo)->param = taosMemoryCalloc(1, sizeof(pRequest->self));
85,100,771✔
1807
  if (NULL == (*pMsgSendInfo)->param) {
85,099,390✔
1808
    taosMemoryFree(*pMsgSendInfo);
×
1809
    return terrno;
×
1810
  }
1811

1812
  *(int64_t*)(*pMsgSendInfo)->param = pRequest->self;
85,099,390✔
1813

1814
  SConnectReq connectReq = {0};
85,099,390✔
1815
  STscObj*    pObj = pRequest->pTscObj;
85,099,390✔
1816

1817
  char* db = getDbOfConnection(pObj);
85,099,390✔
1818
  if (db != NULL) {
85,101,295✔
1819
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
527,280✔
1820
  } else if (terrno) {
84,574,015✔
1821
    taosMemoryFree(*pMsgSendInfo);
×
1822
    return terrno;
×
1823
  }
1824
  taosMemoryFreeClear(db);
85,099,673✔
1825

1826
  connectReq.connType = pObj->connType;
85,099,673✔
1827
  connectReq.pid = appInfo.pid;
85,099,673✔
1828
  connectReq.startTime = appInfo.startTime;
85,099,673✔
1829
  connectReq.totpCode = totpCode;
85,099,673✔
1830
  connectReq.connectTime = taosGetTimestampMs();
85,098,334✔
1831

1832
  tstrncpy(connectReq.app, appInfo.appName, sizeof(connectReq.app));
85,098,334✔
1833
  tstrncpy(connectReq.user, pObj->user, sizeof(connectReq.user));
85,098,334✔
1834
  tstrncpy(connectReq.passwd, pObj->pass, sizeof(connectReq.passwd));
85,098,334✔
1835
  tstrncpy(connectReq.token, pObj->token, sizeof(connectReq.token));
85,098,334✔
1836
  tstrncpy(connectReq.sVer, td_version, sizeof(connectReq.sVer));
85,098,334✔
1837
  tSignConnectReq(&connectReq);
85,098,334✔
1838

1839
  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connectReq);
85,100,045✔
1840
  void*   pReq = taosMemoryMalloc(contLen);
85,096,271✔
1841
  if (NULL == pReq) {
85,100,931✔
1842
    taosMemoryFree(*pMsgSendInfo);
×
1843
    return terrno;
×
1844
  }
1845

1846
  if (-1 == tSerializeSConnectReq(pReq, contLen, &connectReq)) {
85,100,931✔
1847
    taosMemoryFree(*pMsgSendInfo);
×
1848
    taosMemoryFree(pReq);
×
1849
    return terrno;
×
1850
  }
1851

1852
  (*pMsgSendInfo)->msgInfo.len = contLen;
85,097,921✔
1853
  (*pMsgSendInfo)->msgInfo.pData = pReq;
85,097,923✔
1854
  return TSDB_CODE_SUCCESS;
85,097,923✔
1855
}
1856

1857
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,927,250,150✔
1858
  if (NULL == pEpSet) {
1,927,250,150✔
1859
    return;
1,923,870,616✔
1860
  }
1861

1862
  switch (pSendInfo->target.type) {
3,383,496✔
1863
    case TARGET_TYPE_MNODE:
319✔
1864
      if (NULL == pTscObj) {
319✔
1865
        tscError("mnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1866
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1867
        return;
760✔
1868
      }
1869

1870
      SEpSet  originEpset = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
319✔
1871
      SEpSet* pOrig = &originEpset;
319✔
1872
      SEp*    pOrigEp = &pOrig->eps[pOrig->inUse];
319✔
1873
      SEp*    pNewEp = &pEpSet->eps[pEpSet->inUse];
319✔
1874
      tscDebug("mnode epset updated from %d/%d=>%s:%d to %d/%d=>%s:%d in client", pOrig->inUse, pOrig->numOfEps,
319✔
1875
               pOrigEp->fqdn, pOrigEp->port, pEpSet->inUse, pEpSet->numOfEps, pNewEp->fqdn, pNewEp->port);
1876
      updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
319✔
1877
      break;
519,899✔
1878
    case TARGET_TYPE_VNODE: {
3,167,233✔
1879
      if (NULL == pTscObj) {
3,167,233✔
1880
        tscError("vnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
760✔
1881
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1882
        return;
760✔
1883
      }
1884

1885
      SCatalog* pCatalog = NULL;
3,166,473✔
1886
      int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
3,166,473✔
1887
      if (code != TSDB_CODE_SUCCESS) {
3,166,404✔
1888
        tscError("fail to get catalog handle, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1889
                 tstrerror(code));
1890
        return;
×
1891
      }
1892

1893
      code = catalogUpdateVgEpSet(pCatalog, pSendInfo->target.dbFName, pSendInfo->target.vgId, pEpSet);
3,166,404✔
1894
      if (code != TSDB_CODE_SUCCESS) {
3,166,594✔
1895
        tscError("fail to update catalog vg epset, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1896
                 tstrerror(code));
1897
        return;
×
1898
      }
1899
      taosMemoryFreeClear(pSendInfo->target.dbFName);
3,166,594✔
1900
      break;
3,166,594✔
1901
    }
1902
    default:
218,611✔
1903
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
218,611✔
1904
      break;
219,247✔
1905
  }
1906
}
1907

1908
int32_t doProcessMsgFromServerImpl(SRpcMsg* pMsg, SEpSet* pEpSet) {
1,927,900,863✔
1909
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
1,927,900,863✔
1910
  if (pMsg->info.ahandle == NULL) {
1,927,900,245✔
1911
    tscError("doProcessMsgFromServer pMsg->info.ahandle == NULL");
506,787✔
1912
    rpcFreeCont(pMsg->pCont);
506,787✔
1913
    taosMemoryFree(pEpSet);
506,787✔
1914
    return TSDB_CODE_TSC_INTERNAL_ERROR;
506,787✔
1915
  }
1916

1917
  STscObj* pTscObj = NULL;
1,927,393,985✔
1918

1919
  STraceId* trace = &pMsg->info.traceId;
1,927,393,985✔
1920
  char      tbuf[40] = {0};
1,927,393,983✔
1921
  TRACE_TO_STR(trace, tbuf);
1,927,393,083✔
1922

1923
  tscDebug("QID:%s, process message from server, handle:%p, message:%s, size:%d, code:%s", tbuf, pMsg->info.handle,
1,927,414,130✔
1924
           TMSG_INFO(pMsg->msgType), pMsg->contLen, tstrerror(pMsg->code));
1925

1926
  if (pSendInfo->requestObjRefId != 0) {
1,927,413,882✔
1927
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
1,636,989,755✔
1928
    if (pRequest) {
1,636,982,148✔
1929
      if (pRequest->self != pSendInfo->requestObjRefId) {
1,623,257,902✔
1930
        tscError("doProcessMsgFromServer req:0x%" PRId64 " != pSendInfo->requestObjRefId:0x%" PRId64, pRequest->self,
×
1931
                 pSendInfo->requestObjRefId);
1932

1933
        if (TSDB_CODE_SUCCESS != taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId)) {
×
1934
          tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1935
        }
1936
        rpcFreeCont(pMsg->pCont);
×
1937
        taosMemoryFree(pEpSet);
×
1938
        destroySendMsgInfo(pSendInfo);
×
1939
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1940
      }
1941
      pTscObj = pRequest->pTscObj;
1,623,258,199✔
1942
    }
1943
  }
1944

1945
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
1,927,407,281✔
1946

1947
  SDataBuf buf = {.msgType = pMsg->msgType,
1,927,258,031✔
1948
                  .len = pMsg->contLen,
1,927,258,866✔
1949
                  .pData = NULL,
1950
                  .handle = pMsg->info.handle,
1,927,262,069✔
1951
                  .handleRefId = pMsg->info.refId,
1,927,261,502✔
1952
                  .pEpSet = pEpSet};
1953

1954
  if (pMsg->contLen > 0) {
1,927,261,404✔
1955
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
1,887,593,004✔
1956
    if (buf.pData == NULL) {
1,887,625,514✔
1957
      pMsg->code = terrno;
×
1958
    } else {
1959
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
1,887,625,514✔
1960
    }
1961
  }
1962

1963
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
1,927,306,366✔
1964

1965
  if (pTscObj) {
1,927,351,912✔
1966
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
1,623,224,235✔
1967
    if (TSDB_CODE_SUCCESS != code) {
1,623,263,494✔
1968
      tscError("doProcessMsgFromServer taosReleaseRef failed");
1,062✔
1969
      terrno = code;
1,062✔
1970
      pMsg->code = code;
1,062✔
1971
    }
1972
  }
1973

1974
  rpcFreeCont(pMsg->pCont);
1,927,391,171✔
1975
  destroySendMsgInfo(pSendInfo);
1,927,386,721✔
1976
  return TSDB_CODE_SUCCESS;
1,927,384,285✔
1977
}
1978

1979
int32_t doProcessMsgFromServer(void* param) {
1,927,914,141✔
1980
  AsyncArg* arg = (AsyncArg*)param;
1,927,914,141✔
1981
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
1,927,914,141✔
1982
  taosMemoryFree(arg);
1,927,889,376✔
1983
  return code;
1,927,881,589✔
1984
}
1985

1986
void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,927,651,972✔
1987
  int32_t code = 0;
1,927,651,972✔
1988
  SEpSet* tEpSet = NULL;
1,927,651,972✔
1989

1990
  tscDebug("msg callback, ahandle %p", pMsg->info.ahandle);
1,927,651,972✔
1991

1992
  if (pEpSet != NULL) {
1,927,660,859✔
1993
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
3,386,834✔
1994
    if (NULL == tEpSet) {
3,386,748✔
1995
      code = terrno;
×
1996
      pMsg->code = terrno;
×
1997
      goto _exit;
×
1998
    }
1999
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
3,386,748✔
2000
  }
2001

2002
  // pMsg is response msg
2003
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
1,927,660,773✔
2004
    // restore origin code
2005
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
85,052,346✔
2006
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
2007
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
85,052,316✔
2008
      pMsg->code = TSDB_CODE_RPC_BROKEN_LINK;
×
2009
    }
2010
  } else {
2011
    // uniform to one error code: TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED
2012
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
1,842,608,906✔
2013
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
2014
    }
2015
  }
2016

2017
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
1,927,675,439✔
2018
  if (NULL == arg) {
1,927,648,948✔
2019
    code = terrno;
×
2020
    pMsg->code = code;
×
2021
    goto _exit;
×
2022
  }
2023

2024
  arg->msg = *pMsg;
1,927,648,948✔
2025
  arg->pEpset = tEpSet;
1,927,662,238✔
2026

2027
  if ((code = taosAsyncExec(doProcessMsgFromServer, arg, NULL)) != 0) {
1,927,686,296✔
2028
    pMsg->code = code;
×
2029
    taosMemoryFree(arg);
×
2030
    goto _exit;
×
2031
  }
2032
  return;
1,927,776,717✔
2033

2034
_exit:
×
2035
  tscError("failed to sched msg to tsc since %s", tstrerror(code));
×
2036
  code = doProcessMsgFromServerImpl(pMsg, tEpSet);
×
2037
  if (code != 0) {
×
2038
    tscError("failed to sched msg to tsc, tsc ready quit");
×
2039
  }
2040
}
2041

2042
TAOS* taos_connect_totp(const char* ip, const char* user, const char* pass, const char* totp, const char* db,
1,961✔
2043
                        uint16_t port) {
2044
  tscInfo("try to connect to %s:%u by totp, user:%s db:%s", ip, port, user, db);
1,961✔
2045
  if (user == NULL) {
1,961✔
2046
    user = TSDB_DEFAULT_USER;
×
2047
  }
2048

2049
  if (pass == NULL) {
1,961✔
2050
    pass = TSDB_DEFAULT_PASS;
×
2051
  }
2052

2053
  STscObj* pObj = NULL;
1,961✔
2054
  int32_t  code = taos_connect_internal(ip, user, pass, totp, db, port, CONN_TYPE__QUERY, &pObj);
1,961✔
2055
  if (TSDB_CODE_SUCCESS == code) {
1,961✔
2056
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
1,327✔
2057
    if (NULL == rid) {
1,327✔
2058
      tscError("out of memory when taos_connect_totp to %s:%u, user:%s db:%s", ip, port, user, db);
×
2059
      return NULL;
×
2060
    }
2061
    *rid = pObj->id;
1,327✔
2062
    return (TAOS*)rid;
1,327✔
2063
  } else {
2064
    terrno = code;
634✔
2065
  }
2066

2067
  return NULL;
634✔
2068
}
2069

UNCOV
2070
int taos_connect_test(const char* ip, const char* user, const char* pass, const char* totp, const char* db,
×
2071
                      uint16_t port) {
UNCOV
2072
  tscInfo("try to test connect to %s:%u by totp, user:%s db:%s", ip, port, user, db);
×
UNCOV
2073
  if (user == NULL) {
×
2074
    user = TSDB_DEFAULT_USER;
×
2075
  }
2076

UNCOV
2077
  if (pass == NULL) {
×
2078
    pass = TSDB_DEFAULT_PASS;
×
2079
  }
2080

UNCOV
2081
  STscObj* pObj = NULL;
×
UNCOV
2082
  return taos_connect_internal(ip, user, pass, totp, db, port, CONN_TYPE__AUTH_TEST, &pObj);
×
2083
}
2084

2085
TAOS* taos_connect_token(const char* ip, const char* token, const char* db, uint16_t port) {
2,300✔
2086
  tscInfo("try to connect to %s:%u by token, db:%s", ip, port, db);
2,300✔
2087

2088
  STscObj* pObj = NULL;
2,300✔
2089
  int32_t  code = taos_connect_by_auth(ip, NULL, token, NULL, db, port, CONN_TYPE__QUERY, &pObj);
2,300✔
2090
  if (TSDB_CODE_SUCCESS == code) {
2,300✔
2091
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
1,068✔
2092
    if (NULL == rid) {
1,068✔
2093
      tscError("out of memory when taos_connect_token to %s:%u db:%s", ip, port, db);
×
2094
      return NULL;
×
2095
    }
2096
    *rid = pObj->id;
1,068✔
2097
    return (TAOS*)rid;
1,068✔
2098
  } else {
2099
    terrno = code;
1,232✔
2100
  }
2101

2102
  return NULL;
1,232✔
2103
}
2104

2105
TAOS* taos_connect_auth(const char* ip, const char* user, const char* auth, const char* db, uint16_t port) {
100✔
2106
  tscInfo("try to connect to %s:%u by auth, user:%s db:%s", ip, port, user, db);
100✔
2107
  if (user == NULL) {
100✔
2108
    user = TSDB_DEFAULT_USER;
×
2109
  }
2110

2111
  if (auth == NULL) {
100✔
2112
    tscError("No auth info is given, failed to connect to server");
×
2113
    return NULL;
×
2114
  }
2115

2116
  STscObj* pObj = NULL;
100✔
2117
  int32_t  code = taos_connect_by_auth(ip, user, auth, NULL, db, port, CONN_TYPE__QUERY, &pObj);
100✔
2118
  if (TSDB_CODE_SUCCESS == code) {
100✔
UNCOV
2119
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
×
UNCOV
2120
    if (NULL == rid) {
×
2121
      tscError("out of memory when taos connect to %s:%u, user:%s db:%s", ip, port, user, db);
×
2122
    }
UNCOV
2123
    *rid = pObj->id;
×
UNCOV
2124
    return (TAOS*)rid;
×
2125
  }
2126

2127
  return NULL;
100✔
2128
}
2129

2130
void doSetOneRowPtr(SReqResultInfo* pResultInfo) {
2,147,483,647✔
2131
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
2,147,483,647✔
2132
    SResultColumn* pCol = &pResultInfo->pCol[i];
2,147,483,647✔
2133

2134
    int32_t type = pResultInfo->fields[i].type;
2,147,483,647✔
2135
    int32_t schemaBytes = calcSchemaBytesFromTypeBytes(type, pResultInfo->userFields[i].bytes, false);
2,147,483,647✔
2136

2137
    if (IS_VAR_DATA_TYPE(type)) {
2,147,483,647✔
2138
      if (!IS_VAR_NULL_TYPE(type, schemaBytes) && pCol->offset[pResultInfo->current] != -1) {
2,147,483,647✔
2139
        char* pStart = pResultInfo->pCol[i].offset[pResultInfo->current] + pResultInfo->pCol[i].pData;
2,147,483,647✔
2140

2141
        if (IS_STR_DATA_BLOB(type)) {
2,147,483,647✔
2142
          pResultInfo->length[i] = blobDataLen(pStart);
16,894✔
2143
          pResultInfo->row[i] = blobDataVal(pStart);
98✔
2144
        } else {
2145
          pResultInfo->length[i] = varDataLen(pStart);
2,147,483,647✔
2146
          pResultInfo->row[i] = varDataVal(pStart);
2,147,483,647✔
2147
        }
2148
      } else {
2149
        pResultInfo->row[i] = NULL;
266,858,850✔
2150
        pResultInfo->length[i] = 0;
266,990,482✔
2151
      }
2152
    } else {
2153
      if (!colDataIsNull_f(pCol, pResultInfo->current)) {
2,147,483,647✔
2154
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + schemaBytes * pResultInfo->current;
2,147,483,647✔
2155
        pResultInfo->length[i] = schemaBytes;
2,147,483,647✔
2156
      } else {
2157
        pResultInfo->row[i] = NULL;
1,144,733,269✔
2158
        pResultInfo->length[i] = 0;
1,145,173,740✔
2159
      }
2160
    }
2161
  }
2162
}
2,147,483,647✔
2163

2164
void* doFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
×
2165
  if (pRequest == NULL) {
×
2166
    return NULL;
×
2167
  }
2168

2169
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
×
2170
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
×
2171
    // All data has returned to App already, no need to try again
2172
    if (pResultInfo->completed) {
×
2173
      pResultInfo->numOfRows = 0;
×
2174
      return NULL;
×
2175
    }
2176

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

2180
    pRequest->code = schedulerFetchRows(pRequest->body.queryJob, &req);
×
2181
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2182
      pResultInfo->numOfRows = 0;
×
2183
      return NULL;
×
2184
    }
2185

2186
    pRequest->code = setQueryResultFromRsp(&pRequest->body.resInfo, (const SRetrieveTableRsp*)pResInfo->pData,
×
2187
                                           convertUcs4, pRequest->stmtBindVersion > 0);
×
2188
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2189
      pResultInfo->numOfRows = 0;
×
2190
      return NULL;
×
2191
    }
2192

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

2197
    STscObj*            pTscObj = pRequest->pTscObj;
×
2198
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
×
2199
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
×
2200

2201
    if (pResultInfo->numOfRows == 0) {
×
2202
      return NULL;
×
2203
    }
2204
  }
2205

2206
  if (setupOneRowPtr) {
×
2207
    doSetOneRowPtr(pResultInfo);
×
2208
    pResultInfo->current += 1;
×
2209
  }
2210

2211
  return pResultInfo->row;
×
2212
}
2213

2214
static void syncFetchFn(void* param, TAOS_RES* res, int32_t numOfRows) {
204,352,123✔
2215
  tsem_t* sem = param;
204,352,123✔
2216
  if (TSDB_CODE_SUCCESS != tsem_post(sem)) {
204,352,123✔
2217
    tscError("failed to post sem, code:%s", terrstr());
×
2218
  }
2219
}
204,352,123✔
2220

2221
void* doAsyncFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
1,986,116,476✔
2222
  if (pRequest == NULL) {
1,986,116,476✔
2223
    return NULL;
×
2224
  }
2225

2226
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
1,986,116,476✔
2227
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
1,986,128,628✔
2228
    // All data has returned to App already, no need to try again
2229
    if (pResultInfo->completed) {
297,035,382✔
2230
      pResultInfo->numOfRows = 0;
92,683,562✔
2231
      return NULL;
92,683,549✔
2232
    }
2233

2234
    // convert ucs4 to native multi-bytes string
2235
    pResultInfo->convertUcs4 = convertUcs4;
204,352,095✔
2236
    tsem_t sem;
203,700,045✔
2237
    if (TSDB_CODE_SUCCESS != tsem_init(&sem, 0, 0)) {
204,352,063✔
2238
      tscError("failed to init sem, code:%s", terrstr());
×
2239
    }
2240
    taos_fetch_rows_a(pRequest, syncFetchFn, &sem);
204,352,123✔
2241
    if (TSDB_CODE_SUCCESS != tsem_wait(&sem)) {
204,352,123✔
2242
      tscError("failed to wait sem, code:%s", terrstr());
×
2243
    }
2244
    if (TSDB_CODE_SUCCESS != tsem_destroy(&sem)) {
204,351,613✔
2245
      tscError("failed to destroy sem, code:%s", terrstr());
×
2246
    }
2247
    pRequest->inCallback = false;
204,352,123✔
2248
  }
2249

2250
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
1,893,445,736✔
2251
    return NULL;
10,447,483✔
2252
  } else {
2253
    if (setupOneRowPtr) {
1,882,997,042✔
2254
      doSetOneRowPtr(pResultInfo);
1,688,185,091✔
2255
      pResultInfo->current += 1;
1,688,185,695✔
2256
    }
2257

2258
    return pResultInfo->row;
1,882,997,662✔
2259
  }
2260
}
2261

2262
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
283,367,448✔
2263
  if (pResInfo->row == NULL) {
283,367,448✔
2264
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
178,418,275✔
2265
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
178,418,631✔
2266
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
178,416,859✔
2267
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
178,416,874✔
2268

2269
    if (pResInfo->row == NULL || pResInfo->pCol == NULL || pResInfo->length == NULL || pResInfo->convertBuf == NULL) {
178,416,515✔
UNCOV
2270
      taosMemoryFree(pResInfo->row);
×
2271
      taosMemoryFree(pResInfo->pCol);
×
2272
      taosMemoryFree(pResInfo->length);
×
2273
      taosMemoryFree(pResInfo->convertBuf);
×
2274
      return terrno;
×
2275
    }
2276
  }
2277

2278
  return TSDB_CODE_SUCCESS;
283,369,278✔
2279
}
2280

2281
static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength, bool isStmt) {
283,275,707✔
2282
  int32_t idx = -1;
283,275,707✔
2283
  iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt);
283,275,707✔
2284
  if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR;
283,274,271✔
2285

2286
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
1,623,263,378✔
2287
    int32_t type = pResultInfo->fields[i].type;
1,339,993,388✔
2288
    int32_t schemaBytes =
2289
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
1,339,995,457✔
2290

2291
    if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) {
1,339,990,815✔
2292
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
87,874,032✔
2293
      if (p == NULL) {
87,874,032✔
2294
        taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
×
2295
        return terrno;
×
2296
      }
2297

2298
      pResultInfo->convertBuf[i] = p;
87,874,032✔
2299

2300
      SResultColumn* pCol = &pResultInfo->pCol[i];
87,874,032✔
2301
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
2,147,483,647✔
2302
        if (pCol->offset[j] != -1) {
2,147,483,647✔
2303
          char* pStart = pCol->offset[j] + pCol->pData;
2,147,483,647✔
2304

2305
          int32_t len = taosUcs4ToMbsEx((TdUcs4*)varDataVal(pStart), varDataLen(pStart), varDataVal(p), conv);
2,147,483,647✔
2306
          if (len < 0 || len > schemaBytes || (p + len) >= (pResultInfo->convertBuf[i] + colLength[i])) {
2,147,483,647✔
2307
            tscError(
64✔
2308
                "doConvertUCS4 error, invalid data. len:%d, bytes:%d, (p + len):%p, (pResultInfo->convertBuf[i] + "
2309
                "colLength[i]):%p",
2310
                len, schemaBytes, (p + len), (pResultInfo->convertBuf[i] + colLength[i]));
2311
            taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
64✔
2312
            return TSDB_CODE_TSC_INTERNAL_ERROR;
64✔
2313
          }
2314

2315
          varDataSetLen(p, len);
2,147,483,647✔
2316
          pCol->offset[j] = (p - pResultInfo->convertBuf[i]);
2,147,483,647✔
2317
          p += (len + VARSTR_HEADER_SIZE);
2,147,483,647✔
2318
        }
2319
      }
2320

2321
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
87,873,968✔
2322
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
87,873,968✔
2323
    }
2324
  }
2325
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
283,274,586✔
2326
  return TSDB_CODE_SUCCESS;
283,275,047✔
2327
}
2328

2329
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
283,271,836✔
2330
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
1,623,253,432✔
2331
    TAOS_FIELD_E* pFieldE = pResultInfo->fields + i;
1,339,986,531✔
2332
    TAOS_FIELD*   pField = pResultInfo->userFields + i;
1,339,981,295✔
2333
    int32_t       type = pFieldE->type;
1,339,987,126✔
2334
    int32_t       bufLen = 0;
1,339,986,201✔
2335
    char*         p = NULL;
1,339,986,201✔
2336
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
1,339,986,201✔
2337
      continue;
1,337,764,450✔
2338
    } else {
2339
      bufLen = 64;
2,220,608✔
2340
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
2,220,608✔
2341
      pFieldE->bytes = bufLen;
2,220,608✔
2342
      pField->bytes = bufLen;
2,220,608✔
2343
    }
2344
    if (!p) return terrno;
2,220,608✔
2345
    pResultInfo->convertBuf[i] = p;
2,220,608✔
2346

2347
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
1,474,546,484✔
2348
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
1,472,325,876✔
2349
                                  pFieldE->precision, pFieldE->scale, p, bufLen);
1,472,325,876✔
2350
      p += bufLen;
1,472,325,876✔
2351
      if (TSDB_CODE_SUCCESS != code) {
1,472,325,876✔
2352
        return code;
×
2353
      }
2354
    }
2355
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
2,220,608✔
2356
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
2,220,608✔
2357
  }
2358
  return 0;
283,274,896✔
2359
}
2360

2361
int32_t getVersion1BlockMetaSize(const char* p, int32_t numOfCols) {
378,340✔
2362
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) * 3 + sizeof(uint64_t) +
756,300✔
2363
         numOfCols * (sizeof(int8_t) + sizeof(int32_t));
377,960✔
2364
}
2365

2366
static int32_t estimateJsonLen(SReqResultInfo* pResultInfo) {
189,170✔
2367
  char*   p = (char*)pResultInfo->pData;
189,170✔
2368
  int32_t blockVersion = *(int32_t*)p;
189,170✔
2369

2370
  int32_t numOfRows = pResultInfo->numOfRows;
189,170✔
2371
  int32_t numOfCols = pResultInfo->numOfCols;
189,170✔
2372

2373
  // | version | total length | total rows | total columns | flag seg| block group id | column schema | each column
2374
  // length |
2375
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
189,170✔
2376
  if (numOfCols != cols) {
189,170✔
2377
    tscError("estimateJsonLen error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2378
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2379
  }
2380

2381
  int32_t  len = getVersion1BlockMetaSize(p, numOfCols);
189,170✔
2382
  int32_t* colLength = (int32_t*)(p + len);
189,170✔
2383
  len += sizeof(int32_t) * numOfCols;
189,170✔
2384

2385
  char* pStart = p + len;
189,170✔
2386
  for (int32_t i = 0; i < numOfCols; ++i) {
807,923✔
2387
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
618,753✔
2388

2389
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
618,753✔
2390
      int32_t* offset = (int32_t*)pStart;
220,204✔
2391
      int32_t  lenTmp = numOfRows * sizeof(int32_t);
220,204✔
2392
      len += lenTmp;
220,204✔
2393
      pStart += lenTmp;
220,204✔
2394

2395
      int32_t estimateColLen = 0;
220,204✔
2396
      for (int32_t j = 0; j < numOfRows; ++j) {
1,065,971✔
2397
        if (offset[j] == -1) {
845,767✔
2398
          continue;
40,982✔
2399
        }
2400
        char* data = offset[j] + pStart;
804,785✔
2401

2402
        int32_t jsonInnerType = *data;
804,785✔
2403
        char*   jsonInnerData = data + CHAR_BYTES;
804,785✔
2404
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
804,785✔
2405
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
11,160✔
2406
        } else if (tTagIsJson(data)) {
793,625✔
2407
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
192,688✔
2408
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
600,937✔
2409
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
559,087✔
2410
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
41,850✔
2411
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
30,690✔
2412
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
11,160✔
2413
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
11,160✔
2414
        } else if (IS_STR_DATA_BLOB(jsonInnerType)) {
×
2415
          estimateColLen += (BLOBSTR_HEADER_SIZE + 32);
×
2416
        } else {
2417
          tscError("estimateJsonLen error: invalid type:%d", jsonInnerType);
×
2418
          return -1;
×
2419
        }
2420
      }
2421
      len += TMAX(colLen, estimateColLen);
220,204✔
2422
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
398,549✔
2423
      int32_t lenTmp = numOfRows * sizeof(int32_t);
55,800✔
2424
      len += (lenTmp + colLen);
55,800✔
2425
      pStart += lenTmp;
55,800✔
2426
    } else {
2427
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
342,749✔
2428
      len += (lenTmp + colLen);
342,749✔
2429
      pStart += lenTmp;
342,749✔
2430
    }
2431
    pStart += colLen;
618,753✔
2432
  }
2433

2434
  // Ensure the complete structure of the block, including the blankfill field,
2435
  // even though it is not used on the client side.
2436
  len += sizeof(bool);
189,170✔
2437
  return len;
189,170✔
2438
}
2439

2440
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
283,367,432✔
2441
  int32_t numOfRows = pResultInfo->numOfRows;
283,367,432✔
2442
  int32_t numOfCols = pResultInfo->numOfCols;
283,367,432✔
2443
  bool    needConvert = false;
283,366,729✔
2444
  for (int32_t i = 0; i < numOfCols; ++i) {
1,623,354,745✔
2445
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
1,340,174,996✔
2446
      needConvert = true;
189,170✔
2447
      break;
189,170✔
2448
    }
2449
  }
2450

2451
  if (!needConvert) {
283,368,919✔
2452
    return TSDB_CODE_SUCCESS;
283,179,749✔
2453
  }
2454

2455
  tscDebug("start to convert form json format string");
189,170✔
2456

2457
  char*   p = (char*)pResultInfo->pData;
189,170✔
2458
  int32_t blockVersion = *(int32_t*)p;
189,170✔
2459
  int32_t dataLen = estimateJsonLen(pResultInfo);
189,170✔
2460
  if (dataLen <= 0) {
189,170✔
2461
    tscError("doConvertJson error: estimateJsonLen failed");
×
2462
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2463
  }
2464

2465
  taosMemoryFreeClear(pResultInfo->convertJson);
189,170✔
2466
  pResultInfo->convertJson = taosMemoryCalloc(1, dataLen);
189,170✔
2467
  if (pResultInfo->convertJson == NULL) return terrno;
189,170✔
2468
  char* p1 = pResultInfo->convertJson;
189,170✔
2469

2470
  int32_t totalLen = 0;
189,170✔
2471
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
189,170✔
2472
  if (numOfCols != cols) {
189,170✔
2473
    tscError("doConvertJson error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2474
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2475
  }
2476

2477
  int32_t len = getVersion1BlockMetaSize(p, numOfCols);
189,170✔
2478
  (void)memcpy(p1, p, len);
189,170✔
2479

2480
  p += len;
189,170✔
2481
  p1 += len;
189,170✔
2482
  totalLen += len;
189,170✔
2483

2484
  len = sizeof(int32_t) * numOfCols;
189,170✔
2485
  int32_t* colLength = (int32_t*)p;
189,170✔
2486
  int32_t* colLength1 = (int32_t*)p1;
189,170✔
2487
  (void)memcpy(p1, p, len);
189,170✔
2488
  p += len;
189,170✔
2489
  p1 += len;
189,170✔
2490
  totalLen += len;
189,170✔
2491

2492
  char* pStart = p;
189,170✔
2493
  char* pStart1 = p1;
189,170✔
2494
  for (int32_t i = 0; i < numOfCols; ++i) {
807,923✔
2495
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
618,753✔
2496
    int32_t colLen1 = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength1[i]) : colLength1[i];
618,753✔
2497
    if (colLen >= dataLen) {
618,753✔
2498
      tscError("doConvertJson error: colLen:%d >= dataLen:%d", colLen, dataLen);
×
2499
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2500
    }
2501
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
618,753✔
2502
      int32_t* offset = (int32_t*)pStart;
220,204✔
2503
      int32_t* offset1 = (int32_t*)pStart1;
220,204✔
2504
      len = numOfRows * sizeof(int32_t);
220,204✔
2505
      (void)memcpy(pStart1, pStart, len);
220,204✔
2506
      pStart += len;
220,204✔
2507
      pStart1 += len;
220,204✔
2508
      totalLen += len;
220,204✔
2509

2510
      len = 0;
220,204✔
2511
      for (int32_t j = 0; j < numOfRows; ++j) {
1,065,971✔
2512
        if (offset[j] == -1) {
845,767✔
2513
          continue;
40,982✔
2514
        }
2515
        char* data = offset[j] + pStart;
804,785✔
2516

2517
        int32_t jsonInnerType = *data;
804,785✔
2518
        char*   jsonInnerData = data + CHAR_BYTES;
804,785✔
2519
        char    dst[TSDB_MAX_JSON_TAG_LEN] = {0};
804,785✔
2520
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
804,785✔
2521
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s", TSDB_DATA_NULL_STR_L);
11,160✔
2522
          varDataSetLen(dst, strlen(varDataVal(dst)));
11,160✔
2523
        } else if (tTagIsJson(data)) {
793,625✔
2524
          char* jsonString = NULL;
192,688✔
2525
          parseTagDatatoJson(data, &jsonString, pResultInfo->charsetCxt);
192,688✔
2526
          if (jsonString == NULL) {
192,688✔
2527
            tscError("doConvertJson error: parseTagDatatoJson failed");
×
2528
            return terrno;
×
2529
          }
2530
          STR_TO_VARSTR(dst, jsonString);
192,688✔
2531
          taosMemoryFree(jsonString);
192,688✔
2532
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
600,937✔
2533
          *(char*)varDataVal(dst) = '\"';
559,087✔
2534
          char    tmp[TSDB_MAX_JSON_TAG_LEN] = {0};
559,087✔
2535
          int32_t length = taosUcs4ToMbs((TdUcs4*)varDataVal(jsonInnerData), varDataLen(jsonInnerData), varDataVal(tmp),
559,087✔
2536
                                         pResultInfo->charsetCxt);
2537
          if (length <= 0) {
559,087✔
2538
            tscError("charset:%s to %s. convert failed.", DEFAULT_UNICODE_ENCODEC,
465✔
2539
                     pResultInfo->charsetCxt != NULL ? ((SConvInfo*)(pResultInfo->charsetCxt))->charset : tsCharset);
2540
            length = 0;
465✔
2541
          }
2542
          int32_t escapeLength = escapeToPrinted(varDataVal(dst) + CHAR_BYTES, TSDB_MAX_JSON_TAG_LEN - CHAR_BYTES * 2,
559,087✔
2543
                                                 varDataVal(tmp), length);
2544
          varDataSetLen(dst, escapeLength + CHAR_BYTES * 2);
559,087✔
2545
          *(char*)POINTER_SHIFT(varDataVal(dst), escapeLength + CHAR_BYTES) = '\"';
559,087✔
2546
          tscError("value:%s.", varDataVal(dst));
559,087✔
2547
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
41,850✔
2548
          double jsonVd = *(double*)(jsonInnerData);
30,690✔
2549
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%.9lf", jsonVd);
30,690✔
2550
          varDataSetLen(dst, strlen(varDataVal(dst)));
30,690✔
2551
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
11,160✔
2552
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s",
11,160✔
2553
                         (*((char*)jsonInnerData) == 1) ? "true" : "false");
11,160✔
2554
          varDataSetLen(dst, strlen(varDataVal(dst)));
11,160✔
2555
        } else {
2556
          tscError("doConvertJson error: invalid type:%d", jsonInnerType);
×
2557
          return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2558
        }
2559

2560
        offset1[j] = len;
804,785✔
2561
        (void)memcpy(pStart1 + len, dst, varDataTLen(dst));
804,785✔
2562
        len += varDataTLen(dst);
804,785✔
2563
      }
2564
      colLen1 = len;
220,204✔
2565
      totalLen += colLen1;
220,204✔
2566
      colLength1[i] = (blockVersion == BLOCK_VERSION_1) ? htonl(len) : len;
220,204✔
2567
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
398,549✔
2568
      len = numOfRows * sizeof(int32_t);
55,800✔
2569
      (void)memcpy(pStart1, pStart, len);
55,800✔
2570
      pStart += len;
55,800✔
2571
      pStart1 += len;
55,800✔
2572
      totalLen += len;
55,800✔
2573
      totalLen += colLen;
55,800✔
2574
      (void)memcpy(pStart1, pStart, colLen);
55,800✔
2575
    } else {
2576
      len = BitmapLen(pResultInfo->numOfRows);
342,749✔
2577
      (void)memcpy(pStart1, pStart, len);
342,749✔
2578
      pStart += len;
342,749✔
2579
      pStart1 += len;
342,749✔
2580
      totalLen += len;
342,749✔
2581
      totalLen += colLen;
342,749✔
2582
      (void)memcpy(pStart1, pStart, colLen);
342,749✔
2583
    }
2584
    pStart += colLen;
618,753✔
2585
    pStart1 += colLen1;
618,753✔
2586
  }
2587

2588
  // Ensure the complete structure of the block, including the blankfill field,
2589
  // even though it is not used on the client side.
2590
  // (void)memcpy(pStart1, pStart, sizeof(bool));
2591
  totalLen += sizeof(bool);
189,170✔
2592

2593
  *(int32_t*)(pResultInfo->convertJson + 4) = totalLen;
189,170✔
2594
  pResultInfo->pData = pResultInfo->convertJson;
189,170✔
2595
  return TSDB_CODE_SUCCESS;
189,170✔
2596
}
2597

2598
int32_t setResultDataPtr(SReqResultInfo* pResultInfo, bool convertUcs4, bool isStmt) {
306,681,603✔
2599
  bool convertForDecimal = convertUcs4;
306,681,603✔
2600
  if (pResultInfo == NULL || pResultInfo->numOfCols <= 0 || pResultInfo->fields == NULL) {
306,681,603✔
2601
    tscError("setResultDataPtr paras error");
38✔
2602
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2603
  }
2604

2605
  if (pResultInfo->numOfRows == 0) {
306,681,959✔
2606
    return TSDB_CODE_SUCCESS;
23,312,719✔
2607
  }
2608

2609
  if (pResultInfo->pData == NULL) {
283,367,375✔
2610
    tscError("setResultDataPtr error: pData is NULL");
×
2611
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2612
  }
2613

2614
  int32_t code = doPrepareResPtr(pResultInfo);
283,367,410✔
2615
  if (code != TSDB_CODE_SUCCESS) {
283,369,278✔
2616
    return code;
×
2617
  }
2618
  code = doConvertJson(pResultInfo);
283,369,278✔
2619
  if (code != TSDB_CODE_SUCCESS) {
283,367,676✔
2620
    return code;
×
2621
  }
2622

2623
  char* p = (char*)pResultInfo->pData;
283,367,676✔
2624

2625
  // version:
2626
  int32_t blockVersion = *(int32_t*)p;
283,368,035✔
2627
  p += sizeof(int32_t);
283,368,035✔
2628

2629
  int32_t dataLen = *(int32_t*)p;
283,369,112✔
2630
  p += sizeof(int32_t);
283,369,112✔
2631

2632
  int32_t rows = *(int32_t*)p;
283,368,358✔
2633
  p += sizeof(int32_t);
283,368,409✔
2634

2635
  int32_t cols = *(int32_t*)p;
283,368,768✔
2636
  p += sizeof(int32_t);
283,369,127✔
2637

2638
  if (rows != pResultInfo->numOfRows || cols != pResultInfo->numOfCols) {
283,368,753✔
UNCOV
2639
    tscError("setResultDataPtr paras error:rows;%d numOfRows:%" PRId64 " cols:%d numOfCols:%d", rows,
×
2640
             pResultInfo->numOfRows, cols, pResultInfo->numOfCols);
2641
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2642
  }
2643

2644
  int32_t hasColumnSeg = *(int32_t*)p;
283,368,201✔
2645
  p += sizeof(int32_t);
283,368,782✔
2646

2647
  uint64_t groupId = taosGetUInt64Aligned((uint64_t*)p);
283,368,904✔
2648
  p += sizeof(uint64_t);
283,368,904✔
2649

2650
  // check fields
2651
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
1,623,594,367✔
2652
    int8_t type = *(int8_t*)p;
1,340,229,751✔
2653
    p += sizeof(int8_t);
1,340,228,659✔
2654

2655
    int32_t bytes = *(int32_t*)p;
1,340,227,941✔
2656
    p += sizeof(int32_t);
1,340,227,941✔
2657

2658
    if (IS_DECIMAL_TYPE(type) && pResultInfo->fields[i].precision == 0) {
1,340,226,692✔
2659
      extractDecimalTypeInfoFromBytes(&bytes, &pResultInfo->fields[i].precision, &pResultInfo->fields[i].scale);
34,970✔
2660
    }
2661
  }
2662

2663
  int32_t* colLength = (int32_t*)p;
283,367,588✔
2664
  p += sizeof(int32_t) * pResultInfo->numOfCols;
283,367,588✔
2665

2666
  char* pStart = p;
283,367,947✔
2667
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
1,623,602,190✔
2668
    if ((pStart - pResultInfo->pData) >= dataLen) {
1,340,232,471✔
2669
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2670
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2671
    }
2672
    if (blockVersion == BLOCK_VERSION_1) {
1,340,225,635✔
2673
      colLength[i] = htonl(colLength[i]);
1,042,665,882✔
2674
    }
2675
    if (colLength[i] >= dataLen) {
1,340,225,751✔
2676
      tscError("invalid colLength %d, dataLen %d", colLength[i], dataLen);
×
2677
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2678
    }
2679
    if (IS_INVALID_TYPE(pResultInfo->fields[i].type)) {
1,340,230,230✔
2680
      tscError("invalid type %d", pResultInfo->fields[i].type);
175✔
2681
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2682
    }
2683
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
1,340,233,337✔
2684
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
291,159,125✔
2685
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
291,158,143✔
2686
    } else {
2687
      pResultInfo->pCol[i].nullbitmap = pStart;
1,049,077,587✔
2688
      pStart += BitmapLen(pResultInfo->numOfRows);
1,049,077,572✔
2689
    }
2690

2691
    pResultInfo->pCol[i].pData = pStart;
1,340,237,545✔
2692
    pResultInfo->length[i] =
2,147,483,647✔
2693
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
2,147,483,647✔
2694
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
1,340,234,431✔
2695

2696
    pStart += colLength[i];
1,340,234,653✔
2697
  }
2698

2699
  p = pStart;
283,369,240✔
2700
  // bool blankFill = *(bool*)p;
2701
  p += sizeof(bool);
283,369,240✔
2702
  int32_t offset = p - pResultInfo->pData;
283,369,240✔
2703
  if (offset > dataLen) {
283,368,744✔
2704
    tscError("invalid offset %d, dataLen %d", offset, dataLen);
×
2705
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2706
  }
2707

2708
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
2709
  if (convertUcs4) {
283,368,744✔
2710
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
283,275,310✔
2711
  }
2712
#endif
2713
  if (TSDB_CODE_SUCCESS == code && convertForDecimal) {
283,368,186✔
2714
    code = convertDecimalType(pResultInfo);
283,275,047✔
2715
  }
2716
  return code;
283,368,035✔
2717
}
2718

2719
char* getDbOfConnection(STscObj* pObj) {
1,120,665,537✔
2720
  terrno = TSDB_CODE_SUCCESS;
1,120,665,537✔
2721
  char* p = NULL;
1,120,681,992✔
2722
  (void)taosThreadMutexLock(&pObj->mutex);
1,120,681,992✔
2723
  size_t len = strlen(pObj->db);
1,120,691,607✔
2724
  if (len > 0) {
1,120,692,041✔
2725
    p = taosStrndup(pObj->db, tListLen(pObj->db));
717,338,064✔
2726
    if (p == NULL) {
717,330,160✔
2727
      tscError("failed to taosStrndup db name");
×
2728
    }
2729
  }
2730

2731
  (void)taosThreadMutexUnlock(&pObj->mutex);
1,120,684,137✔
2732
  return p;
1,120,682,919✔
2733
}
2734

2735
void setConnectionDB(STscObj* pTscObj, const char* db) {
84,226,330✔
2736
  if (db == NULL || pTscObj == NULL) {
84,226,330✔
2737
    tscError("setConnectionDB para is NULL");
×
2738
    return;
×
2739
  }
2740

2741
  (void)taosThreadMutexLock(&pTscObj->mutex);
84,265,795✔
2742
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
84,279,573✔
2743
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
84,279,573✔
2744
}
2745

2746
void resetConnectDB(STscObj* pTscObj) {
×
2747
  if (pTscObj == NULL) {
×
2748
    return;
×
2749
  }
2750

2751
  (void)taosThreadMutexLock(&pTscObj->mutex);
×
2752
  pTscObj->db[0] = 0;
×
2753
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
×
2754
}
2755

2756
int32_t setQueryResultFromRsp(SReqResultInfo* pResultInfo, const SRetrieveTableRsp* pRsp, bool convertUcs4,
252,607,158✔
2757
                              bool isStmt) {
2758
  if (pResultInfo == NULL || pRsp == NULL) {
252,607,158✔
2759
    tscError("setQueryResultFromRsp paras is null");
35✔
2760
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2761
  }
2762

2763
  taosMemoryFreeClear(pResultInfo->pRspMsg);
252,607,123✔
2764
  pResultInfo->pRspMsg = (const char*)pRsp;
252,607,158✔
2765
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
252,607,158✔
2766
  pResultInfo->current = 0;
252,607,208✔
2767
  pResultInfo->completed = (pRsp->completed == 1);
252,607,208✔
2768
  pResultInfo->precision = pRsp->precision;
252,607,208✔
2769

2770
  // decompress data if needed
2771
  int32_t payloadLen = htonl(pRsp->payloadLen);
252,607,173✔
2772

2773
  if (pRsp->compressed) {
252,607,208✔
2774
    if (pResultInfo->decompBuf == NULL) {
×
2775
      pResultInfo->decompBuf = taosMemoryMalloc(payloadLen);
×
2776
      if (pResultInfo->decompBuf == NULL) {
×
2777
        tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2778
        return terrno;
×
2779
      }
2780
      pResultInfo->decompBufSize = payloadLen;
×
2781
    } else {
2782
      if (pResultInfo->decompBufSize < payloadLen) {
×
2783
        char* p = taosMemoryRealloc(pResultInfo->decompBuf, payloadLen);
×
2784
        if (p == NULL) {
×
2785
          tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2786
          return terrno;
×
2787
        }
2788

2789
        pResultInfo->decompBuf = p;
×
2790
        pResultInfo->decompBufSize = payloadLen;
×
2791
      }
2792
    }
2793
  }
2794

2795
  if (payloadLen > 0) {
252,607,208✔
2796
    int32_t compLen = *(int32_t*)pRsp->data;
229,294,848✔
2797
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
229,294,848✔
2798

2799
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
229,294,883✔
2800

2801
    if (pRsp->compressed && compLen < rawLen) {
229,294,813✔
2802
      int32_t len = tsDecompressString(pStart, compLen, 1, pResultInfo->decompBuf, rawLen, ONE_STAGE_COMP, NULL, 0);
×
2803
      if (len < 0) {
×
2804
        tscError("tsDecompressString failed");
×
2805
        return terrno ? terrno : TSDB_CODE_FAILED;
×
2806
      }
2807
      if (len != rawLen) {
×
2808
        tscError("tsDecompressString failed, len:%d != rawLen:%d", len, rawLen);
×
2809
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2810
      }
2811
      pResultInfo->pData = pResultInfo->decompBuf;
×
2812
      pResultInfo->payloadLen = rawLen;
×
2813
    } else {
2814
      pResultInfo->pData = pStart;
229,294,848✔
2815
      pResultInfo->payloadLen = htonl(pRsp->compLen);
229,294,883✔
2816
      if (pRsp->compLen != pRsp->payloadLen) {
229,294,848✔
2817
        tscError("pRsp->compLen:%d != pRsp->payloadLen:%d", pRsp->compLen, pRsp->payloadLen);
×
2818
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2819
      }
2820
    }
2821
  }
2822

2823
  // TODO handle the compressed case
2824
  pResultInfo->totalRows += pResultInfo->numOfRows;
252,607,208✔
2825

2826
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
252,607,208✔
2827
  return code;
252,606,683✔
2828
}
2829

2830
TSDB_SERVER_STATUS taos_check_server_status(const char* fqdn, int port, char* details, int maxlen) {
196✔
2831
  TSDB_SERVER_STATUS code = TSDB_SRV_STATUS_UNAVAILABLE;
196✔
2832
  void*              clientRpc = NULL;
196✔
2833
  SServerStatusRsp   statusRsp = {0};
196✔
2834
  SEpSet             epSet = {.inUse = 0, .numOfEps = 1};
196✔
2835
  SRpcMsg  rpcMsg = {.info.ahandle = (void*)0x9527, .info.notFreeAhandle = 1, .msgType = TDMT_DND_SERVER_STATUS};
196✔
2836
  SRpcMsg  rpcRsp = {0};
196✔
2837
  SRpcInit rpcInit = {0};
196✔
2838
  char     pass[TSDB_PASSWORD_LEN + 1] = {0};
196✔
2839

2840
  rpcInit.label = "CHK";
196✔
2841
  rpcInit.numOfThreads = 1;
196✔
2842
  rpcInit.cfp = NULL;
196✔
2843
  rpcInit.sessions = 16;
196✔
2844
  rpcInit.connType = TAOS_CONN_CLIENT;
196✔
2845
  rpcInit.idleTime = tsShellActivityTimer * 1000;
196✔
2846
  rpcInit.compressSize = tsCompressMsgSize;
196✔
2847
  rpcInit.user = "_dnd";
196✔
2848

2849
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
196✔
2850
  connLimitNum = TMAX(connLimitNum, 10);
196✔
2851
  connLimitNum = TMIN(connLimitNum, 500);
196✔
2852
  rpcInit.connLimitNum = connLimitNum;
196✔
2853
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
196✔
2854
  rpcInit.readTimeout = tsReadTimeout;
196✔
2855
  rpcInit.ipv6 = tsEnableIpv6;
196✔
2856
  rpcInit.enableSSL = tsEnableTLS;
196✔
2857

2858
  memcpy(rpcInit.caPath, tsTLSCaPath, strlen(tsTLSCaPath));
196✔
2859
  memcpy(rpcInit.certPath, tsTLSSvrCertPath, strlen(tsTLSSvrCertPath));
196✔
2860
  memcpy(rpcInit.keyPath, tsTLSSvrKeyPath, strlen(tsTLSSvrKeyPath));
196✔
2861
  memcpy(rpcInit.cliCertPath, tsTLSCliCertPath, strlen(tsTLSCliCertPath));
196✔
2862
  memcpy(rpcInit.cliKeyPath, tsTLSCliKeyPath, strlen(tsTLSCliKeyPath));
196✔
2863

2864
  if (TSDB_CODE_SUCCESS != taosVersionStrToInt(td_version, &rpcInit.compatibilityVer)) {
196✔
2865
    tscError("faild to convert taos version from str to int, errcode:%s", terrstr());
×
2866
    goto _OVER;
×
2867
  }
2868

2869
  clientRpc = rpcOpen(&rpcInit);
196✔
2870
  if (clientRpc == NULL) {
196✔
2871
    code = terrno;
×
2872
    tscError("failed to init server status client since %s", tstrerror(code));
×
2873
    goto _OVER;
×
2874
  }
2875

2876
  if (fqdn == NULL) {
196✔
2877
    fqdn = tsLocalFqdn;
196✔
2878
  }
2879

2880
  if (port == 0) {
196✔
2881
    port = tsServerPort;
196✔
2882
  }
2883

2884
  tstrncpy(epSet.eps[0].fqdn, fqdn, TSDB_FQDN_LEN);
196✔
2885
  epSet.eps[0].port = (uint16_t)port;
196✔
2886
  int32_t ret = rpcSendRecv(clientRpc, &epSet, &rpcMsg, &rpcRsp);
196✔
2887
  if (TSDB_CODE_SUCCESS != ret) {
196✔
2888
    tscError("failed to send recv since %s", tstrerror(ret));
×
2889
    goto _OVER;
×
2890
  }
2891

2892
  if (rpcRsp.code != 0 || rpcRsp.contLen <= 0 || rpcRsp.pCont == NULL) {
196✔
2893
    tscError("failed to send server status req since %s", terrstr());
46✔
2894
    goto _OVER;
46✔
2895
  }
2896

2897
  if (tDeserializeSServerStatusRsp(rpcRsp.pCont, rpcRsp.contLen, &statusRsp) != 0) {
150✔
2898
    tscError("failed to parse server status rsp since %s", terrstr());
×
2899
    goto _OVER;
×
2900
  }
2901

2902
  code = statusRsp.statusCode;
150✔
2903
  if (details != NULL) {
150✔
2904
    tstrncpy(details, statusRsp.details, maxlen);
150✔
2905
  }
2906

2907
_OVER:
182✔
2908
  if (clientRpc != NULL) {
196✔
2909
    rpcClose(clientRpc);
196✔
2910
  }
2911
  if (rpcRsp.pCont != NULL) {
196✔
2912
    rpcFreeCont(rpcRsp.pCont);
150✔
2913
  }
2914
  return code;
196✔
2915
}
2916

2917
int32_t appendTbToReq(SHashObj* pHash, int32_t pos1, int32_t len1, int32_t pos2, int32_t len2, const char* str,
1,184✔
2918
                      int32_t acctId, char* db) {
2919
  SName name = {0};
1,184✔
2920

2921
  if (len1 <= 0) {
1,184✔
2922
    return -1;
×
2923
  }
2924

2925
  const char* dbName = db;
1,184✔
2926
  const char* tbName = NULL;
1,184✔
2927
  int32_t     dbLen = 0;
1,184✔
2928
  int32_t     tbLen = 0;
1,184✔
2929
  if (len2 > 0) {
1,184✔
2930
    dbName = str + pos1;
×
2931
    dbLen = len1;
×
2932
    tbName = str + pos2;
×
2933
    tbLen = len2;
×
2934
  } else {
2935
    dbLen = strlen(db);
1,184✔
2936
    tbName = str + pos1;
1,184✔
2937
    tbLen = len1;
1,184✔
2938
  }
2939

2940
  if (dbLen <= 0 || tbLen <= 0) {
1,184✔
2941
    return -1;
×
2942
  }
2943

2944
  if (tNameSetDbName(&name, acctId, dbName, dbLen)) {
1,184✔
2945
    return -1;
×
2946
  }
2947

2948
  if (tNameAddTbName(&name, tbName, tbLen)) {
1,184✔
2949
    return -1;
×
2950
  }
2951

2952
  char dbFName[TSDB_DB_FNAME_LEN] = {0};
1,184✔
2953
  (void)snprintf(dbFName, TSDB_DB_FNAME_LEN, "%d.%.*s", acctId, dbLen, dbName);
1,184✔
2954

2955
  STablesReq* pDb = taosHashGet(pHash, dbFName, strlen(dbFName));
1,184✔
2956
  if (pDb) {
1,184✔
2957
    if (NULL == taosArrayPush(pDb->pTables, &name)) {
×
2958
      return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
2959
    }
2960
  } else {
2961
    STablesReq db;
1,184✔
2962
    db.pTables = taosArrayInit(20, sizeof(SName));
1,184✔
2963
    if (NULL == db.pTables) {
1,184✔
2964
      return terrno;
×
2965
    }
2966
    tstrncpy(db.dbFName, dbFName, TSDB_DB_FNAME_LEN);
1,184✔
2967
    if (NULL == taosArrayPush(db.pTables, &name)) {
2,368✔
2968
      return terrno;
×
2969
    }
2970
    TSC_ERR_RET(taosHashPut(pHash, dbFName, strlen(dbFName), &db, sizeof(db)));
1,184✔
2971
  }
2972

2973
  return TSDB_CODE_SUCCESS;
1,184✔
2974
}
2975

2976
int32_t transferTableNameList(const char* tbList, int32_t acctId, char* dbName, SArray** pReq) {
1,184✔
2977
  SHashObj* pHash = taosHashInit(3, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
1,184✔
2978
  if (NULL == pHash) {
1,184✔
2979
    return terrno;
×
2980
  }
2981

2982
  bool    inEscape = false;
1,184✔
2983
  int32_t code = 0;
1,184✔
2984
  void*   pIter = NULL;
1,184✔
2985

2986
  int32_t vIdx = 0;
1,184✔
2987
  int32_t vPos[2];
1,184✔
2988
  int32_t vLen[2];
1,184✔
2989

2990
  (void)memset(vPos, -1, sizeof(vPos));
1,184✔
2991
  (void)memset(vLen, 0, sizeof(vLen));
1,184✔
2992

2993
  for (int32_t i = 0;; ++i) {
5,920✔
2994
    if (0 == *(tbList + i)) {
5,920✔
2995
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
1,184✔
2996
        vLen[vIdx] = i - vPos[vIdx];
1,184✔
2997
      }
2998

2999
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
1,184✔
3000
      if (code) {
1,184✔
3001
        goto _return;
×
3002
      }
3003

3004
      break;
1,184✔
3005
    }
3006

3007
    if ('`' == *(tbList + i)) {
4,736✔
3008
      inEscape = !inEscape;
×
3009
      if (!inEscape) {
×
3010
        if (vPos[vIdx] >= 0) {
×
3011
          vLen[vIdx] = i - vPos[vIdx];
×
3012
        } else {
3013
          goto _return;
×
3014
        }
3015
      }
3016

3017
      continue;
×
3018
    }
3019

3020
    if (inEscape) {
4,736✔
3021
      if (vPos[vIdx] < 0) {
×
3022
        vPos[vIdx] = i;
×
3023
      }
3024
      continue;
×
3025
    }
3026

3027
    if ('.' == *(tbList + i)) {
4,736✔
3028
      if (vPos[vIdx] < 0) {
×
3029
        goto _return;
×
3030
      }
3031
      if (vLen[vIdx] <= 0) {
×
3032
        vLen[vIdx] = i - vPos[vIdx];
×
3033
      }
3034
      vIdx++;
×
3035
      if (vIdx >= 2) {
×
3036
        goto _return;
×
3037
      }
3038
      continue;
×
3039
    }
3040

3041
    if (',' == *(tbList + i)) {
4,736✔
3042
      if (vPos[vIdx] < 0) {
×
3043
        goto _return;
×
3044
      }
3045
      if (vLen[vIdx] <= 0) {
×
3046
        vLen[vIdx] = i - vPos[vIdx];
×
3047
      }
3048

3049
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
×
3050
      if (code) {
×
3051
        goto _return;
×
3052
      }
3053

3054
      (void)memset(vPos, -1, sizeof(vPos));
×
3055
      (void)memset(vLen, 0, sizeof(vLen));
×
3056
      vIdx = 0;
×
3057
      continue;
×
3058
    }
3059

3060
    if (' ' == *(tbList + i) || '\r' == *(tbList + i) || '\t' == *(tbList + i) || '\n' == *(tbList + i)) {
4,736✔
3061
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
×
3062
        vLen[vIdx] = i - vPos[vIdx];
×
3063
      }
3064
      continue;
×
3065
    }
3066

3067
    if (('a' <= *(tbList + i) && 'z' >= *(tbList + i)) || ('A' <= *(tbList + i) && 'Z' >= *(tbList + i)) ||
4,736✔
3068
        ('0' <= *(tbList + i) && '9' >= *(tbList + i)) || ('_' == *(tbList + i))) {
592✔
3069
      if (vLen[vIdx] > 0) {
4,736✔
3070
        goto _return;
×
3071
      }
3072
      if (vPos[vIdx] < 0) {
4,736✔
3073
        vPos[vIdx] = i;
1,184✔
3074
      }
3075
      continue;
4,736✔
3076
    }
3077

3078
    goto _return;
×
3079
  }
3080

3081
  int32_t dbNum = taosHashGetSize(pHash);
1,184✔
3082
  *pReq = taosArrayInit(dbNum, sizeof(STablesReq));
1,184✔
3083
  if (NULL == pReq) {
1,184✔
3084
    TSC_ERR_JRET(terrno);
×
3085
  }
3086
  pIter = taosHashIterate(pHash, NULL);
1,184✔
3087
  while (pIter) {
2,368✔
3088
    STablesReq* pDb = (STablesReq*)pIter;
1,184✔
3089
    if (NULL == taosArrayPush(*pReq, pDb)) {
2,368✔
3090
      TSC_ERR_JRET(terrno);
×
3091
    }
3092
    pIter = taosHashIterate(pHash, pIter);
1,184✔
3093
  }
3094

3095
  taosHashCleanup(pHash);
1,184✔
3096

3097
  return TSDB_CODE_SUCCESS;
1,184✔
3098

3099
_return:
×
3100

3101
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
3102

3103
  pIter = taosHashIterate(pHash, NULL);
×
3104
  while (pIter) {
×
3105
    STablesReq* pDb = (STablesReq*)pIter;
×
3106
    taosArrayDestroy(pDb->pTables);
×
3107
    pIter = taosHashIterate(pHash, pIter);
×
3108
  }
3109

3110
  taosHashCleanup(pHash);
×
3111

3112
  return terrno;
×
3113
}
3114

3115
void syncCatalogFn(SMetaData* pResult, void* param, int32_t code) {
1,184✔
3116
  SSyncQueryParam* pParam = param;
1,184✔
3117
  pParam->pRequest->code = code;
1,184✔
3118

3119
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
1,184✔
3120
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3121
  }
3122
}
1,184✔
3123

3124
void syncQueryFn(void* param, void* res, int32_t code) {
942,427,321✔
3125
  SSyncQueryParam* pParam = param;
942,427,321✔
3126
  pParam->pRequest = res;
942,427,321✔
3127

3128
  if (pParam->pRequest) {
942,430,059✔
3129
    pParam->pRequest->code = code;
942,435,600✔
3130
    clientOperateReport(pParam->pRequest);
942,441,302✔
3131
  }
3132

3133
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
942,417,723✔
3134
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3135
  }
3136
}
942,456,474✔
3137

3138
void taosAsyncQueryImpl(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
941,993,997✔
3139
                        int8_t source) {
3140
  if (sql == NULL || NULL == fp) {
941,993,997✔
3141
    terrno = TSDB_CODE_INVALID_PARA;
647✔
3142
    if (fp) {
×
3143
      fp(param, NULL, terrno);
×
3144
    }
3145

UNCOV
3146
    return;
×
3147
  }
3148

3149
  size_t sqlLen = strlen(sql);
941,997,337✔
3150
  if (sqlLen > (size_t)tsMaxSQLLength) {
941,997,337✔
3151
    tscError("conn:0x%" PRIx64 ", sql string exceeds max length:%d", connId, tsMaxSQLLength);
508✔
3152
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
508✔
3153
    fp(param, NULL, terrno);
508✔
3154
    return;
508✔
3155
  }
3156

3157
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, sql:%s", connId, sql);
941,996,829✔
3158

3159
  SRequestObj* pRequest = NULL;
941,996,995✔
3160
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
941,997,296✔
3161
  if (code != TSDB_CODE_SUCCESS) {
941,995,217✔
3162
    terrno = code;
×
3163
    fp(param, NULL, terrno);
×
3164
    return;
×
3165
  }
3166

3167
  code = connCheckAndUpateMetric(connId);
941,995,217✔
3168
  if (code != TSDB_CODE_SUCCESS) {
941,996,405✔
3169
    terrno = code;
302✔
3170
    fp(param, NULL, terrno);
302✔
3171
    return;
302✔
3172
  }
3173

3174
  pRequest->source = source;
941,996,103✔
3175
  pRequest->body.queryFp = fp;
941,994,002✔
3176
  doAsyncQuery(pRequest, false);
941,996,479✔
3177
}
3178

3179
void taosAsyncQueryImplWithReqid(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
246✔
3180
                                 int64_t reqid) {
3181
  if (sql == NULL || NULL == fp) {
246✔
3182
    terrno = TSDB_CODE_INVALID_PARA;
×
3183
    if (fp) {
×
3184
      fp(param, NULL, terrno);
×
3185
    }
3186

3187
    return;
×
3188
  }
3189

3190
  size_t sqlLen = strlen(sql);
246✔
3191
  if (sqlLen > (size_t)tsMaxSQLLength) {
246✔
3192
    tscError("conn:0x%" PRIx64 ", QID:0x%" PRIx64 ", sql string exceeds max length:%d", connId, reqid, tsMaxSQLLength);
×
3193
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
3194
    fp(param, NULL, terrno);
×
3195
    return;
×
3196
  }
3197

3198
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, QID:0x%" PRIx64 ", sql:%s", connId, reqid, sql);
246✔
3199

3200
  SRequestObj* pRequest = NULL;
246✔
3201
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, reqid);
246✔
3202
  if (code != TSDB_CODE_SUCCESS) {
246✔
3203
    terrno = code;
×
3204
    fp(param, NULL, terrno);
×
3205
    return;
×
3206
  }
3207

3208
  code = connCheckAndUpateMetric(connId);
246✔
3209

3210
  if (code != TSDB_CODE_SUCCESS) {
246✔
3211
    terrno = code;
×
3212
    fp(param, NULL, terrno);
×
3213
    return;
×
3214
  }
3215

3216
  pRequest->body.queryFp = fp;
246✔
3217

3218
  doAsyncQuery(pRequest, false);
246✔
3219
}
3220

3221
TAOS_RES* taosQueryImpl(TAOS* taos, const char* sql, bool validateOnly, int8_t source) {
941,862,844✔
3222
  if (NULL == taos) {
941,862,844✔
3223
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3224
    return NULL;
×
3225
  }
3226

3227
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
941,862,844✔
3228
  if (NULL == param) {
941,864,479✔
3229
    return NULL;
×
3230
  }
3231

3232
  int32_t code = tsem_init(&param->sem, 0, 0);
941,864,479✔
3233
  if (TSDB_CODE_SUCCESS != code) {
941,860,604✔
3234
    taosMemoryFree(param);
×
3235
    return NULL;
×
3236
  }
3237

3238
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
941,860,604✔
3239
  code = tsem_wait(&param->sem);
941,841,001✔
3240
  if (TSDB_CODE_SUCCESS != code) {
941,856,756✔
3241
    taosMemoryFree(param);
×
3242
    return NULL;
×
3243
  }
3244
  code = tsem_destroy(&param->sem);
941,856,756✔
3245
  if (TSDB_CODE_SUCCESS != code) {
941,853,943✔
3246
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3247
  }
3248

3249
  SRequestObj* pRequest = NULL;
941,860,792✔
3250
  if (param->pRequest != NULL) {
941,860,792✔
3251
    param->pRequest->syncQuery = true;
941,859,871✔
3252
    pRequest = param->pRequest;
941,859,041✔
3253
    param->pRequest->inCallback = false;
941,859,374✔
3254
  }
3255
  taosMemoryFree(param);
941,861,676✔
3256

3257
  // tscDebug("QID:0x%" PRIx64 ", taos_query end, conn:0x%" PRIx64 ", res:%p", pRequest ? pRequest->requestId : 0,
3258
  //          *(int64_t*)taos, pRequest);
3259

3260
  return pRequest;
941,861,877✔
3261
}
3262

3263
TAOS_RES* taosQueryImplWithReqid(TAOS* taos, const char* sql, bool validateOnly, int64_t reqid) {
246✔
3264
  if (NULL == taos) {
246✔
3265
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3266
    return NULL;
×
3267
  }
3268

3269
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
246✔
3270
  if (param == NULL) {
246✔
3271
    return NULL;
×
3272
  }
3273
  int32_t code = tsem_init(&param->sem, 0, 0);
246✔
3274
  if (TSDB_CODE_SUCCESS != code) {
246✔
3275
    taosMemoryFree(param);
×
3276
    return NULL;
×
3277
  }
3278

3279
  taosAsyncQueryImplWithReqid(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, reqid);
246✔
3280
  code = tsem_wait(&param->sem);
246✔
3281
  if (TSDB_CODE_SUCCESS != code) {
246✔
3282
    taosMemoryFree(param);
×
3283
    return NULL;
×
3284
  }
3285
  SRequestObj* pRequest = NULL;
246✔
3286
  if (param->pRequest != NULL) {
246✔
3287
    param->pRequest->syncQuery = true;
246✔
3288
    pRequest = param->pRequest;
246✔
3289
  }
3290
  taosMemoryFree(param);
246✔
3291

3292
  // tscDebug("QID:0x%" PRIx64 ", taos_query end, conn:0x%" PRIx64 ", res:%p", pRequest ? pRequest->requestId : 0,
3293
  //   *(int64_t*)taos, pRequest);
3294

3295
  return pRequest;
246✔
3296
}
3297

3298
static void fetchCallback(void* pResult, void* param, int32_t code) {
249,334,273✔
3299
  SRequestObj* pRequest = (SRequestObj*)param;
249,334,273✔
3300

3301
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
249,334,273✔
3302

3303
  tscDebug("req:0x%" PRIx64 ", enter scheduler fetch cb, code:%d - %s, QID:0x%" PRIx64, pRequest->self, code,
249,334,818✔
3304
           tstrerror(code), pRequest->requestId);
3305

3306
  pResultInfo->pData = pResult;
249,334,818✔
3307
  pResultInfo->numOfRows = 0;
249,334,783✔
3308

3309
  if (code != TSDB_CODE_SUCCESS) {
249,334,223✔
3310
    pRequest->code = code;
×
3311
    taosMemoryFreeClear(pResultInfo->pData);
×
3312
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
×
3313
    return;
×
3314
  }
3315

3316
  if (pRequest->code != TSDB_CODE_SUCCESS) {
249,334,223✔
3317
    taosMemoryFreeClear(pResultInfo->pData);
×
3318
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pRequest->code);
×
3319
    return;
×
3320
  }
3321

3322
  pRequest->code = setQueryResultFromRsp(pResultInfo, (const SRetrieveTableRsp*)pResultInfo->pData,
254,351,882✔
3323
                                         pResultInfo->convertUcs4, pRequest->stmtBindVersion > 0);
249,334,748✔
3324
  if (pRequest->code != TSDB_CODE_SUCCESS) {
249,334,293✔
3325
    pResultInfo->numOfRows = 0;
64✔
3326
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self,
64✔
3327
             tstrerror(pRequest->code), pRequest->requestId);
3328
  } else {
3329
    tscDebug(
249,332,418✔
3330
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
3331
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
3332

3333
    STscObj*            pTscObj = pRequest->pTscObj;
249,333,424✔
3334
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
249,334,754✔
3335
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
249,334,754✔
3336
  }
3337

3338
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
249,334,803✔
3339
}
3340

3341
void taosAsyncFetchImpl(SRequestObj* pRequest, __taos_async_fn_t fp, void* param) {
281,479,453✔
3342
  pRequest->body.fetchFp = fp;
281,479,453✔
3343
  ((SSyncQueryParam*)pRequest->body.interParam)->userParam = param;
281,479,455✔
3344

3345
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
281,479,453✔
3346

3347
  // this query has no results or error exists, return directly
3348
  if (taos_num_fields(pRequest) == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
281,479,455✔
3349
    pResultInfo->numOfRows = 0;
×
3350
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
×
3351
    return;
2,159,981✔
3352
  }
3353

3354
  // all data has returned to App already, no need to try again
3355
  if (pResultInfo->completed) {
281,479,455✔
3356
    // it is a local executed query, no need to do async fetch
3357
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
32,144,637✔
3358
      if (pResultInfo->localResultFetched) {
1,390,930✔
3359
        pResultInfo->numOfRows = 0;
695,465✔
3360
        pResultInfo->current = 0;
695,465✔
3361
      } else {
3362
        pResultInfo->localResultFetched = true;
695,465✔
3363
      }
3364
    } else {
3365
      pResultInfo->numOfRows = 0;
30,753,707✔
3366
    }
3367

3368
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
32,144,637✔
3369
    return;
32,144,637✔
3370
  }
3371

3372
  SSchedulerReq req = {
249,334,816✔
3373
      .syncReq = false,
3374
      .fetchFp = fetchCallback,
3375
      .cbParam = pRequest,
3376
  };
3377

3378
  int32_t code = schedulerFetchRows(pRequest->body.queryJob, &req);
249,334,816✔
3379
  if (TSDB_CODE_SUCCESS != code) {
249,334,789✔
3380
    tscError("0x%" PRIx64 " failed to schedule fetch rows", pRequest->requestId);
×
3381
    // pRequest->body.fetchFp(param, pRequest, code);
3382
  }
3383
}
3384

3385
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
942,421,536✔
3386
  pRequest->inCallback = true;
942,421,536✔
3387
  int64_t this = pRequest->self;
942,427,537✔
3388
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
942,418,090✔
3389
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
21,164✔
3390
    code = TSDB_CODE_SUCCESS;
×
3391
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3392
  }
3393

3394
  tscDebug("QID:0x%" PRIx64 ", taos_query end, req:0x%" PRIx64 ", res:%p", pRequest->requestId, pRequest->self,
942,418,090✔
3395
           pRequest);
3396

3397
  if (pRequest->body.queryFp != NULL) {
942,419,002✔
3398
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
942,440,720✔
3399
  }
3400

3401
  SRequestObj* pReq = acquireRequest(this);
942,459,561✔
3402
  if (pReq != NULL) {
942,481,521✔
3403
    pReq->inCallback = false;
940,144,970✔
3404
    (void)releaseRequest(this);
940,145,450✔
3405
  }
3406
}
942,454,288✔
3407

3408
int32_t clientParseSql(void* param, const char* dbName, const char* sql, bool parseOnly, const char* effectiveUser,
587,642✔
3409
                       SParseSqlRes* pRes) {
3410
#ifndef TD_ENTERPRISE
3411
  return TSDB_CODE_SUCCESS;
3412
#else
3413
  return clientParseSqlImpl(param, dbName, sql, parseOnly, effectiveUser, pRes);
587,642✔
3414
#endif
3415
}
3416

3417
void updateConnAccessInfo(SConnAccessInfo* pInfo) {
1,027,082,430✔
3418
  if (pInfo == NULL) {
1,027,082,430✔
3419
    return;
×
3420
  }
3421
  int64_t ts = taosGetTimestampMs();
1,027,095,127✔
3422
  if (pInfo->startTime == 0) {
1,027,095,127✔
3423
    pInfo->startTime = ts;
85,100,830✔
3424
  }
3425
  pInfo->lastAccessTime = ts;
1,027,096,681✔
3426
}
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