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

taosdata / TDengine / #4983

13 Mar 2026 03:38AM UTC coverage: 68.653% (+0.07%) from 68.587%
#4983

push

travis-ci

web-flow
feat/6641435300-save-audit-in-self (#34738)

434 of 584 new or added lines in 10 files covered. (74.32%)

434 existing lines in 121 files now uncovered.

212745 of 309883 relevant lines covered (68.65%)

134272959.11 hits per line

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

70.49
/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) {
639,793,800✔
40
  SRequestObj* pReq = acquireRequest(rId);
639,793,800✔
41
  if (pReq != NULL) {
639,839,655✔
42
    pReq->isQuery = true;
639,821,518✔
43
    (void)releaseRequest(rId);
639,821,433✔
44
  }
45
}
639,816,874✔
46

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

52
  size_t len = strlen(str);
166,958,464✔
53
  if (len <= 0 || len > maxsize) {
166,958,464✔
UNCOV
54
    return false;
×
55
  }
56

57
  return true;
166,959,709✔
58
}
59

60
static bool validateUserName(const char* user) { return stringLengthCheck(user, TSDB_USER_LEN - 1); }
83,199,464✔
61

62
static bool validatePassword(const char* passwd) { return stringLengthCheck(passwd, TSDB_PASSWORD_MAX_LEN); }
83,200,004✔
63

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

66
static char* getClusterKey(const char* user, const char* auth, const char* ip, int32_t port) {
83,201,265✔
67
  char key[512] = {0};
83,201,265✔
68
  if (user == NULL) {
83,201,333✔
69
    (void)snprintf(key, sizeof(key), "%s:%s:%d", auth, ip, port);
2,324✔
70
  } else {
71
    (void)snprintf(key, sizeof(key), "%s:%s:%s:%d", user, auth, ip, port);
83,199,009✔
72
  }
73
  return taosStrdup(key);
83,201,333✔
74
}
75

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

81
  size_t escapeLength = 0;
572,304✔
82
  for (size_t i = 0; i < srcLength; ++i) {
16,231,554✔
83
    if (src[i] == '\"' || src[i] == '\\' || src[i] == '\b' || src[i] == '\f' || src[i] == '\n' || src[i] == '\r' ||
15,659,250✔
84
        src[i] == '\t') {
15,659,250✔
85
      escapeLength += 1;
×
86
    }
87
  }
88

89
  size_t dstLength = srcLength;
572,304✔
90
  if (escapeLength == 0) {
572,304✔
91
    (void)memcpy(dst, src, srcLength);
572,304✔
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;
572,304✔
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;
3,559✔
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,332,074✔
146
  taosHashCleanup(appInfo.pInstMap);
1,332,074✔
147
  taosHashCleanup(appInfo.pInstMapByClusterId);
1,332,074✔
148
  tscInfo("cluster instance map cleaned");
1,332,074✔
149
}
1,332,074✔
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,
83,201,546✔
156
                                    const char* db, uint16_t port, int connType, STscObj** pObj) {
157
  TSC_ERR_RET(taos_init());
83,201,546✔
158

159
  if (user == NULL) {
83,202,782✔
160
    if (auth == NULL || strlen(auth) != (TSDB_TOKEN_LEN - 1)) {
3,123✔
161
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_TOKEN);
799✔
162
    }
163
  } else if (!validateUserName(user)) {
83,199,659✔
164
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
165
  }
166
  int32_t code = 0;
83,199,592✔
167

168
  char localDb[TSDB_DB_NAME_LEN] = {0};
83,199,592✔
169
  if (db != NULL && strlen(db) > 0) {
83,199,592✔
170
    if (!validateDbName(db)) {
558,819✔
171
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_DB_LENGTH);
×
172
    }
173

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

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

187
  SCorEpSet epSet = {0};
83,200,584✔
188
  if (ip) {
83,200,731✔
189
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
81,359,854✔
190
  } else {
191
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
1,840,877✔
192
  }
193

194
  if (port) {
83,200,838✔
195
    epSet.epSet.eps[0].port = port;
80,647,447✔
196
    epSet.epSet.eps[1].port = port;
80,647,447✔
197
  }
198

199
  char* key = getClusterKey(user, auth, ip, port);
83,200,838✔
200
  if (NULL == key) {
83,202,184✔
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,
83,202,184✔
204
          user ? user : "", db, key);
205
  for (int32_t i = 0; i < epSet.epSet.numOfEps; ++i) {
168,247,523✔
206
    tscInfo("ep:%d, %s:%u", i, epSet.epSet.eps[i].fqdn, epSet.epSet.eps[i].port);
85,044,708✔
207
  }
208

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

249
    pInst = &p;
1,412,043✔
250
  } else {
251
    if (NULL == *pInst || NULL == (*pInst)->pAppHbMgr) {
81,790,927✔
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);
81,790,927✔
257
  }
258

259
_return:
83,202,970✔
260

261
  if (TSDB_CODE_SUCCESS != code) {
83,202,970✔
262
    (void)taosThreadMutexUnlock(&appInfo.mutex);
×
263
    taosMemoryFreeClear(key);
×
264
    return code;
×
265
  } else {
266
    code = taosThreadMutexUnlock(&appInfo.mutex);
83,202,970✔
267
    taosMemoryFreeClear(key);
83,201,234✔
268
    if (TSDB_CODE_SUCCESS != code) {
83,202,970✔
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);
83,202,970✔
273
  }
274
}
275

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

283
  taosEncryptPass_c((uint8_t*)pass, strlen(pass), auth);
83,200,701✔
284
  return taos_connect_by_auth(ip, user, auth, totp, db, port, connType, pObj);
83,199,874✔
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) {
515,200✔
297
  if (param == NULL) return;
515,200✔
298
  if (TSDB_CODE_SUCCESS != tsem_destroy(&param->sem)) {
515,200✔
299
    tscError("failed to destroy semaphore in freeQueryParam");
×
300
  }
301
  taosMemoryFree(param);
515,200✔
302
}
303

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

312
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
1,024,607,734✔
313
  if ((*pRequest)->sqlstr == NULL) {
1,024,608,342✔
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);
1,024,611,321✔
321
  (*pRequest)->sqlstr[sqlLen] = 0;
1,024,618,337✔
322
  (*pRequest)->sqlLen = sqlLen;
1,024,618,143✔
323
  (*pRequest)->validateOnly = validateSql;
1,024,620,257✔
324
  (*pRequest)->stmtBindVersion = 0;
1,024,621,347✔
325

326
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
1,024,621,662✔
327

328
  STscObj* pTscObj = (*pRequest)->pTscObj;
1,024,621,006✔
329
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
1,024,620,048✔
330
                             sizeof((*pRequest)->self));
331
  if (err) {
1,024,615,133✔
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;
1,024,615,133✔
340
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
1,024,614,933✔
341
    if (TSDB_CODE_SUCCESS !=
444,299,661✔
342
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
444,295,580✔
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);
1,024,617,441✔
352
  return TSDB_CODE_SUCCESS;
1,024,614,211✔
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,651,592✔
368
  STscObj* pTscObj = pRequest->pTscObj;
6,651,592✔
369

370
  SParseContext cxt = {
6,656,833✔
371
      .requestId = pRequest->requestId,
6,655,776✔
372
      .requestRid = pRequest->self,
6,652,880✔
373
      .acctId = pTscObj->acctId,
6,655,454✔
374
      .db = pRequest->pDb,
6,656,478✔
375
      .topicQuery = topicQuery,
376
      .pSql = pRequest->sqlstr,
6,653,548✔
377
      .sqlLen = pRequest->sqlLen,
6,656,205✔
378
      .pMsg = pRequest->msgBuf,
6,657,138✔
379
      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
380
      .pTransporter = pTscObj->pAppInfo->pTransporter,
6,655,784✔
381
      .pStmtCb = pStmtCb,
382
      .pUser = pTscObj->user,
6,655,413✔
383
      .userId = pTscObj->userId,
6,651,861✔
384
      .isSuperUser = (0 == strcmp(pTscObj->user, TSDB_DEFAULT_USER)),
6,651,270✔
385
      .enableSysInfo = pTscObj->sysInfo,
6,653,259✔
386
      .svrVer = pTscObj->sVer,
6,654,176✔
387
      .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes),
6,651,187✔
388
      .stmtBindVersion = pRequest->stmtBindVersion,
6,657,163✔
389
      .setQueryFp = setQueryRequest,
390
      .timezone = pTscObj->optionInfo.timezone,
6,650,296✔
391
      .charsetCxt = pTscObj->optionInfo.charsetCxt,
6,654,810✔
392
  };
393

394
  cxt.mgmtEpSet = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
6,655,814✔
395
  int32_t code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &cxt.pCatalog);
6,659,479✔
396
  if (code != TSDB_CODE_SUCCESS) {
6,651,993✔
397
    return code;
×
398
  }
399

400
  code = qParseSql(&cxt, pQuery);
6,651,993✔
401
  if (TSDB_CODE_SUCCESS == code) {
6,640,578✔
402
    if ((*pQuery)->haveResultSet) {
6,647,556✔
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,643,184✔
410
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
6,641,376✔
411
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
6,644,180✔
412
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
6,645,554✔
413
  }
414

415
  taosArrayDestroy(cxt.pTableMetaPos);
6,637,348✔
416
  taosArrayDestroy(cxt.pTableVgroupPos);
6,639,828✔
417

418
  return code;
6,644,378✔
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) {
413,602✔
435
  // drop table if exists not_exists_table
436
  if (NULL == pQuery->pCmdMsg) {
413,602✔
437
    return TSDB_CODE_SUCCESS;
×
438
  }
439

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

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

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

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

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

463
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp,
11,386,470✔
464
                              atomic_load_8(&pRequest->pTscObj->biMode), pRequest->pTscObj->optionInfo.charsetCxt);
11,386,435✔
465
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
5,699,425✔
466
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4,
3,157,863✔
467
                                 pRequest->stmtBindVersion > 0);
3,157,863✔
468
  }
469

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

473
  if (pRequest->code != TSDB_CODE_SUCCESS) {
5,699,425✔
474
    pResultInfo->numOfRows = 0;
1,852✔
475
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
1,852✔
476
             pRequest->requestId);
477
  } else {
478
    tscDebug(
5,697,573✔
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,699,425✔
484
}
485

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

492
  // drop table if exists not_exists_table
493
  if (NULL == pQuery->pCmdMsg) {
96,921,202✔
494
    doRequestCallback(pRequest, 0);
6,633✔
495
    return TSDB_CODE_SUCCESS;
6,633✔
496
  }
497

498
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
96,914,617✔
499
  pRequest->type = pMsgInfo->msgType;
96,914,575✔
500
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
96,914,575✔
501
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
96,914,532✔
502

503
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
96,914,527✔
504
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
96,913,386✔
505

506
  int32_t code = asyncSendMsgToServer(pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg);
96,918,108✔
507
  if (code) {
96,922,461✔
508
    doRequestCallback(pRequest, code);
×
509
  }
510
  return code;
96,916,204✔
511
}
512

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

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

521
  return node1->load > node2->load;
206,518✔
522
}
523

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

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

540
  return TSDB_CODE_SUCCESS;
359,987✔
541
}
542

543
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
1,018,600,768✔
544
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
1,018,600,768✔
545
    *required = false;
1,006,412,395✔
546
    return TSDB_CODE_SUCCESS;
1,006,409,908✔
547
  }
548

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

553
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
12,188,373✔
554
  *required = (NULL == pInfo->pQnodeList);
12,188,373✔
555
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
12,188,373✔
556
  return TSDB_CODE_SUCCESS;
12,188,373✔
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) {
7,942,566✔
592
  pRequest->type = pQuery->msgType;
7,942,566✔
593
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
7,942,196✔
594

595
  SPlanContext cxt = {.queryId = pRequest->requestId,
8,301,034✔
596
                      .acctId = pRequest->pTscObj->acctId,
7,936,299✔
597
                      .mgmtEpSet = getEpSet_s(&pAppInfo->mgmtEp),
7,941,228✔
598
                      .pAstRoot = pQuery->pRoot,
7,947,285✔
599
                      .showRewrite = pQuery->showRewrite,
7,946,649✔
600
                      .pMsg = pRequest->msgBuf,
7,944,612✔
601
                      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
602
                      .pUser = pRequest->pTscObj->user,
7,941,054✔
603
                      .userId = pRequest->pTscObj->userId,
7,939,407✔
604
                      .timezone = pRequest->pTscObj->optionInfo.timezone,
7,940,353✔
605
                      .sysInfo = pRequest->pTscObj->sysInfo};
7,939,125✔
606

607
  return qCreateQueryPlan(&cxt, pPlan, pNodeList);
7,937,067✔
608
}
609

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

617
  pResInfo->numOfCols = numOfCols;
244,908,428✔
618
  if (pResInfo->fields != NULL) {
244,908,088✔
619
    taosMemoryFree(pResInfo->fields);
14,323✔
620
  }
621
  if (pResInfo->userFields != NULL) {
244,906,272✔
622
    taosMemoryFree(pResInfo->userFields);
14,323✔
623
  }
624
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD_E));
244,905,744✔
625
  if (NULL == pResInfo->fields) return terrno;
244,904,493✔
626
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
244,905,446✔
627
  if (NULL == pResInfo->userFields) {
244,890,161✔
628
    taosMemoryFree(pResInfo->fields);
×
629
    return terrno;
×
630
  }
631
  if (numOfCols != pResInfo->numOfCols) {
244,891,393✔
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,214,007,791✔
637
    pResInfo->fields[i].type = pSchema[i].type;
969,102,044✔
638

639
    pResInfo->userFields[i].type = pSchema[i].type;
969,099,612✔
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);
969,101,938✔
642
    pResInfo->fields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, isStmt);
969,109,306✔
643
    if (IS_DECIMAL_TYPE(pSchema[i].type) && pExtSchema) {
969,118,825✔
644
      decimalFromTypeMod(pExtSchema[i].typeMod, &pResInfo->fields[i].precision, &pResInfo->fields[i].scale);
1,341,687✔
645
    }
646

647
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
969,120,664✔
648
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
969,119,097✔
649
  }
650
  return TSDB_CODE_SUCCESS;
244,912,529✔
651
}
652

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

659
  pResInfo->precision = precision;
190,706,499✔
660
}
661

662
int32_t buildVnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pDbVgList) {
194,731,817✔
663
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
194,731,817✔
664
  if (NULL == nodeList) {
194,741,209✔
665
    return terrno;
×
666
  }
667
  char* policy = (tsQueryPolicy == QUERY_POLICY_VNODE) ? "vnode" : "client";
194,742,510✔
668

669
  int32_t dbNum = taosArrayGetSize(pDbVgList);
194,742,510✔
670
  for (int32_t i = 0; i < dbNum; ++i) {
387,170,128✔
671
    SArray* pVg = taosArrayGetP(pDbVgList, i);
192,403,001✔
672
    if (NULL == pVg) {
192,409,866✔
673
      continue;
×
674
    }
675
    int32_t vgNum = taosArrayGetSize(pVg);
192,409,866✔
676
    if (vgNum <= 0) {
192,409,979✔
677
      continue;
572,393✔
678
    }
679

680
    for (int32_t j = 0; j < vgNum; ++j) {
662,054,591✔
681
      SVgroupInfo* pInfo = taosArrayGet(pVg, j);
470,213,786✔
682
      if (NULL == pInfo) {
470,236,836✔
683
        taosArrayDestroy(nodeList);
×
684
        return TSDB_CODE_OUT_OF_RANGE;
×
685
      }
686
      SQueryNodeLoad load = {0};
470,236,836✔
687
      load.addr.nodeId = pInfo->vgId;
470,228,527✔
688
      load.addr.epSet = pInfo->epSet;
470,252,842✔
689

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

697
  int32_t vnodeNum = taosArrayGetSize(nodeList);
194,767,127✔
698
  if (vnodeNum > 0) {
194,768,909✔
699
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
191,535,748✔
700
    goto _return;
191,533,128✔
701
  }
702

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

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

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

721
_return:
80,393✔
722

723
  *pNodeList = nodeList;
194,754,176✔
724

725
  return TSDB_CODE_SUCCESS;
194,750,828✔
726
}
727

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

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

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

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

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

767
_return:
×
768

769
  *pNodeList = nodeList;
1,534,736✔
770

771
  return TSDB_CODE_SUCCESS;
1,534,736✔
772
}
773

774
void freeVgList(void* list) {
7,859,440✔
775
  SArray* pList = *(SArray**)list;
7,859,440✔
776
  taosArrayDestroy(pList);
7,862,378✔
777
}
7,852,285✔
778

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

785
  switch (tsQueryPolicy) {
188,327,951✔
786
    case QUERY_POLICY_VNODE:
186,806,167✔
787
    case QUERY_POLICY_CLIENT: {
788
      if (pResultMeta) {
186,806,167✔
789
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
186,815,067✔
790
        if (NULL == pDbVgList) {
186,807,991✔
791
          code = terrno;
×
792
          goto _return;
×
793
        }
794
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
186,807,991✔
795
        for (int32_t i = 0; i < dbNum; ++i) {
371,349,931✔
796
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
184,537,742✔
797
          if (pRes->code || NULL == pRes->pRes) {
184,542,170✔
798
            continue;
536✔
799
          }
800

801
          if (NULL == taosArrayPush(pDbVgList, &pRes->pRes)) {
369,087,828✔
802
            code = terrno;
×
803
            goto _return;
×
804
          }
805
        }
806
      } else {
807
        fp = freeVgList;
9✔
808

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

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

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

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

845
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
186,812,189✔
846
      break;
186,805,274✔
847
    }
848
    case QUERY_POLICY_HYBRID:
1,534,736✔
849
    case QUERY_POLICY_QNODE: {
850
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
1,560,472✔
851
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
25,736✔
852
        if (pRes->code) {
25,736✔
853
          pQnodeList = NULL;
×
854
        } else {
855
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
25,736✔
856
          if (NULL == pQnodeList) {
25,736✔
857
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
858
            goto _return;
×
859
          }
860
        }
861
      } else {
862
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
1,509,000✔
863
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
1,509,000✔
864
        if (pInst->pQnodeList) {
1,509,000✔
865
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
1,509,000✔
866
          if (NULL == pQnodeList) {
1,509,000✔
867
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
868
            goto _return;
×
869
          }
870
        }
871
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
1,509,000✔
872
      }
873

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

882
_return:
188,340,010✔
883
  taosArrayDestroyEx(pDbVgList, fp);
188,340,010✔
884
  taosArrayDestroy(pQnodeList);
188,344,532✔
885

886
  return code;
188,349,511✔
887
}
888

889
int32_t buildSyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList) {
7,934,043✔
890
  SArray* pDbVgList = NULL;
7,934,043✔
891
  SArray* pQnodeList = NULL;
7,934,043✔
892
  int32_t code = 0;
7,937,303✔
893

894
  switch (tsQueryPolicy) {
7,937,303✔
895
    case QUERY_POLICY_VNODE:
7,931,230✔
896
    case QUERY_POLICY_CLIENT: {
897
      int32_t dbNum = taosArrayGetSize(pRequest->dbList);
7,931,230✔
898
      if (dbNum > 0) {
7,941,790✔
899
        SCatalog*     pCtg = NULL;
7,862,209✔
900
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
7,859,571✔
901
        code = catalogGetHandle(pInst->clusterId, &pCtg);
7,858,329✔
902
        if (code != TSDB_CODE_SUCCESS) {
7,854,950✔
903
          goto _return;
×
904
        }
905

906
        pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
7,854,950✔
907
        if (NULL == pDbVgList) {
7,857,343✔
908
          code = terrno;
×
909
          goto _return;
×
910
        }
911
        SArray* pVgList = NULL;
7,857,370✔
912
        for (int32_t i = 0; i < dbNum; ++i) {
15,714,732✔
913
          char*            dbFName = taosArrayGet(pRequest->dbList, i);
7,855,699✔
914
          SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
7,856,989✔
915
                                   .requestId = pRequest->requestId,
7,862,019✔
916
                                   .requestObjRefId = pRequest->self,
7,856,043✔
917
                                   .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
7,850,707✔
918

919
          // catalogGetDBVgList will handle dbFName == null.
920
          code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
7,865,403✔
921
          if (code) {
7,858,904✔
922
            goto _return;
×
923
          }
924

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

932
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
7,942,950✔
933
      break;
7,940,461✔
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:
6,073✔
943
      tscError("unknown query policy: %d", tsQueryPolicy);
6,073✔
944
      return TSDB_CODE_APP_ERROR;
×
945
  }
946

947
_return:
7,942,064✔
948

949
  taosArrayDestroyEx(pDbVgList, freeVgList);
7,941,489✔
950
  taosArrayDestroy(pQnodeList);
7,936,590✔
951

952
  return code;
7,941,343✔
953
}
954

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

958
  SExecResult      res = {0};
7,941,991✔
959
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
7,940,246✔
960
                           .requestId = pRequest->requestId,
7,941,734✔
961
                           .requestObjRefId = pRequest->self};
7,935,939✔
962
  SSchedulerReq    req = {
8,303,031✔
963
         .syncReq = true,
964
         .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
7,941,349✔
965
         .pConn = &conn,
966
         .pNodeList = pNodeList,
967
         .pDag = pDag,
968
         .sql = pRequest->sqlstr,
7,941,349✔
969
         .startTs = pRequest->metric.start,
7,925,332✔
970
         .execFp = NULL,
971
         .cbParam = NULL,
972
         .chkKillFp = chkRequestKilled,
973
         .chkKillParam = (void*)pRequest->self,
7,930,934✔
974
         .pExecRes = &res,
975
         .source = pRequest->source,
7,937,204✔
976
         .pWorkerCb = getTaskPoolWorkerCb(),
7,938,002✔
977
  };
978

979
  int32_t code = schedulerExecJob(&req, &pRequest->body.queryJob);
7,938,901✔
980

981
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
7,946,775✔
982
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
7,949,487✔
983

984
  if (code != TSDB_CODE_SUCCESS) {
7,947,803✔
985
    schedulerFreeJob(&pRequest->body.queryJob, 0);
×
986

987
    pRequest->code = code;
×
988
    terrno = code;
×
989
    return pRequest->code;
13✔
990
  }
991

992
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_DELETE == pRequest->type ||
7,947,803✔
993
      TDMT_VND_CREATE_TABLE == pRequest->type) {
65,300✔
994
    pRequest->body.resInfo.numOfRows = res.numOfRows;
7,928,507✔
995
    if (TDMT_VND_SUBMIT == pRequest->type) {
7,929,526✔
996
      STscObj*            pTscObj = pRequest->pTscObj;
7,882,805✔
997
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
7,883,165✔
998
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
7,884,188✔
999
    }
1000

1001
    schedulerFreeJob(&pRequest->body.queryJob, 0);
7,929,672✔
1002
  }
1003

1004
  pRequest->code = res.code;
7,948,083✔
1005
  terrno = res.code;
7,948,213✔
1006
  return pRequest->code;
7,944,763✔
1007
}
1008

1009
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
580,273,641✔
1010
  SArray*      pArray = NULL;
580,273,641✔
1011
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
580,273,641✔
1012
  if (NULL == pRsp->aCreateTbRsp) {
580,273,641✔
1013
    return TSDB_CODE_SUCCESS;
568,347,013✔
1014
  }
1015

1016
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
11,934,378✔
1017
  for (int32_t i = 0; i < tbNum; ++i) {
26,820,450✔
1018
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
14,887,060✔
1019
    if (pTbRsp->pMeta) {
14,885,104✔
1020
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
14,616,513✔
1021
    }
1022
  }
1023

1024
  return TSDB_CODE_SUCCESS;
11,933,390✔
1025
}
1026

1027
int32_t handleQueryExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
149,913,495✔
1028
  int32_t code = 0;
149,913,495✔
1029
  SArray* pArray = NULL;
149,913,495✔
1030
  SArray* pTbArray = (SArray*)res;
149,913,495✔
1031
  int32_t tbNum = taosArrayGetSize(pTbArray);
149,913,495✔
1032
  if (tbNum <= 0) {
149,914,484✔
1033
    return TSDB_CODE_SUCCESS;
×
1034
  }
1035

1036
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
149,914,484✔
1037
  if (NULL == pArray) {
149,914,983✔
1038
    return terrno;
4✔
1039
  }
1040

1041
  for (int32_t i = 0; i < tbNum; ++i) {
487,460,742✔
1042
    STbVerInfo* tbInfo = taosArrayGet(pTbArray, i);
337,542,555✔
1043
    if (NULL == tbInfo) {
337,543,333✔
1044
      code = terrno;
×
1045
      goto _return;
×
1046
    }
1047
    STbSVersion tbSver = {
337,543,333✔
1048
        .tbFName = tbInfo->tbFName, .sver = tbInfo->sversion, .tver = tbInfo->tversion, .rver = tbInfo->rversion};
337,543,325✔
1049
    if (NULL == taosArrayPush(pArray, &tbSver)) {
337,545,633✔
1050
      code = terrno;
×
1051
      goto _return;
×
1052
    }
1053
  }
1054

1055
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
149,918,187✔
1056
                           .requestId = pRequest->requestId,
149,918,526✔
1057
                           .requestObjRefId = pRequest->self,
149,918,543✔
1058
                           .mgmtEps = *epset};
1059

1060
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
149,918,198✔
1061

1062
_return:
149,914,567✔
1063

1064
  taosArrayDestroy(pArray);
149,914,514✔
1065
  return code;
149,916,084✔
1066
}
1067

1068
int32_t handleAlterTbExecRes(void* res, SCatalog* pCatalog) {
8,425,028✔
1069
  return catalogUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
8,425,028✔
1070
}
1071

1072
int32_t handleCreateTbExecRes(void* res, SCatalog* pCatalog) {
74,137,129✔
1073
  return catalogAsyncUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
74,137,129✔
1074
}
1075

1076
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
835,391,717✔
1077
  if (NULL == pRequest->body.resInfo.execRes.res) {
835,391,717✔
1078
    return pRequest->code;
50,465,035✔
1079
  }
1080

1081
  SCatalog*     pCatalog = NULL;
784,915,020✔
1082
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
784,923,666✔
1083

1084
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
784,944,070✔
1085
  if (code) {
784,931,356✔
1086
    return code;
×
1087
  }
1088

1089
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
784,931,356✔
1090
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
784,941,698✔
1091

1092
  switch (pRes->msgType) {
784,940,343✔
1093
    case TDMT_VND_ALTER_TABLE:
3,811,170✔
1094
    case TDMT_MND_ALTER_STB: {
1095
      code = handleAlterTbExecRes(pRes->res, pCatalog);
3,811,170✔
1096
      break;
3,811,170✔
1097
    }
1098
    case TDMT_VND_CREATE_TABLE: {
50,535,338✔
1099
      SArray* pList = (SArray*)pRes->res;
50,535,338✔
1100
      int32_t num = taosArrayGetSize(pList);
50,542,930✔
1101
      for (int32_t i = 0; i < num; ++i) {
108,166,536✔
1102
        void* res = taosArrayGetP(pList, i);
57,618,377✔
1103
        // handleCreateTbExecRes will handle res == null
1104
        code = handleCreateTbExecRes(res, pCatalog);
57,618,770✔
1105
      }
1106
      break;
50,548,159✔
1107
    }
1108
    case TDMT_MND_CREATE_STB: {
392,389✔
1109
      code = handleCreateTbExecRes(pRes->res, pCatalog);
392,389✔
1110
      break;
392,389✔
1111
    }
1112
    case TDMT_VND_SUBMIT: {
580,272,419✔
1113
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
580,272,419✔
1114

1115
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
580,276,893✔
1116
      break;
580,276,885✔
1117
    }
1118
    case TDMT_SCH_QUERY:
149,914,333✔
1119
    case TDMT_SCH_MERGE_QUERY: {
1120
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
149,914,333✔
1121
      break;
149,916,695✔
1122
    }
1123
    default:
832✔
1124
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self,
832✔
1125
               pRequest->type, pRequest->requestId);
1126
      code = TSDB_CODE_APP_ERROR;
×
1127
  }
1128

1129
  return code;
784,945,298✔
1130
}
1131

1132
static bool incompletaFileParsing(SNode* pStmt) {
814,923,026✔
1133
  return QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pStmt) ? false : ((SVnodeModifyOpStmt*)pStmt)->fileProcessing;
814,923,026✔
1134
}
1135

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

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

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

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

1154
void returnToUser(SRequestObj* pRequest) {
70,820,558✔
1155
  if (pRequest->relation.userRefId == pRequest->self || 0 == pRequest->relation.userRefId) {
70,820,558✔
1156
    // return to client
1157
    doRequestCallback(pRequest, pRequest->code);
70,820,558✔
1158
    return;
70,818,435✔
1159
  }
1160

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

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

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

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

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

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

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

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

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

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

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

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

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

1256
  blockDataDestroy(pBlock);
×
1257
}
1258

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

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

1276
// todo refacto the error code  mgmt
1277
void schedulerExecCb(SExecResult* pResult, void* param, int32_t code) {
827,117,657✔
1278
  SSqlCallbackWrapper* pWrapper = param;
827,117,657✔
1279
  SRequestObj*         pRequest = pWrapper->pRequest;
827,117,657✔
1280
  STscObj*             pTscObj = pRequest->pTscObj;
827,124,081✔
1281

1282
  pRequest->code = code;
827,123,374✔
1283
  if (pResult) {
827,105,112✔
1284
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
827,050,587✔
1285
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
827,058,486✔
1286
  }
1287

1288
  int32_t type = pRequest->type;
827,096,996✔
1289
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
827,089,758✔
1290
    if (pResult) {
626,599,906✔
1291
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
626,573,647✔
1292

1293
      // record the insert rows
1294
      if (TDMT_VND_SUBMIT == type) {
626,585,111✔
1295
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
572,789,789✔
1296
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
572,794,451✔
1297
      }
1298
    }
1299
    schedulerFreeJob(&pRequest->body.queryJob, 0);
626,616,413✔
1300
  }
1301

1302
  taosMemoryFree(pResult);
827,130,461✔
1303
  tscDebug("req:0x%" PRIx64 ", enter scheduler exec cb, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
827,125,119✔
1304
           pRequest->requestId);
1305

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

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

1324
  pRequest->metric.execCostUs = taosGetTimestampUs() - pRequest->metric.execStart;
827,049,594✔
1325
  int32_t code1 = handleQueryExecRsp(pRequest);
827,041,036✔
1326
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
827,043,143✔
1327
    pRequest->code = code1;
×
1328
  }
1329

1330
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
1,641,969,138✔
1331
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
814,922,374✔
1332
    continueInsertFromCsv(pWrapper, pRequest);
11,919✔
1333
    return;
11,919✔
1334
  }
1335

1336
  if (pRequest->relation.nextRefId) {
827,041,764✔
1337
    handlePostSubQuery(pWrapper);
×
1338
  } else {
1339
    destorySqlCallbackWrapper(pWrapper);
827,042,869✔
1340
    pRequest->pWrapper = NULL;
827,023,273✔
1341

1342
    // return to client
1343
    doRequestCallback(pRequest, code);
827,029,396✔
1344
  }
1345
}
1346

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

1351
  if (pQuery->pRoot) {
8,353,408✔
1352
    pRequest->stmtType = pQuery->pRoot->type;
7,942,582✔
1353
  }
1354

1355
  if (pQuery->pRoot && !pRequest->inRetry) {
8,352,980✔
1356
    STscObj*            pTscObj = pRequest->pTscObj;
7,942,946✔
1357
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
7,943,120✔
1358
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type) {
7,947,217✔
1359
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
7,931,418✔
1360
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
9,563✔
1361
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
9,563✔
1362
    }
1363
  }
1364

1365
  pRequest->body.execMode = pQuery->execMode;
8,354,781✔
1366
  switch (pQuery->execMode) {
8,358,837✔
1367
    case QUERY_EXEC_MODE_LOCAL:
×
1368
      if (!pRequest->validateOnly) {
×
1369
        if (NULL == pQuery->pRoot) {
×
1370
          terrno = TSDB_CODE_INVALID_PARA;
×
1371
          code = terrno;
×
1372
        } else {
1373
          code = execLocalCmd(pRequest, pQuery);
×
1374
        }
1375
      }
1376
      break;
×
1377
    case QUERY_EXEC_MODE_RPC:
413,602✔
1378
      if (!pRequest->validateOnly) {
413,602✔
1379
        code = execDdlQuery(pRequest, pQuery);
413,602✔
1380
      }
1381
      break;
413,602✔
1382
    case QUERY_EXEC_MODE_SCHEDULE: {
7,937,276✔
1383
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
7,937,276✔
1384
      if (NULL == pMnodeList) {
7,936,129✔
1385
        code = terrno;
×
1386
        break;
×
1387
      }
1388
      SQueryPlan* pDag = NULL;
7,936,129✔
1389
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
7,936,129✔
1390
      if (TSDB_CODE_SUCCESS == code) {
7,940,613✔
1391
        pRequest->body.subplanNum = pDag->numOfSubplans;
7,935,391✔
1392
        if (!pRequest->validateOnly) {
7,939,622✔
1393
          SArray* pNodeList = NULL;
7,930,244✔
1394
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
7,932,009✔
1395

1396
          if (TSDB_CODE_SUCCESS == code) {
7,937,566✔
1397
            code = sessMetricCheckValue((SSessMetric*)pRequest->pTscObj->pSessMetric, SESSION_MAX_CALL_VNODE_NUM,
7,944,241✔
1398
                                        taosArrayGetSize(pNodeList));
7,939,595✔
1399
          }
1400

1401
          if (TSDB_CODE_SUCCESS == code) {
7,935,374✔
1402
            code = scheduleQuery(pRequest, pDag, pNodeList);
7,935,374✔
1403
          }
1404
          taosArrayDestroy(pNodeList);
7,944,967✔
1405
        }
1406
      }
1407
      taosArrayDestroy(pMnodeList);
7,943,484✔
1408
      break;
7,946,104✔
1409
    }
1410
    case QUERY_EXEC_MODE_EMPTY_RESULT:
×
1411
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
1412
      break;
×
1413
    default:
×
1414
      break;
×
1415
  }
1416

1417
  if (!keepQuery) {
8,360,680✔
1418
    qDestroyQuery(pQuery);
×
1419
  }
1420

1421
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
8,360,680✔
1422
    int ret = removeMeta(pRequest->pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type));
22,142✔
1423
    if (TSDB_CODE_SUCCESS != ret) {
22,142✔
1424
      tscError("req:0x%" PRIx64 ", remove meta failed,code:%d, QID:0x%" PRIx64, pRequest->self, ret,
×
1425
               pRequest->requestId);
1426
    }
1427
  }
1428

1429
  if (TSDB_CODE_SUCCESS == code) {
8,359,030✔
1430
    code = handleQueryExecRsp(pRequest);
8,358,116✔
1431
  }
1432

1433
  if (TSDB_CODE_SUCCESS != code) {
8,361,410✔
1434
    pRequest->code = code;
3,889✔
1435
  }
1436

1437
  if (res) {
8,361,410✔
1438
    *res = pRequest->body.resInfo.execRes.res;
×
1439
    pRequest->body.resInfo.execRes.res = NULL;
×
1440
  }
1441
}
8,361,410✔
1442

1443
static int32_t asyncExecSchQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta,
827,501,795✔
1444
                                 SSqlCallbackWrapper* pWrapper) {
1445
  int32_t code = TSDB_CODE_SUCCESS;
827,501,795✔
1446
  pRequest->type = pQuery->msgType;
827,501,795✔
1447
  SArray*     pMnodeList = NULL;
827,506,584✔
1448
  SArray*     pNodeList = NULL;
827,506,584✔
1449
  SQueryPlan* pDag = NULL;
827,484,087✔
1450
  int64_t     st = taosGetTimestampUs();
827,512,637✔
1451

1452
  if (!pRequest->parseOnly) {
827,512,637✔
1453
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
827,519,373✔
1454
    if (NULL == pMnodeList) {
827,520,861✔
1455
      code = terrno;
×
1456
    }
1457
    SPlanContext cxt = {.queryId = pRequest->requestId,
909,329,763✔
1458
                        .acctId = pRequest->pTscObj->acctId,
827,551,375✔
1459
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
827,560,450✔
1460
                        .pAstRoot = pQuery->pRoot,
827,570,851✔
1461
                        .showRewrite = pQuery->showRewrite,
827,557,413✔
1462
                        .isView = pWrapper->pParseCtx->isView,
827,562,316✔
1463
                        .isAudit = pWrapper->pParseCtx->isAudit,
827,550,247✔
1464
                        .privInfo = pWrapper->pParseCtx->privInfo,
827,545,715✔
1465
                        .pMsg = pRequest->msgBuf,
827,560,450✔
1466
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1467
                        .pUser = pRequest->pTscObj->user,
827,550,473✔
1468
                        .userId = pRequest->pTscObj->userId,
827,547,976✔
1469
                        .sysInfo = pRequest->pTscObj->sysInfo,
827,566,907✔
1470
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
827,558,835✔
1471
                        .allocatorId = pRequest->stmtBindVersion > 0 ? 0 : pRequest->allocatorRefId};
827,544,424✔
1472
    if (TSDB_CODE_SUCCESS == code) {
827,557,078✔
1473
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
827,539,670✔
1474
    }
1475
    if (code) {
827,511,175✔
1476
      tscError("req:0x%" PRIx64 " requestId:0x%" PRIx64 ", failed to create query plan, code:%s msg:%s", pRequest->self,
247,583✔
1477
               pRequest->requestId, tstrerror(code), cxt.pMsg);
1478
    } else {
1479
      pRequest->body.subplanNum = pDag->numOfSubplans;
827,263,592✔
1480
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
827,296,967✔
1481
    }
1482
  }
1483

1484
  pRequest->metric.execStart = taosGetTimestampUs();
827,516,031✔
1485
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
827,516,388✔
1486

1487
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
827,537,188✔
1488
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
827,066,113✔
1489
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
188,348,121✔
1490
    }
1491

1492
    if (code == TSDB_CODE_SUCCESS) {
827,091,648✔
1493
      code = sessMetricCheckValue((SSessMetric*)pRequest->pTscObj->pSessMetric, SESSION_MAX_CALL_VNODE_NUM,
827,065,669✔
1494
                                  taosArrayGetSize(pNodeList));
827,093,815✔
1495
    }
1496

1497
    if (code == TSDB_CODE_SUCCESS) {
827,090,144✔
1498
      SRequestConnInfo conn = {.pTrans = getAppInfo(pRequest)->pTransporter,
827,087,204✔
1499
                               .requestId = pRequest->requestId,
827,084,791✔
1500
                               .requestObjRefId = pRequest->self};
827,116,302✔
1501
      SSchedulerReq    req = {
867,968,995✔
1502
             .syncReq = false,
1503
             .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
827,076,362✔
1504
             .pConn = &conn,
1505
             .pNodeList = pNodeList,
1506
             .pDag = pDag,
1507
             .allocatorRefId = pRequest->allocatorRefId,
827,076,362✔
1508
             .sql = pRequest->sqlstr,
827,063,094✔
1509
             .startTs = pRequest->metric.start,
827,088,913✔
1510
             .execFp = schedulerExecCb,
1511
             .cbParam = pWrapper,
1512
             .chkKillFp = chkRequestKilled,
1513
             .chkKillParam = (void*)pRequest->self,
827,085,210✔
1514
             .pExecRes = NULL,
1515
             .source = pRequest->source,
827,053,314✔
1516
             .pWorkerCb = getTaskPoolWorkerCb(),
827,067,168✔
1517
      };
1518

1519
      if (TSDB_CODE_SUCCESS == code) {
827,059,151✔
1520
        code = schedulerExecJob(&req, &pRequest->body.queryJob);
827,109,613✔
1521
      }
1522
      taosArrayDestroy(pNodeList);
827,062,599✔
1523
      taosArrayDestroy(pMnodeList);
827,120,718✔
1524
      return code;
827,104,178✔
1525
    }
1526
  }
1527

1528
  qDestroyQueryPlan(pDag);
489,867✔
1529
  tscDebug("req:0x%" PRIx64 ", plan not executed, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
437,051✔
1530
           pRequest->requestId);
1531
  destorySqlCallbackWrapper(pWrapper);
437,051✔
1532
  pRequest->pWrapper = NULL;
437,051✔
1533
  if (TSDB_CODE_SUCCESS != code) {
437,051✔
1534
    pRequest->code = code;
250,523✔
1535
  }
1536

1537
  doRequestCallback(pRequest, code);
437,051✔
1538

1539
  // todo not to be released here
1540
  taosArrayDestroy(pMnodeList);
437,051✔
1541
  taosArrayDestroy(pNodeList);
437,051✔
1542

1543
  return code;
434,366✔
1544
}
1545

1546
void launchAsyncQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta, SSqlCallbackWrapper* pWrapper) {
931,000,844✔
1547
  int32_t code = 0;
931,000,844✔
1548

1549
  if (pRequest->parseOnly) {
931,000,844✔
1550
    doRequestCallback(pRequest, 0);
291,316✔
1551
    return;
291,316✔
1552
  }
1553

1554
  pRequest->body.execMode = pQuery->execMode;
930,727,954✔
1555
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
930,715,671✔
1556
    destorySqlCallbackWrapper(pWrapper);
103,218,145✔
1557
    pRequest->pWrapper = NULL;
103,218,834✔
1558
  }
1559

1560
  if (pQuery->pRoot && !pRequest->inRetry) {
930,702,141✔
1561
    STscObj*            pTscObj = pRequest->pTscObj;
930,749,011✔
1562
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
930,741,900✔
1563
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
930,751,069✔
1564
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
638,754,493✔
1565
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
572,531,569✔
1566
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
358,222,784✔
1567
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
140,608,051✔
1568
    }
1569
  }
1570

1571
  switch (pQuery->execMode) {
930,732,324✔
1572
    case QUERY_EXEC_MODE_LOCAL:
5,709,704✔
1573
      asyncExecLocalCmd(pRequest, pQuery);
5,709,704✔
1574
      break;
5,709,739✔
1575
    case QUERY_EXEC_MODE_RPC:
96,928,493✔
1576
      code = asyncExecDdlQuery(pRequest, pQuery);
96,928,493✔
1577
      break;
96,921,904✔
1578
    case QUERY_EXEC_MODE_SCHEDULE: {
827,527,234✔
1579
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
827,527,234✔
1580
      break;
827,541,866✔
1581
    }
1582
    case QUERY_EXEC_MODE_EMPTY_RESULT:
575,707✔
1583
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
575,707✔
1584
      doRequestCallback(pRequest, 0);
575,707✔
1585
      break;
575,707✔
1586
    default:
×
1587
      tscError("req:0x%" PRIx64 ", invalid execMode %d", pRequest->self, pQuery->execMode);
×
1588
      doRequestCallback(pRequest, -1);
×
1589
      break;
×
1590
  }
1591
}
1592

1593
int32_t refreshMeta(STscObj* pTscObj, SRequestObj* pRequest) {
11,877✔
1594
  SCatalog* pCatalog = NULL;
11,877✔
1595
  int32_t   code = 0;
11,877✔
1596
  int32_t   dbNum = taosArrayGetSize(pRequest->dbList);
11,877✔
1597
  int32_t   tblNum = taosArrayGetSize(pRequest->tableList);
11,877✔
1598

1599
  if (dbNum <= 0 && tblNum <= 0) {
11,877✔
1600
    return TSDB_CODE_APP_ERROR;
11,877✔
1601
  }
1602

1603
  code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
×
1604
  if (code != TSDB_CODE_SUCCESS) {
×
1605
    return code;
×
1606
  }
1607

1608
  SRequestConnInfo conn = {.pTrans = pTscObj->pAppInfo->pTransporter,
×
1609
                           .requestId = pRequest->requestId,
×
1610
                           .requestObjRefId = pRequest->self,
×
1611
                           .mgmtEps = getEpSet_s(&pTscObj->pAppInfo->mgmtEp)};
×
1612

1613
  for (int32_t i = 0; i < dbNum; ++i) {
×
1614
    char* dbFName = taosArrayGet(pRequest->dbList, i);
×
1615

1616
    // catalogRefreshDBVgInfo will handle dbFName == null.
1617
    code = catalogRefreshDBVgInfo(pCatalog, &conn, dbFName);
×
1618
    if (code != TSDB_CODE_SUCCESS) {
×
1619
      return code;
×
1620
    }
1621
  }
1622

1623
  for (int32_t i = 0; i < tblNum; ++i) {
×
1624
    SName* tableName = taosArrayGet(pRequest->tableList, i);
×
1625

1626
    // catalogRefreshTableMeta will handle tableName == null.
1627
    code = catalogRefreshTableMeta(pCatalog, &conn, tableName, -1);
×
1628
    if (code != TSDB_CODE_SUCCESS) {
×
1629
      return code;
×
1630
    }
1631
  }
1632

1633
  return code;
×
1634
}
1635

1636
int32_t removeMeta(STscObj* pTscObj, SArray* tbList, bool isView) {
4,757,223✔
1637
  SCatalog* pCatalog = NULL;
4,757,223✔
1638
  int32_t   tbNum = taosArrayGetSize(tbList);
4,757,223✔
1639
  int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
4,757,223✔
1640
  if (code != TSDB_CODE_SUCCESS) {
4,757,223✔
1641
    return code;
×
1642
  }
1643

1644
  if (isView) {
4,757,223✔
1645
    for (int32_t i = 0; i < tbNum; ++i) {
685,532✔
1646
      SName* pViewName = taosArrayGet(tbList, i);
342,766✔
1647
      char   dbFName[TSDB_DB_FNAME_LEN];
339,402✔
1648
      if (NULL == pViewName) {
342,766✔
1649
        continue;
×
1650
      }
1651
      (void)tNameGetFullDbName(pViewName, dbFName);
342,766✔
1652
      TSC_ERR_RET(catalogRemoveViewMeta(pCatalog, dbFName, 0, pViewName->tname, 0));
342,766✔
1653
    }
1654
  } else {
1655
    for (int32_t i = 0; i < tbNum; ++i) {
6,939,504✔
1656
      SName* pTbName = taosArrayGet(tbList, i);
2,525,047✔
1657
      TSC_ERR_RET(catalogRemoveTableMeta(pCatalog, pTbName));
2,525,047✔
1658
    }
1659
  }
1660

1661
  return TSDB_CODE_SUCCESS;
4,757,223✔
1662
}
1663

1664
int32_t initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet) {
83,200,534✔
1665
  pEpSet->version = 0;
83,200,534✔
1666

1667
  // init mnode ip set
1668
  SEpSet* mgmtEpSet = &(pEpSet->epSet);
83,200,974✔
1669
  mgmtEpSet->numOfEps = 0;
83,201,258✔
1670
  mgmtEpSet->inUse = 0;
83,201,309✔
1671

1672
  if (firstEp && firstEp[0] != 0) {
83,200,949✔
1673
    if (strlen(firstEp) >= TSDB_EP_LEN) {
83,201,780✔
1674
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1675
      return -1;
×
1676
    }
1677

1678
    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
83,201,780✔
1679
    if (code != TSDB_CODE_SUCCESS) {
83,201,157✔
1680
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1681
      return terrno;
×
1682
    }
1683
    // uint32_t addr = 0;
1684
    SIpAddr addr = {0};
83,201,157✔
1685
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
83,200,823✔
1686
    if (code) {
83,201,395✔
1687
      tscError("failed to resolve firstEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
173✔
1688
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1689
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
189✔
1690
    } else {
1691
      mgmtEpSet->numOfEps++;
83,202,502✔
1692
    }
1693
  }
1694

1695
  if (secondEp && secondEp[0] != 0) {
83,200,773✔
1696
    if (strlen(secondEp) >= TSDB_EP_LEN) {
1,840,732✔
1697
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1698
      return terrno;
×
1699
    }
1700

1701
    int32_t code = taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
1,840,732✔
1702
    if (code != TSDB_CODE_SUCCESS) {
1,841,738✔
1703
      return code;
×
1704
    }
1705
    SIpAddr addr = {0};
1,841,738✔
1706
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
1,841,098✔
1707
    if (code) {
1,841,427✔
1708
      tscError("failed to resolve secondEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
37✔
1709
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1710
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
×
1711
    } else {
1712
      mgmtEpSet->numOfEps++;
1,841,390✔
1713
    }
1714
  }
1715

1716
  if (mgmtEpSet->numOfEps == 0) {
83,202,274✔
1717
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
189✔
1718
    return TSDB_CODE_RPC_NETWORK_UNAVAIL;
189✔
1719
  }
1720

1721
  return 0;
83,201,062✔
1722
}
1723

1724
int32_t taosConnectImpl(const char* user, const char* auth, int32_t totpCode, const char* db, __taos_async_fn_t fp,
83,200,732✔
1725
                        void* param, SAppInstInfo* pAppInfo, int connType, STscObj** pTscObj) {
1726
  *pTscObj = NULL;
83,200,732✔
1727
  int32_t code = createTscObj(user, auth, db, connType, pAppInfo, pTscObj);
83,200,732✔
1728
  if (TSDB_CODE_SUCCESS != code) {
83,202,520✔
1729
    return code;
×
1730
  }
1731

1732
  SRequestObj* pRequest = NULL;
83,202,520✔
1733
  code = createRequest((*pTscObj)->id, TDMT_MND_CONNECT, 0, &pRequest);
83,202,520✔
1734
  if (TSDB_CODE_SUCCESS != code) {
83,202,610✔
1735
    destroyTscObj(*pTscObj);
×
1736
    return code;
×
1737
  }
1738

1739
  pRequest->sqlstr = taosStrdup("taos_connect");
83,202,610✔
1740
  if (pRequest->sqlstr) {
83,202,545✔
1741
    pRequest->sqlLen = strlen(pRequest->sqlstr);
83,202,472✔
1742
  } else {
1743
    return terrno;
×
1744
  }
1745

1746
  SMsgSendInfo* body = NULL;
83,202,508✔
1747
  code = buildConnectMsg(pRequest, &body, totpCode);
83,202,473✔
1748
  if (TSDB_CODE_SUCCESS != code) {
83,198,796✔
1749
    destroyTscObj(*pTscObj);
×
1750
    return code;
×
1751
  }
1752

1753
  // int64_t transporterId = 0;
1754
  SEpSet epset = getEpSet_s(&(*pTscObj)->pAppInfo->mgmtEp);
83,198,796✔
1755
  code = asyncSendMsgToServer((*pTscObj)->pAppInfo->pTransporter, &epset, NULL, body);
83,201,572✔
1756
  if (TSDB_CODE_SUCCESS != code) {
83,197,932✔
1757
    destroyTscObj(*pTscObj);
×
1758
    tscError("failed to send connect msg to server, code:%s", tstrerror(code));
×
1759
    return code;
×
1760
  }
1761
  if (TSDB_CODE_SUCCESS != tsem_wait(&pRequest->body.rspSem)) {
83,197,932✔
1762
    destroyTscObj(*pTscObj);
×
1763
    tscError("failed to wait sem, code:%s", terrstr());
×
1764
    return terrno;
×
1765
  }
1766
  if (pRequest->code != TSDB_CODE_SUCCESS) {
83,200,884✔
1767
    const char* errorMsg = (code == TSDB_CODE_RPC_FQDN_ERROR) ? taos_errstr(pRequest) : tstrerror(pRequest->code);
14,216✔
1768
    tscError("failed to connect to server, reason: %s", errorMsg);
14,216✔
1769

1770
    terrno = pRequest->code;
14,216✔
1771
    destroyRequest(pRequest);
14,216✔
1772
    taos_close_internal(*pTscObj);
14,216✔
1773
    *pTscObj = NULL;
14,216✔
1774
    return terrno;
14,216✔
1775
  }
1776
  if (connType == CONN_TYPE__AUTH_TEST) {
83,186,668✔
1777
    terrno = TSDB_CODE_SUCCESS;
×
1778
    destroyRequest(pRequest);
×
1779
    taos_close_internal(*pTscObj);
×
1780
    *pTscObj = NULL;
1,133✔
1781
    return TSDB_CODE_SUCCESS;
1,133✔
1782
  }
1783

1784
  tscInfo("conn:0x%" PRIx64 ", connection is opening, connId:%u, dnodeConn:%p, QID:0x%" PRIx64, (*pTscObj)->id,
83,186,668✔
1785
          (*pTscObj)->connId, (*pTscObj)->pAppInfo->pTransporter, pRequest->requestId);
1786
  destroyRequest(pRequest);
83,189,569✔
1787
  return code;
83,185,500✔
1788
}
1789

1790
static int32_t buildConnectMsg(SRequestObj* pRequest, SMsgSendInfo** pMsgSendInfo, int32_t totpCode) {
83,199,619✔
1791
  *pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
83,199,619✔
1792
  if (*pMsgSendInfo == NULL) {
83,202,357✔
1793
    return terrno;
×
1794
  }
1795

1796
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
83,202,392✔
1797

1798
  (*pMsgSendInfo)->requestObjRefId = pRequest->self;
83,202,392✔
1799
  (*pMsgSendInfo)->requestId = pRequest->requestId;
83,202,392✔
1800
  (*pMsgSendInfo)->fp = getMsgRspHandle((*pMsgSendInfo)->msgType);
83,202,357✔
1801
  (*pMsgSendInfo)->param = taosMemoryCalloc(1, sizeof(pRequest->self));
83,202,185✔
1802
  if (NULL == (*pMsgSendInfo)->param) {
83,202,652✔
1803
    taosMemoryFree(*pMsgSendInfo);
×
1804
    return terrno;
×
1805
  }
1806

1807
  *(int64_t*)(*pMsgSendInfo)->param = pRequest->self;
83,202,502✔
1808

1809
  SConnectReq connectReq = {0};
83,202,650✔
1810
  STscObj*    pObj = pRequest->pTscObj;
83,202,688✔
1811

1812
  char* db = getDbOfConnection(pObj);
83,202,540✔
1813
  if (db != NULL) {
83,201,924✔
1814
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
559,087✔
1815
  } else if (terrno) {
82,642,837✔
1816
    taosMemoryFree(*pMsgSendInfo);
×
1817
    return terrno;
×
1818
  }
1819
  taosMemoryFreeClear(db);
83,202,628✔
1820

1821
  connectReq.connType = pObj->connType;
83,202,738✔
1822
  connectReq.pid = appInfo.pid;
83,202,738✔
1823
  connectReq.startTime = appInfo.startTime;
83,202,666✔
1824
  connectReq.totpCode = totpCode;
83,202,666✔
1825
  connectReq.connectTime = taosGetTimestampMs();
83,200,743✔
1826

1827
  tstrncpy(connectReq.app, appInfo.appName, sizeof(connectReq.app));
83,200,743✔
1828
  tstrncpy(connectReq.user, pObj->user, sizeof(connectReq.user));
83,200,631✔
1829
  tstrncpy(connectReq.passwd, pObj->pass, sizeof(connectReq.passwd));
83,200,630✔
1830
  tstrncpy(connectReq.token, pObj->token, sizeof(connectReq.token));
83,200,589✔
1831
  tstrncpy(connectReq.sVer, td_version, sizeof(connectReq.sVer));
83,200,590✔
1832
  tSignConnectReq(&connectReq);
83,200,590✔
1833

1834
  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connectReq);
83,201,927✔
1835
  void*   pReq = taosMemoryMalloc(contLen);
83,199,284✔
1836
  if (NULL == pReq) {
83,201,206✔
1837
    taosMemoryFree(*pMsgSendInfo);
×
1838
    return terrno;
×
1839
  }
1840

1841
  if (-1 == tSerializeSConnectReq(pReq, contLen, &connectReq)) {
83,201,206✔
1842
    taosMemoryFree(*pMsgSendInfo);
15✔
1843
    taosMemoryFree(pReq);
×
1844
    return terrno;
×
1845
  }
1846

1847
  (*pMsgSendInfo)->msgInfo.len = contLen;
83,197,570✔
1848
  (*pMsgSendInfo)->msgInfo.pData = pReq;
83,197,778✔
1849
  return TSDB_CODE_SUCCESS;
83,198,009✔
1850
}
1851

1852
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
2,009,794,137✔
1853
  if (NULL == pEpSet) {
2,009,794,137✔
1854
    return;
2,005,492,833✔
1855
  }
1856

1857
  switch (pSendInfo->target.type) {
4,309,201✔
1858
    case TARGET_TYPE_MNODE:
1,024✔
1859
      if (NULL == pTscObj) {
1,024✔
1860
        tscError("mnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1861
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1862
        return;
×
1863
      }
1864

1865
      SEpSet  originEpset = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
1,024✔
1866
      SEpSet* pOrig = &originEpset;
1,024✔
1867
      SEp*    pOrigEp = &pOrig->eps[pOrig->inUse];
1,024✔
1868
      SEp*    pNewEp = &pEpSet->eps[pEpSet->inUse];
1,024✔
1869
      tscDebug("mnode epset updated from %d/%d=>%s:%d to %d/%d=>%s:%d in client", pOrig->inUse, pOrig->numOfEps,
1,024✔
1870
               pOrigEp->fqdn, pOrigEp->port, pEpSet->inUse, pEpSet->numOfEps, pNewEp->fqdn, pNewEp->port);
1871
      updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
1,024✔
1872
      break;
495,249✔
1873
    case TARGET_TYPE_VNODE: {
4,103,264✔
1874
      if (NULL == pTscObj) {
4,103,264✔
1875
        tscError("vnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1876
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1877
        return;
×
1878
      }
1879

1880
      SCatalog* pCatalog = NULL;
4,103,264✔
1881
      int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
4,103,264✔
1882
      if (code != TSDB_CODE_SUCCESS) {
4,103,277✔
1883
        tscError("fail to get catalog handle, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1884
                 tstrerror(code));
1885
        return;
×
1886
      }
1887

1888
      code = catalogUpdateVgEpSet(pCatalog, pSendInfo->target.dbFName, pSendInfo->target.vgId, pEpSet);
4,103,277✔
1889
      if (code != TSDB_CODE_SUCCESS) {
4,103,283✔
1890
        tscError("fail to update catalog vg epset, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1891
                 tstrerror(code));
1892
        return;
×
1893
      }
1894
      taosMemoryFreeClear(pSendInfo->target.dbFName);
4,103,283✔
1895
      break;
4,103,329✔
1896
    }
1897
    default:
211,539✔
1898
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
211,539✔
1899
      break;
212,172✔
1900
  }
1901
}
1902

1903
int32_t doProcessMsgFromServerImpl(SRpcMsg* pMsg, SEpSet* pEpSet) {
2,010,599,247✔
1904
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
2,010,599,247✔
1905
  if (pMsg->info.ahandle == NULL) {
2,010,604,323✔
1906
    tscError("doProcessMsgFromServer pMsg->info.ahandle == NULL");
624,202✔
1907
    rpcFreeCont(pMsg->pCont);
624,202✔
1908
    taosMemoryFree(pEpSet);
624,202✔
1909
    return TSDB_CODE_TSC_INTERNAL_ERROR;
624,202✔
1910
  }
1911

1912
  STscObj* pTscObj = NULL;
2,009,980,093✔
1913

1914
  STraceId* trace = &pMsg->info.traceId;
2,009,980,093✔
1915
  char      tbuf[40] = {0};
2,009,981,750✔
1916
  TRACE_TO_STR(trace, tbuf);
2,009,980,679✔
1917

1918
  tscDebug("QID:%s, process message from server, handle:%p, message:%s, size:%d, code:%s", tbuf, pMsg->info.handle,
2,010,009,676✔
1919
           TMSG_INFO(pMsg->msgType), pMsg->contLen, tstrerror(pMsg->code));
1920

1921
  if (pSendInfo->requestObjRefId != 0) {
2,010,010,536✔
1922
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
1,711,232,629✔
1923
    if (pRequest) {
1,711,232,018✔
1924
      if (pRequest->self != pSendInfo->requestObjRefId) {
1,697,849,574✔
1925
        tscError("doProcessMsgFromServer req:0x%" PRId64 " != pSendInfo->requestObjRefId:0x%" PRId64, pRequest->self,
×
1926
                 pSendInfo->requestObjRefId);
1927

1928
        if (TSDB_CODE_SUCCESS != taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId)) {
×
1929
          tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1930
        }
1931
        rpcFreeCont(pMsg->pCont);
×
1932
        taosMemoryFree(pEpSet);
×
1933
        destroySendMsgInfo(pSendInfo);
×
1934
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1935
      }
1936
      pTscObj = pRequest->pTscObj;
1,697,845,217✔
1937
    }
1938
  }
1939

1940
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
2,010,005,272✔
1941

1942
  SDataBuf buf = {.msgType = pMsg->msgType,
2,009,807,503✔
1943
                  .len = pMsg->contLen,
2,009,809,622✔
1944
                  .pData = NULL,
1945
                  .handle = pMsg->info.handle,
2,009,815,339✔
1946
                  .handleRefId = pMsg->info.refId,
2,009,815,169✔
1947
                  .pEpSet = pEpSet};
1948

1949
  if (pMsg->contLen > 0) {
2,009,817,254✔
1950
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
1,968,310,901✔
1951
    if (buf.pData == NULL) {
1,968,355,087✔
1952
      pMsg->code = terrno;
×
1953
    } else {
1954
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
1,968,355,087✔
1955
    }
1956
  }
1957

1958
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
2,009,883,854✔
1959

1960
  if (pTscObj) {
2,009,946,012✔
1961
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
1,697,831,238✔
1962
    if (TSDB_CODE_SUCCESS != code) {
1,697,862,355✔
1963
      tscError("doProcessMsgFromServer taosReleaseRef failed");
387✔
1964
      terrno = code;
387✔
1965
      pMsg->code = code;
387✔
1966
    }
1967
  }
1968

1969
  rpcFreeCont(pMsg->pCont);
2,009,977,129✔
1970
  destroySendMsgInfo(pSendInfo);
2,009,994,750✔
1971
  return TSDB_CODE_SUCCESS;
2,009,984,694✔
1972
}
1973

1974
int32_t doProcessMsgFromServer(void* param) {
2,010,629,519✔
1975
  AsyncArg* arg = (AsyncArg*)param;
2,010,629,519✔
1976
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
2,010,629,519✔
1977
  taosMemoryFree(arg);
2,010,603,752✔
1978
  return code;
2,010,632,749✔
1979
}
1980

1981
void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
2,010,294,976✔
1982
  int32_t code = 0;
2,010,294,976✔
1983
  SEpSet* tEpSet = NULL;
2,010,294,976✔
1984

1985
  tscDebug("msg callback, ahandle %p", pMsg->info.ahandle);
2,010,294,976✔
1986

1987
  if (pEpSet != NULL) {
2,010,341,165✔
1988
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
4,316,499✔
1989
    if (NULL == tEpSet) {
4,316,434✔
1990
      code = terrno;
×
1991
      pMsg->code = terrno;
×
1992
      goto _exit;
×
1993
    }
1994
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
4,316,434✔
1995
  }
1996

1997
  // pMsg is response msg
1998
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
2,010,341,100✔
1999
    // restore origin code
2000
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
83,140,006✔
2001
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
2002
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
83,140,006✔
2003
      pMsg->code = TSDB_CODE_RPC_BROKEN_LINK;
×
2004
    }
2005
  } else {
2006
    // uniform to one error code: TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED
2007
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
1,927,185,489✔
2008
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
2009
    }
2010
  }
2011

2012
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
2,010,346,320✔
2013
  if (NULL == arg) {
2,010,321,700✔
2014
    code = terrno;
×
2015
    pMsg->code = code;
×
2016
    goto _exit;
×
2017
  }
2018

2019
  arg->msg = *pMsg;
2,010,321,700✔
2020
  arg->pEpset = tEpSet;
2,010,325,028✔
2021

2022
  if ((code = taosAsyncExec(doProcessMsgFromServer, arg, NULL)) != 0) {
2,010,362,069✔
2023
    pMsg->code = code;
56,896✔
2024
    taosMemoryFree(arg);
56,896✔
2025
    goto _exit;
×
2026
  }
2027
  return;
2,010,450,313✔
2028

2029
_exit:
×
2030
  tscError("failed to sched msg to tsc since %s", tstrerror(code));
×
2031
  code = doProcessMsgFromServerImpl(pMsg, tEpSet);
×
2032
  if (code != 0) {
×
2033
    tscError("failed to sched msg to tsc, tsc ready quit");
×
2034
  }
2035
}
2036

2037
TAOS* taos_connect_totp(const char* ip, const char* user, const char* pass, const char* totp, const char* db,
2,148✔
2038
                        uint16_t port) {
2039
  tscInfo("try to connect to %s:%u by totp, user:%s db:%s", ip, port, user, db);
2,148✔
2040
  if (user == NULL) {
2,148✔
2041
    user = TSDB_DEFAULT_USER;
×
2042
  }
2043

2044
  if (pass == NULL) {
2,148✔
2045
    pass = TSDB_DEFAULT_PASS;
×
2046
  }
2047

2048
  STscObj* pObj = NULL;
2,148✔
2049
  int32_t  code = taos_connect_internal(ip, user, pass, totp, db, port, CONN_TYPE__QUERY, &pObj);
2,148✔
2050
  if (TSDB_CODE_SUCCESS == code) {
2,148✔
2051
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
1,449✔
2052
    if (NULL == rid) {
1,449✔
2053
      tscError("out of memory when taos_connect_totp to %s:%u, user:%s db:%s", ip, port, user, db);
×
2054
      return NULL;
×
2055
    }
2056
    *rid = pObj->id;
1,449✔
2057
    return (TAOS*)rid;
1,449✔
2058
  } else {
2059
    terrno = code;
699✔
2060
  }
2061

2062
  return NULL;
699✔
2063
}
2064

2065
int taos_connect_test(const char* ip, const char* user, const char* pass, const char* totp, const char* db,
×
2066
                      uint16_t port) {
2067
  tscInfo("try to test connect to %s:%u by totp, user:%s db:%s", ip, port, user, db);
×
2068
  if (user == NULL) {
×
2069
    user = TSDB_DEFAULT_USER;
×
2070
  }
2071

2072
  if (pass == NULL) {
×
2073
    pass = TSDB_DEFAULT_PASS;
×
2074
  }
2075

2076
  STscObj* pObj = NULL;
×
2077
  return taos_connect_internal(ip, user, pass, totp, db, port, CONN_TYPE__AUTH_TEST, &pObj);
×
2078
}
2079

2080
TAOS* taos_connect_token(const char* ip, const char* token, const char* db, uint16_t port) {
2,479✔
2081
  tscInfo("try to connect to %s:%u by token, db:%s", ip, port, db);
2,479✔
2082

2083
  STscObj* pObj = NULL;
2,479✔
2084
  int32_t  code = taos_connect_by_auth(ip, NULL, token, NULL, db, port, CONN_TYPE__QUERY, &pObj);
2,479✔
2085
  if (TSDB_CODE_SUCCESS == code) {
2,479✔
2086
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
1,152✔
2087
    if (NULL == rid) {
1,152✔
2088
      tscError("out of memory when taos_connect_token to %s:%u db:%s", ip, port, db);
×
2089
      return NULL;
×
2090
    }
2091
    *rid = pObj->id;
1,152✔
2092
    return (TAOS*)rid;
1,152✔
2093
  } else {
2094
    terrno = code;
1,327✔
2095
  }
2096

2097
  return NULL;
1,327✔
2098
}
2099

2100
TAOS* taos_connect_auth(const char* ip, const char* user, const char* auth, const char* db, uint16_t port) {
134✔
2101
  tscInfo("try to connect to %s:%u by auth, user:%s db:%s", ip, port, user, db);
134✔
2102
  if (user == NULL) {
134✔
2103
    user = TSDB_DEFAULT_USER;
×
2104
  }
2105

2106
  if (auth == NULL) {
134✔
2107
    tscError("No auth info is given, failed to connect to server");
×
2108
    return NULL;
×
2109
  }
2110

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

2122
  return NULL;
134✔
2123
}
2124

2125
// TAOS* taos_connect_l(const char* ip, int ipLen, const char* user, int userLen, const char* pass, int passLen,
2126
//                      const char* db, int dbLen, uint16_t port) {
2127
//   char ipStr[TSDB_EP_LEN] = {0};
2128
//   char dbStr[TSDB_DB_NAME_LEN] = {0};
2129
//   char userStr[TSDB_USER_LEN] = {0};
2130
//   char passStr[TSDB_PASSWORD_LEN] = {0};
2131
//
2132
//   tstrncpy(ipStr, ip, TMIN(TSDB_EP_LEN - 1, ipLen));
2133
//   tstrncpy(userStr, user, TMIN(TSDB_USER_LEN - 1, userLen));
2134
//   tstrncpy(passStr, pass, TMIN(TSDB_PASSWORD_LEN - 1, passLen));
2135
//   tstrncpy(dbStr, db, TMIN(TSDB_DB_NAME_LEN - 1, dbLen));
2136
//   return taos_connect(ipStr, userStr, passStr, dbStr, port);
2137
// }
2138

2139
void doSetOneRowPtr(SReqResultInfo* pResultInfo) {
2,147,483,647✔
2140
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
2,147,483,647✔
2141
    SResultColumn* pCol = &pResultInfo->pCol[i];
2,147,483,647✔
2142

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

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

2150
        if (IS_STR_DATA_BLOB(type)) {
2,147,483,647✔
2151
          pResultInfo->length[i] = blobDataLen(pStart);
60✔
2152
          pResultInfo->row[i] = blobDataVal(pStart);
105✔
2153
        } else {
2154
          pResultInfo->length[i] = varDataLen(pStart);
2,147,483,647✔
2155
          pResultInfo->row[i] = varDataVal(pStart);
2,147,483,647✔
2156
        }
2157
      } else {
2158
        pResultInfo->row[i] = NULL;
268,743,689✔
2159
        pResultInfo->length[i] = 0;
268,766,098✔
2160
      }
2161
    } else {
2162
      if (!colDataIsNull_f(pCol, pResultInfo->current)) {
2,147,483,647✔
2163
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + schemaBytes * pResultInfo->current;
2,147,483,647✔
2164
        pResultInfo->length[i] = schemaBytes;
2,147,483,647✔
2165
      } else {
2166
        pResultInfo->row[i] = NULL;
1,145,172,019✔
2167
        pResultInfo->length[i] = 0;
1,145,477,830✔
2168
      }
2169
    }
2170
  }
2171
}
2,147,483,647✔
2172

2173
void* doFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
×
2174
  if (pRequest == NULL) {
×
2175
    return NULL;
×
2176
  }
2177

2178
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
×
2179
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
×
2180
    // All data has returned to App already, no need to try again
2181
    if (pResultInfo->completed) {
×
2182
      pResultInfo->numOfRows = 0;
×
2183
      return NULL;
×
2184
    }
2185

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

2189
    pRequest->code = schedulerFetchRows(pRequest->body.queryJob, &req);
×
2190
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2191
      pResultInfo->numOfRows = 0;
×
2192
      return NULL;
×
2193
    }
2194

2195
    pRequest->code = setQueryResultFromRsp(&pRequest->body.resInfo, (const SRetrieveTableRsp*)pResInfo->pData,
×
2196
                                           convertUcs4, pRequest->stmtBindVersion > 0);
×
2197
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2198
      pResultInfo->numOfRows = 0;
×
2199
      return NULL;
×
2200
    }
2201

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

2206
    STscObj*            pTscObj = pRequest->pTscObj;
×
2207
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
×
2208
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
×
2209

2210
    if (pResultInfo->numOfRows == 0) {
×
2211
      return NULL;
×
2212
    }
2213
  }
2214

2215
  if (setupOneRowPtr) {
×
2216
    doSetOneRowPtr(pResultInfo);
×
2217
    pResultInfo->current += 1;
×
2218
  }
2219

2220
  return pResultInfo->row;
×
2221
}
2222

2223
static void syncFetchFn(void* param, TAOS_RES* res, int32_t numOfRows) {
204,778,433✔
2224
  tsem_t* sem = param;
204,778,433✔
2225
  if (TSDB_CODE_SUCCESS != tsem_post(sem)) {
204,778,433✔
2226
    tscError("failed to post sem, code:%s", terrstr());
×
2227
  }
2228
}
204,778,447✔
2229

2230
void* doAsyncFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
1,599,012,033✔
2231
  if (pRequest == NULL) {
1,599,012,033✔
2232
    return NULL;
×
2233
  }
2234

2235
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
1,599,012,033✔
2236
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
1,599,016,259✔
2237
    // All data has returned to App already, no need to try again
2238
    if (pResultInfo->completed) {
296,436,076✔
2239
      pResultInfo->numOfRows = 0;
91,679,400✔
2240
      return NULL;
91,679,361✔
2241
    }
2242

2243
    // convert ucs4 to native multi-bytes string
2244
    pResultInfo->convertUcs4 = convertUcs4;
204,778,363✔
2245
    tsem_t sem;
204,199,067✔
2246
    if (TSDB_CODE_SUCCESS != tsem_init(&sem, 0, 0)) {
204,778,398✔
2247
      tscError("failed to init sem, code:%s", terrstr());
×
2248
    }
2249
    taos_fetch_rows_a(pRequest, syncFetchFn, &sem);
204,778,339✔
2250
    if (TSDB_CODE_SUCCESS != tsem_wait(&sem)) {
204,778,447✔
2251
      tscError("failed to wait sem, code:%s", terrstr());
×
2252
    }
2253
    if (TSDB_CODE_SUCCESS != tsem_destroy(&sem)) {
204,778,447✔
2254
      tscError("failed to destroy sem, code:%s", terrstr());
×
2255
    }
2256
    pRequest->inCallback = false;
204,778,447✔
2257
  }
2258

2259
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
1,507,341,031✔
2260
    return NULL;
10,886,338✔
2261
  } else {
2262
    if (setupOneRowPtr) {
1,496,455,354✔
2263
      doSetOneRowPtr(pResultInfo);
1,301,301,493✔
2264
      pResultInfo->current += 1;
1,301,300,656✔
2265
    }
2266

2267
    return pResultInfo->row;
1,496,454,461✔
2268
  }
2269
}
2270

2271
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
283,106,832✔
2272
  if (pResInfo->row == NULL) {
283,106,832✔
2273
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
177,203,619✔
2274
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
177,205,096✔
2275
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
177,205,086✔
2276
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
177,203,065✔
2277

2278
    if (pResInfo->row == NULL || pResInfo->pCol == NULL || pResInfo->length == NULL || pResInfo->convertBuf == NULL) {
177,202,241✔
2279
      taosMemoryFree(pResInfo->row);
109✔
2280
      taosMemoryFree(pResInfo->pCol);
×
2281
      taosMemoryFree(pResInfo->length);
×
2282
      taosMemoryFree(pResInfo->convertBuf);
×
2283
      return terrno;
×
2284
    }
2285
  }
2286

2287
  return TSDB_CODE_SUCCESS;
283,107,204✔
2288
}
2289

2290
static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength, bool isStmt) {
283,013,401✔
2291
  int32_t idx = -1;
283,013,401✔
2292
  iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt);
283,013,509✔
2293
  if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR;
283,008,857✔
2294

2295
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
1,633,060,151✔
2296
    int32_t type = pResultInfo->fields[i].type;
1,350,060,889✔
2297
    int32_t schemaBytes =
2298
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
1,350,057,771✔
2299

2300
    if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) {
1,350,054,401✔
2301
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
88,717,515✔
2302
      if (p == NULL) {
88,717,515✔
2303
        taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
×
2304
        return terrno;
×
2305
      }
2306

2307
      pResultInfo->convertBuf[i] = p;
88,717,515✔
2308

2309
      SResultColumn* pCol = &pResultInfo->pCol[i];
88,717,515✔
2310
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
2,147,483,647✔
2311
        if (pCol->offset[j] != -1) {
2,147,483,647✔
2312
          char* pStart = pCol->offset[j] + pCol->pData;
2,147,483,647✔
2313

2314
          int32_t len = taosUcs4ToMbsEx((TdUcs4*)varDataVal(pStart), varDataLen(pStart), varDataVal(p), conv);
2,147,483,647✔
2315
          if (len < 0 || len > schemaBytes || (p + len) >= (pResultInfo->convertBuf[i] + colLength[i])) {
2,147,483,647✔
2316
            tscError(
63✔
2317
                "doConvertUCS4 error, invalid data. len:%d, bytes:%d, (p + len):%p, (pResultInfo->convertBuf[i] + "
2318
                "colLength[i]):%p",
2319
                len, schemaBytes, (p + len), (pResultInfo->convertBuf[i] + colLength[i]));
2320
            taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
63✔
2321
            return TSDB_CODE_TSC_INTERNAL_ERROR;
63✔
2322
          }
2323

2324
          varDataSetLen(p, len);
2,147,483,647✔
2325
          pCol->offset[j] = (p - pResultInfo->convertBuf[i]);
2,147,483,647✔
2326
          p += (len + VARSTR_HEADER_SIZE);
2,147,483,647✔
2327
        }
2328
      }
2329

2330
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
88,717,452✔
2331
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
88,717,452✔
2332
    }
2333
  }
2334
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
283,012,392✔
2335
  return TSDB_CODE_SUCCESS;
283,012,726✔
2336
}
2337

2338
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
283,010,926✔
2339
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
1,633,059,295✔
2340
    TAOS_FIELD_E* pFieldE = pResultInfo->fields + i;
1,350,053,563✔
2341
    TAOS_FIELD*   pField = pResultInfo->userFields + i;
1,350,053,110✔
2342
    int32_t       type = pFieldE->type;
1,350,051,006✔
2343
    int32_t       bufLen = 0;
1,350,052,742✔
2344
    char*         p = NULL;
1,350,052,742✔
2345
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
1,350,052,742✔
2346
      continue;
1,348,495,898✔
2347
    } else {
2348
      bufLen = 64;
1,553,714✔
2349
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
1,553,714✔
2350
      pFieldE->bytes = bufLen;
1,553,714✔
2351
      pField->bytes = bufLen;
1,553,714✔
2352
    }
2353
    if (!p) return terrno;
1,553,714✔
2354
    pResultInfo->convertBuf[i] = p;
1,553,714✔
2355

2356
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
985,829,296✔
2357
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
984,275,582✔
2358
                                  pFieldE->precision, pFieldE->scale, p, bufLen);
984,275,582✔
2359
      p += bufLen;
984,275,582✔
2360
      if (TSDB_CODE_SUCCESS != code) {
984,275,582✔
2361
        return code;
×
2362
      }
2363
    }
2364
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
1,553,714✔
2365
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
1,553,714✔
2366
  }
2367
  return 0;
283,011,969✔
2368
}
2369

2370
int32_t getVersion1BlockMetaSize(const char* p, int32_t numOfCols) {
398,254✔
2371
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) * 3 + sizeof(uint64_t) +
796,508✔
2372
         numOfCols * (sizeof(int8_t) + sizeof(int32_t));
398,254✔
2373
}
2374

2375
static int32_t estimateJsonLen(SReqResultInfo* pResultInfo) {
199,127✔
2376
  char*   p = (char*)pResultInfo->pData;
199,127✔
2377
  int32_t blockVersion = *(int32_t*)p;
199,127✔
2378

2379
  int32_t numOfRows = pResultInfo->numOfRows;
199,127✔
2380
  int32_t numOfCols = pResultInfo->numOfCols;
199,127✔
2381

2382
  // | version | total length | total rows | total columns | flag seg| block group id | column schema | each column
2383
  // length |
2384
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
199,127✔
2385
  if (numOfCols != cols) {
199,127✔
2386
    tscError("estimateJsonLen error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2387
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2388
  }
2389

2390
  int32_t  len = getVersion1BlockMetaSize(p, numOfCols);
199,127✔
2391
  int32_t* colLength = (int32_t*)(p + len);
199,127✔
2392
  len += sizeof(int32_t) * numOfCols;
199,127✔
2393

2394
  char* pStart = p + len;
199,127✔
2395
  for (int32_t i = 0; i < numOfCols; ++i) {
849,374✔
2396
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
650,247✔
2397

2398
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
650,247✔
2399
      int32_t* offset = (int32_t*)pStart;
230,894✔
2400
      int32_t  lenTmp = numOfRows * sizeof(int32_t);
230,894✔
2401
      len += lenTmp;
230,894✔
2402
      pStart += lenTmp;
230,894✔
2403

2404
      int32_t estimateColLen = 0;
230,894✔
2405
      for (int32_t j = 0; j < numOfRows; ++j) {
1,110,039✔
2406
        if (offset[j] == -1) {
879,145✔
2407
          continue;
48,786✔
2408
        }
2409
        char* data = offset[j] + pStart;
830,359✔
2410

2411
        int32_t jsonInnerType = *data;
830,359✔
2412
        char*   jsonInnerData = data + CHAR_BYTES;
830,359✔
2413
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
830,359✔
2414
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
11,496✔
2415
        } else if (tTagIsJson(data)) {
818,863✔
2416
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
202,970✔
2417
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
615,893✔
2418
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
572,783✔
2419
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
43,110✔
2420
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
31,614✔
2421
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
11,496✔
2422
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
11,496✔
2423
        } else if (IS_STR_DATA_BLOB(jsonInnerType)) {
×
2424
          estimateColLen += (BLOBSTR_HEADER_SIZE + 32);
×
2425
        } else {
2426
          tscError("estimateJsonLen error: invalid type:%d", jsonInnerType);
×
2427
          return -1;
×
2428
        }
2429
      }
2430
      len += TMAX(colLen, estimateColLen);
230,894✔
2431
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
419,353✔
2432
      int32_t lenTmp = numOfRows * sizeof(int32_t);
57,480✔
2433
      len += (lenTmp + colLen);
57,480✔
2434
      pStart += lenTmp;
57,480✔
2435
    } else {
2436
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
361,873✔
2437
      len += (lenTmp + colLen);
361,873✔
2438
      pStart += lenTmp;
361,873✔
2439
    }
2440
    pStart += colLen;
650,247✔
2441
  }
2442

2443
  // Ensure the complete structure of the block, including the blankfill field,
2444
  // even though it is not used on the client side.
2445
  len += sizeof(bool);
199,127✔
2446
  return len;
199,127✔
2447
}
2448

2449
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
283,104,482✔
2450
  int32_t numOfRows = pResultInfo->numOfRows;
283,104,482✔
2451
  int32_t numOfCols = pResultInfo->numOfCols;
283,104,842✔
2452
  bool    needConvert = false;
283,102,873✔
2453
  for (int32_t i = 0; i < numOfCols; ++i) {
1,633,143,885✔
2454
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
1,350,235,410✔
2455
      needConvert = true;
199,127✔
2456
      break;
199,127✔
2457
    }
2458
  }
2459

2460
  if (!needConvert) {
283,107,602✔
2461
    return TSDB_CODE_SUCCESS;
282,908,475✔
2462
  }
2463

2464
  tscDebug("start to convert form json format string");
199,127✔
2465

2466
  char*   p = (char*)pResultInfo->pData;
199,127✔
2467
  int32_t blockVersion = *(int32_t*)p;
199,127✔
2468
  int32_t dataLen = estimateJsonLen(pResultInfo);
199,127✔
2469
  if (dataLen <= 0) {
199,127✔
2470
    tscError("doConvertJson error: estimateJsonLen failed");
×
2471
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2472
  }
2473

2474
  taosMemoryFreeClear(pResultInfo->convertJson);
199,127✔
2475
  pResultInfo->convertJson = taosMemoryCalloc(1, dataLen);
199,127✔
2476
  if (pResultInfo->convertJson == NULL) return terrno;
199,127✔
2477
  char* p1 = pResultInfo->convertJson;
199,127✔
2478

2479
  int32_t totalLen = 0;
199,127✔
2480
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
199,127✔
2481
  if (numOfCols != cols) {
199,127✔
2482
    tscError("doConvertJson error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2483
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2484
  }
2485

2486
  int32_t len = getVersion1BlockMetaSize(p, numOfCols);
199,127✔
2487
  (void)memcpy(p1, p, len);
199,127✔
2488

2489
  p += len;
199,127✔
2490
  p1 += len;
199,127✔
2491
  totalLen += len;
199,127✔
2492

2493
  len = sizeof(int32_t) * numOfCols;
199,127✔
2494
  int32_t* colLength = (int32_t*)p;
199,127✔
2495
  int32_t* colLength1 = (int32_t*)p1;
199,127✔
2496
  (void)memcpy(p1, p, len);
199,127✔
2497
  p += len;
199,127✔
2498
  p1 += len;
199,127✔
2499
  totalLen += len;
199,127✔
2500

2501
  char* pStart = p;
199,127✔
2502
  char* pStart1 = p1;
199,127✔
2503
  for (int32_t i = 0; i < numOfCols; ++i) {
849,374✔
2504
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
650,247✔
2505
    int32_t colLen1 = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength1[i]) : colLength1[i];
650,247✔
2506
    if (colLen >= dataLen) {
650,247✔
2507
      tscError("doConvertJson error: colLen:%d >= dataLen:%d", colLen, dataLen);
×
2508
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2509
    }
2510
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
650,247✔
2511
      int32_t* offset = (int32_t*)pStart;
230,894✔
2512
      int32_t* offset1 = (int32_t*)pStart1;
230,894✔
2513
      len = numOfRows * sizeof(int32_t);
230,894✔
2514
      (void)memcpy(pStart1, pStart, len);
230,894✔
2515
      pStart += len;
230,894✔
2516
      pStart1 += len;
230,894✔
2517
      totalLen += len;
230,894✔
2518

2519
      len = 0;
230,894✔
2520
      for (int32_t j = 0; j < numOfRows; ++j) {
1,110,039✔
2521
        if (offset[j] == -1) {
879,145✔
2522
          continue;
48,786✔
2523
        }
2524
        char* data = offset[j] + pStart;
830,359✔
2525

2526
        int32_t jsonInnerType = *data;
830,359✔
2527
        char*   jsonInnerData = data + CHAR_BYTES;
830,359✔
2528
        char    dst[TSDB_MAX_JSON_TAG_LEN] = {0};
830,359✔
2529
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
830,359✔
2530
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s", TSDB_DATA_NULL_STR_L);
11,496✔
2531
          varDataSetLen(dst, strlen(varDataVal(dst)));
11,496✔
2532
        } else if (tTagIsJson(data)) {
818,863✔
2533
          char* jsonString = NULL;
202,970✔
2534
          parseTagDatatoJson(data, &jsonString, pResultInfo->charsetCxt);
202,970✔
2535
          if (jsonString == NULL) {
202,970✔
2536
            tscError("doConvertJson error: parseTagDatatoJson failed");
×
2537
            return terrno;
×
2538
          }
2539
          STR_TO_VARSTR(dst, jsonString);
202,970✔
2540
          taosMemoryFree(jsonString);
202,970✔
2541
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
615,893✔
2542
          *(char*)varDataVal(dst) = '\"';
572,783✔
2543
          char    tmp[TSDB_MAX_JSON_TAG_LEN] = {0};
572,783✔
2544
          int32_t length = taosUcs4ToMbs((TdUcs4*)varDataVal(jsonInnerData), varDataLen(jsonInnerData), varDataVal(tmp),
572,783✔
2545
                                         pResultInfo->charsetCxt);
2546
          if (length <= 0) {
572,783✔
2547
            tscError("charset:%s to %s. convert failed.", DEFAULT_UNICODE_ENCODEC,
479✔
2548
                     pResultInfo->charsetCxt != NULL ? ((SConvInfo*)(pResultInfo->charsetCxt))->charset : tsCharset);
2549
            length = 0;
479✔
2550
          }
2551
          int32_t escapeLength = escapeToPrinted(varDataVal(dst) + CHAR_BYTES, TSDB_MAX_JSON_TAG_LEN - CHAR_BYTES * 2,
572,783✔
2552
                                                 varDataVal(tmp), length);
2553
          varDataSetLen(dst, escapeLength + CHAR_BYTES * 2);
572,783✔
2554
          *(char*)POINTER_SHIFT(varDataVal(dst), escapeLength + CHAR_BYTES) = '\"';
572,783✔
2555
          tscError("value:%s.", varDataVal(dst));
572,783✔
2556
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
43,110✔
2557
          double jsonVd = *(double*)(jsonInnerData);
31,614✔
2558
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%.9lf", jsonVd);
31,614✔
2559
          varDataSetLen(dst, strlen(varDataVal(dst)));
31,614✔
2560
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
11,496✔
2561
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s",
11,496✔
2562
                         (*((char*)jsonInnerData) == 1) ? "true" : "false");
11,496✔
2563
          varDataSetLen(dst, strlen(varDataVal(dst)));
11,496✔
2564
        } else {
2565
          tscError("doConvertJson error: invalid type:%d", jsonInnerType);
×
2566
          return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2567
        }
2568

2569
        offset1[j] = len;
830,359✔
2570
        (void)memcpy(pStart1 + len, dst, varDataTLen(dst));
830,359✔
2571
        len += varDataTLen(dst);
830,359✔
2572
      }
2573
      colLen1 = len;
230,894✔
2574
      totalLen += colLen1;
230,894✔
2575
      colLength1[i] = (blockVersion == BLOCK_VERSION_1) ? htonl(len) : len;
230,894✔
2576
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
419,353✔
2577
      len = numOfRows * sizeof(int32_t);
57,480✔
2578
      (void)memcpy(pStart1, pStart, len);
57,480✔
2579
      pStart += len;
57,480✔
2580
      pStart1 += len;
57,480✔
2581
      totalLen += len;
57,480✔
2582
      totalLen += colLen;
57,480✔
2583
      (void)memcpy(pStart1, pStart, colLen);
57,480✔
2584
    } else {
2585
      len = BitmapLen(pResultInfo->numOfRows);
361,873✔
2586
      (void)memcpy(pStart1, pStart, len);
361,873✔
2587
      pStart += len;
361,873✔
2588
      pStart1 += len;
361,873✔
2589
      totalLen += len;
361,873✔
2590
      totalLen += colLen;
361,873✔
2591
      (void)memcpy(pStart1, pStart, colLen);
361,873✔
2592
    }
2593
    pStart += colLen;
650,247✔
2594
    pStart1 += colLen1;
650,247✔
2595
  }
2596

2597
  // Ensure the complete structure of the block, including the blankfill field,
2598
  // even though it is not used on the client side.
2599
  // (void)memcpy(pStart1, pStart, sizeof(bool));
2600
  totalLen += sizeof(bool);
199,127✔
2601

2602
  *(int32_t*)(pResultInfo->convertJson + 4) = totalLen;
199,127✔
2603
  pResultInfo->pData = pResultInfo->convertJson;
199,127✔
2604
  return TSDB_CODE_SUCCESS;
199,127✔
2605
}
2606

2607
int32_t setResultDataPtr(SReqResultInfo* pResultInfo, bool convertUcs4, bool isStmt) {
306,570,280✔
2608
  bool convertForDecimal = convertUcs4;
306,570,280✔
2609
  if (pResultInfo == NULL || pResultInfo->numOfCols <= 0 || pResultInfo->fields == NULL) {
306,570,280✔
2610
    tscError("setResultDataPtr paras error");
14✔
2611
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2612
  }
2613

2614
  if (pResultInfo->numOfRows == 0) {
306,570,165✔
2615
    return TSDB_CODE_SUCCESS;
23,462,364✔
2616
  }
2617

2618
  if (pResultInfo->pData == NULL) {
283,107,553✔
2619
    tscError("setResultDataPtr error: pData is NULL");
×
2620
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2621
  }
2622

2623
  int32_t code = doPrepareResPtr(pResultInfo);
283,105,911✔
2624
  if (code != TSDB_CODE_SUCCESS) {
283,107,526✔
2625
    return code;
×
2626
  }
2627
  code = doConvertJson(pResultInfo);
283,107,526✔
2628
  if (code != TSDB_CODE_SUCCESS) {
283,104,952✔
2629
    return code;
×
2630
  }
2631

2632
  char* p = (char*)pResultInfo->pData;
283,104,952✔
2633

2634
  // version:
2635
  int32_t blockVersion = *(int32_t*)p;
283,105,312✔
2636
  p += sizeof(int32_t);
283,106,088✔
2637

2638
  int32_t dataLen = *(int32_t*)p;
283,106,088✔
2639
  p += sizeof(int32_t);
283,106,812✔
2640

2641
  int32_t rows = *(int32_t*)p;
283,107,203✔
2642
  p += sizeof(int32_t);
283,107,147✔
2643

2644
  int32_t cols = *(int32_t*)p;
283,107,513✔
2645
  p += sizeof(int32_t);
283,107,563✔
2646

2647
  if (rows != pResultInfo->numOfRows || cols != pResultInfo->numOfCols) {
283,108,312✔
2648
    tscError("setResultDataPtr paras error:rows;%d numOfRows:%" PRId64 " cols:%d numOfCols:%d", rows,
2,711✔
2649
             pResultInfo->numOfRows, cols, pResultInfo->numOfCols);
2650
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2651
  }
2652

2653
  int32_t hasColumnSeg = *(int32_t*)p;
283,105,214✔
2654
  p += sizeof(int32_t);
283,106,691✔
2655

2656
  uint64_t groupId = taosGetUInt64Aligned((uint64_t*)p);
283,107,954✔
2657
  p += sizeof(uint64_t);
283,107,954✔
2658

2659
  // check fields
2660
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
1,633,399,934✔
2661
    int8_t type = *(int8_t*)p;
1,350,298,025✔
2662
    p += sizeof(int8_t);
1,350,296,597✔
2663

2664
    int32_t bytes = *(int32_t*)p;
1,350,297,355✔
2665
    p += sizeof(int32_t);
1,350,297,321✔
2666

2667
    if (IS_DECIMAL_TYPE(type) && pResultInfo->fields[i].precision == 0) {
1,350,299,466✔
2668
      extractDecimalTypeInfoFromBytes(&bytes, &pResultInfo->fields[i].precision, &pResultInfo->fields[i].scale);
34,320✔
2669
    }
2670
  }
2671

2672
  int32_t* colLength = (int32_t*)p;
283,108,592✔
2673
  p += sizeof(int32_t) * pResultInfo->numOfCols;
283,108,592✔
2674

2675
  char* pStart = p;
283,107,948✔
2676
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
1,633,411,895✔
2677
    if ((pStart - pResultInfo->pData) >= dataLen) {
1,350,305,081✔
2678
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2679
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2680
    }
2681
    if (blockVersion == BLOCK_VERSION_1) {
1,350,298,062✔
2682
      colLength[i] = htonl(colLength[i]);
1,052,663,881✔
2683
    }
2684
    if (colLength[i] >= dataLen) {
1,350,299,554✔
2685
      tscError("invalid colLength %d, dataLen %d", colLength[i], dataLen);
×
2686
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2687
    }
2688
    if (IS_INVALID_TYPE(pResultInfo->fields[i].type)) {
1,350,299,277✔
2689
      tscError("invalid type %d", pResultInfo->fields[i].type);
213✔
2690
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2691
    }
2692
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
1,350,303,821✔
2693
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
293,262,361✔
2694
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
293,275,136✔
2695
    } else {
2696
      pResultInfo->pCol[i].nullbitmap = pStart;
1,057,031,426✔
2697
      pStart += BitmapLen(pResultInfo->numOfRows);
1,057,033,347✔
2698
    }
2699

2700
    pResultInfo->pCol[i].pData = pStart;
1,350,307,716✔
2701
    pResultInfo->length[i] =
2,147,483,647✔
2702
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
2,147,483,647✔
2703
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
1,350,307,336✔
2704

2705
    pStart += colLength[i];
1,350,304,098✔
2706
  }
2707

2708
  p = pStart;
283,108,647✔
2709
  // bool blankFill = *(bool*)p;
2710
  p += sizeof(bool);
283,108,647✔
2711
  int32_t offset = p - pResultInfo->pData;
283,108,647✔
2712
  if (offset > dataLen) {
283,108,319✔
2713
    tscError("invalid offset %d, dataLen %d", offset, dataLen);
×
2714
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2715
  }
2716

2717
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
2718
  if (convertUcs4) {
283,108,319✔
2719
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
283,013,506✔
2720
  }
2721
#endif
2722
  if (TSDB_CODE_SUCCESS == code && convertForDecimal) {
283,107,602✔
2723
    code = convertDecimalType(pResultInfo);
283,012,726✔
2724
  }
2725
  return code;
283,107,238✔
2726
}
2727

2728
char* getDbOfConnection(STscObj* pObj) {
1,190,985,519✔
2729
  terrno = TSDB_CODE_SUCCESS;
1,190,985,519✔
2730
  char* p = NULL;
1,191,003,775✔
2731
  (void)taosThreadMutexLock(&pObj->mutex);
1,191,003,775✔
2732
  size_t len = strlen(pObj->db);
1,191,022,911✔
2733
  if (len > 0) {
1,191,023,823✔
2734
    p = taosStrndup(pObj->db, tListLen(pObj->db));
841,594,804✔
2735
    if (p == NULL) {
841,592,699✔
2736
      tscError("failed to taosStrndup db name");
×
2737
    }
2738
  }
2739

2740
  (void)taosThreadMutexUnlock(&pObj->mutex);
1,191,021,718✔
2741
  return p;
1,190,997,992✔
2742
}
2743

2744
void setConnectionDB(STscObj* pTscObj, const char* db) {
82,763,418✔
2745
  if (db == NULL || pTscObj == NULL) {
82,763,418✔
2746
    tscError("setConnectionDB para is NULL");
×
2747
    return;
×
2748
  }
2749

2750
  (void)taosThreadMutexLock(&pTscObj->mutex);
82,806,403✔
2751
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
82,822,013✔
2752
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
82,821,965✔
2753
}
2754

2755
void resetConnectDB(STscObj* pTscObj) {
×
2756
  if (pTscObj == NULL) {
×
2757
    return;
×
2758
  }
2759

2760
  (void)taosThreadMutexLock(&pTscObj->mutex);
×
2761
  pTscObj->db[0] = 0;
×
2762
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
×
2763
}
2764

2765
int32_t setQueryResultFromRsp(SReqResultInfo* pResultInfo, const SRetrieveTableRsp* pRsp, bool convertUcs4,
252,386,972✔
2766
                              bool isStmt) {
2767
  if (pResultInfo == NULL || pRsp == NULL) {
252,386,972✔
UNCOV
2768
    tscError("setQueryResultFromRsp paras is null");
×
2769
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2770
  }
2771

2772
  taosMemoryFreeClear(pResultInfo->pRspMsg);
252,387,006✔
2773
  pResultInfo->pRspMsg = (const char*)pRsp;
252,387,002✔
2774
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
252,387,048✔
2775
  pResultInfo->current = 0;
252,386,975✔
2776
  pResultInfo->completed = (pRsp->completed == 1);
252,386,975✔
2777
  pResultInfo->precision = pRsp->precision;
252,387,010✔
2778

2779
  // decompress data if needed
2780
  int32_t payloadLen = htonl(pRsp->payloadLen);
252,386,964✔
2781

2782
  if (pRsp->compressed) {
252,386,994✔
2783
    if (pResultInfo->decompBuf == NULL) {
×
2784
      pResultInfo->decompBuf = taosMemoryMalloc(payloadLen);
×
2785
      if (pResultInfo->decompBuf == NULL) {
×
2786
        tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2787
        return terrno;
×
2788
      }
2789
      pResultInfo->decompBufSize = payloadLen;
×
2790
    } else {
2791
      if (pResultInfo->decompBufSize < payloadLen) {
×
2792
        char* p = taosMemoryRealloc(pResultInfo->decompBuf, payloadLen);
×
2793
        if (p == NULL) {
×
2794
          tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2795
          return terrno;
×
2796
        }
2797

2798
        pResultInfo->decompBuf = p;
×
2799
        pResultInfo->decompBufSize = payloadLen;
×
2800
      }
2801
    }
2802
  }
2803

2804
  if (payloadLen > 0) {
252,386,942✔
2805
    int32_t compLen = *(int32_t*)pRsp->data;
228,925,048✔
2806
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
228,925,044✔
2807

2808
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
228,924,974✔
2809

2810
    if (pRsp->compressed && compLen < rawLen) {
228,924,959✔
2811
      int32_t len = tsDecompressString(pStart, compLen, 1, pResultInfo->decompBuf, rawLen, ONE_STAGE_COMP, NULL, 0);
×
2812
      if (len < 0) {
×
2813
        tscError("tsDecompressString failed");
×
2814
        return terrno ? terrno : TSDB_CODE_FAILED;
×
2815
      }
2816
      if (len != rawLen) {
×
2817
        tscError("tsDecompressString failed, len:%d != rawLen:%d", len, rawLen);
×
2818
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2819
      }
2820
      pResultInfo->pData = pResultInfo->decompBuf;
×
2821
      pResultInfo->payloadLen = rawLen;
×
2822
    } else {
2823
      pResultInfo->pData = pStart;
228,924,980✔
2824
      pResultInfo->payloadLen = htonl(pRsp->compLen);
228,925,013✔
2825
      if (pRsp->compLen != pRsp->payloadLen) {
228,924,976✔
2826
        tscError("pRsp->compLen:%d != pRsp->payloadLen:%d", pRsp->compLen, pRsp->payloadLen);
×
2827
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2828
      }
2829
    }
2830
  }
2831

2832
  // TODO handle the compressed case
2833
  pResultInfo->totalRows += pResultInfo->numOfRows;
252,386,797✔
2834

2835
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
252,386,971✔
2836
  return code;
252,387,009✔
2837
}
2838

2839
TSDB_SERVER_STATUS taos_check_server_status(const char* fqdn, int port, char* details, int maxlen) {
284✔
2840
  TSDB_SERVER_STATUS code = TSDB_SRV_STATUS_UNAVAILABLE;
284✔
2841
  void*              clientRpc = NULL;
284✔
2842
  SServerStatusRsp   statusRsp = {0};
284✔
2843
  SEpSet             epSet = {.inUse = 0, .numOfEps = 1};
284✔
2844
  SRpcMsg  rpcMsg = {.info.ahandle = (void*)0x9527, .info.notFreeAhandle = 1, .msgType = TDMT_DND_SERVER_STATUS};
284✔
2845
  SRpcMsg  rpcRsp = {0};
284✔
2846
  SRpcInit rpcInit = {0};
284✔
2847
  char     pass[TSDB_PASSWORD_LEN + 1] = {0};
284✔
2848

2849
  rpcInit.label = "CHK";
284✔
2850
  rpcInit.numOfThreads = 1;
284✔
2851
  rpcInit.cfp = NULL;
284✔
2852
  rpcInit.sessions = 16;
284✔
2853
  rpcInit.connType = TAOS_CONN_CLIENT;
284✔
2854
  rpcInit.idleTime = tsShellActivityTimer * 1000;
284✔
2855
  rpcInit.compressSize = tsCompressMsgSize;
284✔
2856
  rpcInit.user = "_dnd";
284✔
2857

2858
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
284✔
2859
  connLimitNum = TMAX(connLimitNum, 10);
284✔
2860
  connLimitNum = TMIN(connLimitNum, 500);
284✔
2861
  rpcInit.connLimitNum = connLimitNum;
284✔
2862
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
284✔
2863
  rpcInit.readTimeout = tsReadTimeout;
284✔
2864
  rpcInit.ipv6 = tsEnableIpv6;
284✔
2865
  rpcInit.enableSSL = tsEnableTLS;
284✔
2866

2867
  memcpy(rpcInit.caPath, tsTLSCaPath, strlen(tsTLSCaPath));
284✔
2868
  memcpy(rpcInit.certPath, tsTLSSvrCertPath, strlen(tsTLSSvrCertPath));
284✔
2869
  memcpy(rpcInit.keyPath, tsTLSSvrKeyPath, strlen(tsTLSSvrKeyPath));
284✔
2870
  memcpy(rpcInit.cliCertPath, tsTLSCliCertPath, strlen(tsTLSCliCertPath));
284✔
2871
  memcpy(rpcInit.cliKeyPath, tsTLSCliKeyPath, strlen(tsTLSCliKeyPath));
284✔
2872

2873
  if (TSDB_CODE_SUCCESS != taosVersionStrToInt(td_version, &rpcInit.compatibilityVer)) {
284✔
2874
    tscError("faild to convert taos version from str to int, errcode:%s", terrstr());
×
2875
    goto _OVER;
×
2876
  }
2877

2878
  clientRpc = rpcOpen(&rpcInit);
284✔
2879
  if (clientRpc == NULL) {
284✔
2880
    code = terrno;
×
2881
    tscError("failed to init server status client since %s", tstrerror(code));
×
2882
    goto _OVER;
×
2883
  }
2884

2885
  if (fqdn == NULL) {
284✔
2886
    fqdn = tsLocalFqdn;
284✔
2887
  }
2888

2889
  if (port == 0) {
284✔
2890
    port = tsServerPort;
284✔
2891
  }
2892

2893
  tstrncpy(epSet.eps[0].fqdn, fqdn, TSDB_FQDN_LEN);
284✔
2894
  epSet.eps[0].port = (uint16_t)port;
284✔
2895
  int32_t ret = rpcSendRecv(clientRpc, &epSet, &rpcMsg, &rpcRsp);
284✔
2896
  if (TSDB_CODE_SUCCESS != ret) {
284✔
2897
    tscError("failed to send recv since %s", tstrerror(ret));
×
2898
    goto _OVER;
×
2899
  }
2900

2901
  if (rpcRsp.code != 0 || rpcRsp.contLen <= 0 || rpcRsp.pCont == NULL) {
284✔
2902
    tscError("failed to send server status req since %s", terrstr());
68✔
2903
    goto _OVER;
68✔
2904
  }
2905

2906
  if (tDeserializeSServerStatusRsp(rpcRsp.pCont, rpcRsp.contLen, &statusRsp) != 0) {
216✔
2907
    tscError("failed to parse server status rsp since %s", terrstr());
×
2908
    goto _OVER;
×
2909
  }
2910

2911
  code = statusRsp.statusCode;
216✔
2912
  if (details != NULL) {
216✔
2913
    tstrncpy(details, statusRsp.details, maxlen);
216✔
2914
  }
2915

2916
_OVER:
268✔
2917
  if (clientRpc != NULL) {
284✔
2918
    rpcClose(clientRpc);
284✔
2919
  }
2920
  if (rpcRsp.pCont != NULL) {
284✔
2921
    rpcFreeCont(rpcRsp.pCont);
216✔
2922
  }
2923
  return code;
284✔
2924
}
2925

2926
int32_t appendTbToReq(SHashObj* pHash, int32_t pos1, int32_t len1, int32_t pos2, int32_t len2, const char* str,
1,194✔
2927
                      int32_t acctId, char* db) {
2928
  SName name = {0};
1,194✔
2929

2930
  if (len1 <= 0) {
1,194✔
2931
    return -1;
×
2932
  }
2933

2934
  const char* dbName = db;
1,194✔
2935
  const char* tbName = NULL;
1,194✔
2936
  int32_t     dbLen = 0;
1,194✔
2937
  int32_t     tbLen = 0;
1,194✔
2938
  if (len2 > 0) {
1,194✔
2939
    dbName = str + pos1;
×
2940
    dbLen = len1;
×
2941
    tbName = str + pos2;
×
2942
    tbLen = len2;
×
2943
  } else {
2944
    dbLen = strlen(db);
1,194✔
2945
    tbName = str + pos1;
1,194✔
2946
    tbLen = len1;
1,194✔
2947
  }
2948

2949
  if (dbLen <= 0 || tbLen <= 0) {
1,194✔
2950
    return -1;
×
2951
  }
2952

2953
  if (tNameSetDbName(&name, acctId, dbName, dbLen)) {
1,194✔
2954
    return -1;
×
2955
  }
2956

2957
  if (tNameAddTbName(&name, tbName, tbLen)) {
1,194✔
2958
    return -1;
×
2959
  }
2960

2961
  char dbFName[TSDB_DB_FNAME_LEN] = {0};
1,194✔
2962
  (void)snprintf(dbFName, TSDB_DB_FNAME_LEN, "%d.%.*s", acctId, dbLen, dbName);
1,194✔
2963

2964
  STablesReq* pDb = taosHashGet(pHash, dbFName, strlen(dbFName));
1,194✔
2965
  if (pDb) {
1,194✔
2966
    if (NULL == taosArrayPush(pDb->pTables, &name)) {
×
2967
      return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
2968
    }
2969
  } else {
2970
    STablesReq db;
1,194✔
2971
    db.pTables = taosArrayInit(20, sizeof(SName));
1,194✔
2972
    if (NULL == db.pTables) {
1,194✔
2973
      return terrno;
×
2974
    }
2975
    tstrncpy(db.dbFName, dbFName, TSDB_DB_FNAME_LEN);
1,194✔
2976
    if (NULL == taosArrayPush(db.pTables, &name)) {
2,388✔
2977
      return terrno;
×
2978
    }
2979
    TSC_ERR_RET(taosHashPut(pHash, dbFName, strlen(dbFName), &db, sizeof(db)));
1,194✔
2980
  }
2981

2982
  return TSDB_CODE_SUCCESS;
1,194✔
2983
}
2984

2985
int32_t transferTableNameList(const char* tbList, int32_t acctId, char* dbName, SArray** pReq) {
1,194✔
2986
  SHashObj* pHash = taosHashInit(3, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
1,194✔
2987
  if (NULL == pHash) {
1,194✔
2988
    return terrno;
×
2989
  }
2990

2991
  bool    inEscape = false;
1,194✔
2992
  int32_t code = 0;
1,194✔
2993
  void*   pIter = NULL;
1,194✔
2994

2995
  int32_t vIdx = 0;
1,194✔
2996
  int32_t vPos[2];
1,194✔
2997
  int32_t vLen[2];
1,194✔
2998

2999
  (void)memset(vPos, -1, sizeof(vPos));
1,194✔
3000
  (void)memset(vLen, 0, sizeof(vLen));
1,194✔
3001

3002
  for (int32_t i = 0;; ++i) {
5,970✔
3003
    if (0 == *(tbList + i)) {
5,970✔
3004
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
1,194✔
3005
        vLen[vIdx] = i - vPos[vIdx];
1,194✔
3006
      }
3007

3008
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
1,194✔
3009
      if (code) {
1,194✔
3010
        goto _return;
×
3011
      }
3012

3013
      break;
1,194✔
3014
    }
3015

3016
    if ('`' == *(tbList + i)) {
4,776✔
3017
      inEscape = !inEscape;
×
3018
      if (!inEscape) {
×
3019
        if (vPos[vIdx] >= 0) {
×
3020
          vLen[vIdx] = i - vPos[vIdx];
×
3021
        } else {
3022
          goto _return;
×
3023
        }
3024
      }
3025

3026
      continue;
×
3027
    }
3028

3029
    if (inEscape) {
4,776✔
3030
      if (vPos[vIdx] < 0) {
×
3031
        vPos[vIdx] = i;
×
3032
      }
3033
      continue;
×
3034
    }
3035

3036
    if ('.' == *(tbList + i)) {
4,776✔
3037
      if (vPos[vIdx] < 0) {
×
3038
        goto _return;
×
3039
      }
3040
      if (vLen[vIdx] <= 0) {
×
3041
        vLen[vIdx] = i - vPos[vIdx];
×
3042
      }
3043
      vIdx++;
×
3044
      if (vIdx >= 2) {
×
3045
        goto _return;
×
3046
      }
3047
      continue;
×
3048
    }
3049

3050
    if (',' == *(tbList + i)) {
4,776✔
3051
      if (vPos[vIdx] < 0) {
×
3052
        goto _return;
×
3053
      }
3054
      if (vLen[vIdx] <= 0) {
×
3055
        vLen[vIdx] = i - vPos[vIdx];
×
3056
      }
3057

3058
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
×
3059
      if (code) {
×
3060
        goto _return;
×
3061
      }
3062

3063
      (void)memset(vPos, -1, sizeof(vPos));
×
3064
      (void)memset(vLen, 0, sizeof(vLen));
×
3065
      vIdx = 0;
×
3066
      continue;
×
3067
    }
3068

3069
    if (' ' == *(tbList + i) || '\r' == *(tbList + i) || '\t' == *(tbList + i) || '\n' == *(tbList + i)) {
4,776✔
3070
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
×
3071
        vLen[vIdx] = i - vPos[vIdx];
×
3072
      }
3073
      continue;
×
3074
    }
3075

3076
    if (('a' <= *(tbList + i) && 'z' >= *(tbList + i)) || ('A' <= *(tbList + i) && 'Z' >= *(tbList + i)) ||
4,776✔
3077
        ('0' <= *(tbList + i) && '9' >= *(tbList + i)) || ('_' == *(tbList + i))) {
597✔
3078
      if (vLen[vIdx] > 0) {
4,776✔
3079
        goto _return;
×
3080
      }
3081
      if (vPos[vIdx] < 0) {
4,776✔
3082
        vPos[vIdx] = i;
1,194✔
3083
      }
3084
      continue;
4,776✔
3085
    }
3086

3087
    goto _return;
×
3088
  }
3089

3090
  int32_t dbNum = taosHashGetSize(pHash);
1,194✔
3091
  *pReq = taosArrayInit(dbNum, sizeof(STablesReq));
1,194✔
3092
  if (NULL == pReq) {
1,194✔
3093
    TSC_ERR_JRET(terrno);
×
3094
  }
3095
  pIter = taosHashIterate(pHash, NULL);
1,194✔
3096
  while (pIter) {
2,388✔
3097
    STablesReq* pDb = (STablesReq*)pIter;
1,194✔
3098
    if (NULL == taosArrayPush(*pReq, pDb)) {
2,388✔
3099
      TSC_ERR_JRET(terrno);
×
3100
    }
3101
    pIter = taosHashIterate(pHash, pIter);
1,194✔
3102
  }
3103

3104
  taosHashCleanup(pHash);
1,194✔
3105

3106
  return TSDB_CODE_SUCCESS;
1,194✔
3107

3108
_return:
×
3109

3110
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
3111

3112
  pIter = taosHashIterate(pHash, NULL);
×
3113
  while (pIter) {
×
3114
    STablesReq* pDb = (STablesReq*)pIter;
×
3115
    taosArrayDestroy(pDb->pTables);
×
3116
    pIter = taosHashIterate(pHash, pIter);
×
3117
  }
3118

3119
  taosHashCleanup(pHash);
×
3120

3121
  return terrno;
×
3122
}
3123

3124
void syncCatalogFn(SMetaData* pResult, void* param, int32_t code) {
1,194✔
3125
  SSyncQueryParam* pParam = param;
1,194✔
3126
  pParam->pRequest->code = code;
1,194✔
3127

3128
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
1,194✔
3129
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3130
  }
3131
}
1,194✔
3132

3133
void syncQueryFn(void* param, void* res, int32_t code) {
1,016,728,353✔
3134
  SSyncQueryParam* pParam = param;
1,016,728,353✔
3135
  pParam->pRequest = res;
1,016,728,353✔
3136

3137
  if (pParam->pRequest) {
1,016,732,223✔
3138
    pParam->pRequest->code = code;
1,016,738,223✔
3139
    clientOperateReport(pParam->pRequest);
1,016,745,392✔
3140
  }
3141

3142
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
1,016,682,688✔
3143
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3144
  }
3145
}
1,016,769,654✔
3146

3147
void taosAsyncQueryImpl(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
1,016,376,305✔
3148
                        int8_t source) {
3149
  if (sql == NULL || NULL == fp) {
1,016,376,305✔
3150
    terrno = TSDB_CODE_INVALID_PARA;
33✔
3151
    if (fp) {
×
3152
      fp(param, NULL, terrno);
×
3153
    }
3154

3155
    return;
×
3156
  }
3157

3158
  size_t sqlLen = strlen(sql);
1,016,383,234✔
3159
  if (sqlLen > (size_t)tsMaxSQLLength) {
1,016,383,234✔
3160
    tscError("conn:0x%" PRIx64 ", sql string exceeds max length:%d", connId, tsMaxSQLLength);
564✔
3161
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
564✔
3162
    fp(param, NULL, terrno);
564✔
3163
    return;
564✔
3164
  }
3165

3166
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, sql:%s", connId, sql);
1,016,382,670✔
3167

3168
  SRequestObj* pRequest = NULL;
1,016,382,845✔
3169
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
1,016,382,555✔
3170
  if (code != TSDB_CODE_SUCCESS) {
1,016,379,676✔
3171
    terrno = code;
×
3172
    fp(param, NULL, terrno);
×
3173
    return;
×
3174
  }
3175

3176
  code = connCheckAndUpateMetric(connId);
1,016,379,676✔
3177
  if (code != TSDB_CODE_SUCCESS) {
1,016,382,601✔
3178
    terrno = code;
294✔
3179
    fp(param, NULL, terrno);
294✔
3180
    return;
294✔
3181
  }
3182

3183
  pRequest->source = source;
1,016,382,307✔
3184
  pRequest->body.queryFp = fp;
1,016,382,793✔
3185
  doAsyncQuery(pRequest, false);
1,016,379,519✔
3186
}
3187

3188
void taosAsyncQueryImplWithReqid(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
276✔
3189
                                 int64_t reqid) {
3190
  if (sql == NULL || NULL == fp) {
276✔
3191
    terrno = TSDB_CODE_INVALID_PARA;
×
3192
    if (fp) {
×
3193
      fp(param, NULL, terrno);
×
3194
    }
3195

3196
    return;
×
3197
  }
3198

3199
  size_t sqlLen = strlen(sql);
276✔
3200
  if (sqlLen > (size_t)tsMaxSQLLength) {
276✔
3201
    tscError("conn:0x%" PRIx64 ", QID:0x%" PRIx64 ", sql string exceeds max length:%d", connId, reqid, tsMaxSQLLength);
×
3202
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
3203
    fp(param, NULL, terrno);
×
3204
    return;
×
3205
  }
3206

3207
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, QID:0x%" PRIx64 ", sql:%s", connId, reqid, sql);
276✔
3208

3209
  SRequestObj* pRequest = NULL;
276✔
3210
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, reqid);
276✔
3211
  if (code != TSDB_CODE_SUCCESS) {
276✔
3212
    terrno = code;
×
3213
    fp(param, NULL, terrno);
×
3214
    return;
×
3215
  }
3216

3217
  code = connCheckAndUpateMetric(connId);
276✔
3218

3219
  if (code != TSDB_CODE_SUCCESS) {
276✔
3220
    terrno = code;
×
3221
    fp(param, NULL, terrno);
×
3222
    return;
×
3223
  }
3224

3225
  pRequest->body.queryFp = fp;
276✔
3226

3227
  doAsyncQuery(pRequest, false);
276✔
3228
}
3229

3230
TAOS_RES* taosQueryImpl(TAOS* taos, const char* sql, bool validateOnly, int8_t source) {
1,016,249,340✔
3231
  if (NULL == taos) {
1,016,249,340✔
3232
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3233
    return NULL;
×
3234
  }
3235

3236
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
1,016,249,340✔
3237
  if (NULL == param) {
1,016,258,500✔
3238
    return NULL;
×
3239
  }
3240

3241
  int32_t code = tsem_init(&param->sem, 0, 0);
1,016,258,500✔
3242
  if (TSDB_CODE_SUCCESS != code) {
1,016,247,065✔
3243
    taosMemoryFree(param);
×
3244
    return NULL;
×
3245
  }
3246

3247
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
1,016,247,065✔
3248
  code = tsem_wait(&param->sem);
1,016,203,462✔
3249
  if (TSDB_CODE_SUCCESS != code) {
1,016,237,977✔
3250
    taosMemoryFree(param);
×
3251
    return NULL;
×
3252
  }
3253
  code = tsem_destroy(&param->sem);
1,016,237,977✔
3254
  if (TSDB_CODE_SUCCESS != code) {
1,016,237,567✔
3255
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3256
  }
3257

3258
  SRequestObj* pRequest = NULL;
1,016,233,507✔
3259
  if (param->pRequest != NULL) {
1,016,233,507✔
3260
    param->pRequest->syncQuery = true;
1,016,231,582✔
3261
    pRequest = param->pRequest;
1,016,233,493✔
3262
    param->pRequest->inCallback = false;
1,016,233,382✔
3263
  }
3264
  taosMemoryFree(param);
1,016,234,823✔
3265

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

3269
  return pRequest;
1,016,249,598✔
3270
}
3271

3272
TAOS_RES* taosQueryImplWithReqid(TAOS* taos, const char* sql, bool validateOnly, int64_t reqid) {
276✔
3273
  if (NULL == taos) {
276✔
3274
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3275
    return NULL;
×
3276
  }
3277

3278
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
276✔
3279
  if (param == NULL) {
276✔
3280
    return NULL;
×
3281
  }
3282
  int32_t code = tsem_init(&param->sem, 0, 0);
276✔
3283
  if (TSDB_CODE_SUCCESS != code) {
276✔
3284
    taosMemoryFree(param);
×
3285
    return NULL;
×
3286
  }
3287

3288
  taosAsyncQueryImplWithReqid(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, reqid);
276✔
3289
  code = tsem_wait(&param->sem);
276✔
3290
  if (TSDB_CODE_SUCCESS != code) {
276✔
3291
    taosMemoryFree(param);
×
3292
    return NULL;
×
3293
  }
3294
  SRequestObj* pRequest = NULL;
276✔
3295
  if (param->pRequest != NULL) {
276✔
3296
    param->pRequest->syncQuery = true;
276✔
3297
    pRequest = param->pRequest;
276✔
3298
  }
3299
  taosMemoryFree(param);
276✔
3300

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

3304
  return pRequest;
276✔
3305
}
3306

3307
static void fetchCallback(void* pResult, void* param, int32_t code) {
249,137,141✔
3308
  SRequestObj* pRequest = (SRequestObj*)param;
249,137,141✔
3309

3310
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
249,137,141✔
3311

3312
  tscDebug("req:0x%" PRIx64 ", enter scheduler fetch cb, code:%d - %s, QID:0x%" PRIx64, pRequest->self, code,
249,137,106✔
3313
           tstrerror(code), pRequest->requestId);
3314

3315
  pResultInfo->pData = pResult;
249,137,078✔
3316
  pResultInfo->numOfRows = 0;
249,137,043✔
3317

3318
  if (code != TSDB_CODE_SUCCESS) {
249,136,931✔
3319
    pRequest->code = code;
×
3320
    taosMemoryFreeClear(pResultInfo->pData);
×
3321
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
×
3322
    return;
×
3323
  }
3324

3325
  if (pRequest->code != TSDB_CODE_SUCCESS) {
249,136,931✔
3326
    taosMemoryFreeClear(pResultInfo->pData);
×
3327
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pRequest->code);
×
3328
    return;
×
3329
  }
3330

3331
  pRequest->code = setQueryResultFromRsp(pResultInfo, (const SRetrieveTableRsp*)pResultInfo->pData,
253,844,952✔
3332
                                         pResultInfo->convertUcs4, pRequest->stmtBindVersion > 0);
249,137,039✔
3333
  if (pRequest->code != TSDB_CODE_SUCCESS) {
249,137,107✔
3334
    pResultInfo->numOfRows = 0;
63✔
3335
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self,
63✔
3336
             tstrerror(pRequest->code), pRequest->requestId);
3337
  } else {
3338
    tscDebug(
249,136,558✔
3339
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
3340
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
3341

3342
    STscObj*            pTscObj = pRequest->pTscObj;
249,136,974✔
3343
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
249,137,116✔
3344
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
249,137,048✔
3345
  }
3346

3347
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
249,137,107✔
3348
}
3349

3350
void taosAsyncFetchImpl(SRequestObj* pRequest, __taos_async_fn_t fp, void* param) {
280,976,883✔
3351
  pRequest->body.fetchFp = fp;
280,976,883✔
3352
  ((SSyncQueryParam*)pRequest->body.interParam)->userParam = param;
280,976,883✔
3353

3354
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
280,976,883✔
3355

3356
  // this query has no results or error exists, return directly
3357
  if (taos_num_fields(pRequest) == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
280,976,883✔
3358
    pResultInfo->numOfRows = 0;
35✔
3359
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
×
3360
    return;
2,052,498✔
3361
  }
3362

3363
  // all data has returned to App already, no need to try again
3364
  if (pResultInfo->completed) {
280,976,848✔
3365
    // it is a local executed query, no need to do async fetch
3366
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
31,839,704✔
3367
      if (pResultInfo->localResultFetched) {
1,416,600✔
3368
        pResultInfo->numOfRows = 0;
708,300✔
3369
        pResultInfo->current = 0;
708,300✔
3370
      } else {
3371
        pResultInfo->localResultFetched = true;
708,300✔
3372
      }
3373
    } else {
3374
      pResultInfo->numOfRows = 0;
30,423,104✔
3375
    }
3376

3377
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
31,839,704✔
3378
    return;
31,839,704✔
3379
  }
3380

3381
  SSchedulerReq req = {
249,137,144✔
3382
      .syncReq = false,
3383
      .fetchFp = fetchCallback,
3384
      .cbParam = pRequest,
3385
  };
3386

3387
  int32_t code = schedulerFetchRows(pRequest->body.queryJob, &req);
249,137,179✔
3388
  if (TSDB_CODE_SUCCESS != code) {
249,137,066✔
3389
    tscError("0x%" PRIx64 " failed to schedule fetch rows", pRequest->requestId);
×
3390
    // pRequest->body.fetchFp(param, pRequest, code);
3391
  }
3392
}
3393

3394
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
1,016,721,212✔
3395
  pRequest->inCallback = true;
1,016,721,212✔
3396
  int64_t this = pRequest->self;
1,016,729,702✔
3397
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
1,016,702,775✔
3398
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
23,236✔
3399
    code = TSDB_CODE_SUCCESS;
×
3400
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3401
  }
3402

3403
  tscDebug("QID:0x%" PRIx64 ", taos_query end, req:0x%" PRIx64 ", res:%p", pRequest->requestId, pRequest->self,
1,016,702,775✔
3404
           pRequest);
3405

3406
  if (pRequest->body.queryFp != NULL) {
1,016,704,205✔
3407
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
1,016,737,988✔
3408
  }
3409

3410
  SRequestObj* pReq = acquireRequest(this);
1,016,767,164✔
3411
  if (pReq != NULL) {
1,016,792,529✔
3412
    pReq->inCallback = false;
1,015,113,540✔
3413
    (void)releaseRequest(this);
1,015,114,726✔
3414
  }
3415
}
1,016,783,063✔
3416

3417
int32_t clientParseSql(void* param, const char* dbName, const char* sql, bool parseOnly, const char* effectiveUser,
515,200✔
3418
                       SParseSqlRes* pRes) {
3419
#ifndef TD_ENTERPRISE
3420
  return TSDB_CODE_SUCCESS;
3421
#else
3422
  return clientParseSqlImpl(param, dbName, sql, parseOnly, effectiveUser, pRes);
515,200✔
3423
#endif
3424
}
3425

3426
void updateConnAccessInfo(SConnAccessInfo* pInfo) {
1,099,565,243✔
3427
  if (pInfo == NULL) {
1,099,565,243✔
3428
    return;
×
3429
  }
3430
  int64_t ts = taosGetTimestampMs();
1,099,577,299✔
3431
  if (pInfo->startTime == 0) {
1,099,577,299✔
3432
    pInfo->startTime = ts;
83,201,873✔
3433
  }
3434
  pInfo->lastAccessTime = ts;
1,099,578,815✔
3435
}
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