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

taosdata / TDengine / #4885

15 Dec 2025 03:26AM UTC coverage: 65.258% (+4.6%) from 60.617%
#4885

push

travis-ci

web-flow
feat(tmq): [TS-6379]remove limition for table operation in tmq  (#33834)

872 of 1074 new or added lines in 16 files covered. (81.19%)

659 existing lines in 92 files now uncovered.

177890 of 272597 relevant lines covered (65.26%)

103732965.73 hits per line

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

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

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

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

38
void setQueryRequest(int64_t rId) {
120,048,533✔
39
  SRequestObj* pReq = acquireRequest(rId);
120,048,533✔
40
  if (pReq != NULL) {
120,050,302✔
41
    pReq->isQuery = true;
120,039,616✔
42
    (void)releaseRequest(rId);
120,039,890✔
43
  }
44
}
120,050,007✔
45

46
static bool stringLengthCheck(const char* str, size_t maxsize) {
7,710,188✔
47
  if (str == NULL) {
7,710,188✔
48
    return false;
×
49
  }
50

51
  size_t len = strlen(str);
7,710,188✔
52
  if (len <= 0 || len > maxsize) {
7,710,188✔
53
    return false;
×
54
  }
55

56
  return true;
7,710,221✔
57
}
58

59
static bool validateUserName(const char* user) { return stringLengthCheck(user, TSDB_USER_LEN - 1); }
3,238,825✔
60

61
static bool validatePassword(const char* passwd) { return stringLengthCheck(passwd, TSDB_PASSWORD_MAX_LEN); }
3,238,067✔
62

63
static bool validateDbName(const char* db) { return stringLengthCheck(db, TSDB_DB_NAME_LEN - 1); }
1,233,352✔
64

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

71
static int32_t escapeToPrinted(char* dst, size_t maxDstLength, const char* src, size_t srcLength) {
672,606✔
72
  if (dst == NULL || src == NULL || srcLength == 0) {
672,606✔
73
    return 0;
554✔
74
  }
75
  
76
  size_t escapeLength = 0;
672,052✔
77
  for(size_t i = 0; i < srcLength; ++i) {
19,096,100✔
78
    if( src[i] == '\"' || src[i] == '\\' || src[i] == '\b' || src[i] == '\f' || src[i] == '\n' ||
18,424,048✔
79
        src[i] == '\r' || src[i] == '\t') {
18,424,048✔
80
      escapeLength += 1; 
×
81
    }    
82
  }
83

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

125
  return dstLength;
672,052✔
126
}
127

128
bool chkRequestKilled(void* param) {
2,147,483,647✔
129
  bool         killed = false;
2,147,483,647✔
130
  SRequestObj* pRequest = acquireRequest((int64_t)param);
2,147,483,647✔
131
  if (NULL == pRequest || pRequest->killed) {
2,147,483,647✔
132
    killed = true;
×
133
  }
134

135
  (void)releaseRequest((int64_t)param);
2,147,483,647✔
136

137
  return killed;
2,147,483,647✔
138
}
139

140
void cleanupAppInfo() {
1,645,364✔
141
  taosHashCleanup(appInfo.pInstMap);
1,645,364✔
142
  taosHashCleanup(appInfo.pInstMapByClusterId);
1,645,364✔
143
  tscInfo("cluster instance map cleaned");
1,645,364✔
144
}
1,645,364✔
145

146
static int32_t taosConnectImpl(const char* user, const char* auth, int32_t totpCode, const char* db, __taos_async_fn_t fp, void* param,
147
                               SAppInstInfo* pAppInfo, int connType, STscObj** pTscObj);
148

149
int32_t taos_connect_internal(const char* ip, const char* user, const char* pass, const char* auth, const char* totp, const char* db,
3,238,825✔
150
                              uint16_t port, int connType, STscObj** pObj) {
151
  TSC_ERR_RET(taos_init());
3,238,825✔
152
  if (!validateUserName(user)) {
3,238,825✔
153
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
154
  }
155
  int32_t code = 0;
3,238,754✔
156

157
  char localDb[TSDB_DB_NAME_LEN] = {0};
3,238,754✔
158
  if (db != NULL && strlen(db) > 0) {
3,238,754✔
159
    if (!validateDbName(db)) {
1,233,352✔
160
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_DB_LENGTH);
×
161
    }
162

163
    tstrncpy(localDb, db, sizeof(localDb));
1,233,352✔
164
    (void)strdequote(localDb);
1,233,352✔
165
  }
166

167
  char secretEncrypt[TSDB_PASSWORD_LEN + 1] = {0};
3,238,713✔
168
  if (auth == NULL) {
3,238,713✔
169
    if (!validatePassword(pass)) {
3,238,115✔
170
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_PASS_LENGTH);
×
171
    }
172

173
    taosEncryptPass_c((uint8_t*)pass, strlen(pass), secretEncrypt);
3,238,011✔
174
  } else {
175
    tstrncpy(secretEncrypt, auth, tListLen(secretEncrypt));
598✔
176
  }
177

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

187
  SCorEpSet epSet = {0};
3,238,651✔
188
  if (ip) {
3,238,693✔
189
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
969,974✔
190
  } else {
191
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
2,268,719✔
192
  }
193

194
  if (port) {
3,238,151✔
195
    epSet.epSet.eps[0].port = port;
116,308✔
196
    epSet.epSet.eps[1].port = port;
116,308✔
197
  }
198

199
  char* key = getClusterKey(user, secretEncrypt, ip, port);
3,238,151✔
200
  if (NULL == key) {
3,238,072✔
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,
3,238,072✔
204
          user, db, key);
205
  for (int32_t i = 0; i < epSet.epSet.numOfEps; ++i) {
8,745,346✔
206
    tscInfo("ep:%d, %s:%u", i, epSet.epSet.eps[i].fqdn, epSet.epSet.eps[i].port);
5,507,072✔
207
  }
208
  // for (int32_t i = 0; i < epSet.epSet.numOfEps; i++) {
209
  //   if ((code = taosValidFqdn(tsEnableIpv6, epSet.epSet.eps[i].fqdn)) != 0) {
210
  //     taosMemFree(key);
211
  //     tscError("ipv6 flag %d, the local FQDN %s does not resolve to the ip address since %s", tsEnableIpv6,
212
  //              epSet.epSet.eps[i].fqdn, tstrerror(code));
213
  //     TSC_ERR_RET(code);
214
  //   }
215
  // }
216

217
  SAppInstInfo** pInst = NULL;
3,238,274✔
218
  code = taosThreadMutexLock(&appInfo.mutex);
3,238,274✔
219
  if (TSDB_CODE_SUCCESS != code) {
3,238,274✔
220
    tscError("failed to lock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
221
    TSC_ERR_RET(code);
×
222
  }
223

224
  pInst = taosHashGet(appInfo.pInstMap, key, strlen(key));
3,238,274✔
225
  SAppInstInfo* p = NULL;
3,238,274✔
226
  if (pInst == NULL) {
3,238,274✔
227
    p = taosMemoryCalloc(1, sizeof(struct SAppInstInfo));
1,705,292✔
228
    if (NULL == p) {
1,705,292✔
229
      TSC_ERR_JRET(terrno);
×
230
    }
231
    p->mgmtEp = epSet;
1,705,292✔
232
    code = taosThreadMutexInit(&p->qnodeMutex, NULL);
1,705,292✔
233
    if (TSDB_CODE_SUCCESS != code) {
1,705,292✔
234
      taosMemoryFree(p);
×
235
      TSC_ERR_JRET(code);
×
236
    }
237
    code = openTransporter(user, secretEncrypt, tsNumOfCores / 2, &p->pTransporter);
1,705,292✔
238
    if (TSDB_CODE_SUCCESS != code) {
1,705,292✔
239
      taosMemoryFree(p);
58✔
240
      TSC_ERR_JRET(code);
58✔
241
    }
242
    code = appHbMgrInit(p, key, &p->pAppHbMgr);
1,705,234✔
243
    if (TSDB_CODE_SUCCESS != code) {
1,705,234✔
244
      destroyAppInst(&p);
×
245
      TSC_ERR_JRET(code);
×
246
    }
247
    code = taosHashPut(appInfo.pInstMap, key, strlen(key), &p, POINTER_BYTES);
1,705,234✔
248
    if (TSDB_CODE_SUCCESS != code) {
1,705,234✔
249
      destroyAppInst(&p);
×
250
      TSC_ERR_JRET(code);
×
251
    }
252
    p->instKey = key;
1,705,234✔
253
    key = NULL;
1,705,234✔
254
    tscInfo("new app inst mgr:%p, user:%s, ip:%s, port:%d", p, user, epSet.epSet.eps[0].fqdn, epSet.epSet.eps[0].port);
1,705,234✔
255

256
    pInst = &p;
1,705,234✔
257
  } else {
258
    if (NULL == *pInst || NULL == (*pInst)->pAppHbMgr) {
1,532,982✔
259
      tscError("*pInst:%p, pAppHgMgr:%p", *pInst, (*pInst) ? (*pInst)->pAppHbMgr : NULL);
×
260
      TSC_ERR_JRET(TSDB_CODE_TSC_INTERNAL_ERROR);
×
261
    }
262
    // reset to 0 in case of conn with duplicated user key but its user has ever been dropped.
263
    atomic_store_8(&(*pInst)->pAppHbMgr->connHbFlag, 0);
1,532,982✔
264
  }
265

266
_return:
3,238,274✔
267

268
  if (TSDB_CODE_SUCCESS != code) {
3,238,274✔
269
    (void)taosThreadMutexUnlock(&appInfo.mutex);
58✔
270
    taosMemoryFreeClear(key);
58✔
271
    return code;
58✔
272
  } else {
273
    code = taosThreadMutexUnlock(&appInfo.mutex);
3,238,216✔
274
    taosMemoryFreeClear(key);
3,238,216✔
275
    if (TSDB_CODE_SUCCESS != code) {
3,238,216✔
276
      tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
277
      return code;
×
278
    }
279
    return taosConnectImpl(user, &secretEncrypt[0], totpCode, localDb, NULL, NULL, *pInst, connType, pObj);
3,238,216✔
280
  }
281
}
282

283
// SAppInstInfo* getAppInstInfo(const char* clusterKey) {
284
//   SAppInstInfo** ppAppInstInfo = taosHashGet(appInfo.pInstMap, clusterKey, strlen(clusterKey));
285
//   if (ppAppInstInfo != NULL && *ppAppInstInfo != NULL) {
286
//     return *ppAppInstInfo;
287
//   } else {
288
//     return NULL;
289
//   }
290
// }
291

292
void freeQueryParam(SSyncQueryParam* param) {
579,840✔
293
  if (param == NULL) return;
579,840✔
294
  if (TSDB_CODE_SUCCESS != tsem_destroy(&param->sem)) {
579,840✔
295
    tscError("failed to destroy semaphore in freeQueryParam");
×
296
  }
297
  taosMemoryFree(param);
579,840✔
298
}
299

300
int32_t buildRequest(uint64_t connId, const char* sql, int sqlLen, void* param, bool validateSql,
652,643,625✔
301
                     SRequestObj** pRequest, int64_t reqid) {
302
  int32_t code = createRequest(connId, TSDB_SQL_SELECT, reqid, pRequest);
652,643,625✔
303
  if (TSDB_CODE_SUCCESS != code) {
652,644,356✔
304
    tscError("failed to malloc sqlObj, %s", sql);
×
305
    return code;
×
306
  }
307

308
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
652,644,356✔
309
  if ((*pRequest)->sqlstr == NULL) {
652,645,684✔
310
    tscError("req:0x%" PRIx64 ", failed to prepare sql string buffer, %s", (*pRequest)->self, sql);
×
311
    destroyRequest(*pRequest);
×
312
    *pRequest = NULL;
×
313
    return terrno;
×
314
  }
315

316
  (void)strntolower((*pRequest)->sqlstr, sql, (int32_t)sqlLen);
652,644,232✔
317
  (*pRequest)->sqlstr[sqlLen] = 0;
652,653,574✔
318
  (*pRequest)->sqlLen = sqlLen;
652,654,079✔
319
  (*pRequest)->validateOnly = validateSql;
652,655,507✔
320
  (*pRequest)->stmtBindVersion = 0;
652,654,989✔
321

322
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
652,651,867✔
323

324
  STscObj* pTscObj = (*pRequest)->pTscObj;
652,652,891✔
325
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
652,651,121✔
326
                             sizeof((*pRequest)->self));
327
  if (err) {
652,647,026✔
328
    tscError("req:0x%" PRId64 ", failed to add to request container, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
329
             (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
330
    destroyRequest(*pRequest);
×
331
    *pRequest = NULL;
×
332
    return terrno;
×
333
  }
334

335
  (*pRequest)->allocatorRefId = -1;
652,647,026✔
336
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
652,654,920✔
337
    if (TSDB_CODE_SUCCESS !=
180,988,398✔
338
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
180,980,140✔
339
      tscError("req:0x%" PRId64 ", failed to create node allocator, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
340
               (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
341
      destroyRequest(*pRequest);
×
342
      *pRequest = NULL;
×
343
      return terrno;
×
344
    }
345
  }
346

347
  tscDebug("req:0x%" PRIx64 ", build request, QID:0x%" PRIx64, (*pRequest)->self, (*pRequest)->requestId);
652,664,118✔
348
  return TSDB_CODE_SUCCESS;
652,648,240✔
349
}
350

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

363
int32_t parseSql(SRequestObj* pRequest, bool topicQuery, SQuery** pQuery, SStmtCallback* pStmtCb) {
882,819✔
364
  STscObj* pTscObj = pRequest->pTscObj;
882,819✔
365

366
  SParseContext cxt = {
883,634✔
367
      .requestId = pRequest->requestId,
883,379✔
368
      .requestRid = pRequest->self,
883,349✔
369
      .acctId = pTscObj->acctId,
883,236✔
370
      .db = pRequest->pDb,
882,665✔
371
      .topicQuery = topicQuery,
372
      .pSql = pRequest->sqlstr,
883,196✔
373
      .sqlLen = pRequest->sqlLen,
883,355✔
374
      .pMsg = pRequest->msgBuf,
883,389✔
375
      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
376
      .pTransporter = pTscObj->pAppInfo->pTransporter,
882,580✔
377
      .pStmtCb = pStmtCb,
378
      .pUser = pTscObj->user,
883,508✔
379
      .isSuperUser = (0 == strcmp(pTscObj->user, TSDB_DEFAULT_USER)),
882,637✔
380
      .enableSysInfo = pTscObj->sysInfo,
883,820✔
381
      .svrVer = pTscObj->sVer,
882,697✔
382
      .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes),
883,553✔
383
      .stmtBindVersion = pRequest->stmtBindVersion,
882,892✔
384
      .setQueryFp = setQueryRequest,
385
      .timezone = pTscObj->optionInfo.timezone,
883,279✔
386
      .charsetCxt = pTscObj->optionInfo.charsetCxt,
882,797✔
387
  };
388

389
  cxt.mgmtEpSet = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
883,617✔
390
  int32_t code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &cxt.pCatalog);
884,300✔
391
  if (code != TSDB_CODE_SUCCESS) {
883,114✔
392
    return code;
×
393
  }
394

395
  code = qParseSql(&cxt, pQuery);
883,114✔
396
  if (TSDB_CODE_SUCCESS == code) {
882,548✔
397
    if ((*pQuery)->haveResultSet) {
880,985✔
398
      code = setResSchemaInfo(&pRequest->body.resInfo, (*pQuery)->pResSchema, (*pQuery)->numOfResCols,
×
399
                              (*pQuery)->pResExtSchema, pRequest->stmtBindVersion > 0);
×
400
      setResPrecision(&pRequest->body.resInfo, (*pQuery)->precision);
×
401
    }
402
  }
403

404
  if (TSDB_CODE_SUCCESS == code || NEED_CLIENT_HANDLE_ERROR(code)) {
882,824✔
405
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
880,884✔
406
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
881,983✔
407
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
881,520✔
408
  }
409

410
  taosArrayDestroy(cxt.pTableMetaPos);
883,870✔
411
  taosArrayDestroy(cxt.pTableVgroupPos);
883,503✔
412

413
  return code;
883,298✔
414
}
415

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

426
  return code;
×
427
}
428

429
int32_t execDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
356,620✔
430
  // drop table if exists not_exists_table
431
  if (NULL == pQuery->pCmdMsg) {
356,620✔
432
    return TSDB_CODE_SUCCESS;
×
433
  }
434

435
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
356,620✔
436
  pRequest->type = pMsgInfo->msgType;
356,620✔
437
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
356,620✔
438
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
356,620✔
439

440
  STscObj*      pTscObj = pRequest->pTscObj;
356,620✔
441
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
356,620✔
442

443
  // int64_t transporterId = 0;
444
  TSC_ERR_RET(asyncSendMsgToServer(pTscObj->pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg));
356,620✔
445
  TSC_ERR_RET(tsem_wait(&pRequest->body.rspSem));
356,620✔
446
  return TSDB_CODE_SUCCESS;
356,620✔
447
}
448

449
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
1,221,909,724✔
450

451
void asyncExecLocalCmd(SRequestObj* pRequest, SQuery* pQuery) {
5,263,385✔
452
  SRetrieveTableRsp* pRsp = NULL;
5,263,385✔
453
  if (pRequest->validateOnly) {
5,263,385✔
454
    doRequestCallback(pRequest, 0);
12,879✔
455
    return;
12,879✔
456
  }
457

458
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp,
10,486,281✔
459
                              atomic_load_8(&pRequest->pTscObj->biMode), pRequest->pTscObj->optionInfo.charsetCxt);
10,486,281✔
460
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
5,250,506✔
461
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4,
2,853,891✔
462
                                 pRequest->stmtBindVersion > 0);
2,853,891✔
463
  }
464

465
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
5,250,506✔
466
  pRequest->code = code;
5,250,506✔
467

468
  if (pRequest->code != TSDB_CODE_SUCCESS) {
5,250,506✔
469
    pResultInfo->numOfRows = 0;
3,997✔
470
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
3,997✔
471
             pRequest->requestId);
472
  } else {
473
    tscDebug(
5,246,509✔
474
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
475
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
476
  }
477

478
  doRequestCallback(pRequest, code);
5,250,506✔
479
}
480

481
int32_t asyncExecDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
17,304,387✔
482
  if (pRequest->validateOnly) {
17,304,387✔
483
    doRequestCallback(pRequest, 0);
×
484
    return TSDB_CODE_SUCCESS;
×
485
  }
486

487
  // drop table if exists not_exists_table
488
  if (NULL == pQuery->pCmdMsg) {
17,304,667✔
489
    doRequestCallback(pRequest, 0);
7,952✔
490
    return TSDB_CODE_SUCCESS;
7,952✔
491
  }
492

493
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
17,296,435✔
494
  pRequest->type = pMsgInfo->msgType;
17,296,715✔
495
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
17,295,935✔
496
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
17,295,642✔
497

498
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
17,295,935✔
499
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
17,296,181✔
500

501
  int32_t code = asyncSendMsgToServer(pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg);
17,296,435✔
502
  if (code) {
17,296,435✔
503
    doRequestCallback(pRequest, code);
×
504
  }
505
  return code;
17,296,435✔
506
}
507

508
int compareQueryNodeLoad(const void* elem1, const void* elem2) {
446,375✔
509
  SQueryNodeLoad* node1 = (SQueryNodeLoad*)elem1;
446,375✔
510
  SQueryNodeLoad* node2 = (SQueryNodeLoad*)elem2;
446,375✔
511

512
  if (node1->load < node2->load) {
446,375✔
513
    return -1;
×
514
  }
515

516
  return node1->load > node2->load;
446,375✔
517
}
518

519
int32_t updateQnodeList(SAppInstInfo* pInfo, SArray* pNodeList) {
64,763✔
520
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
64,763✔
521
  if (pInfo->pQnodeList) {
64,763✔
522
    taosArrayDestroy(pInfo->pQnodeList);
62,104✔
523
    pInfo->pQnodeList = NULL;
62,104✔
524
    tscDebug("QnodeList cleared in cluster 0x%" PRIx64, pInfo->clusterId);
62,104✔
525
  }
526

527
  if (pNodeList) {
64,763✔
528
    pInfo->pQnodeList = taosArrayDup(pNodeList, NULL);
64,763✔
529
    taosArraySort(pInfo->pQnodeList, compareQueryNodeLoad);
64,763✔
530
    tscDebug("QnodeList updated in cluster 0x%" PRIx64 ", num:%ld", pInfo->clusterId,
64,763✔
531
             taosArrayGetSize(pInfo->pQnodeList));
532
  }
533
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
64,763✔
534

535
  return TSDB_CODE_SUCCESS;
64,763✔
536
}
537

538
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
652,510,942✔
539
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
652,510,942✔
540
    *required = false;
652,351,087✔
541
    return TSDB_CODE_SUCCESS;
652,348,595✔
542
  }
543

544
  int32_t       code = TSDB_CODE_SUCCESS;
159,855✔
545
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
159,855✔
546
  *required = false;
159,855✔
547

548
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
159,855✔
549
  *required = (NULL == pInfo->pQnodeList);
159,855✔
550
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
159,855✔
551
  return TSDB_CODE_SUCCESS;
159,855✔
552
}
553

554
int32_t getQnodeList(SRequestObj* pRequest, SArray** pNodeList) {
×
555
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
×
556
  int32_t       code = 0;
×
557

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

578
    if (TSDB_CODE_SUCCESS == code && *pNodeList) {
×
579
      code = updateQnodeList(pInfo, *pNodeList);
×
580
    }
581
  }
582

583
  return code;
×
584
}
585

586
int32_t getPlan(SRequestObj* pRequest, SQuery* pQuery, SQueryPlan** pPlan, SArray* pNodeList) {
6,784,150✔
587
  pRequest->type = pQuery->msgType;
6,784,150✔
588
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
6,784,362✔
589

590
  SPlanContext cxt = {.queryId = pRequest->requestId,
7,684,645✔
591
                      .acctId = pRequest->pTscObj->acctId,
6,784,057✔
592
                      .mgmtEpSet = getEpSet_s(&pAppInfo->mgmtEp),
6,783,964✔
593
                      .pAstRoot = pQuery->pRoot,
6,784,952✔
594
                      .showRewrite = pQuery->showRewrite,
6,784,952✔
595
                      .pMsg = pRequest->msgBuf,
6,784,581✔
596
                      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
597
                      .pUser = pRequest->pTscObj->user,
6,784,740✔
598
                      .timezone = pRequest->pTscObj->optionInfo.timezone,
6,784,568✔
599
                      .sysInfo = pRequest->pTscObj->sysInfo};
6,784,634✔
600

601
  return qCreateQueryPlan(&cxt, pPlan, pNodeList);
6,784,114✔
602
}
603

604
int32_t setResSchemaInfo(SReqResultInfo* pResInfo, const SSchema* pSchema, int32_t numOfCols,
123,080,057✔
605
                         const SExtSchema* pExtSchema, bool isStmt) {
606
  if (pResInfo == NULL || pSchema == NULL || numOfCols <= 0) {
123,080,057✔
607
    tscError("invalid paras, pResInfo == NULL || pSchema == NULL || numOfCols <= 0");
4✔
608
    return TSDB_CODE_INVALID_PARA;
×
609
  }
610

611
  pResInfo->numOfCols = numOfCols;
123,081,009✔
612
  if (pResInfo->fields != NULL) {
123,080,686✔
613
    taosMemoryFree(pResInfo->fields);
20,885✔
614
  }
615
  if (pResInfo->userFields != NULL) {
123,079,752✔
616
    taosMemoryFree(pResInfo->userFields);
20,885✔
617
  }
618
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD_E));
123,079,588✔
619
  if (NULL == pResInfo->fields) return terrno;
123,074,702✔
620
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
123,076,404✔
621
  if (NULL == pResInfo->userFields) {
123,079,215✔
622
    taosMemoryFree(pResInfo->fields);
×
623
    return terrno;
×
624
  }
625
  if (numOfCols != pResInfo->numOfCols) {
123,076,789✔
626
    tscError("numOfCols:%d != pResInfo->numOfCols:%d", numOfCols, pResInfo->numOfCols);
×
627
    return TSDB_CODE_FAILED;
×
628
  }
629

630
  for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
727,951,629✔
631
    pResInfo->fields[i].type = pSchema[i].type;
604,871,334✔
632

633
    pResInfo->userFields[i].type = pSchema[i].type;
604,872,194✔
634
    // userFields must convert to type bytes, no matter isStmt or not
635
    pResInfo->userFields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, false);
604,873,251✔
636
    pResInfo->fields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, isStmt);
604,872,735✔
637
    if (IS_DECIMAL_TYPE(pSchema[i].type) && pExtSchema) {
604,875,006✔
638
      decimalFromTypeMod(pExtSchema[i].typeMod, &pResInfo->fields[i].precision, &pResInfo->fields[i].scale);
1,800,364✔
639
    }
640

641
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
604,874,353✔
642
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
604,873,743✔
643
  }
644
  return TSDB_CODE_SUCCESS;
123,082,129✔
645
}
646

647
void setResPrecision(SReqResultInfo* pResInfo, int32_t precision) {
87,861,987✔
648
  if (precision != TSDB_TIME_PRECISION_MILLI && precision != TSDB_TIME_PRECISION_MICRO &&
87,861,987✔
649
      precision != TSDB_TIME_PRECISION_NANO) {
650
    return;
×
651
  }
652

653
  pResInfo->precision = precision;
87,861,987✔
654
}
655

656
int32_t buildVnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pDbVgList) {
92,313,055✔
657
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
92,313,055✔
658
  if (NULL == nodeList) {
92,317,287✔
659
    return terrno;
187✔
660
  }
661
  char* policy = (tsQueryPolicy == QUERY_POLICY_VNODE) ? "vnode" : "client";
92,317,153✔
662

663
  int32_t dbNum = taosArrayGetSize(pDbVgList);
92,317,153✔
664
  for (int32_t i = 0; i < dbNum; ++i) {
182,461,301✔
665
    SArray* pVg = taosArrayGetP(pDbVgList, i);
90,141,170✔
666
    if (NULL == pVg) {
90,142,549✔
667
      continue;
×
668
    }
669
    int32_t vgNum = taosArrayGetSize(pVg);
90,142,549✔
670
    if (vgNum <= 0) {
90,142,209✔
671
      continue;
716,680✔
672
    }
673

674
    for (int32_t j = 0; j < vgNum; ++j) {
291,442,443✔
675
      SVgroupInfo* pInfo = taosArrayGet(pVg, j);
202,015,219✔
676
      if (NULL == pInfo) {
202,017,040✔
677
        taosArrayDestroy(nodeList);
×
678
        return TSDB_CODE_OUT_OF_RANGE;
×
679
      }
680
      SQueryNodeLoad load = {0};
202,017,040✔
681
      load.addr.nodeId = pInfo->vgId;
202,015,132✔
682
      load.addr.epSet = pInfo->epSet;
202,017,161✔
683

684
      if (NULL == taosArrayPush(nodeList, &load)) {
202,013,954✔
685
        taosArrayDestroy(nodeList);
×
686
        return terrno;
×
687
      }
688
    }
689
  }
690

691
  int32_t vnodeNum = taosArrayGetSize(nodeList);
92,320,131✔
692
  if (vnodeNum > 0) {
92,320,397✔
693
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
89,137,475✔
694
    goto _return;
89,137,496✔
695
  }
696

697
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
3,182,922✔
698
  if (mnodeNum <= 0) {
3,181,217✔
699
    tscDebug("0x%" PRIx64 " %s policy, empty node list", pRequest->requestId, policy);
×
700
    goto _return;
×
701
  }
702

703
  void* pData = taosArrayGet(pMnodeList, 0);
3,181,217✔
704
  if (NULL == pData) {
3,181,217✔
705
    taosArrayDestroy(nodeList);
×
706
    return TSDB_CODE_OUT_OF_RANGE;
×
707
  }
708
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
3,181,217✔
709
    taosArrayDestroy(nodeList);
×
710
    return terrno;
×
711
  }
712

713
  tscDebug("0x%" PRIx64 " %s policy, use mnode list, num:%d", pRequest->requestId, policy, mnodeNum);
3,181,217✔
714

715
_return:
53,448✔
716

717
  *pNodeList = nodeList;
92,318,490✔
718

719
  return TSDB_CODE_SUCCESS;
92,317,664✔
720
}
721

722
int32_t buildQnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pQnodeList) {
88,035✔
723
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
88,035✔
724
  if (NULL == nodeList) {
88,035✔
725
    return terrno;
×
726
  }
727

728
  int32_t qNodeNum = taosArrayGetSize(pQnodeList);
88,035✔
729
  if (qNodeNum > 0) {
88,035✔
730
    void* pData = taosArrayGet(pQnodeList, 0);
345✔
731
    if (NULL == pData) {
345✔
732
      taosArrayDestroy(nodeList);
×
733
      return TSDB_CODE_OUT_OF_RANGE;
×
734
    }
735
    if (NULL == taosArrayAddBatch(nodeList, pData, qNodeNum)) {
345✔
736
      taosArrayDestroy(nodeList);
×
737
      return terrno;
×
738
    }
739
    tscDebug("0x%" PRIx64 " qnode policy, use qnode list, num:%d", pRequest->requestId, qNodeNum);
345✔
740
    goto _return;
345✔
741
  }
742

743
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
87,690✔
744
  if (mnodeNum <= 0) {
87,690✔
745
    tscDebug("0x%" PRIx64 " qnode policy, empty node list", pRequest->requestId);
60✔
746
    goto _return;
60✔
747
  }
748

749
  void* pData = taosArrayGet(pMnodeList, 0);
87,630✔
750
  if (NULL == pData) {
87,630✔
751
    taosArrayDestroy(nodeList);
×
752
    return TSDB_CODE_OUT_OF_RANGE;
×
753
  }
754
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
87,630✔
755
    taosArrayDestroy(nodeList);
×
756
    return terrno;
×
757
  }
758

759
  tscDebug("0x%" PRIx64 " qnode policy, use mnode list, num:%d", pRequest->requestId, mnodeNum);
87,630✔
760

761
_return:
×
762

763
  *pNodeList = nodeList;
88,035✔
764

765
  return TSDB_CODE_SUCCESS;
88,035✔
766
}
767

768
void freeVgList(void* list) {
6,732,680✔
769
  SArray* pList = *(SArray**)list;
6,732,680✔
770
  taosArrayDestroy(pList);
6,736,043✔
771
}
6,736,009✔
772

773
int32_t buildAsyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SMetaData* pResultMeta) {
85,620,614✔
774
  SArray* pDbVgList = NULL;
85,620,614✔
775
  SArray* pQnodeList = NULL;
85,620,614✔
776
  FDelete fp = NULL;
85,620,614✔
777
  int32_t code = 0;
85,620,614✔
778

779
  switch (tsQueryPolicy) {
85,620,614✔
780
    case QUERY_POLICY_VNODE:
85,530,784✔
781
    case QUERY_POLICY_CLIENT: {
782
      if (pResultMeta) {
85,530,784✔
783
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
85,532,296✔
784
        if (NULL == pDbVgList) {
85,533,610✔
785
          code = terrno;
×
786
          goto _return;
×
787
        }
788
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
85,533,610✔
789
        for (int32_t i = 0; i < dbNum; ++i) {
168,940,428✔
790
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
83,406,351✔
791
          if (pRes->code || NULL == pRes->pRes) {
83,407,109✔
792
            continue;
1,111✔
793
          }
794

795
          if (NULL == taosArrayPush(pDbVgList, &pRes->pRes)) {
166,810,109✔
796
            code = terrno;
×
797
            goto _return;
×
798
          }
799
        }
800
      } else {
UNCOV
801
        fp = freeVgList;
×
802

UNCOV
803
        int32_t dbNum = taosArrayGetSize(pRequest->dbList);
×
804
        if (dbNum > 0) {
×
805
          SCatalog*     pCtg = NULL;
×
806
          SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
×
807
          code = catalogGetHandle(pInst->clusterId, &pCtg);
×
808
          if (code != TSDB_CODE_SUCCESS) {
×
809
            goto _return;
×
810
          }
811

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

825
            // catalogGetDBVgList will handle dbFName == null.
826
            code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
×
827
            if (code) {
×
828
              goto _return;
×
829
            }
830

831
            if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
×
832
              code = terrno;
×
833
              goto _return;
×
834
            }
835
          }
836
        }
837
      }
838

839
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
85,534,077✔
840
      break;
85,533,828✔
841
    }
842
    case QUERY_POLICY_HYBRID:
88,035✔
843
    case QUERY_POLICY_QNODE: {
844
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
175,845✔
845
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
87,810✔
846
        if (pRes->code) {
87,810✔
847
          pQnodeList = NULL;
×
848
        } else {
849
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
87,810✔
850
          if (NULL == pQnodeList) {
87,810✔
851
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
852
            goto _return;
×
853
          }
854
        }
855
      } else {
856
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
225✔
857
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
225✔
858
        if (pInst->pQnodeList) {
225✔
859
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
225✔
860
          if (NULL == pQnodeList) {
225✔
861
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
862
            goto _return;
×
863
          }
864
        }
865
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
225✔
866
      }
867

868
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
88,035✔
869
      break;
88,035✔
870
    }
871
    default:
1,795✔
872
      tscError("unknown query policy: %d", tsQueryPolicy);
1,795✔
873
      return TSDB_CODE_APP_ERROR;
×
874
  }
875

876
_return:
85,621,863✔
877
  taosArrayDestroyEx(pDbVgList, fp);
85,621,863✔
878
  taosArrayDestroy(pQnodeList);
85,621,636✔
879

880
  return code;
85,621,651✔
881
}
882

883
int32_t buildSyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList) {
6,781,574✔
884
  SArray* pDbVgList = NULL;
6,781,574✔
885
  SArray* pQnodeList = NULL;
6,781,574✔
886
  int32_t code = 0;
6,781,953✔
887

888
  switch (tsQueryPolicy) {
6,781,953✔
889
    case QUERY_POLICY_VNODE:
6,782,607✔
890
    case QUERY_POLICY_CLIENT: {
891
      int32_t dbNum = taosArrayGetSize(pRequest->dbList);
6,782,607✔
892
      if (dbNum > 0) {
6,784,063✔
893
        SCatalog*     pCtg = NULL;
6,736,226✔
894
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
6,735,431✔
895
        code = catalogGetHandle(pInst->clusterId, &pCtg);
6,735,431✔
896
        if (code != TSDB_CODE_SUCCESS) {
6,733,842✔
897
          goto _return;
×
898
        }
899

900
        pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
6,733,842✔
901
        if (NULL == pDbVgList) {
6,735,360✔
902
          code = terrno;
×
903
          goto _return;
×
904
        }
905
        SArray* pVgList = NULL;
6,735,393✔
906
        for (int32_t i = 0; i < dbNum; ++i) {
13,469,662✔
907
          char*            dbFName = taosArrayGet(pRequest->dbList, i);
6,733,197✔
908
          SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
6,734,377✔
909
                                   .requestId = pRequest->requestId,
6,731,641✔
910
                                   .requestObjRefId = pRequest->self,
6,732,769✔
911
                                   .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
6,733,989✔
912

913
          // catalogGetDBVgList will handle dbFName == null.
914
          code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
6,737,306✔
915
          if (code) {
6,735,860✔
916
            goto _return;
×
917
          }
918

919
          if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
6,735,679✔
920
            code = terrno;
×
921
            goto _return;
×
922
          }
923
        }
924
      }
925

926
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
6,784,854✔
927
      break;
6,783,260✔
928
    }
929
    case QUERY_POLICY_HYBRID:
×
930
    case QUERY_POLICY_QNODE: {
931
      TSC_ERR_JRET(getQnodeList(pRequest, &pQnodeList));
×
932

933
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
×
934
      break;
×
935
    }
936
    default:
398✔
937
      tscError("unknown query policy: %d", tsQueryPolicy);
398✔
938
      return TSDB_CODE_APP_ERROR;
×
939
  }
940

941
_return:
6,783,670✔
942

943
  taosArrayDestroyEx(pDbVgList, freeVgList);
6,783,591✔
944
  taosArrayDestroy(pQnodeList);
6,783,562✔
945

946
  return code;
6,784,158✔
947
}
948

949
int32_t scheduleQuery(SRequestObj* pRequest, SQueryPlan* pDag, SArray* pNodeList) {
6,782,867✔
950
  void* pTransporter = pRequest->pTscObj->pAppInfo->pTransporter;
6,782,867✔
951

952
  SExecResult      res = {0};
6,783,989✔
953
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
6,783,724✔
954
                           .requestId = pRequest->requestId,
6,783,141✔
955
                           .requestObjRefId = pRequest->self};
6,783,234✔
956
  SSchedulerReq    req = {
7,683,328✔
957
         .syncReq = true,
958
         .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
6,783,627✔
959
         .pConn = &conn,
960
         .pNodeList = pNodeList,
961
         .pDag = pDag,
962
         .sql = pRequest->sqlstr,
6,783,627✔
963
         .startTs = pRequest->metric.start,
6,782,695✔
964
         .execFp = NULL,
965
         .cbParam = NULL,
966
         .chkKillFp = chkRequestKilled,
967
         .chkKillParam = (void*)pRequest->self,
6,782,938✔
968
         .pExecRes = &res,
969
         .source = pRequest->source,
6,782,545✔
970
         .pWorkerCb = getTaskPoolWorkerCb(),
6,781,741✔
971
  };
972

973
  int32_t code = schedulerExecJob(&req, &pRequest->body.queryJob);
6,782,691✔
974

975
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
6,784,955✔
976
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
6,784,160✔
977

978
  if (code != TSDB_CODE_SUCCESS) {
6,783,162✔
979
    schedulerFreeJob(&pRequest->body.queryJob, 0);
×
980

981
    pRequest->code = code;
×
982
    terrno = code;
×
983
    return pRequest->code;
×
984
  }
985

986
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_DELETE == pRequest->type ||
6,783,162✔
987
      TDMT_VND_CREATE_TABLE == pRequest->type) {
18,271✔
988
    pRequest->body.resInfo.numOfRows = res.numOfRows;
6,772,161✔
989
    if (TDMT_VND_SUBMIT == pRequest->type) {
6,772,607✔
990
      STscObj*            pTscObj = pRequest->pTscObj;
6,765,221✔
991
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
6,766,267✔
992
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
6,766,148✔
993
    }
994

995
    schedulerFreeJob(&pRequest->body.queryJob, 0);
6,772,322✔
996
  }
997

998
  pRequest->code = res.code;
6,784,750✔
999
  terrno = res.code;
6,783,955✔
1000
  return pRequest->code;
6,783,051✔
1001
}
1002

1003
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
476,074,604✔
1004
  SArray*      pArray = NULL;
476,074,604✔
1005
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
476,074,604✔
1006
  if (NULL == pRsp->aCreateTbRsp) {
476,074,604✔
1007
    return TSDB_CODE_SUCCESS;
466,650,923✔
1008
  }
1009

1010
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
9,428,562✔
1011
  for (int32_t i = 0; i < tbNum; ++i) {
22,553,985✔
1012
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
13,125,125✔
1013
    if (pTbRsp->pMeta) {
13,125,072✔
1014
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
12,486,496✔
1015
    }
1016
  }
1017

1018
  return TSDB_CODE_SUCCESS;
9,428,860✔
1019
}
1020

1021
int32_t handleQueryExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
72,581,481✔
1022
  int32_t code = 0;
72,581,481✔
1023
  SArray* pArray = NULL;
72,581,481✔
1024
  SArray* pTbArray = (SArray*)res;
72,581,481✔
1025
  int32_t tbNum = taosArrayGetSize(pTbArray);
72,581,481✔
1026
  if (tbNum <= 0) {
72,581,033✔
1027
    return TSDB_CODE_SUCCESS;
×
1028
  }
1029

1030
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
72,581,033✔
1031
  if (NULL == pArray) {
72,582,035✔
1032
    return terrno;
×
1033
  }
1034

1035
  for (int32_t i = 0; i < tbNum; ++i) {
192,318,819✔
1036
    STbVerInfo* tbInfo = taosArrayGet(pTbArray, i);
119,738,039✔
1037
    if (NULL == tbInfo) {
119,738,572✔
1038
      code = terrno;
×
1039
      goto _return;
×
1040
    }
1041
    STbSVersion tbSver = {
119,738,572✔
1042
        .tbFName = tbInfo->tbFName, .sver = tbInfo->sversion, .tver = tbInfo->tversion, .rver = tbInfo->rversion};
119,738,039✔
1043
    if (NULL == taosArrayPush(pArray, &tbSver)) {
119,738,572✔
1044
      code = terrno;
×
1045
      goto _return;
×
1046
    }
1047
  }
1048

1049
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
72,580,780✔
1050
                           .requestId = pRequest->requestId,
72,581,468✔
1051
                           .requestObjRefId = pRequest->self,
72,581,742✔
1052
                           .mgmtEps = *epset};
1053

1054
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
72,581,245✔
1055

1056
_return:
72,582,035✔
1057

1058
  taosArrayDestroy(pArray);
72,581,504✔
1059
  return code;
72,581,742✔
1060
}
1061

1062
int32_t handleAlterTbExecRes(void* res, SCatalog* pCatalog) {
9,269,901✔
1063
  return catalogUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
9,269,901✔
1064
}
1065

1066
int32_t handleCreateTbExecRes(void* res, SCatalog* pCatalog) {
56,226,770✔
1067
  return catalogAsyncUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
56,226,770✔
1068
}
1069

1070
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
614,875,006✔
1071
  if (NULL == pRequest->body.resInfo.execRes.res) {
614,875,006✔
1072
    return pRequest->code;
24,806,811✔
1073
  }
1074

1075
  SCatalog*     pCatalog = NULL;
590,066,121✔
1076
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
590,069,380✔
1077

1078
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
590,079,534✔
1079
  if (code) {
590,064,920✔
1080
    return code;
×
1081
  }
1082

1083
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
590,064,920✔
1084
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
590,078,156✔
1085

1086
  switch (pRes->msgType) {
590,078,961✔
1087
    case TDMT_VND_ALTER_TABLE:
3,957,914✔
1088
    case TDMT_MND_ALTER_STB: {
1089
      code = handleAlterTbExecRes(pRes->res, pCatalog);
3,957,914✔
1090
      break;
3,957,914✔
1091
    }
1092
    case TDMT_VND_CREATE_TABLE: {
37,098,956✔
1093
      SArray* pList = (SArray*)pRes->res;
37,098,956✔
1094
      int32_t num = taosArrayGetSize(pList);
37,105,819✔
1095
      for (int32_t i = 0; i < num; ++i) {
78,878,792✔
1096
        void* res = taosArrayGetP(pList, i);
41,767,661✔
1097
        // handleCreateTbExecRes will handle res == null
1098
        code = handleCreateTbExecRes(res, pCatalog);
41,767,440✔
1099
      }
1100
      break;
37,111,131✔
1101
    }
1102
    case TDMT_MND_CREATE_STB: {
348,969✔
1103
      code = handleCreateTbExecRes(pRes->res, pCatalog);
348,969✔
1104
      break;
348,969✔
1105
    }
1106
    case TDMT_VND_SUBMIT: {
476,073,108✔
1107
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
476,073,108✔
1108

1109
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
476,082,915✔
1110
      break;
476,076,682✔
1111
    }
1112
    case TDMT_SCH_QUERY:
72,581,742✔
1113
    case TDMT_SCH_MERGE_QUERY: {
1114
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
72,581,742✔
1115
      break;
72,579,524✔
1116
    }
1117
    default:
250✔
1118
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self,
250✔
1119
               pRequest->type, pRequest->requestId);
1120
      code = TSDB_CODE_APP_ERROR;
×
1121
  }
1122

1123
  return code;
590,074,220✔
1124
}
1125

1126
static bool incompletaFileParsing(SNode* pStmt) {
606,760,446✔
1127
  return QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pStmt) ? false : ((SVnodeModifyOpStmt*)pStmt)->fileProcessing;
606,760,446✔
1128
}
1129

1130
void continuePostSubQuery(SRequestObj* pRequest, SSDataBlock* pBlock) {
×
1131
  SSqlCallbackWrapper* pWrapper = pRequest->pWrapper;
×
1132

1133
  int32_t code = nodesAcquireAllocator(pWrapper->pParseCtx->allocatorId);
×
1134
  if (TSDB_CODE_SUCCESS == code) {
×
1135
    int64_t analyseStart = taosGetTimestampUs();
×
1136
    code = qContinueParsePostQuery(pWrapper->pParseCtx, pRequest->pQuery, pBlock);
×
1137
    pRequest->metric.analyseCostUs += taosGetTimestampUs() - analyseStart;
×
1138
  }
1139

1140
  if (TSDB_CODE_SUCCESS == code) {
×
1141
    code = qContinuePlanPostQuery(pRequest->pPostPlan);
×
1142
  }
1143

1144
  code = nodesReleaseAllocator(pWrapper->pParseCtx->allocatorId);
×
1145
  handleQueryAnslyseRes(pWrapper, NULL, code);
×
1146
}
×
1147

1148
void returnToUser(SRequestObj* pRequest) {
12,775,227✔
1149
  if (pRequest->relation.userRefId == pRequest->self || 0 == pRequest->relation.userRefId) {
12,775,227✔
1150
    // return to client
1151
    doRequestCallback(pRequest, pRequest->code);
12,775,227✔
1152
    return;
12,775,227✔
1153
  }
1154

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

1168
static int32_t createResultBlock(TAOS_RES* pRes, int32_t numOfRows, SSDataBlock** pBlock) {
×
1169
  int64_t     lastTs = 0;
×
1170
  TAOS_FIELD* pResFields = taos_fetch_fields(pRes);
×
1171
  int32_t     numOfFields = taos_num_fields(pRes);
×
1172

1173
  int32_t code = createDataBlock(pBlock);
×
1174
  if (code) {
×
1175
    return code;
×
1176
  }
1177

1178
  for (int32_t i = 0; i < numOfFields; ++i) {
×
1179
    SColumnInfoData colInfoData = createColumnInfoData(pResFields[i].type, pResFields[i].bytes, i + 1);
×
1180
    code = blockDataAppendColInfo(*pBlock, &colInfoData);
×
1181
    if (TSDB_CODE_SUCCESS != code) {
×
1182
      blockDataDestroy(*pBlock);
×
1183
      return code;
×
1184
    }
1185
  }
1186

1187
  code = blockDataEnsureCapacity(*pBlock, numOfRows);
×
1188
  if (TSDB_CODE_SUCCESS != code) {
×
1189
    blockDataDestroy(*pBlock);
×
1190
    return code;
×
1191
  }
1192

1193
  for (int32_t i = 0; i < numOfRows; ++i) {
×
1194
    TAOS_ROW pRow = taos_fetch_row(pRes);
×
1195
    if (NULL == pRow[0] || NULL == pRow[1] || NULL == pRow[2]) {
×
1196
      tscError("invalid data from vnode");
×
1197
      blockDataDestroy(*pBlock);
×
1198
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1199
    }
1200
    int64_t ts = *(int64_t*)pRow[0];
×
1201
    if (lastTs < ts) {
×
1202
      lastTs = ts;
×
1203
    }
1204

1205
    for (int32_t j = 0; j < numOfFields; ++j) {
×
1206
      SColumnInfoData* pColInfoData = taosArrayGet((*pBlock)->pDataBlock, j);
×
1207
      code = colDataSetVal(pColInfoData, i, pRow[j], false);
×
1208
      if (TSDB_CODE_SUCCESS != code) {
×
1209
        blockDataDestroy(*pBlock);
×
1210
        return code;
×
1211
      }
1212
    }
1213

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

1218
  (*pBlock)->info.window.ekey = lastTs;
×
1219
  (*pBlock)->info.rows = numOfRows;
×
1220

1221
  tscInfo("[create stream with histroy] lastKey:%" PRId64 " numOfRows:%d from all vgroups", lastTs, numOfRows);
×
1222
  return TSDB_CODE_SUCCESS;
×
1223
}
1224

1225
void postSubQueryFetchCb(void* param, TAOS_RES* res, int32_t rowNum) {
×
1226
  SRequestObj* pRequest = (SRequestObj*)res;
×
1227
  if (pRequest->code) {
×
1228
    returnToUser(pRequest);
×
1229
    return;
×
1230
  }
1231

1232
  SSDataBlock* pBlock = NULL;
×
1233
  pRequest->code = createResultBlock(res, rowNum, &pBlock);
×
1234
  if (TSDB_CODE_SUCCESS != pRequest->code) {
×
1235
    tscError("req:0x%" PRIx64 ", create result block failed, QID:0x%" PRIx64 " %s", pRequest->self, pRequest->requestId,
×
1236
             tstrerror(pRequest->code));
1237
    returnToUser(pRequest);
×
1238
    return;
×
1239
  }
1240

1241
  SRequestObj* pNextReq = acquireRequest(pRequest->relation.nextRefId);
×
1242
  if (pNextReq) {
×
1243
    continuePostSubQuery(pNextReq, pBlock);
×
1244
    (void)releaseRequest(pRequest->relation.nextRefId);
×
1245
  } else {
1246
    tscError("req:0x%" PRIx64 ", next req ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1247
             pRequest->relation.nextRefId, pRequest->requestId);
1248
  }
1249

1250
  blockDataDestroy(pBlock);
×
1251
}
1252

1253
void handlePostSubQuery(SSqlCallbackWrapper* pWrapper) {
×
1254
  SRequestObj* pRequest = pWrapper->pRequest;
×
1255
  if (TD_RES_QUERY(pRequest)) {
×
1256
    taosAsyncFetchImpl(pRequest, postSubQueryFetchCb, pWrapper);
×
1257
    return;
×
1258
  }
1259

1260
  SRequestObj* pNextReq = acquireRequest(pRequest->relation.nextRefId);
×
1261
  if (pNextReq) {
×
1262
    continuePostSubQuery(pNextReq, NULL);
×
1263
    (void)releaseRequest(pRequest->relation.nextRefId);
×
1264
  } else {
1265
    tscError("req:0x%" PRIx64 ", next req ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1266
             pRequest->relation.nextRefId, pRequest->requestId);
1267
  }
1268
}
1269

1270
// todo refacto the error code  mgmt
1271
void schedulerExecCb(SExecResult* pResult, void* param, int32_t code) {
607,789,500✔
1272
  SSqlCallbackWrapper* pWrapper = param;
607,789,500✔
1273
  SRequestObj*         pRequest = pWrapper->pRequest;
607,789,500✔
1274
  STscObj*             pTscObj = pRequest->pTscObj;
607,792,900✔
1275

1276
  pRequest->code = code;
607,792,842✔
1277
  if (pResult) {
607,794,820✔
1278
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
607,755,445✔
1279
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
607,759,185✔
1280
  }
1281

1282
  int32_t type = pRequest->type;
607,778,220✔
1283
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
607,761,911✔
1284
    if (pResult) {
509,963,834✔
1285
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
509,956,030✔
1286

1287
      // record the insert rows
1288
      if (TDMT_VND_SUBMIT == type) {
509,963,831✔
1289
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
469,457,869✔
1290
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
469,458,231✔
1291
      }
1292
    }
1293
    schedulerFreeJob(&pRequest->body.queryJob, 0);
509,974,180✔
1294
  }
1295

1296
  taosMemoryFree(pResult);
607,793,321✔
1297
  tscDebug("req:0x%" PRIx64 ", enter scheduler exec cb, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
607,785,534✔
1298
           pRequest->requestId);
1299

1300
  if (code != TSDB_CODE_SUCCESS && NEED_CLIENT_HANDLE_ERROR(code) && pRequest->sqlstr != NULL &&
607,782,326✔
1301
      pRequest->stmtBindVersion == 0) {
46,393✔
1302
    tscDebug("req:0x%" PRIx64 ", client retry to handle the error, code:%s, tryCount:%d, QID:0x%" PRIx64,
46,393✔
1303
             pRequest->self, tstrerror(code), pRequest->retry, pRequest->requestId);
1304
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
46,393✔
1305
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1306
    }
1307
    restartAsyncQuery(pRequest, code);
46,393✔
1308
    return;
46,393✔
1309
  }
1310

1311
  tscTrace("req:0x%" PRIx64 ", scheduler exec cb, request type:%s", pRequest->self, TMSG_INFO(pRequest->type));
607,735,933✔
1312
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
607,735,933✔
1313
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
2,914,331✔
1314
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1315
    }
1316
  }
1317

1318
  pRequest->metric.execCostUs = taosGetTimestampUs() - pRequest->metric.execStart;
607,745,167✔
1319
  int32_t code1 = handleQueryExecRsp(pRequest);
607,739,437✔
1320
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
607,743,932✔
1321
    pRequest->code = code1;
×
1322
  }
1323

1324
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
1,214,505,411✔
1325
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
606,756,564✔
1326
    continueInsertFromCsv(pWrapper, pRequest);
12,361✔
1327
    return;
12,361✔
1328
  }
1329

1330
  if (pRequest->relation.nextRefId) {
607,740,332✔
1331
    handlePostSubQuery(pWrapper);
×
1332
  } else {
1333
    destorySqlCallbackWrapper(pWrapper);
607,740,972✔
1334
    pRequest->pWrapper = NULL;
607,729,162✔
1335

1336
    // return to client
1337
    doRequestCallback(pRequest, code);
607,732,529✔
1338
  }
1339
}
1340

1341
void launchQueryImpl(SRequestObj* pRequest, SQuery* pQuery, bool keepQuery, void** res) {
7,136,688✔
1342
  int32_t code = 0;
7,136,688✔
1343
  int32_t subplanNum = 0;
7,136,688✔
1344

1345
  if (pQuery->pRoot) {
7,136,688✔
1346
    pRequest->stmtType = pQuery->pRoot->type;
6,782,510✔
1347
  }
1348

1349
  if (pQuery->pRoot && !pRequest->inRetry) {
7,137,241✔
1350
    STscObj*            pTscObj = pRequest->pTscObj;
6,783,335✔
1351
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
6,780,911✔
1352
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type) {
6,783,053✔
1353
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
6,772,157✔
1354
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
10,895✔
1355
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
10,718✔
1356
    }
1357
  }
1358

1359
  pRequest->body.execMode = pQuery->execMode;
7,138,606✔
1360
  switch (pQuery->execMode) {
7,139,480✔
1361
    case QUERY_EXEC_MODE_LOCAL:
×
1362
      if (!pRequest->validateOnly) {
×
1363
        if (NULL == pQuery->pRoot) {
×
1364
          terrno = TSDB_CODE_INVALID_PARA;
×
1365
          code = terrno;
×
1366
        } else {
1367
          code = execLocalCmd(pRequest, pQuery);
×
1368
        }
1369
      }
1370
      break;
×
1371
    case QUERY_EXEC_MODE_RPC:
356,620✔
1372
      if (!pRequest->validateOnly) {
356,620✔
1373
        code = execDdlQuery(pRequest, pQuery);
356,620✔
1374
      }
1375
      break;
356,620✔
1376
    case QUERY_EXEC_MODE_SCHEDULE: {
6,780,692✔
1377
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
6,780,692✔
1378
      if (NULL == pMnodeList) {
6,784,140✔
1379
        code = terrno;
×
1380
        break;
×
1381
      }
1382
      SQueryPlan* pDag = NULL;
6,784,140✔
1383
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
6,784,405✔
1384
      if (TSDB_CODE_SUCCESS == code) {
6,782,463✔
1385
        pRequest->body.subplanNum = pDag->numOfSubplans;
6,782,210✔
1386
        if (!pRequest->validateOnly) {
6,784,442✔
1387
          SArray* pNodeList = NULL;
6,782,643✔
1388
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
6,782,219✔
1389
          if (TSDB_CODE_SUCCESS == code) {
6,782,642✔
1390
            code = scheduleQuery(pRequest, pDag, pNodeList);
6,783,259✔
1391
          }
1392
          taosArrayDestroy(pNodeList);
6,782,079✔
1393
        }
1394
      }
1395
      taosArrayDestroy(pMnodeList);
6,783,309✔
1396
      break;
6,783,742✔
1397
    }
1398
    case QUERY_EXEC_MODE_EMPTY_RESULT:
×
1399
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
1400
      break;
×
1401
    default:
×
1402
      break;
×
1403
  }
1404

1405
  if (!keepQuery) {
7,140,353✔
1406
    qDestroyQuery(pQuery);
×
1407
  }
1408

1409
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
7,140,353✔
1410
    int ret = removeMeta(pRequest->pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type));
7,837✔
1411
    if (TSDB_CODE_SUCCESS != ret) {
7,837✔
1412
      tscError("req:0x%" PRIx64 ", remove meta failed,code:%d, QID:0x%" PRIx64, pRequest->self, ret,
×
1413
               pRequest->requestId);
1414
    }
1415
  }
1416

1417
  if (TSDB_CODE_SUCCESS == code) {
7,139,655✔
1418
    code = handleQueryExecRsp(pRequest);
7,138,898✔
1419
  }
1420

1421
  if (TSDB_CODE_SUCCESS != code) {
7,140,013✔
1422
    pRequest->code = code;
5,144✔
1423
  }
1424

1425
  if (res) {
7,140,013✔
1426
    *res = pRequest->body.resInfo.execRes.res;
×
1427
    pRequest->body.resInfo.execRes.res = NULL;
×
1428
  }
1429
}
7,140,013✔
1430

1431
static int32_t asyncExecSchQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta,
608,279,121✔
1432
                                 SSqlCallbackWrapper* pWrapper) {
1433
  int32_t code = TSDB_CODE_SUCCESS;
608,279,121✔
1434
  pRequest->type = pQuery->msgType;
608,279,121✔
1435
  SArray*     pMnodeList = NULL;
608,285,421✔
1436
  SQueryPlan* pDag = NULL;
608,285,421✔
1437
  int64_t     st = taosGetTimestampUs();
608,270,166✔
1438

1439
  if (!pRequest->parseOnly) {
608,270,166✔
1440
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
608,271,882✔
1441
    if (NULL == pMnodeList) {
608,271,520✔
1442
      code = terrno;
×
1443
    }
1444
    SPlanContext cxt = {.queryId = pRequest->requestId,
614,175,536✔
1445
                        .acctId = pRequest->pTscObj->acctId,
608,292,156✔
1446
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
608,290,026✔
1447
                        .pAstRoot = pQuery->pRoot,
608,306,000✔
1448
                        .showRewrite = pQuery->showRewrite,
608,308,143✔
1449
                        .isView = pWrapper->pParseCtx->isView,
608,296,159✔
1450
                        .isAudit = pWrapper->pParseCtx->isAudit,
608,301,756✔
1451
                        .pMsg = pRequest->msgBuf,
608,284,191✔
1452
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1453
                        .pUser = pRequest->pTscObj->user,
608,292,921✔
1454
                        .sysInfo = pRequest->pTscObj->sysInfo,
608,287,279✔
1455
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
608,289,663✔
1456
                        .allocatorId = pRequest->stmtBindVersion > 0 ? 0 : pRequest->allocatorRefId};
608,288,687✔
1457
    if (TSDB_CODE_SUCCESS == code) {
608,295,431✔
1458
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
608,297,652✔
1459
    }
1460
    if (code) {
608,289,392✔
1461
      tscError("req:0x%" PRIx64 ", failed to create query plan, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
278,308✔
1462
               pRequest->requestId);
1463
    } else {
1464
      pRequest->body.subplanNum = pDag->numOfSubplans;
608,011,084✔
1465
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
608,006,561✔
1466
    }
1467
  }
1468

1469
  pRequest->metric.execStart = taosGetTimestampUs();
608,289,128✔
1470
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
608,287,775✔
1471

1472
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
611,222,001✔
1473
    SArray* pNodeList = NULL;
607,766,710✔
1474
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
607,785,485✔
1475
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
85,621,383✔
1476
    }
1477

1478
    SRequestConnInfo conn = {.pTrans = getAppInfo(pRequest)->pTransporter,
607,770,931✔
1479
                             .requestId = pRequest->requestId,
607,782,020✔
1480
                             .requestObjRefId = pRequest->self};
607,778,865✔
1481
    SSchedulerReq    req = {
610,729,422✔
1482
           .syncReq = false,
1483
           .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
607,766,839✔
1484
           .pConn = &conn,
1485
           .pNodeList = pNodeList,
1486
           .pDag = pDag,
1487
           .allocatorRefId = pRequest->allocatorRefId,
607,766,839✔
1488
           .sql = pRequest->sqlstr,
607,758,823✔
1489
           .startTs = pRequest->metric.start,
607,776,820✔
1490
           .execFp = schedulerExecCb,
1491
           .cbParam = pWrapper,
1492
           .chkKillFp = chkRequestKilled,
1493
           .chkKillParam = (void*)pRequest->self,
607,762,313✔
1494
           .pExecRes = NULL,
1495
           .source = pRequest->source,
607,754,876✔
1496
           .pWorkerCb = getTaskPoolWorkerCb(),
607,757,045✔
1497
    };
1498
    if (TSDB_CODE_SUCCESS == code) {
607,762,060✔
1499
      code = schedulerExecJob(&req, &pRequest->body.queryJob);
607,790,084✔
1500
    }
1501

1502
    taosArrayDestroy(pNodeList);
607,757,369✔
1503
  } else {
1504
    qDestroyQueryPlan(pDag);
520,482✔
1505
    tscDebug("req:0x%" PRIx64 ", plan not executed, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
511,345✔
1506
             pRequest->requestId);
1507
    destorySqlCallbackWrapper(pWrapper);
511,345✔
1508
    pRequest->pWrapper = NULL;
511,345✔
1509
    if (TSDB_CODE_SUCCESS != code) {
511,345✔
1510
      pRequest->code = terrno;
278,308✔
1511
    }
1512

1513
    doRequestCallback(pRequest, code);
511,345✔
1514
  }
1515

1516
  // todo not to be released here
1517
  taosArrayDestroy(pMnodeList);
608,302,250✔
1518

1519
  return code;
608,294,238✔
1520
}
1521

1522
void launchAsyncQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta, SSqlCallbackWrapper* pWrapper) {
631,518,507✔
1523
  int32_t code = 0;
631,518,507✔
1524

1525
  if (pRequest->parseOnly) {
631,518,507✔
1526
    doRequestCallback(pRequest, 0);
300,644✔
1527
    return;
300,644✔
1528
  }
1529

1530
  pRequest->body.execMode = pQuery->execMode;
631,230,863✔
1531
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
631,228,231✔
1532
    destorySqlCallbackWrapper(pWrapper);
22,938,502✔
1533
    pRequest->pWrapper = NULL;
22,938,968✔
1534
  }
1535

1536
  if (pQuery->pRoot && !pRequest->inRetry) {
631,213,861✔
1537
    STscObj*            pTscObj = pRequest->pTscObj;
631,218,915✔
1538
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
631,238,961✔
1539
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
631,231,388✔
1540
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
522,161,205✔
1541
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
469,415,234✔
1542
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
161,813,410✔
1543
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
80,646,503✔
1544
    }
1545
  }
1546

1547
  switch (pQuery->execMode) {
631,237,056✔
1548
    case QUERY_EXEC_MODE_LOCAL:
5,263,385✔
1549
      asyncExecLocalCmd(pRequest, pQuery);
5,263,385✔
1550
      break;
5,263,385✔
1551
    case QUERY_EXEC_MODE_RPC:
17,303,872✔
1552
      code = asyncExecDdlQuery(pRequest, pQuery);
17,303,872✔
1553
      break;
17,304,667✔
1554
    case QUERY_EXEC_MODE_SCHEDULE: {
608,283,398✔
1555
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
608,283,398✔
1556
      break;
608,295,813✔
1557
    }
1558
    case QUERY_EXEC_MODE_EMPTY_RESULT:
371,230✔
1559
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
371,230✔
1560
      doRequestCallback(pRequest, 0);
371,230✔
1561
      break;
371,230✔
1562
    default:
×
1563
      tscError("req:0x%" PRIx64 ", invalid execMode %d", pRequest->self, pQuery->execMode);
×
1564
      doRequestCallback(pRequest, -1);
×
1565
      break;
×
1566
  }
1567
}
1568

1569
int32_t refreshMeta(STscObj* pTscObj, SRequestObj* pRequest) {
11,506✔
1570
  SCatalog* pCatalog = NULL;
11,506✔
1571
  int32_t   code = 0;
11,506✔
1572
  int32_t   dbNum = taosArrayGetSize(pRequest->dbList);
11,506✔
1573
  int32_t   tblNum = taosArrayGetSize(pRequest->tableList);
11,506✔
1574

1575
  if (dbNum <= 0 && tblNum <= 0) {
11,506✔
1576
    return TSDB_CODE_APP_ERROR;
11,506✔
1577
  }
1578

1579
  code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
×
1580
  if (code != TSDB_CODE_SUCCESS) {
×
1581
    return code;
×
1582
  }
1583

1584
  SRequestConnInfo conn = {.pTrans = pTscObj->pAppInfo->pTransporter,
×
1585
                           .requestId = pRequest->requestId,
×
1586
                           .requestObjRefId = pRequest->self,
×
1587
                           .mgmtEps = getEpSet_s(&pTscObj->pAppInfo->mgmtEp)};
×
1588

1589
  for (int32_t i = 0; i < dbNum; ++i) {
×
1590
    char* dbFName = taosArrayGet(pRequest->dbList, i);
×
1591

1592
    // catalogRefreshDBVgInfo will handle dbFName == null.
1593
    code = catalogRefreshDBVgInfo(pCatalog, &conn, dbFName);
×
1594
    if (code != TSDB_CODE_SUCCESS) {
×
1595
      return code;
×
1596
    }
1597
  }
1598

1599
  for (int32_t i = 0; i < tblNum; ++i) {
×
1600
    SName* tableName = taosArrayGet(pRequest->tableList, i);
×
1601

1602
    // catalogRefreshTableMeta will handle tableName == null.
1603
    code = catalogRefreshTableMeta(pCatalog, &conn, tableName, -1);
×
1604
    if (code != TSDB_CODE_SUCCESS) {
×
1605
      return code;
×
1606
    }
1607
  }
1608

1609
  return code;
×
1610
}
1611

1612
int32_t removeMeta(STscObj* pTscObj, SArray* tbList, bool isView) {
4,260,100✔
1613
  SCatalog* pCatalog = NULL;
4,260,100✔
1614
  int32_t   tbNum = taosArrayGetSize(tbList);
4,260,100✔
1615
  int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
4,260,100✔
1616
  if (code != TSDB_CODE_SUCCESS) {
4,260,100✔
1617
    return code;
×
1618
  }
1619

1620
  if (isView) {
4,260,100✔
1621
    for (int32_t i = 0; i < tbNum; ++i) {
855,214✔
1622
      SName* pViewName = taosArrayGet(tbList, i);
427,607✔
1623
      char   dbFName[TSDB_DB_FNAME_LEN];
425,057✔
1624
      if (NULL == pViewName) {
427,607✔
1625
        continue;
×
1626
      }
1627
      (void)tNameGetFullDbName(pViewName, dbFName);
427,607✔
1628
      TSC_ERR_RET(catalogRemoveViewMeta(pCatalog, dbFName, 0, pViewName->tname, 0));
427,607✔
1629
    }
1630
  } else {
1631
    for (int32_t i = 0; i < tbNum; ++i) {
5,731,933✔
1632
      SName* pTbName = taosArrayGet(tbList, i);
1,899,440✔
1633
      TSC_ERR_RET(catalogRemoveTableMeta(pCatalog, pTbName));
1,899,440✔
1634
    }
1635
  }
1636

1637
  return TSDB_CODE_SUCCESS;
4,260,100✔
1638
}
1639

1640
int32_t initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet) {
3,238,660✔
1641
  pEpSet->version = 0;
3,238,660✔
1642

1643
  // init mnode ip set
1644
  SEpSet* mgmtEpSet = &(pEpSet->epSet);
3,238,713✔
1645
  mgmtEpSet->numOfEps = 0;
3,238,459✔
1646
  mgmtEpSet->inUse = 0;
3,238,713✔
1647

1648
  if (firstEp && firstEp[0] != 0) {
3,238,713✔
1649
    if (strlen(firstEp) >= TSDB_EP_LEN) {
3,237,862✔
1650
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1651
      return -1;
×
1652
    }
1653

1654
    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
3,237,862✔
1655
    if (code != TSDB_CODE_SUCCESS) {
3,237,686✔
1656
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1657
      return terrno;
×
1658
    }
1659
    // uint32_t addr = 0;
1660
    SIpAddr addr = {0};
3,237,686✔
1661
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
3,237,705✔
1662
    if (code) {
3,237,943✔
1663
      tscError("failed to resolve firstEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
615✔
1664
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1665
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
584✔
1666
    } else {
1667
      mgmtEpSet->numOfEps++;
3,237,349✔
1668
    }
1669
  }
1670

1671
  if (secondEp && secondEp[0] != 0) {
3,238,116✔
1672
    if (strlen(secondEp) >= TSDB_EP_LEN) {
2,268,541✔
1673
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1674
      return terrno;
×
1675
    }
1676

1677
    int32_t code = taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
2,268,541✔
1678
    if (code != TSDB_CODE_SUCCESS) {
2,268,798✔
1679
      return code;
×
1680
    }
1681
    SIpAddr addr = {0};
2,268,798✔
1682
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
2,268,798✔
1683
    if (code) {
2,268,541✔
1684
      tscError("failed to resolve secondEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
56✔
1685
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1686
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
×
1687
    } else {
1688
      mgmtEpSet->numOfEps++;
2,268,485✔
1689
    }
1690
  }
1691

1692
  if (mgmtEpSet->numOfEps == 0) {
3,237,803✔
1693
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
584✔
1694
    return TSDB_CODE_RPC_NETWORK_UNAVAIL;
584✔
1695
  }
1696

1697
  return 0;
3,237,732✔
1698
}
1699

1700
int32_t taosConnectImpl(const char* user, const char* auth, int32_t totpCode, const char* db, __taos_async_fn_t fp, void* param,
3,238,216✔
1701
                        SAppInstInfo* pAppInfo, int connType, STscObj** pTscObj) {
1702
  *pTscObj = NULL;
3,238,216✔
1703
  int32_t code = createTscObj(user, auth, db, connType, pAppInfo, pTscObj);
3,238,216✔
1704
  if (TSDB_CODE_SUCCESS != code) {
3,238,216✔
1705
    return code;
×
1706
  }
1707

1708
  SRequestObj* pRequest = NULL;
3,238,216✔
1709
  code = createRequest((*pTscObj)->id, TDMT_MND_CONNECT, 0, &pRequest);
3,238,216✔
1710
  if (TSDB_CODE_SUCCESS != code) {
3,238,216✔
1711
    destroyTscObj(*pTscObj);
×
1712
    return code;
×
1713
  }
1714

1715
  pRequest->sqlstr = taosStrdup("taos_connect");
3,238,216✔
1716
  if (pRequest->sqlstr) {
3,238,183✔
1717
    pRequest->sqlLen = strlen(pRequest->sqlstr);
3,238,183✔
1718
  } else {
1719
    return terrno;
×
1720
  }
1721

1722
  SMsgSendInfo* body = NULL;
3,238,183✔
1723
  code = buildConnectMsg(pRequest, &body, totpCode);
3,238,183✔
1724
  if (TSDB_CODE_SUCCESS != code) {
3,237,080✔
1725
    destroyTscObj(*pTscObj);
×
1726
    return code;
×
1727
  }
1728

1729
  // int64_t transporterId = 0;
1730
  SEpSet epset = getEpSet_s(&(*pTscObj)->pAppInfo->mgmtEp);
3,237,080✔
1731
  code = asyncSendMsgToServer((*pTscObj)->pAppInfo->pTransporter, &epset, NULL, body);
3,237,903✔
1732
  if (TSDB_CODE_SUCCESS != code) {
3,237,926✔
1733
    destroyTscObj(*pTscObj);
×
1734
    tscError("failed to send connect msg to server, code:%s", tstrerror(code));
×
1735
    return code;
×
1736
  }
1737
  if (TSDB_CODE_SUCCESS != tsem_wait(&pRequest->body.rspSem)) {
3,237,926✔
1738
    destroyTscObj(*pTscObj);
×
1739
    tscError("failed to wait sem, code:%s", terrstr());
×
1740
    return terrno;
×
1741
  }
1742
  if (pRequest->code != TSDB_CODE_SUCCESS) {
3,238,216✔
1743
    const char* errorMsg = (code == TSDB_CODE_RPC_FQDN_ERROR) ? taos_errstr(pRequest) : tstrerror(pRequest->code);
6,629✔
1744
    tscError("failed to connect to server, reason: %s", errorMsg);
6,629✔
1745

1746
    terrno = pRequest->code;
6,629✔
1747
    destroyRequest(pRequest);
6,629✔
1748
    taos_close_internal(*pTscObj);
6,629✔
1749
    *pTscObj = NULL;
6,629✔
1750
    return terrno;
6,629✔
1751
  }
1752
  if (connType == CONN_TYPE__AUTH_TEST) {
3,231,587✔
1753
    terrno = TSDB_CODE_SUCCESS;
×
1754
    destroyRequest(pRequest);
×
1755
    taos_close_internal(*pTscObj);
×
1756
    *pTscObj = NULL;
×
1757
    return TSDB_CODE_SUCCESS;
×
1758
  }
1759

1760
  tscInfo("conn:0x%" PRIx64 ", connection is opening, connId:%u, dnodeConn:%p, QID:0x%" PRIx64, (*pTscObj)->id,
3,231,587✔
1761
          (*pTscObj)->connId, (*pTscObj)->pAppInfo->pTransporter, pRequest->requestId);
1762
  destroyRequest(pRequest);
3,231,621✔
1763
  return code;
3,231,587✔
1764
}
1765

1766
static int32_t buildConnectMsg(SRequestObj* pRequest, SMsgSendInfo** pMsgSendInfo, int32_t totpCode) {
3,238,183✔
1767
  *pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
3,238,183✔
1768
  if (*pMsgSendInfo == NULL) {
3,238,183✔
1769
    return terrno;
×
1770
  }
1771

1772
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
3,238,183✔
1773

1774
  (*pMsgSendInfo)->requestObjRefId = pRequest->self;
3,238,183✔
1775
  (*pMsgSendInfo)->requestId = pRequest->requestId;
3,238,183✔
1776
  (*pMsgSendInfo)->fp = getMsgRspHandle((*pMsgSendInfo)->msgType);
3,238,183✔
1777
  (*pMsgSendInfo)->param = taosMemoryCalloc(1, sizeof(pRequest->self));
3,238,183✔
1778
  if (NULL == (*pMsgSendInfo)->param) {
3,238,183✔
1779
    taosMemoryFree(*pMsgSendInfo);
×
1780
    return terrno;
×
1781
  }
1782

1783
  *(int64_t*)(*pMsgSendInfo)->param = pRequest->self;
3,238,183✔
1784

1785
  SConnectReq connectReq = {0};
3,236,593✔
1786
  STscObj*    pObj = pRequest->pTscObj;
3,236,593✔
1787

1788
  char* db = getDbOfConnection(pObj);
3,236,593✔
1789
  if (db != NULL) {
3,238,183✔
1790
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
1,233,352✔
1791
  } else if (terrno) {
2,004,831✔
1792
    taosMemoryFree(*pMsgSendInfo);
×
1793
    return terrno;
×
1794
  }
1795
  taosMemoryFreeClear(db);
3,238,216✔
1796

1797
  connectReq.connType = pObj->connType;
3,238,216✔
1798
  connectReq.pid = appInfo.pid;
3,238,216✔
1799
  connectReq.startTime = appInfo.startTime;
3,238,216✔
1800
  connectReq.totpCode = totpCode;
3,238,216✔
1801

1802
  tstrncpy(connectReq.app, appInfo.appName, sizeof(connectReq.app));
3,238,216✔
1803
  tstrncpy(connectReq.user, pObj->user, sizeof(connectReq.user));
3,238,216✔
1804
  tstrncpy(connectReq.passwd, pObj->pass, sizeof(connectReq.passwd));
3,238,216✔
1805
  tstrncpy(connectReq.sVer, td_version, sizeof(connectReq.sVer));
3,238,216✔
1806

1807
  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connectReq);
3,238,216✔
1808
  void*   pReq = taosMemoryMalloc(contLen);
3,237,841✔
1809
  if (NULL == pReq) {
3,237,859✔
1810
    taosMemoryFree(*pMsgSendInfo);
×
1811
    return terrno;
×
1812
  }
1813

1814
  if (-1 == tSerializeSConnectReq(pReq, contLen, &connectReq)) {
3,237,859✔
1815
    taosMemoryFree(*pMsgSendInfo);
×
1816
    taosMemoryFree(pReq);
×
1817
    return terrno;
×
1818
  }
1819

1820
  (*pMsgSendInfo)->msgInfo.len = contLen;
3,237,926✔
1821
  (*pMsgSendInfo)->msgInfo.pData = pReq;
3,238,183✔
1822
  return TSDB_CODE_SUCCESS;
3,238,183✔
1823
}
1824

1825
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,046,974,466✔
1826
  if (NULL == pEpSet) {
1,046,974,466✔
1827
    return;
1,042,382,629✔
1828
  }
1829

1830
  switch (pSendInfo->target.type) {
4,591,837✔
1831
    case TARGET_TYPE_MNODE:
1,026✔
1832
      if (NULL == pTscObj) {
1,026✔
1833
        tscError("mnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1834
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1835
        return;
×
1836
      }
1837

1838
      SEpSet  originEpset = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
1,026✔
1839
      SEpSet* pOrig = &originEpset;
1,026✔
1840
      SEp*    pOrigEp = &pOrig->eps[pOrig->inUse];
1,026✔
1841
      SEp*    pNewEp = &pEpSet->eps[pEpSet->inUse];
1,026✔
1842
      tscDebug("mnode epset updated from %d/%d=>%s:%d to %d/%d=>%s:%d in client", pOrig->inUse, pOrig->numOfEps,
1,026✔
1843
               pOrigEp->fqdn, pOrigEp->port, pEpSet->inUse, pEpSet->numOfEps, pNewEp->fqdn, pNewEp->port);
1844
      updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
1,026✔
1845
      break;
1,120,069✔
1846
    case TARGET_TYPE_VNODE: {
4,347,617✔
1847
      if (NULL == pTscObj) {
4,347,617✔
1848
        tscError("vnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1849
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1850
        return;
×
1851
      }
1852

1853
      SCatalog* pCatalog = NULL;
4,347,617✔
1854
      int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
4,347,617✔
1855
      if (code != TSDB_CODE_SUCCESS) {
4,347,550✔
1856
        tscError("fail to get catalog handle, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1857
                 tstrerror(code));
1858
        return;
×
1859
      }
1860

1861
      code = catalogUpdateVgEpSet(pCatalog, pSendInfo->target.dbFName, pSendInfo->target.vgId, pEpSet);
4,347,550✔
1862
      if (code != TSDB_CODE_SUCCESS) {
4,347,849✔
1863
        tscError("fail to update catalog vg epset, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
33✔
1864
                 tstrerror(code));
1865
        return;
×
1866
      }
1867
      taosMemoryFreeClear(pSendInfo->target.dbFName);
4,347,816✔
1868
      break;
4,347,528✔
1869
    }
1870
    default:
245,388✔
1871
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
245,388✔
1872
      break;
245,289✔
1873
  }
1874
}
1875

1876
int32_t doProcessMsgFromServerImpl(SRpcMsg* pMsg, SEpSet* pEpSet) {
1,047,610,751✔
1877
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
1,047,610,751✔
1878
  if (pMsg->info.ahandle == NULL) {
1,047,612,607✔
1879
    tscError("doProcessMsgFromServer pMsg->info.ahandle == NULL");
631,665✔
1880
    rpcFreeCont(pMsg->pCont);
631,665✔
1881
    taosMemoryFree(pEpSet);
631,665✔
1882
    return TSDB_CODE_TSC_INTERNAL_ERROR;
631,665✔
1883
  }
1884

1885
  STscObj* pTscObj = NULL;
1,046,980,012✔
1886

1887
  STraceId* trace = &pMsg->info.traceId;
1,046,980,012✔
1888
  char      tbuf[40] = {0};
1,046,979,715✔
1889
  TRACE_TO_STR(trace, tbuf);
1,046,979,675✔
1890

1891
  tscDebug("QID:%s, process message from server, handle:%p, message:%s, size:%d, code:%s", tbuf, pMsg->info.handle,
1,046,981,353✔
1892
           TMSG_INFO(pMsg->msgType), pMsg->contLen, tstrerror(pMsg->code));
1893

1894
  if (pSendInfo->requestObjRefId != 0) {
1,046,980,881✔
1895
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
903,818,904✔
1896
    if (pRequest) {
903,819,856✔
1897
      if (pRequest->self != pSendInfo->requestObjRefId) {
903,509,896✔
1898
        tscError("doProcessMsgFromServer req:0x%" PRId64 " != pSendInfo->requestObjRefId:0x%" PRId64, pRequest->self,
×
1899
                 pSendInfo->requestObjRefId);
1900

1901
        if (TSDB_CODE_SUCCESS != taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId)) {
×
1902
          tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1903
        }
1904
        rpcFreeCont(pMsg->pCont);
×
1905
        taosMemoryFree(pEpSet);
×
1906
        destroySendMsgInfo(pSendInfo);
×
1907
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1908
      }
1909
      pTscObj = pRequest->pTscObj;
903,509,166✔
1910
    }
1911
  }
1912

1913
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
1,046,980,966✔
1914

1915
  SDataBuf buf = {.msgType = pMsg->msgType,
1,046,975,735✔
1916
                  .len = pMsg->contLen,
1,046,976,248✔
1917
                  .pData = NULL,
1918
                  .handle = pMsg->info.handle,
1,046,976,724✔
1919
                  .handleRefId = pMsg->info.refId,
1,046,977,206✔
1920
                  .pEpSet = pEpSet};
1921

1922
  if (pMsg->contLen > 0) {
1,046,980,515✔
1923
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
1,025,557,316✔
1924
    if (buf.pData == NULL) {
1,025,551,300✔
1925
      pMsg->code = terrno;
×
1926
    } else {
1927
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
1,025,551,300✔
1928
    }
1929
  }
1930

1931
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
1,046,980,270✔
1932

1933
  if (pTscObj) {
1,046,958,980✔
1934
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
903,495,641✔
1935
    if (TSDB_CODE_SUCCESS != code) {
903,511,336✔
1936
      tscError("doProcessMsgFromServer taosReleaseRef failed");
795✔
1937
      terrno = code;
795✔
1938
      pMsg->code = code;
795✔
1939
    }
1940
  }
1941

1942
  rpcFreeCont(pMsg->pCont);
1,046,974,675✔
1943
  destroySendMsgInfo(pSendInfo);
1,046,968,562✔
1944
  return TSDB_CODE_SUCCESS;
1,046,957,373✔
1945
}
1946

1947
int32_t doProcessMsgFromServer(void* param) {
1,047,611,631✔
1948
  AsyncArg* arg = (AsyncArg*)param;
1,047,611,631✔
1949
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
1,047,611,631✔
1950
  taosMemoryFree(arg);
1,047,586,102✔
1951
  return code;
1,047,597,302✔
1952
}
1953

1954
void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,047,598,362✔
1955
  int32_t code = 0;
1,047,598,362✔
1956
  SEpSet* tEpSet = NULL;
1,047,598,362✔
1957

1958
  tscDebug("msg callback, ahandle %p", pMsg->info.ahandle);
1,047,598,362✔
1959

1960
  if (pEpSet != NULL) {
1,047,609,020✔
1961
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
4,594,032✔
1962
    if (NULL == tEpSet) {
4,594,032✔
1963
      code = terrno;
×
1964
      pMsg->code = terrno;
×
1965
      goto _exit;
×
1966
    }
1967
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
4,594,032✔
1968
  }
1969

1970
  // pMsg is response msg
1971
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
1,047,609,020✔
1972
    // restore origin code
1973
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
3,238,216✔
1974
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1975
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
3,238,216✔
1976
      pMsg->code = TSDB_CODE_RPC_BROKEN_LINK;
×
1977
    }
1978
  } else {
1979
    // uniform to one error code: TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED
1980
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
1,044,366,427✔
1981
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
1982
    }
1983
  }
1984

1985
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
1,047,606,642✔
1986
  if (NULL == arg) {
1,047,603,938✔
1987
    code = terrno;
×
1988
    pMsg->code = code;
×
1989
    goto _exit;
×
1990
  }
1991

1992
  arg->msg = *pMsg;
1,047,603,938✔
1993
  arg->pEpset = tEpSet;
1,047,603,959✔
1994

1995
  if ((code = taosAsyncExec(doProcessMsgFromServer, arg, NULL)) != 0) {
1,047,606,067✔
1996
    pMsg->code = code;
50✔
1997
    taosMemoryFree(arg);
50✔
1998
    goto _exit;
×
1999
  }
2000
  return;
1,047,608,448✔
2001

2002
_exit:
×
2003
  tscError("failed to sched msg to tsc since %s", tstrerror(code));
×
2004
  code = doProcessMsgFromServerImpl(pMsg, tEpSet);
×
2005
  if (code != 0) {
×
2006
    tscError("failed to sched msg to tsc, tsc ready quit");
×
2007
  }
2008
}
2009

2010

2011

2012
TAOS *taos_connect_totp(const char *ip, const char *user, const char *pass, const char* totp, const char *db, uint16_t port) {
×
2013
  tscInfo("try to connect to %s:%u by totp, user:%s db:%s", ip, port, user, db);
×
2014
  if (user == NULL) {
×
2015
    user = TSDB_DEFAULT_USER;
×
2016
  }
2017

2018
  if (pass == NULL) {
×
2019
    pass = TSDB_DEFAULT_PASS;
×
2020
  }
2021

2022
  STscObj *pObj = NULL;
×
2023
  int32_t  code = taos_connect_internal(ip, user, pass, NULL, totp, db, port, CONN_TYPE__QUERY, &pObj);
×
2024
  if (TSDB_CODE_SUCCESS == code) {
×
2025
    int64_t *rid = taosMemoryCalloc(1, sizeof(int64_t));
×
2026
    if (NULL == rid) {
×
2027
      tscError("out of memory when taos connect to %s:%u, user:%s db:%s", ip, port, user, db);
×
2028
      return NULL;
×
2029
    }
2030
    *rid = pObj->id;
×
2031
    return (TAOS *)rid;
×
2032
  } else {
2033
    terrno = code;
×
2034
  }
2035

2036
  return NULL;
×
2037
}
2038

2039

2040
int taos_connect_test(const char *ip, const char *user, const char *pass, const char* totp, const char *db, uint16_t port) {
×
2041
  tscInfo("try to connect to %s:%u by totp, user:%s db:%s", ip, port, user, db);
×
2042
  if (user == NULL) {
×
2043
    user = TSDB_DEFAULT_USER;
×
2044
  }
2045

2046
  if (pass == NULL) {
×
2047
    pass = TSDB_DEFAULT_PASS;
×
2048
  }
2049

2050
  STscObj *pObj = NULL;
×
2051
  return taos_connect_internal(ip, user, pass, NULL, totp, db, port, CONN_TYPE__AUTH_TEST, &pObj);
×
2052
}
2053

2054

2055
TAOS *taos_connect_token(const char *ip, const char *token, const char *db, uint16_t port) {
×
2056
  return NULL;
×
2057
}
2058

2059

2060
TAOS* taos_connect_auth(const char* ip, const char* user, const char* auth, const char* db, uint16_t port) {
598✔
2061
  tscInfo("try to connect to %s:%u by auth, user:%s db:%s", ip, port, user, db);
598✔
2062
  if (user == NULL) {
598✔
2063
    user = TSDB_DEFAULT_USER;
×
2064
  }
2065

2066
  if (auth == NULL) {
598✔
2067
    tscError("No auth info is given, failed to connect to server");
×
2068
    return NULL;
×
2069
  }
2070

2071
  STscObj* pObj = NULL;
598✔
2072
  int32_t  code = taos_connect_internal(ip, user, NULL, auth, NULL, db, port, CONN_TYPE__QUERY, &pObj);
598✔
2073
  if (TSDB_CODE_SUCCESS == code) {
598✔
2074
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
144✔
2075
    if (NULL == rid) {
144✔
2076
      tscError("out of memory when taos connect to %s:%u, user:%s db:%s", ip, port, user, db);
×
2077
    }
2078
    *rid = pObj->id;
144✔
2079
    return (TAOS*)rid;
144✔
2080
  }
2081

2082
  return NULL;
454✔
2083
}
2084

2085
// TAOS* taos_connect_l(const char* ip, int ipLen, const char* user, int userLen, const char* pass, int passLen,
2086
//                      const char* db, int dbLen, uint16_t port) {
2087
//   char ipStr[TSDB_EP_LEN] = {0};
2088
//   char dbStr[TSDB_DB_NAME_LEN] = {0};
2089
//   char userStr[TSDB_USER_LEN] = {0};
2090
//   char passStr[TSDB_PASSWORD_LEN] = {0};
2091
//
2092
//   tstrncpy(ipStr, ip, TMIN(TSDB_EP_LEN - 1, ipLen));
2093
//   tstrncpy(userStr, user, TMIN(TSDB_USER_LEN - 1, userLen));
2094
//   tstrncpy(passStr, pass, TMIN(TSDB_PASSWORD_LEN - 1, passLen));
2095
//   tstrncpy(dbStr, db, TMIN(TSDB_DB_NAME_LEN - 1, dbLen));
2096
//   return taos_connect(ipStr, userStr, passStr, dbStr, port);
2097
// }
2098

2099
void doSetOneRowPtr(SReqResultInfo* pResultInfo) {
2,147,483,647✔
2100
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
2,147,483,647✔
2101
    SResultColumn* pCol = &pResultInfo->pCol[i];
2,147,483,647✔
2102

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

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

2110
        if (IS_STR_DATA_BLOB(type)) {
2,147,483,647✔
2111
          pResultInfo->length[i] = blobDataLen(pStart);
×
2112
          pResultInfo->row[i] = blobDataVal(pStart);
×
2113
        } else {
2114
          pResultInfo->length[i] = varDataLen(pStart);
2,147,483,647✔
2115
          pResultInfo->row[i] = varDataVal(pStart);
2,147,483,647✔
2116
        }
2117
      } else {
2118
        pResultInfo->row[i] = NULL;
277,003,509✔
2119
        pResultInfo->length[i] = 0;
277,071,313✔
2120
      }
2121
    } else {
2122
      if (!colDataIsNull_f(pCol, pResultInfo->current)) {
2,147,483,647✔
2123
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + schemaBytes * pResultInfo->current;
2,147,483,647✔
2124
        pResultInfo->length[i] = schemaBytes;
2,147,483,647✔
2125
      } else {
2126
        pResultInfo->row[i] = NULL;
938,553,449✔
2127
        pResultInfo->length[i] = 0;
940,162,272✔
2128
      }
2129
    }
2130
  }
2131
}
2,147,483,647✔
2132

2133
void* doFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
×
2134
  if (pRequest == NULL) {
×
2135
    return NULL;
×
2136
  }
2137

2138
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
×
2139
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
×
2140
    // All data has returned to App already, no need to try again
2141
    if (pResultInfo->completed) {
×
2142
      pResultInfo->numOfRows = 0;
×
2143
      return NULL;
×
2144
    }
2145

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

2149
    pRequest->code = schedulerFetchRows(pRequest->body.queryJob, &req);
×
2150
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2151
      pResultInfo->numOfRows = 0;
×
2152
      return NULL;
×
2153
    }
2154

2155
    pRequest->code = setQueryResultFromRsp(&pRequest->body.resInfo, (const SRetrieveTableRsp*)pResInfo->pData,
×
2156
                                           convertUcs4, pRequest->stmtBindVersion > 0);
×
2157
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2158
      pResultInfo->numOfRows = 0;
×
2159
      return NULL;
×
2160
    }
2161

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

2166
    STscObj*            pTscObj = pRequest->pTscObj;
×
2167
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
×
2168
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
×
2169

2170
    if (pResultInfo->numOfRows == 0) {
×
2171
      return NULL;
×
2172
    }
2173
  }
2174

2175
  if (setupOneRowPtr) {
×
2176
    doSetOneRowPtr(pResultInfo);
×
2177
    pResultInfo->current += 1;
×
2178
  }
2179

2180
  return pResultInfo->row;
×
2181
}
2182

2183
static void syncFetchFn(void* param, TAOS_RES* res, int32_t numOfRows) {
92,463,578✔
2184
  tsem_t* sem = param;
92,463,578✔
2185
  if (TSDB_CODE_SUCCESS != tsem_post(sem)) {
92,463,578✔
2186
    tscError("failed to post sem, code:%s", terrstr());
×
2187
  }
2188
}
92,463,578✔
2189

2190
void* doAsyncFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
1,798,927,340✔
2191
  if (pRequest == NULL) {
1,798,927,340✔
2192
    return NULL;
×
2193
  }
2194

2195
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
1,798,927,340✔
2196
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
1,798,940,095✔
2197
    // All data has returned to App already, no need to try again
2198
    if (pResultInfo->completed) {
164,999,233✔
2199
      pResultInfo->numOfRows = 0;
72,546,332✔
2200
      return NULL;
72,547,086✔
2201
    }
2202

2203
    // convert ucs4 to native multi-bytes string
2204
    pResultInfo->convertUcs4 = convertUcs4;
92,463,315✔
2205
    tsem_t sem;
91,744,492✔
2206
    if (TSDB_CODE_SUCCESS != tsem_init(&sem, 0, 0)) {
92,463,081✔
2207
      tscError("failed to init sem, code:%s", terrstr());
×
2208
    }
2209
    taos_fetch_rows_a(pRequest, syncFetchFn, &sem);
92,462,531✔
2210
    if (TSDB_CODE_SUCCESS != tsem_wait(&sem)) {
92,463,578✔
2211
      tscError("failed to wait sem, code:%s", terrstr());
×
2212
    }
2213
    if (TSDB_CODE_SUCCESS != tsem_destroy(&sem)) {
92,463,081✔
2214
      tscError("failed to destroy sem, code:%s", terrstr());
×
2215
    }
2216
    pRequest->inCallback = false;
92,463,578✔
2217
  }
2218

2219
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
1,726,409,511✔
2220
    return NULL;
6,959,490✔
2221
  } else {
2222
    if (setupOneRowPtr) {
1,719,451,034✔
2223
      doSetOneRowPtr(pResultInfo);
1,636,167,097✔
2224
      pResultInfo->current += 1;
1,636,149,645✔
2225
    }
2226

2227
    return pResultInfo->row;
1,719,447,486✔
2228
  }
2229
}
2230

2231
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
126,612,481✔
2232
  if (pResInfo->row == NULL) {
126,612,481✔
2233
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
111,781,359✔
2234
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
111,781,227✔
2235
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
111,780,762✔
2236
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
111,780,717✔
2237

2238
    if (pResInfo->row == NULL || pResInfo->pCol == NULL || pResInfo->length == NULL || pResInfo->convertBuf == NULL) {
111,781,045✔
2239
      taosMemoryFree(pResInfo->row);
1,012✔
2240
      taosMemoryFree(pResInfo->pCol);
×
2241
      taosMemoryFree(pResInfo->length);
×
2242
      taosMemoryFree(pResInfo->convertBuf);
×
2243
      return terrno;
×
2244
    }
2245
  }
2246

2247
  return TSDB_CODE_SUCCESS;
126,613,523✔
2248
}
2249

2250
static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength, bool isStmt) {
126,352,466✔
2251
  int32_t idx = -1;
126,352,466✔
2252
  iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt);
126,352,672✔
2253
  if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR;
126,349,370✔
2254

2255
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
715,921,383✔
2256
    int32_t type = pResultInfo->fields[i].type;
589,576,303✔
2257
    int32_t schemaBytes =
2258
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
589,575,959✔
2259

2260
    if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) {
589,572,394✔
2261
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
21,565,303✔
2262
      if (p == NULL) {
21,565,046✔
2263
        taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
×
2264
        return terrno;
×
2265
      }
2266

2267
      pResultInfo->convertBuf[i] = p;
21,565,046✔
2268

2269
      SResultColumn* pCol = &pResultInfo->pCol[i];
21,565,046✔
2270
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
2,147,483,647✔
2271
        if (pCol->offset[j] != -1) {
2,147,483,647✔
2272
          char* pStart = pCol->offset[j] + pCol->pData;
2,147,483,647✔
2273

2274
          int32_t len = taosUcs4ToMbsEx((TdUcs4*)varDataVal(pStart), varDataLen(pStart), varDataVal(p), conv);
2,147,483,647✔
2275
          if (len < 0 || len > schemaBytes || (p + len) >= (pResultInfo->convertBuf[i] + colLength[i])) {
2,147,483,647✔
2276
            tscError(
334✔
2277
                "doConvertUCS4 error, invalid data. len:%d, bytes:%d, (p + len):%p, (pResultInfo->convertBuf[i] + "
2278
                "colLength[i]):%p",
2279
                len, schemaBytes, (p + len), (pResultInfo->convertBuf[i] + colLength[i]));
2280
            taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
334✔
2281
            return TSDB_CODE_TSC_INTERNAL_ERROR;
76✔
2282
          }
2283

2284
          varDataSetLen(p, len);
2,147,483,647✔
2285
          pCol->offset[j] = (p - pResultInfo->convertBuf[i]);
2,147,483,647✔
2286
          p += (len + VARSTR_HEADER_SIZE);
2,147,483,647✔
2287
        }
2288
      }
2289

2290
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
21,565,227✔
2291
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
21,565,227✔
2292
    }
2293
  }
2294
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
126,352,059✔
2295
  return TSDB_CODE_SUCCESS;
126,351,532✔
2296
}
2297

2298
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
126,350,586✔
2299
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
715,929,058✔
2300
    TAOS_FIELD_E* pFieldE = pResultInfo->fields + i;
589,581,509✔
2301
    TAOS_FIELD*   pField = pResultInfo->userFields + i;
589,582,204✔
2302
    int32_t       type = pFieldE->type;
589,580,845✔
2303
    int32_t       bufLen = 0;
589,582,650✔
2304
    char*         p = NULL;
589,582,650✔
2305
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
589,582,650✔
2306
      continue;
587,561,482✔
2307
    } else {
2308
      bufLen = 64;
2,020,165✔
2309
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
2,020,165✔
2310
      pFieldE->bytes = bufLen;
2,020,165✔
2311
      pField->bytes = bufLen;
2,020,165✔
2312
    }
2313
    if (!p) return terrno;
2,020,165✔
2314
    pResultInfo->convertBuf[i] = p;
2,020,165✔
2315

2316
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
1,538,725,339✔
2317
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
1,536,705,174✔
2318
                                  pFieldE->precision, pFieldE->scale, p, bufLen);
1,536,705,174✔
2319
      p += bufLen;
1,536,705,174✔
2320
      if (TSDB_CODE_SUCCESS != code) {
1,536,705,174✔
2321
        return code;
×
2322
      }
2323
    }
2324
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
2,020,165✔
2325
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
2,020,165✔
2326
  }
2327
  return 0;
126,350,490✔
2328
}
2329

2330
int32_t getVersion1BlockMetaSize(const char* p, int32_t numOfCols) {
397,036✔
2331
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) * 3 + sizeof(uint64_t) +
794,072✔
2332
         numOfCols * (sizeof(int8_t) + sizeof(int32_t));
397,036✔
2333
}
2334

2335
static int32_t estimateJsonLen(SReqResultInfo* pResultInfo) {
198,518✔
2336
  char*   p = (char*)pResultInfo->pData;
198,518✔
2337
  int32_t blockVersion = *(int32_t*)p;
198,518✔
2338

2339
  int32_t numOfRows = pResultInfo->numOfRows;
198,518✔
2340
  int32_t numOfCols = pResultInfo->numOfCols;
198,518✔
2341

2342
  // | version | total length | total rows | total columns | flag seg| block group id | column schema | each column
2343
  // length |
2344
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
198,518✔
2345
  if (numOfCols != cols) {
198,518✔
2346
    tscError("estimateJsonLen error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2347
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2348
  }
2349

2350
  int32_t  len = getVersion1BlockMetaSize(p, numOfCols);
198,518✔
2351
  int32_t* colLength = (int32_t*)(p + len);
198,518✔
2352
  len += sizeof(int32_t) * numOfCols;
198,518✔
2353

2354
  char* pStart = p + len;
198,518✔
2355
  for (int32_t i = 0; i < numOfCols; ++i) {
863,476✔
2356
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
664,958✔
2357

2358
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
664,958✔
2359
      int32_t* offset = (int32_t*)pStart;
235,752✔
2360
      int32_t  lenTmp = numOfRows * sizeof(int32_t);
235,752✔
2361
      len += lenTmp;
235,752✔
2362
      pStart += lenTmp;
235,752✔
2363

2364
      int32_t estimateColLen = 0;
235,752✔
2365
      for (int32_t j = 0; j < numOfRows; ++j) {
1,240,742✔
2366
        if (offset[j] == -1) {
1,004,990✔
2367
          continue;
50,376✔
2368
        }
2369
        char* data = offset[j] + pStart;
954,614✔
2370

2371
        int32_t jsonInnerType = *data;
954,614✔
2372
        char*   jsonInnerData = data + CHAR_BYTES;
954,614✔
2373
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
954,614✔
2374
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
13,296✔
2375
        } else if (tTagIsJson(data)) {
941,318✔
2376
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
218,852✔
2377
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
722,466✔
2378
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
672,606✔
2379
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
49,860✔
2380
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
36,564✔
2381
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
13,296✔
2382
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
13,296✔
2383
        } else if (IS_STR_DATA_BLOB(jsonInnerType)) {
×
2384
          estimateColLen += (BLOBSTR_HEADER_SIZE + 32);
×
2385
        } else {
2386
          tscError("estimateJsonLen error: invalid type:%d", jsonInnerType);
×
2387
          return -1;
×
2388
        }
2389
      }
2390
      len += TMAX(colLen, estimateColLen);
235,752✔
2391
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
429,206✔
2392
      int32_t lenTmp = numOfRows * sizeof(int32_t);
55,400✔
2393
      len += (lenTmp + colLen);
55,400✔
2394
      pStart += lenTmp;
55,400✔
2395
    } else {
2396
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
373,806✔
2397
      len += (lenTmp + colLen);
373,806✔
2398
      pStart += lenTmp;
373,806✔
2399
    }
2400
    pStart += colLen;
664,958✔
2401
  }
2402

2403
  // Ensure the complete structure of the block, including the blankfill field,
2404
  // even though it is not used on the client side.
2405
  len += sizeof(bool);
198,518✔
2406
  return len;
198,518✔
2407
}
2408

2409
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
126,612,596✔
2410
  int32_t numOfRows = pResultInfo->numOfRows;
126,612,596✔
2411
  int32_t numOfCols = pResultInfo->numOfCols;
126,612,869✔
2412
  bool    needConvert = false;
126,614,037✔
2413
  for (int32_t i = 0; i < numOfCols; ++i) {
717,479,146✔
2414
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
591,064,534✔
2415
      needConvert = true;
198,518✔
2416
      break;
198,518✔
2417
    }
2418
  }
2419

2420
  if (!needConvert) {
126,613,130✔
2421
    return TSDB_CODE_SUCCESS;
126,414,612✔
2422
  }
2423

2424
  tscDebug("start to convert form json format string");
198,518✔
2425

2426
  char*   p = (char*)pResultInfo->pData;
198,518✔
2427
  int32_t blockVersion = *(int32_t*)p;
198,518✔
2428
  int32_t dataLen = estimateJsonLen(pResultInfo);
198,518✔
2429
  if (dataLen <= 0) {
198,518✔
2430
    tscError("doConvertJson error: estimateJsonLen failed");
×
2431
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2432
  }
2433

2434
  taosMemoryFreeClear(pResultInfo->convertJson);
198,518✔
2435
  pResultInfo->convertJson = taosMemoryCalloc(1, dataLen);
198,518✔
2436
  if (pResultInfo->convertJson == NULL) return terrno;
198,518✔
2437
  char* p1 = pResultInfo->convertJson;
198,518✔
2438

2439
  int32_t totalLen = 0;
198,518✔
2440
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
198,518✔
2441
  if (numOfCols != cols) {
198,518✔
2442
    tscError("doConvertJson error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2443
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2444
  }
2445

2446
  int32_t len = getVersion1BlockMetaSize(p, numOfCols);
198,518✔
2447
  (void)memcpy(p1, p, len);
198,518✔
2448

2449
  p += len;
198,518✔
2450
  p1 += len;
198,518✔
2451
  totalLen += len;
198,518✔
2452

2453
  len = sizeof(int32_t) * numOfCols;
198,518✔
2454
  int32_t* colLength = (int32_t*)p;
198,518✔
2455
  int32_t* colLength1 = (int32_t*)p1;
198,518✔
2456
  (void)memcpy(p1, p, len);
198,518✔
2457
  p += len;
198,518✔
2458
  p1 += len;
198,518✔
2459
  totalLen += len;
198,518✔
2460

2461
  char* pStart = p;
198,518✔
2462
  char* pStart1 = p1;
198,518✔
2463
  for (int32_t i = 0; i < numOfCols; ++i) {
863,476✔
2464
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
664,958✔
2465
    int32_t colLen1 = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength1[i]) : colLength1[i];
664,958✔
2466
    if (colLen >= dataLen) {
664,958✔
2467
      tscError("doConvertJson error: colLen:%d >= dataLen:%d", colLen, dataLen);
×
2468
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2469
    }
2470
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
664,958✔
2471
      int32_t* offset = (int32_t*)pStart;
235,752✔
2472
      int32_t* offset1 = (int32_t*)pStart1;
235,752✔
2473
      len = numOfRows * sizeof(int32_t);
235,752✔
2474
      (void)memcpy(pStart1, pStart, len);
235,752✔
2475
      pStart += len;
235,752✔
2476
      pStart1 += len;
235,752✔
2477
      totalLen += len;
235,752✔
2478

2479
      len = 0;
235,752✔
2480
      for (int32_t j = 0; j < numOfRows; ++j) {
1,240,742✔
2481
        if (offset[j] == -1) {
1,004,990✔
2482
          continue;
50,376✔
2483
        }
2484
        char* data = offset[j] + pStart;
954,614✔
2485

2486
        int32_t jsonInnerType = *data;
954,614✔
2487
        char*   jsonInnerData = data + CHAR_BYTES;
954,614✔
2488
        char    dst[TSDB_MAX_JSON_TAG_LEN] = {0};
954,614✔
2489
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
954,614✔
2490
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s", TSDB_DATA_NULL_STR_L);
13,296✔
2491
          varDataSetLen(dst, strlen(varDataVal(dst)));
13,296✔
2492
        } else if (tTagIsJson(data)) {
941,318✔
2493
          char* jsonString = NULL;
218,852✔
2494
          parseTagDatatoJson(data, &jsonString, pResultInfo->charsetCxt);
218,852✔
2495
          if (jsonString == NULL) {
218,852✔
2496
            tscError("doConvertJson error: parseTagDatatoJson failed");
×
2497
            return terrno;
×
2498
          }
2499
          STR_TO_VARSTR(dst, jsonString);
218,852✔
2500
          taosMemoryFree(jsonString);
218,852✔
2501
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
722,466✔
2502
          *(char*)varDataVal(dst) = '\"';
672,606✔
2503
          char    tmp[TSDB_MAX_JSON_TAG_LEN] = {0};
672,606✔
2504
          int32_t length = taosUcs4ToMbs((TdUcs4*)varDataVal(jsonInnerData), varDataLen(jsonInnerData),
672,606✔
2505
                                         varDataVal(tmp), pResultInfo->charsetCxt);
2506
          if (length <= 0) {
672,606✔
2507
            tscError("charset:%s to %s. convert failed.", DEFAULT_UNICODE_ENCODEC,
554✔
2508
                     pResultInfo->charsetCxt != NULL ? ((SConvInfo*)(pResultInfo->charsetCxt))->charset : tsCharset);
2509
            length = 0;
554✔
2510
          }
2511
          int32_t escapeLength = escapeToPrinted(varDataVal(dst) + CHAR_BYTES, TSDB_MAX_JSON_TAG_LEN - CHAR_BYTES * 2,varDataVal(tmp), length);
672,606✔
2512
          varDataSetLen(dst, escapeLength + CHAR_BYTES * 2);
672,606✔
2513
          *(char*)POINTER_SHIFT(varDataVal(dst), escapeLength + CHAR_BYTES) = '\"';
672,606✔
2514
          tscError("value:%s.", varDataVal(dst));
672,606✔
2515
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
49,860✔
2516
          double jsonVd = *(double*)(jsonInnerData);
36,564✔
2517
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%.9lf", jsonVd);
36,564✔
2518
          varDataSetLen(dst, strlen(varDataVal(dst)));
36,564✔
2519
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
13,296✔
2520
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s",
13,296✔
2521
                         (*((char*)jsonInnerData) == 1) ? "true" : "false");
13,296✔
2522
          varDataSetLen(dst, strlen(varDataVal(dst)));
13,296✔
2523
        } else {
2524
          tscError("doConvertJson error: invalid type:%d", jsonInnerType);
×
2525
          return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2526
        }
2527

2528
        offset1[j] = len;
954,614✔
2529
        (void)memcpy(pStart1 + len, dst, varDataTLen(dst));
954,614✔
2530
        len += varDataTLen(dst);
954,614✔
2531
      }
2532
      colLen1 = len;
235,752✔
2533
      totalLen += colLen1;
235,752✔
2534
      colLength1[i] = (blockVersion == BLOCK_VERSION_1) ? htonl(len) : len;
235,752✔
2535
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
429,206✔
2536
      len = numOfRows * sizeof(int32_t);
55,400✔
2537
      (void)memcpy(pStart1, pStart, len);
55,400✔
2538
      pStart += len;
55,400✔
2539
      pStart1 += len;
55,400✔
2540
      totalLen += len;
55,400✔
2541
      totalLen += colLen;
55,400✔
2542
      (void)memcpy(pStart1, pStart, colLen);
55,400✔
2543
    } else {
2544
      len = BitmapLen(pResultInfo->numOfRows);
373,806✔
2545
      (void)memcpy(pStart1, pStart, len);
373,806✔
2546
      pStart += len;
373,806✔
2547
      pStart1 += len;
373,806✔
2548
      totalLen += len;
373,806✔
2549
      totalLen += colLen;
373,806✔
2550
      (void)memcpy(pStart1, pStart, colLen);
373,806✔
2551
    }
2552
    pStart += colLen;
664,958✔
2553
    pStart1 += colLen1;
664,958✔
2554
  }
2555

2556
  // Ensure the complete structure of the block, including the blankfill field,
2557
  // even though it is not used on the client side.
2558
  // (void)memcpy(pStart1, pStart, sizeof(bool));
2559
  totalLen += sizeof(bool);
198,518✔
2560

2561
  *(int32_t*)(pResultInfo->convertJson + 4) = totalLen;
198,518✔
2562
  pResultInfo->pData = pResultInfo->convertJson;
198,518✔
2563
  return TSDB_CODE_SUCCESS;
198,518✔
2564
}
2565

2566
int32_t setResultDataPtr(SReqResultInfo* pResultInfo, bool convertUcs4, bool isStmt) {
133,925,906✔
2567
  bool convertForDecimal = convertUcs4;
133,925,906✔
2568
  if (pResultInfo == NULL || pResultInfo->numOfCols <= 0 || pResultInfo->fields == NULL) {
133,925,906✔
2569
    tscError("setResultDataPtr paras error");
1,129✔
2570
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2571
  }
2572

2573
  if (pResultInfo->numOfRows == 0) {
133,924,612✔
2574
    return TSDB_CODE_SUCCESS;
7,312,338✔
2575
  }
2576

2577
  if (pResultInfo->pData == NULL) {
126,612,563✔
2578
    tscError("setResultDataPtr error: pData is NULL");
×
2579
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2580
  }
2581

2582
  int32_t code = doPrepareResPtr(pResultInfo);
126,612,713✔
2583
  if (code != TSDB_CODE_SUCCESS) {
126,613,160✔
2584
    return code;
×
2585
  }
2586
  code = doConvertJson(pResultInfo);
126,613,160✔
2587
  if (code != TSDB_CODE_SUCCESS) {
126,611,590✔
2588
    return code;
×
2589
  }
2590

2591
  char* p = (char*)pResultInfo->pData;
126,611,590✔
2592

2593
  // version:
2594
  int32_t blockVersion = *(int32_t*)p;
126,611,847✔
2595
  p += sizeof(int32_t);
126,612,638✔
2596

2597
  int32_t dataLen = *(int32_t*)p;
126,613,005✔
2598
  p += sizeof(int32_t);
126,613,111✔
2599

2600
  int32_t rows = *(int32_t*)p;
126,612,956✔
2601
  p += sizeof(int32_t);
126,613,811✔
2602

2603
  int32_t cols = *(int32_t*)p;
126,613,338✔
2604
  p += sizeof(int32_t);
126,612,805✔
2605

2606
  if (rows != pResultInfo->numOfRows || cols != pResultInfo->numOfCols) {
126,614,284✔
2607
    tscError("setResultDataPtr paras error:rows;%d numOfRows:%" PRId64 " cols:%d numOfCols:%d", rows,
1,407✔
2608
             pResultInfo->numOfRows, cols, pResultInfo->numOfCols);
2609
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2610
  }
2611

2612
  int32_t hasColumnSeg = *(int32_t*)p;
126,612,756✔
2613
  p += sizeof(int32_t);
126,613,902✔
2614

2615
  uint64_t groupId = taosGetUInt64Aligned((uint64_t*)p);
126,612,805✔
2616
  p += sizeof(uint64_t);
126,612,805✔
2617

2618
  // check fields
2619
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
717,725,018✔
2620
    int8_t type = *(int8_t*)p;
591,115,986✔
2621
    p += sizeof(int8_t);
591,114,806✔
2622

2623
    int32_t bytes = *(int32_t*)p;
591,115,044✔
2624
    p += sizeof(int32_t);
591,114,754✔
2625

2626
    if (IS_DECIMAL_TYPE(type) && pResultInfo->fields[i].precision == 0) {
591,114,994✔
2627
      extractDecimalTypeInfoFromBytes(&bytes, &pResultInfo->fields[i].precision, &pResultInfo->fields[i].scale);
317,356✔
2628
    }
2629
  }
2630

2631
  int32_t* colLength = (int32_t*)p;
126,613,142✔
2632
  p += sizeof(int32_t) * pResultInfo->numOfCols;
126,613,142✔
2633

2634
  char* pStart = p;
126,613,762✔
2635
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
717,737,966✔
2636
    if ((pStart - pResultInfo->pData) >= dataLen) {
591,125,666✔
2637
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2638
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2639
    }
2640
    if (blockVersion == BLOCK_VERSION_1) {
591,122,514✔
2641
      colLength[i] = htonl(colLength[i]);
429,455,084✔
2642
    }
2643
    if (colLength[i] >= dataLen) {
591,122,535✔
2644
      tscError("invalid colLength %d, dataLen %d", colLength[i], dataLen);
×
2645
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2646
    }
2647
    if (IS_INVALID_TYPE(pResultInfo->fields[i].type)) {
591,121,599✔
2648
      tscError("invalid type %d", pResultInfo->fields[i].type);
2,724✔
2649
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2650
    }
2651
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
591,123,076✔
2652
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
148,871,469✔
2653
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
148,870,320✔
2654
    } else {
2655
      pResultInfo->pCol[i].nullbitmap = pStart;
442,254,070✔
2656
      pStart += BitmapLen(pResultInfo->numOfRows);
442,257,069✔
2657
    }
2658

2659
    pResultInfo->pCol[i].pData = pStart;
591,126,388✔
2660
    pResultInfo->length[i] =
1,182,248,324✔
2661
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
1,176,330,344✔
2662
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
591,124,538✔
2663

2664
    pStart += colLength[i];
591,122,442✔
2665
  }
2666

2667
  p = pStart;
126,613,662✔
2668
  // bool blankFill = *(bool*)p;
2669
  p += sizeof(bool);
126,613,662✔
2670
  int32_t offset = p - pResultInfo->pData;
126,613,868✔
2671
  if (offset > dataLen) {
126,614,023✔
2672
    tscError("invalid offset %d, dataLen %d", offset, dataLen);
×
2673
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2674
  }
2675

2676
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
2677
  if (convertUcs4) {
126,614,023✔
2678
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
126,353,039✔
2679
  }
2680
#endif
2681
  if (TSDB_CODE_SUCCESS == code && convertForDecimal) {
126,612,486✔
2682
    code = convertDecimalType(pResultInfo);
126,351,532✔
2683
  }
2684
  return code;
126,611,705✔
2685
}
2686

2687
char* getDbOfConnection(STscObj* pObj) {
659,118,787✔
2688
  terrno = TSDB_CODE_SUCCESS;
659,118,787✔
2689
  char* p = NULL;
659,122,399✔
2690
  (void)taosThreadMutexLock(&pObj->mutex);
659,122,399✔
2691
  size_t len = strlen(pObj->db);
659,125,890✔
2692
  if (len > 0) {
659,125,943✔
2693
    p = taosStrndup(pObj->db, tListLen(pObj->db));
584,083,985✔
2694
    if (p == NULL) {
584,076,945✔
2695
      tscError("failed to taosStrndup db name");
×
2696
    }
2697
  }
2698

2699
  (void)taosThreadMutexUnlock(&pObj->mutex);
659,118,903✔
2700
  return p;
659,120,324✔
2701
}
2702

2703
void setConnectionDB(STscObj* pTscObj, const char* db) {
2,571,805✔
2704
  if (db == NULL || pTscObj == NULL) {
2,571,805✔
2705
    tscError("setConnectionDB para is NULL");
×
2706
    return;
×
2707
  }
2708

2709
  (void)taosThreadMutexLock(&pTscObj->mutex);
2,571,805✔
2710
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
2,571,805✔
2711
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
2,571,805✔
2712
}
2713

2714
void resetConnectDB(STscObj* pTscObj) {
×
2715
  if (pTscObj == NULL) {
×
2716
    return;
×
2717
  }
2718

2719
  (void)taosThreadMutexLock(&pTscObj->mutex);
×
2720
  pTscObj->db[0] = 0;
×
2721
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
×
2722
}
2723

2724
int32_t setQueryResultFromRsp(SReqResultInfo* pResultInfo, const SRetrieveTableRsp* pRsp, bool convertUcs4,
98,707,749✔
2725
                              bool isStmt) {
2726
  if (pResultInfo == NULL || pRsp == NULL) {
98,707,749✔
2727
    tscError("setQueryResultFromRsp paras is null");
518✔
2728
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2729
  }
2730

2731
  taosMemoryFreeClear(pResultInfo->pRspMsg);
98,707,231✔
2732
  pResultInfo->pRspMsg = (const char*)pRsp;
98,707,492✔
2733
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
98,707,488✔
2734
  pResultInfo->current = 0;
98,707,749✔
2735
  pResultInfo->completed = (pRsp->completed == 1);
98,707,749✔
2736
  pResultInfo->precision = pRsp->precision;
98,706,973✔
2737

2738
  // decompress data if needed
2739
  int32_t payloadLen = htonl(pRsp->payloadLen);
98,707,227✔
2740

2741
  if (pRsp->compressed) {
98,707,227✔
2742
    if (pResultInfo->decompBuf == NULL) {
×
2743
      pResultInfo->decompBuf = taosMemoryMalloc(payloadLen);
×
2744
      if (pResultInfo->decompBuf == NULL) {
×
2745
        tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2746
        return terrno;
×
2747
      }
2748
      pResultInfo->decompBufSize = payloadLen;
×
2749
    } else {
2750
      if (pResultInfo->decompBufSize < payloadLen) {
×
2751
        char* p = taosMemoryRealloc(pResultInfo->decompBuf, payloadLen);
×
2752
        if (p == NULL) {
×
2753
          tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2754
          return terrno;
×
2755
        }
2756

2757
        pResultInfo->decompBuf = p;
×
2758
        pResultInfo->decompBufSize = payloadLen;
×
2759
      }
2760
    }
2761
  }
2762

2763
  if (payloadLen > 0) {
98,707,492✔
2764
    int32_t compLen = *(int32_t*)pRsp->data;
91,395,823✔
2765
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
91,395,566✔
2766

2767
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
91,395,562✔
2768

2769
    if (pRsp->compressed && compLen < rawLen) {
91,395,823✔
2770
      int32_t len = tsDecompressString(pStart, compLen, 1, pResultInfo->decompBuf, rawLen, ONE_STAGE_COMP, NULL, 0);
×
2771
      if (len < 0) {
×
2772
        tscError("tsDecompressString failed");
×
2773
        return terrno ? terrno : TSDB_CODE_FAILED;
×
2774
      }
2775
      if (len != rawLen) {
×
2776
        tscError("tsDecompressString failed, len:%d != rawLen:%d", len, rawLen);
×
2777
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2778
      }
2779
      pResultInfo->pData = pResultInfo->decompBuf;
×
2780
      pResultInfo->payloadLen = rawLen;
×
2781
    } else {
2782
      pResultInfo->pData = pStart;
91,395,566✔
2783
      pResultInfo->payloadLen = htonl(pRsp->compLen);
91,395,823✔
2784
      if (pRsp->compLen != pRsp->payloadLen) {
91,395,823✔
2785
        tscError("pRsp->compLen:%d != pRsp->payloadLen:%d", pRsp->compLen, pRsp->payloadLen);
×
2786
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2787
      }
2788
    }
2789
  }
2790

2791
  // TODO handle the compressed case
2792
  pResultInfo->totalRows += pResultInfo->numOfRows;
98,706,716✔
2793

2794
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
98,707,488✔
2795
  return code;
98,705,780✔
2796
}
2797

2798
TSDB_SERVER_STATUS taos_check_server_status(const char* fqdn, int port, char* details, int maxlen) {
748✔
2799
  TSDB_SERVER_STATUS code = TSDB_SRV_STATUS_UNAVAILABLE;
748✔
2800
  void*              clientRpc = NULL;
748✔
2801
  SServerStatusRsp   statusRsp = {0};
748✔
2802
  SEpSet             epSet = {.inUse = 0, .numOfEps = 1};
748✔
2803
  SRpcMsg  rpcMsg = {.info.ahandle = (void*)0x9527, .info.notFreeAhandle = 1, .msgType = TDMT_DND_SERVER_STATUS};
748✔
2804
  SRpcMsg  rpcRsp = {0};
748✔
2805
  SRpcInit rpcInit = {0};
748✔
2806
  char     pass[TSDB_PASSWORD_LEN + 1] = {0};
748✔
2807

2808
  rpcInit.label = "CHK";
748✔
2809
  rpcInit.numOfThreads = 1;
748✔
2810
  rpcInit.cfp = NULL;
748✔
2811
  rpcInit.sessions = 16;
748✔
2812
  rpcInit.connType = TAOS_CONN_CLIENT;
748✔
2813
  rpcInit.idleTime = tsShellActivityTimer * 1000;
748✔
2814
  rpcInit.compressSize = tsCompressMsgSize;
748✔
2815
  rpcInit.user = "_dnd";
748✔
2816

2817
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
748✔
2818
  connLimitNum = TMAX(connLimitNum, 10);
748✔
2819
  connLimitNum = TMIN(connLimitNum, 500);
748✔
2820
  rpcInit.connLimitNum = connLimitNum;
748✔
2821
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
748✔
2822
  rpcInit.readTimeout = tsReadTimeout;
748✔
2823
  rpcInit.ipv6 = tsEnableIpv6;
748✔
2824
  rpcInit.enableSSL = tsEnableTLS;
748✔
2825

2826
  memcpy(rpcInit.caPath, tsTLSCaPath, strlen(tsTLSCaPath));
748✔
2827
  memcpy(rpcInit.certPath, tsTLSSvrCertPath, strlen(tsTLSSvrCertPath));
748✔
2828
  memcpy(rpcInit.keyPath, tsTLSSvrKeyPath, strlen(tsTLSSvrKeyPath));
748✔
2829
  memcpy(rpcInit.cliCertPath, tsTLSCliCertPath, strlen(tsTLSCliCertPath));
748✔
2830
  memcpy(rpcInit.cliKeyPath, tsTLSCliKeyPath, strlen(tsTLSCliKeyPath));
748✔
2831

2832
  if (TSDB_CODE_SUCCESS != taosVersionStrToInt(td_version, &rpcInit.compatibilityVer)) {
748✔
2833
    tscError("faild to convert taos version from str to int, errcode:%s", terrstr());
×
2834
    goto _OVER;
×
2835
  }
2836

2837
  clientRpc = rpcOpen(&rpcInit);
748✔
2838
  if (clientRpc == NULL) {
748✔
2839
    code = terrno;
×
2840
    tscError("failed to init server status client since %s", tstrerror(code));
×
2841
    goto _OVER;
×
2842
  }
2843

2844
  if (fqdn == NULL) {
748✔
2845
    fqdn = tsLocalFqdn;
748✔
2846
  }
2847

2848
  if (port == 0) {
748✔
2849
    port = tsServerPort;
748✔
2850
  }
2851

2852
  tstrncpy(epSet.eps[0].fqdn, fqdn, TSDB_FQDN_LEN);
748✔
2853
  epSet.eps[0].port = (uint16_t)port;
748✔
2854
  int32_t ret = rpcSendRecv(clientRpc, &epSet, &rpcMsg, &rpcRsp);
748✔
2855
  if (TSDB_CODE_SUCCESS != ret) {
748✔
2856
    tscError("failed to send recv since %s", tstrerror(ret));
×
2857
    goto _OVER;
×
2858
  }
2859

2860
  if (rpcRsp.code != 0 || rpcRsp.contLen <= 0 || rpcRsp.pCont == NULL) {
748✔
2861
    tscError("failed to send server status req since %s", terrstr());
141✔
2862
    goto _OVER;
141✔
2863
  }
2864

2865
  if (tDeserializeSServerStatusRsp(rpcRsp.pCont, rpcRsp.contLen, &statusRsp) != 0) {
607✔
2866
    tscError("failed to parse server status rsp since %s", terrstr());
×
2867
    goto _OVER;
×
2868
  }
2869

2870
  code = statusRsp.statusCode;
607✔
2871
  if (details != NULL) {
607✔
2872
    tstrncpy(details, statusRsp.details, maxlen);
607✔
2873
  }
2874

2875
_OVER:
713✔
2876
  if (clientRpc != NULL) {
748✔
2877
    rpcClose(clientRpc);
748✔
2878
  }
2879
  if (rpcRsp.pCont != NULL) {
748✔
2880
    rpcFreeCont(rpcRsp.pCont);
607✔
2881
  }
2882
  return code;
748✔
2883
}
2884

2885
int32_t appendTbToReq(SHashObj* pHash, int32_t pos1, int32_t len1, int32_t pos2, int32_t len2, const char* str,
1,292✔
2886
                      int32_t acctId, char* db) {
2887
  SName name = {0};
1,292✔
2888

2889
  if (len1 <= 0) {
1,292✔
2890
    return -1;
×
2891
  }
2892

2893
  const char* dbName = db;
1,292✔
2894
  const char* tbName = NULL;
1,292✔
2895
  int32_t     dbLen = 0;
1,292✔
2896
  int32_t     tbLen = 0;
1,292✔
2897
  if (len2 > 0) {
1,292✔
2898
    dbName = str + pos1;
×
2899
    dbLen = len1;
×
2900
    tbName = str + pos2;
×
2901
    tbLen = len2;
×
2902
  } else {
2903
    dbLen = strlen(db);
1,292✔
2904
    tbName = str + pos1;
1,292✔
2905
    tbLen = len1;
1,292✔
2906
  }
2907

2908
  if (dbLen <= 0 || tbLen <= 0) {
1,292✔
2909
    return -1;
×
2910
  }
2911

2912
  if (tNameSetDbName(&name, acctId, dbName, dbLen)) {
1,292✔
2913
    return -1;
×
2914
  }
2915

2916
  if (tNameAddTbName(&name, tbName, tbLen)) {
1,292✔
2917
    return -1;
×
2918
  }
2919

2920
  char dbFName[TSDB_DB_FNAME_LEN] = {0};
1,292✔
2921
  (void)snprintf(dbFName, TSDB_DB_FNAME_LEN, "%d.%.*s", acctId, dbLen, dbName);
1,292✔
2922

2923
  STablesReq* pDb = taosHashGet(pHash, dbFName, strlen(dbFName));
1,292✔
2924
  if (pDb) {
1,292✔
2925
    if (NULL == taosArrayPush(pDb->pTables, &name)) {
×
2926
      return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
2927
    }
2928
  } else {
2929
    STablesReq db;
1,292✔
2930
    db.pTables = taosArrayInit(20, sizeof(SName));
1,292✔
2931
    if (NULL == db.pTables) {
1,292✔
2932
      return terrno;
×
2933
    }
2934
    tstrncpy(db.dbFName, dbFName, TSDB_DB_FNAME_LEN);
1,292✔
2935
    if (NULL == taosArrayPush(db.pTables, &name)) {
2,584✔
2936
      return terrno;
×
2937
    }
2938
    TSC_ERR_RET(taosHashPut(pHash, dbFName, strlen(dbFName), &db, sizeof(db)));
1,292✔
2939
  }
2940

2941
  return TSDB_CODE_SUCCESS;
1,292✔
2942
}
2943

2944
int32_t transferTableNameList(const char* tbList, int32_t acctId, char* dbName, SArray** pReq) {
1,292✔
2945
  SHashObj* pHash = taosHashInit(3, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
1,292✔
2946
  if (NULL == pHash) {
1,292✔
2947
    return terrno;
×
2948
  }
2949

2950
  bool    inEscape = false;
1,292✔
2951
  int32_t code = 0;
1,292✔
2952
  void*   pIter = NULL;
1,292✔
2953

2954
  int32_t vIdx = 0;
1,292✔
2955
  int32_t vPos[2];
1,292✔
2956
  int32_t vLen[2];
1,292✔
2957

2958
  (void)memset(vPos, -1, sizeof(vPos));
1,292✔
2959
  (void)memset(vLen, 0, sizeof(vLen));
1,292✔
2960

2961
  for (int32_t i = 0;; ++i) {
6,460✔
2962
    if (0 == *(tbList + i)) {
6,460✔
2963
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
1,292✔
2964
        vLen[vIdx] = i - vPos[vIdx];
1,292✔
2965
      }
2966

2967
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
1,292✔
2968
      if (code) {
1,292✔
2969
        goto _return;
×
2970
      }
2971

2972
      break;
1,292✔
2973
    }
2974

2975
    if ('`' == *(tbList + i)) {
5,168✔
2976
      inEscape = !inEscape;
×
2977
      if (!inEscape) {
×
2978
        if (vPos[vIdx] >= 0) {
×
2979
          vLen[vIdx] = i - vPos[vIdx];
×
2980
        } else {
2981
          goto _return;
×
2982
        }
2983
      }
2984

2985
      continue;
×
2986
    }
2987

2988
    if (inEscape) {
5,168✔
2989
      if (vPos[vIdx] < 0) {
×
2990
        vPos[vIdx] = i;
×
2991
      }
2992
      continue;
×
2993
    }
2994

2995
    if ('.' == *(tbList + i)) {
5,168✔
2996
      if (vPos[vIdx] < 0) {
×
2997
        goto _return;
×
2998
      }
2999
      if (vLen[vIdx] <= 0) {
×
3000
        vLen[vIdx] = i - vPos[vIdx];
×
3001
      }
3002
      vIdx++;
×
3003
      if (vIdx >= 2) {
×
3004
        goto _return;
×
3005
      }
3006
      continue;
×
3007
    }
3008

3009
    if (',' == *(tbList + i)) {
5,168✔
3010
      if (vPos[vIdx] < 0) {
×
3011
        goto _return;
×
3012
      }
3013
      if (vLen[vIdx] <= 0) {
×
3014
        vLen[vIdx] = i - vPos[vIdx];
×
3015
      }
3016

3017
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
×
3018
      if (code) {
×
3019
        goto _return;
×
3020
      }
3021

3022
      (void)memset(vPos, -1, sizeof(vPos));
×
3023
      (void)memset(vLen, 0, sizeof(vLen));
×
3024
      vIdx = 0;
×
3025
      continue;
×
3026
    }
3027

3028
    if (' ' == *(tbList + i) || '\r' == *(tbList + i) || '\t' == *(tbList + i) || '\n' == *(tbList + i)) {
5,168✔
3029
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
×
3030
        vLen[vIdx] = i - vPos[vIdx];
×
3031
      }
3032
      continue;
×
3033
    }
3034

3035
    if (('a' <= *(tbList + i) && 'z' >= *(tbList + i)) || ('A' <= *(tbList + i) && 'Z' >= *(tbList + i)) ||
5,168✔
3036
        ('0' <= *(tbList + i) && '9' >= *(tbList + i)) || ('_' == *(tbList + i))) {
646✔
3037
      if (vLen[vIdx] > 0) {
5,168✔
3038
        goto _return;
×
3039
      }
3040
      if (vPos[vIdx] < 0) {
5,168✔
3041
        vPos[vIdx] = i;
1,292✔
3042
      }
3043
      continue;
5,168✔
3044
    }
3045

3046
    goto _return;
×
3047
  }
3048

3049
  int32_t dbNum = taosHashGetSize(pHash);
1,292✔
3050
  *pReq = taosArrayInit(dbNum, sizeof(STablesReq));
1,292✔
3051
  if (NULL == pReq) {
1,292✔
3052
    TSC_ERR_JRET(terrno);
×
3053
  }
3054
  pIter = taosHashIterate(pHash, NULL);
1,292✔
3055
  while (pIter) {
2,584✔
3056
    STablesReq* pDb = (STablesReq*)pIter;
1,292✔
3057
    if (NULL == taosArrayPush(*pReq, pDb)) {
2,584✔
3058
      TSC_ERR_JRET(terrno);
×
3059
    }
3060
    pIter = taosHashIterate(pHash, pIter);
1,292✔
3061
  }
3062

3063
  taosHashCleanup(pHash);
1,292✔
3064

3065
  return TSDB_CODE_SUCCESS;
1,292✔
3066

3067
_return:
×
3068

3069
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
3070

3071
  pIter = taosHashIterate(pHash, NULL);
×
3072
  while (pIter) {
×
3073
    STablesReq* pDb = (STablesReq*)pIter;
×
3074
    taosArrayDestroy(pDb->pTables);
×
3075
    pIter = taosHashIterate(pHash, pIter);
×
3076
  }
3077

3078
  taosHashCleanup(pHash);
×
3079

3080
  return terrno;
×
3081
}
3082

3083
void syncCatalogFn(SMetaData* pResult, void* param, int32_t code) {
1,292✔
3084
  SSyncQueryParam* pParam = param;
1,292✔
3085
  pParam->pRequest->code = code;
1,292✔
3086

3087
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
1,292✔
3088
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3089
  }
3090
}
1,292✔
3091

3092
void syncQueryFn(void* param, void* res, int32_t code) {
650,677,202✔
3093
  SSyncQueryParam* pParam = param;
650,677,202✔
3094
  pParam->pRequest = res;
650,677,202✔
3095

3096
  if (pParam->pRequest) {
650,680,633✔
3097
    pParam->pRequest->code = code;
650,666,612✔
3098
    clientOperateReport(pParam->pRequest);
650,672,029✔
3099
  }
3100

3101
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
650,670,694✔
3102
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3103
  }
3104
}
650,685,113✔
3105

3106
void taosAsyncQueryImpl(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
650,138,318✔
3107
                        int8_t source) {
3108
  if (sql == NULL || NULL == fp) {
650,138,318✔
3109
    terrno = TSDB_CODE_INVALID_PARA;
257✔
3110
    if (fp) {
×
3111
      fp(param, NULL, terrno);
×
3112
    }
3113

3114
    return;
×
3115
  }
3116

3117
  size_t sqlLen = strlen(sql);
650,138,672✔
3118
  if (sqlLen > (size_t)tsMaxSQLLength) {
650,138,672✔
3119
    tscError("conn:0x%" PRIx64 ", sql string exceeds max length:%d", connId, tsMaxSQLLength);
1,308✔
3120
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
1,308✔
3121
    fp(param, NULL, terrno);
1,308✔
3122
    return;
1,308✔
3123
  }
3124

3125
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, sql:%s", connId, sql);
650,137,364✔
3126

3127
  SRequestObj* pRequest = NULL;
650,137,726✔
3128
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
650,137,800✔
3129
  if (code != TSDB_CODE_SUCCESS) {
650,135,806✔
3130
    terrno = code;
×
3131
    fp(param, NULL, terrno);
×
3132
    return;
×
3133
  }
3134

3135
  pRequest->source = source;
650,135,806✔
3136
  pRequest->body.queryFp = fp;
650,140,353✔
3137
  doAsyncQuery(pRequest, false);
650,138,655✔
3138
}
3139

3140
void taosAsyncQueryImplWithReqid(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
872✔
3141
                                 int64_t reqid) {
3142
  if (sql == NULL || NULL == fp) {
872✔
3143
    terrno = TSDB_CODE_INVALID_PARA;
×
3144
    if (fp) {
×
3145
      fp(param, NULL, terrno);
×
3146
    }
3147

3148
    return;
×
3149
  }
3150

3151
  size_t sqlLen = strlen(sql);
872✔
3152
  if (sqlLen > (size_t)tsMaxSQLLength) {
872✔
3153
    tscError("conn:0x%" PRIx64 ", QID:0x%" PRIx64 ", sql string exceeds max length:%d", connId, reqid, tsMaxSQLLength);
×
3154
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
3155
    fp(param, NULL, terrno);
×
3156
    return;
×
3157
  }
3158

3159
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, QID:0x%" PRIx64 ", sql:%s", connId, reqid, sql);
872✔
3160

3161
  SRequestObj* pRequest = NULL;
872✔
3162
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, reqid);
872✔
3163
  if (code != TSDB_CODE_SUCCESS) {
872✔
3164
    terrno = code;
×
3165
    fp(param, NULL, terrno);
×
3166
    return;
×
3167
  }
3168

3169
  pRequest->body.queryFp = fp;
872✔
3170
  doAsyncQuery(pRequest, false);
872✔
3171
}
3172

3173
TAOS_RES* taosQueryImpl(TAOS* taos, const char* sql, bool validateOnly, int8_t source) {
650,093,703✔
3174
  if (NULL == taos) {
650,093,703✔
3175
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3176
    return NULL;
×
3177
  }
3178

3179
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
650,093,703✔
3180
  if (NULL == param) {
650,099,307✔
3181
    return NULL;
×
3182
  }
3183
  int32_t code = tsem_init(&param->sem, 0, 0);
650,099,307✔
3184
  if (TSDB_CODE_SUCCESS != code) {
650,092,473✔
3185
    taosMemoryFree(param);
×
3186
    return NULL;
×
3187
  }
3188

3189
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
650,092,473✔
3190
  code = tsem_wait(&param->sem);
650,094,922✔
3191
  if (TSDB_CODE_SUCCESS != code) {
650,101,226✔
3192
    taosMemoryFree(param);
×
3193
    return NULL;
×
3194
  }
3195
  code = tsem_destroy(&param->sem);
650,101,226✔
3196
  if (TSDB_CODE_SUCCESS != code) {
650,103,299✔
3197
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3198
  }
3199

3200
  SRequestObj* pRequest = NULL;
650,103,299✔
3201
  if (param->pRequest != NULL) {
650,103,299✔
3202
    param->pRequest->syncQuery = true;
650,102,528✔
3203
    pRequest = param->pRequest;
650,102,700✔
3204
    param->pRequest->inCallback = false;
650,101,942✔
3205
  }
3206
  taosMemoryFree(param);
650,101,754✔
3207

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

3211
  return pRequest;
650,103,043✔
3212
}
3213

3214
TAOS_RES* taosQueryImplWithReqid(TAOS* taos, const char* sql, bool validateOnly, int64_t reqid) {
872✔
3215
  if (NULL == taos) {
872✔
3216
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3217
    return NULL;
×
3218
  }
3219

3220
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
872✔
3221
  if (param == NULL) {
872✔
3222
    return NULL;
×
3223
  }
3224
  int32_t code = tsem_init(&param->sem, 0, 0);
872✔
3225
  if (TSDB_CODE_SUCCESS != code) {
872✔
3226
    taosMemoryFree(param);
×
3227
    return NULL;
×
3228
  }
3229

3230
  taosAsyncQueryImplWithReqid(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, reqid);
872✔
3231
  code = tsem_wait(&param->sem);
872✔
3232
  if (TSDB_CODE_SUCCESS != code) {
872✔
3233
    taosMemoryFree(param);
×
3234
    return NULL;
×
3235
  }
3236
  SRequestObj* pRequest = NULL;
872✔
3237
  if (param->pRequest != NULL) {
872✔
3238
    param->pRequest->syncQuery = true;
872✔
3239
    pRequest = param->pRequest;
872✔
3240
  }
3241
  taosMemoryFree(param);
872✔
3242

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

3246
  return pRequest;
872✔
3247
}
3248

3249
static void fetchCallback(void* pResult, void* param, int32_t code) {
95,759,792✔
3250
  SRequestObj* pRequest = (SRequestObj*)param;
95,759,792✔
3251

3252
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
95,759,792✔
3253

3254
  tscDebug("req:0x%" PRIx64 ", enter scheduler fetch cb, code:%d - %s, QID:0x%" PRIx64, pRequest->self, code,
95,759,792✔
3255
           tstrerror(code), pRequest->requestId);
3256

3257
  pResultInfo->pData = pResult;
95,759,792✔
3258
  pResultInfo->numOfRows = 0;
95,759,792✔
3259

3260
  if (code != TSDB_CODE_SUCCESS) {
95,758,498✔
3261
    pRequest->code = code;
×
3262
    taosMemoryFreeClear(pResultInfo->pData);
×
3263
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
×
3264
    return;
×
3265
  }
3266

3267
  if (pRequest->code != TSDB_CODE_SUCCESS) {
95,758,498✔
3268
    taosMemoryFreeClear(pResultInfo->pData);
×
3269
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pRequest->code);
×
3270
    return;
×
3271
  }
3272

3273
  pRequest->code = setQueryResultFromRsp(pResultInfo, (const SRetrieveTableRsp*)pResultInfo->pData,
96,480,875✔
3274
                                         pResultInfo->convertUcs4, pRequest->stmtBindVersion > 0);
95,759,274✔
3275
  if (pRequest->code != TSDB_CODE_SUCCESS) {
95,758,029✔
3276
    pResultInfo->numOfRows = 0;
76✔
3277
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self,
76✔
3278
             tstrerror(pRequest->code), pRequest->requestId);
3279
  } else {
3280
    tscDebug(
95,757,265✔
3281
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
3282
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
3283

3284
    STscObj*            pTscObj = pRequest->pTscObj;
95,757,265✔
3285
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
95,759,716✔
3286
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
95,759,459✔
3287
  }
3288

3289
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
95,759,535✔
3290
}
3291

3292
void taosAsyncFetchImpl(SRequestObj* pRequest, __taos_async_fn_t fp, void* param) {
100,235,123✔
3293
  pRequest->body.fetchFp = fp;
100,235,123✔
3294
  ((SSyncQueryParam*)pRequest->body.interParam)->userParam = param;
100,235,123✔
3295

3296
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
100,235,399✔
3297

3298
  // this query has no results or error exists, return directly
3299
  if (taos_num_fields(pRequest) == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
100,235,399✔
3300
    pResultInfo->numOfRows = 0;
×
3301
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
×
3302
    return;
706✔
3303
  }
3304

3305
  // all data has returned to App already, no need to try again
3306
  if (pResultInfo->completed) {
100,235,399✔
3307
    // it is a local executed query, no need to do async fetch
3308
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
4,475,607✔
3309
      if (pResultInfo->localResultFetched) {
1,602,770✔
3310
        pResultInfo->numOfRows = 0;
801,385✔
3311
        pResultInfo->current = 0;
801,385✔
3312
      } else {
3313
        pResultInfo->localResultFetched = true;
801,385✔
3314
      }
3315
    } else {
3316
      pResultInfo->numOfRows = 0;
2,872,837✔
3317
    }
3318

3319
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
4,475,607✔
3320
    return;
4,475,607✔
3321
  }
3322

3323
  SSchedulerReq req = {
95,759,792✔
3324
      .syncReq = false,
3325
      .fetchFp = fetchCallback,
3326
      .cbParam = pRequest,
3327
  };
3328

3329
  int32_t code = schedulerFetchRows(pRequest->body.queryJob, &req);
95,759,792✔
3330
  if (TSDB_CODE_SUCCESS != code) {
95,759,038✔
3331
    tscError("0x%" PRIx64 " failed to schedule fetch rows", pRequest->requestId);
×
3332
    // pRequest->body.fetchFp(param, pRequest, code);
3333
  }
3334
}
3335

3336
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
650,657,297✔
3337
  pRequest->inCallback = true;
650,657,297✔
3338
  int64_t this = pRequest->self;
650,664,977✔
3339
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
650,642,930✔
3340
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
87,600✔
3341
    code = TSDB_CODE_SUCCESS;
×
3342
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3343
  }
3344

3345
  tscDebug("QID:0x%" PRIx64 ", taos_query end, req:0x%" PRIx64 ", res:%p", pRequest->requestId, pRequest->self,
650,642,930✔
3346
           pRequest);
3347

3348
  if (pRequest->body.queryFp != NULL) {
650,645,088✔
3349
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
650,660,025✔
3350
  }
3351

3352
  SRequestObj* pReq = acquireRequest(this);
650,664,200✔
3353
  if (pReq != NULL) {
650,664,165✔
3354
    pReq->inCallback = false;
649,553,195✔
3355
    (void)releaseRequest(this);
649,554,439✔
3356
  }
3357
}
650,664,258✔
3358

3359
int32_t clientParseSql(void* param, const char* dbName, const char* sql, bool parseOnly, const char* effectiveUser,
579,840✔
3360
                       SParseSqlRes* pRes) {
3361
#ifndef TD_ENTERPRISE
3362
  return TSDB_CODE_SUCCESS;
3363
#else
3364
  return clientParseSqlImpl(param, dbName, sql, parseOnly, effectiveUser, pRes);
579,840✔
3365
#endif
3366
}
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