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

taosdata / TDengine / #4875

09 Dec 2025 01:22AM UTC coverage: 64.472% (-0.2%) from 64.623%
#4875

push

travis-ci

guanshengliang
fix: temporarily disable memory leak detection for UDF tests (#33856)

162014 of 251293 relevant lines covered (64.47%)

104318075.66 hits per line

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

71.04
/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);
37

38
void setQueryRequest(int64_t rId) {
116,287,361✔
39
  SRequestObj* pReq = acquireRequest(rId);
116,287,361✔
40
  if (pReq != NULL) {
116,289,545✔
41
    pReq->isQuery = true;
116,279,350✔
42
    (void)releaseRequest(rId);
116,277,414✔
43
  }
44
}
116,288,745✔
45

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

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

56
  return true;
7,759,832✔
57
}
58

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

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

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

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

71
static int32_t escapeToPrinted(char* dst, size_t maxDstLength, const char* src, size_t srcLength) {
637,515✔
72
  if (dst == NULL || src == NULL || srcLength == 0) {
637,515✔
73
    return 0;
533✔
74
  }
75
  
76
  size_t escapeLength = 0;
636,982✔
77
  for(size_t i = 0; i < srcLength; ++i) {
18,064,706✔
78
    if( src[i] == '\"' || src[i] == '\\' || src[i] == '\b' || src[i] == '\f' || src[i] == '\n' ||
17,427,724✔
79
        src[i] == '\r' || src[i] == '\t') {
17,427,724✔
80
      escapeLength += 1; 
×
81
    }    
82
  }
83

84
  size_t dstLength = srcLength;
636,982✔
85
  if(escapeLength == 0) {
636,982✔
86
     (void)memcpy(dst, src, srcLength);
636,982✔
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;
636,982✔
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,276,019✔
141
  taosHashCleanup(appInfo.pInstMap);
1,276,019✔
142
  taosHashCleanup(appInfo.pInstMapByClusterId);
1,276,019✔
143
  tscInfo("cluster instance map cleaned");
1,276,019✔
144
}
1,276,019✔
145

146
static int32_t taosConnectImpl(const char* user, const char* auth, 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* db,
3,156,393✔
150
                              uint16_t port, int connType, STscObj** pObj) {
151
  TSC_ERR_RET(taos_init());
3,156,393✔
152
  if (!validateUserName(user)) {
3,156,393✔
153
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
154
  }
155
  int32_t code = 0;
3,156,181✔
156

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

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

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

173
    taosEncryptPass_c((uint8_t*)pass, strlen(pass), secretEncrypt);
3,155,831✔
174
  } else {
175
    tstrncpy(secretEncrypt, auth, tListLen(secretEncrypt));
759✔
176
  }
177

178
  SCorEpSet epSet = {0};
3,156,055✔
179
  if (ip) {
3,155,808✔
180
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
1,125,032✔
181
  } else {
182
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
2,030,776✔
183
  }
184

185
  if (port) {
3,153,351✔
186
    epSet.epSet.eps[0].port = port;
143,867✔
187
    epSet.epSet.eps[1].port = port;
143,867✔
188
  }
189

190
  char* key = getClusterKey(user, secretEncrypt, ip, port);
3,153,351✔
191
  if (NULL == key) {
3,154,826✔
192
    TSC_ERR_RET(terrno);
×
193
  }
194
  tscInfo("connecting to server, numOfEps:%d inUse:%d user:%s db:%s key:%s", epSet.epSet.numOfEps, epSet.epSet.inUse,
3,154,826✔
195
          user, db, key);
196
  for (int32_t i = 0; i < epSet.epSet.numOfEps; ++i) {
8,342,729✔
197
    tscInfo("ep:%d, %s:%u", i, epSet.epSet.eps[i].fqdn, epSet.epSet.eps[i].port);
5,186,904✔
198
  }
199
  // for (int32_t i = 0; i < epSet.epSet.numOfEps; i++) {
200
  //   if ((code = taosValidFqdn(tsEnableIpv6, epSet.epSet.eps[i].fqdn)) != 0) {
201
  //     taosMemFree(key);
202
  //     tscError("ipv6 flag %d, the local FQDN %s does not resolve to the ip address since %s", tsEnableIpv6,
203
  //              epSet.epSet.eps[i].fqdn, tstrerror(code));
204
  //     TSC_ERR_RET(code);
205
  //   }
206
  // }
207

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

215
  pInst = taosHashGet(appInfo.pInstMap, key, strlen(key));
3,155,825✔
216
  SAppInstInfo* p = NULL;
3,155,825✔
217
  if (pInst == NULL) {
3,155,825✔
218
    p = taosMemoryCalloc(1, sizeof(struct SAppInstInfo));
1,340,722✔
219
    if (NULL == p) {
1,340,722✔
220
      TSC_ERR_JRET(terrno);
×
221
    }
222
    p->mgmtEp = epSet;
1,340,722✔
223
    code = taosThreadMutexInit(&p->qnodeMutex, NULL);
1,340,722✔
224
    if (TSDB_CODE_SUCCESS != code) {
1,340,722✔
225
      taosMemoryFree(p);
×
226
      TSC_ERR_JRET(code);
×
227
    }
228
    code = openTransporter(user, secretEncrypt, tsNumOfCores / 2, &p->pTransporter);
1,340,722✔
229
    if (TSDB_CODE_SUCCESS != code) {
1,340,722✔
230
      taosMemoryFree(p);
48✔
231
      TSC_ERR_JRET(code);
48✔
232
    }
233
    code = appHbMgrInit(p, key, &p->pAppHbMgr);
1,340,674✔
234
    if (TSDB_CODE_SUCCESS != code) {
1,340,674✔
235
      destroyAppInst(&p);
×
236
      TSC_ERR_JRET(code);
×
237
    }
238
    code = taosHashPut(appInfo.pInstMap, key, strlen(key), &p, POINTER_BYTES);
1,340,674✔
239
    if (TSDB_CODE_SUCCESS != code) {
1,340,674✔
240
      destroyAppInst(&p);
×
241
      TSC_ERR_JRET(code);
×
242
    }
243
    p->instKey = key;
1,340,674✔
244
    key = NULL;
1,340,674✔
245
    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,340,674✔
246

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

257
_return:
3,155,825✔
258

259
  if (TSDB_CODE_SUCCESS != code) {
3,155,825✔
260
    (void)taosThreadMutexUnlock(&appInfo.mutex);
48✔
261
    taosMemoryFreeClear(key);
48✔
262
    return code;
48✔
263
  } else {
264
    code = taosThreadMutexUnlock(&appInfo.mutex);
3,155,777✔
265
    taosMemoryFreeClear(key);
3,155,777✔
266
    if (TSDB_CODE_SUCCESS != code) {
3,155,777✔
267
      tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
268
      return code;
×
269
    }
270
    return taosConnectImpl(user, &secretEncrypt[0], localDb, NULL, NULL, *pInst, connType, pObj);
3,155,777✔
271
  }
272
}
273

274
// SAppInstInfo* getAppInstInfo(const char* clusterKey) {
275
//   SAppInstInfo** ppAppInstInfo = taosHashGet(appInfo.pInstMap, clusterKey, strlen(clusterKey));
276
//   if (ppAppInstInfo != NULL && *ppAppInstInfo != NULL) {
277
//     return *ppAppInstInfo;
278
//   } else {
279
//     return NULL;
280
//   }
281
// }
282

283
void freeQueryParam(SSyncQueryParam* param) {
557,421✔
284
  if (param == NULL) return;
557,421✔
285
  if (TSDB_CODE_SUCCESS != tsem_destroy(&param->sem)) {
557,421✔
286
    tscError("failed to destroy semaphore in freeQueryParam");
×
287
  }
288
  taosMemoryFree(param);
557,421✔
289
}
290

291
int32_t buildRequest(uint64_t connId, const char* sql, int sqlLen, void* param, bool validateSql,
624,352,335✔
292
                     SRequestObj** pRequest, int64_t reqid) {
293
  int32_t code = createRequest(connId, TSDB_SQL_SELECT, reqid, pRequest);
624,352,335✔
294
  if (TSDB_CODE_SUCCESS != code) {
624,352,544✔
295
    tscError("failed to malloc sqlObj, %s", sql);
×
296
    return code;
×
297
  }
298

299
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
624,352,544✔
300
  if ((*pRequest)->sqlstr == NULL) {
624,352,633✔
301
    tscError("req:0x%" PRIx64 ", failed to prepare sql string buffer, %s", (*pRequest)->self, sql);
×
302
    destroyRequest(*pRequest);
×
303
    *pRequest = NULL;
×
304
    return terrno;
×
305
  }
306

307
  (void)strntolower((*pRequest)->sqlstr, sql, (int32_t)sqlLen);
624,351,890✔
308
  (*pRequest)->sqlstr[sqlLen] = 0;
624,363,175✔
309
  (*pRequest)->sqlLen = sqlLen;
624,362,802✔
310
  (*pRequest)->validateOnly = validateSql;
624,363,738✔
311
  (*pRequest)->stmtBindVersion = 0;
624,362,140✔
312

313
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
624,362,142✔
314

315
  STscObj* pTscObj = (*pRequest)->pTscObj;
624,362,210✔
316
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
624,359,378✔
317
                             sizeof((*pRequest)->self));
318
  if (err) {
624,361,325✔
319
    tscError("req:0x%" PRId64 ", failed to add to request container, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
320
             (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
321
    destroyRequest(*pRequest);
×
322
    *pRequest = NULL;
×
323
    return terrno;
×
324
  }
325

326
  (*pRequest)->allocatorRefId = -1;
624,361,325✔
327
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
624,353,104✔
328
    if (TSDB_CODE_SUCCESS !=
177,289,707✔
329
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
177,285,846✔
330
      tscError("req:0x%" PRId64 ", failed to create node allocator, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
331
               (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
332
      destroyRequest(*pRequest);
×
333
      *pRequest = NULL;
×
334
      return terrno;
×
335
    }
336
  }
337

338
  tscDebug("req:0x%" PRIx64 ", build request, QID:0x%" PRIx64, (*pRequest)->self, (*pRequest)->requestId);
624,353,296✔
339
  return TSDB_CODE_SUCCESS;
624,351,883✔
340
}
341

342
int32_t buildPreviousRequest(SRequestObj* pRequest, const char* sql, SRequestObj** pNewRequest) {
×
343
  int32_t code =
344
      buildRequest(pRequest->pTscObj->id, sql, strlen(sql), pRequest, pRequest->validateOnly, pNewRequest, 0);
×
345
  if (TSDB_CODE_SUCCESS == code) {
×
346
    pRequest->relation.prevRefId = (*pNewRequest)->self;
×
347
    (*pNewRequest)->relation.nextRefId = pRequest->self;
×
348
    (*pNewRequest)->relation.userRefId = pRequest->self;
×
349
    (*pNewRequest)->isSubReq = true;
×
350
  }
351
  return code;
×
352
}
353

354
int32_t parseSql(SRequestObj* pRequest, bool topicQuery, SQuery** pQuery, SStmtCallback* pStmtCb) {
751,919✔
355
  STscObj* pTscObj = pRequest->pTscObj;
751,919✔
356

357
  SParseContext cxt = {
752,090✔
358
      .requestId = pRequest->requestId,
752,531✔
359
      .requestRid = pRequest->self,
751,364✔
360
      .acctId = pTscObj->acctId,
751,635✔
361
      .db = pRequest->pDb,
751,106✔
362
      .topicQuery = topicQuery,
363
      .pSql = pRequest->sqlstr,
751,760✔
364
      .sqlLen = pRequest->sqlLen,
752,090✔
365
      .pMsg = pRequest->msgBuf,
752,267✔
366
      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
367
      .pTransporter = pTscObj->pAppInfo->pTransporter,
751,482✔
368
      .pStmtCb = pStmtCb,
369
      .pUser = pTscObj->user,
752,131✔
370
      .isSuperUser = (0 == strcmp(pTscObj->user, TSDB_DEFAULT_USER)),
751,975✔
371
      .enableSysInfo = pTscObj->sysInfo,
751,794✔
372
      .svrVer = pTscObj->sVer,
751,598✔
373
      .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes),
752,260✔
374
      .stmtBindVersion = pRequest->stmtBindVersion,
751,992✔
375
      .setQueryFp = setQueryRequest,
376
      .timezone = pTscObj->optionInfo.timezone,
751,564✔
377
      .charsetCxt = pTscObj->optionInfo.charsetCxt,
751,920✔
378
  };
379

380
  cxt.mgmtEpSet = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
752,473✔
381
  int32_t code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &cxt.pCatalog);
752,623✔
382
  if (code != TSDB_CODE_SUCCESS) {
752,535✔
383
    return code;
×
384
  }
385

386
  code = qParseSql(&cxt, pQuery);
752,535✔
387
  if (TSDB_CODE_SUCCESS == code) {
752,207✔
388
    if ((*pQuery)->haveResultSet) {
750,552✔
389
      code = setResSchemaInfo(&pRequest->body.resInfo, (*pQuery)->pResSchema, (*pQuery)->numOfResCols,
×
390
                              (*pQuery)->pResExtSchema, pRequest->stmtBindVersion > 0);
×
391
      setResPrecision(&pRequest->body.resInfo, (*pQuery)->precision);
×
392
    }
393
  }
394

395
  if (TSDB_CODE_SUCCESS == code || NEED_CLIENT_HANDLE_ERROR(code)) {
752,241✔
396
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
750,275✔
397
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
750,027✔
398
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
750,129✔
399
  }
400

401
  taosArrayDestroy(cxt.pTableMetaPos);
751,867✔
402
  taosArrayDestroy(cxt.pTableVgroupPos);
751,983✔
403

404
  return code;
752,221✔
405
}
406

407
int32_t execLocalCmd(SRequestObj* pRequest, SQuery* pQuery) {
×
408
  SRetrieveTableRsp* pRsp = NULL;
×
409
  int8_t             biMode = atomic_load_8(&pRequest->pTscObj->biMode);
×
410
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp, biMode,
×
411
                              pRequest->pTscObj->optionInfo.charsetCxt);
×
412
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
×
413
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4,
×
414
                                 pRequest->stmtBindVersion > 0);
×
415
  }
416

417
  return code;
×
418
}
419

420
int32_t execDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
385,060✔
421
  // drop table if exists not_exists_table
422
  if (NULL == pQuery->pCmdMsg) {
385,060✔
423
    return TSDB_CODE_SUCCESS;
×
424
  }
425

426
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
385,060✔
427
  pRequest->type = pMsgInfo->msgType;
385,060✔
428
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
385,060✔
429
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
385,060✔
430

431
  STscObj*      pTscObj = pRequest->pTscObj;
385,060✔
432
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
385,060✔
433

434
  // int64_t transporterId = 0;
435
  TSC_ERR_RET(asyncSendMsgToServer(pTscObj->pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg));
384,902✔
436
  TSC_ERR_RET(tsem_wait(&pRequest->body.rspSem));
385,218✔
437
  return TSDB_CODE_SUCCESS;
385,218✔
438
}
439

440
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
1,175,900,444✔
441

442
void asyncExecLocalCmd(SRequestObj* pRequest, SQuery* pQuery) {
5,315,596✔
443
  SRetrieveTableRsp* pRsp = NULL;
5,315,596✔
444
  if (pRequest->validateOnly) {
5,315,596✔
445
    doRequestCallback(pRequest, 0);
12,069✔
446
    return;
12,069✔
447
  }
448

449
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp,
10,510,880✔
450
                              atomic_load_8(&pRequest->pTscObj->biMode), pRequest->pTscObj->optionInfo.charsetCxt);
10,511,668✔
451
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
5,303,527✔
452
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4,
2,748,692✔
453
                                 pRequest->stmtBindVersion > 0);
2,748,692✔
454
  }
455

456
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
5,303,418✔
457
  pRequest->code = code;
5,303,418✔
458

459
  if (pRequest->code != TSDB_CODE_SUCCESS) {
5,303,418✔
460
    pResultInfo->numOfRows = 0;
3,990✔
461
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
3,990✔
462
             pRequest->requestId);
463
  } else {
464
    tscDebug(
5,299,428✔
465
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
466
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
467
  }
468

469
  doRequestCallback(pRequest, code);
5,303,418✔
470
}
471

472
int32_t asyncExecDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
17,653,630✔
473
  if (pRequest->validateOnly) {
17,653,630✔
474
    doRequestCallback(pRequest, 0);
×
475
    return TSDB_CODE_SUCCESS;
×
476
  }
477

478
  // drop table if exists not_exists_table
479
  if (NULL == pQuery->pCmdMsg) {
17,653,630✔
480
    doRequestCallback(pRequest, 0);
7,675✔
481
    return TSDB_CODE_SUCCESS;
7,675✔
482
  }
483

484
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
17,645,702✔
485
  pRequest->type = pMsgInfo->msgType;
17,645,667✔
486
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
17,645,955✔
487
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
17,645,667✔
488

489
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
17,645,702✔
490
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
17,645,615✔
491

492
  int32_t code = asyncSendMsgToServer(pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg);
17,645,697✔
493
  if (code) {
17,646,128✔
494
    doRequestCallback(pRequest, code);
×
495
  }
496
  return code;
17,646,128✔
497
}
498

499
int compareQueryNodeLoad(const void* elem1, const void* elem2) {
379,667✔
500
  SQueryNodeLoad* node1 = (SQueryNodeLoad*)elem1;
379,667✔
501
  SQueryNodeLoad* node2 = (SQueryNodeLoad*)elem2;
379,667✔
502

503
  if (node1->load < node2->load) {
379,667✔
504
    return -1;
×
505
  }
506

507
  return node1->load > node2->load;
379,667✔
508
}
509

510
int32_t updateQnodeList(SAppInstInfo* pInfo, SArray* pNodeList) {
91,410✔
511
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
91,410✔
512
  if (pInfo->pQnodeList) {
91,410✔
513
    taosArrayDestroy(pInfo->pQnodeList);
86,127✔
514
    pInfo->pQnodeList = NULL;
86,127✔
515
    tscDebug("QnodeList cleared in cluster 0x%" PRIx64, pInfo->clusterId);
86,127✔
516
  }
517

518
  if (pNodeList) {
91,410✔
519
    pInfo->pQnodeList = taosArrayDup(pNodeList, NULL);
91,410✔
520
    taosArraySort(pInfo->pQnodeList, compareQueryNodeLoad);
91,410✔
521
    tscDebug("QnodeList updated in cluster 0x%" PRIx64 ", num:%ld", pInfo->clusterId,
91,410✔
522
             taosArrayGetSize(pInfo->pQnodeList));
523
  }
524
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
91,410✔
525

526
  return TSDB_CODE_SUCCESS;
91,410✔
527
}
528

529
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
624,124,236✔
530
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
624,124,236✔
531
    *required = false;
623,608,228✔
532
    return TSDB_CODE_SUCCESS;
623,605,675✔
533
  }
534

535
  int32_t       code = TSDB_CODE_SUCCESS;
516,008✔
536
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
516,008✔
537
  *required = false;
516,008✔
538

539
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
516,008✔
540
  *required = (NULL == pInfo->pQnodeList);
516,008✔
541
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
516,008✔
542
  return TSDB_CODE_SUCCESS;
516,008✔
543
}
544

545
int32_t getQnodeList(SRequestObj* pRequest, SArray** pNodeList) {
×
546
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
×
547
  int32_t       code = 0;
×
548

549
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
×
550
  if (pInfo->pQnodeList) {
×
551
    *pNodeList = taosArrayDup(pInfo->pQnodeList, NULL);
×
552
  }
553
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
×
554
  if (NULL == *pNodeList) {
×
555
    SCatalog* pCatalog = NULL;
×
556
    code = catalogGetHandle(pRequest->pTscObj->pAppInfo->clusterId, &pCatalog);
×
557
    if (TSDB_CODE_SUCCESS == code) {
×
558
      *pNodeList = taosArrayInit(5, sizeof(SQueryNodeLoad));
×
559
      if (NULL == pNodeList) {
×
560
        TSC_ERR_RET(terrno);
×
561
      }
562
      SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
×
563
                               .requestId = pRequest->requestId,
×
564
                               .requestObjRefId = pRequest->self,
×
565
                               .mgmtEps = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp)};
×
566
      code = catalogGetQnodeList(pCatalog, &conn, *pNodeList);
×
567
    }
568

569
    if (TSDB_CODE_SUCCESS == code && *pNodeList) {
×
570
      code = updateQnodeList(pInfo, *pNodeList);
×
571
    }
572
  }
573

574
  return code;
×
575
}
576

577
int32_t getPlan(SRequestObj* pRequest, SQuery* pQuery, SQueryPlan** pPlan, SArray* pNodeList) {
11,761,567✔
578
  pRequest->type = pQuery->msgType;
11,761,567✔
579
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
11,761,951✔
580

581
  SPlanContext cxt = {.queryId = pRequest->requestId,
18,028,956✔
582
                      .acctId = pRequest->pTscObj->acctId,
11,761,228✔
583
                      .mgmtEpSet = getEpSet_s(&pAppInfo->mgmtEp),
11,761,486✔
584
                      .pAstRoot = pQuery->pRoot,
11,763,232✔
585
                      .showRewrite = pQuery->showRewrite,
11,762,960✔
586
                      .pMsg = pRequest->msgBuf,
11,763,096✔
587
                      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
588
                      .pUser = pRequest->pTscObj->user,
11,762,827✔
589
                      .timezone = pRequest->pTscObj->optionInfo.timezone,
11,761,696✔
590
                      .sysInfo = pRequest->pTscObj->sysInfo};
11,762,589✔
591

592
  return qCreateQueryPlan(&cxt, pPlan, pNodeList);
11,761,898✔
593
}
594

595
int32_t setResSchemaInfo(SReqResultInfo* pResInfo, const SSchema* pSchema, int32_t numOfCols,
119,553,112✔
596
                         const SExtSchema* pExtSchema, bool isStmt) {
597
  if (pResInfo == NULL || pSchema == NULL || numOfCols <= 0) {
119,553,112✔
598
    tscError("invalid paras, pResInfo == NULL || pSchema == NULL || numOfCols <= 0");
122✔
599
    return TSDB_CODE_INVALID_PARA;
×
600
  }
601

602
  pResInfo->numOfCols = numOfCols;
119,553,574✔
603
  if (pResInfo->fields != NULL) {
119,552,678✔
604
    taosMemoryFree(pResInfo->fields);
23,749✔
605
  }
606
  if (pResInfo->userFields != NULL) {
119,552,600✔
607
    taosMemoryFree(pResInfo->userFields);
23,749✔
608
  }
609
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD_E));
119,551,581✔
610
  if (NULL == pResInfo->fields) return terrno;
119,549,346✔
611
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
119,549,681✔
612
  if (NULL == pResInfo->userFields) {
119,551,015✔
613
    taosMemoryFree(pResInfo->fields);
×
614
    return terrno;
×
615
  }
616
  if (numOfCols != pResInfo->numOfCols) {
119,549,846✔
617
    tscError("numOfCols:%d != pResInfo->numOfCols:%d", numOfCols, pResInfo->numOfCols);
×
618
    return TSDB_CODE_FAILED;
×
619
  }
620

621
  for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
709,125,261✔
622
    pResInfo->fields[i].type = pSchema[i].type;
589,565,916✔
623

624
    pResInfo->userFields[i].type = pSchema[i].type;
589,567,307✔
625
    // userFields must convert to type bytes, no matter isStmt or not
626
    pResInfo->userFields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, false);
589,570,931✔
627
    pResInfo->fields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, isStmt);
589,565,476✔
628
    if (IS_DECIMAL_TYPE(pSchema[i].type) && pExtSchema) {
589,559,190✔
629
      decimalFromTypeMod(pExtSchema[i].typeMod, &pResInfo->fields[i].precision, &pResInfo->fields[i].scale);
1,448,404✔
630
    }
631

632
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
589,557,364✔
633
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
589,568,541✔
634
  }
635
  return TSDB_CODE_SUCCESS;
119,554,967✔
636
}
637

638
void setResPrecision(SReqResultInfo* pResInfo, int32_t precision) {
85,490,305✔
639
  if (precision != TSDB_TIME_PRECISION_MILLI && precision != TSDB_TIME_PRECISION_MICRO &&
85,490,305✔
640
      precision != TSDB_TIME_PRECISION_NANO) {
641
    return;
×
642
  }
643

644
  pResInfo->precision = precision;
85,490,305✔
645
}
646

647
int32_t buildVnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pDbVgList) {
94,663,618✔
648
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
94,663,618✔
649
  if (NULL == nodeList) {
94,668,710✔
650
    return terrno;
462✔
651
  }
652
  char* policy = (tsQueryPolicy == QUERY_POLICY_VNODE) ? "vnode" : "client";
94,668,825✔
653

654
  int32_t dbNum = taosArrayGetSize(pDbVgList);
94,668,825✔
655
  for (int32_t i = 0; i < dbNum; ++i) {
186,917,629✔
656
    SArray* pVg = taosArrayGetP(pDbVgList, i);
92,241,201✔
657
    if (NULL == pVg) {
92,242,697✔
658
      continue;
×
659
    }
660
    int32_t vgNum = taosArrayGetSize(pVg);
92,242,697✔
661
    if (vgNum <= 0) {
92,241,578✔
662
      continue;
681,514✔
663
    }
664

665
    for (int32_t j = 0; j < vgNum; ++j) {
301,819,504✔
666
      SVgroupInfo* pInfo = taosArrayGet(pVg, j);
210,253,970✔
667
      if (NULL == pInfo) {
210,256,203✔
668
        taosArrayDestroy(nodeList);
×
669
        return TSDB_CODE_OUT_OF_RANGE;
×
670
      }
671
      SQueryNodeLoad load = {0};
210,256,203✔
672
      load.addr.nodeId = pInfo->vgId;
210,257,140✔
673
      load.addr.epSet = pInfo->epSet;
210,257,441✔
674

675
      if (NULL == taosArrayPush(nodeList, &load)) {
210,255,681✔
676
        taosArrayDestroy(nodeList);
×
677
        return terrno;
×
678
      }
679
    }
680
  }
681

682
  int32_t vnodeNum = taosArrayGetSize(nodeList);
94,676,428✔
683
  if (vnodeNum > 0) {
94,673,989✔
684
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
91,260,276✔
685
    goto _return;
91,257,485✔
686
  }
687

688
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
3,413,713✔
689
  if (mnodeNum <= 0) {
3,413,827✔
690
    tscDebug("0x%" PRIx64 " %s policy, empty node list", pRequest->requestId, policy);
×
691
    goto _return;
×
692
  }
693

694
  void* pData = taosArrayGet(pMnodeList, 0);
3,413,827✔
695
  if (NULL == pData) {
3,413,827✔
696
    taosArrayDestroy(nodeList);
×
697
    return TSDB_CODE_OUT_OF_RANGE;
×
698
  }
699
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
3,413,827✔
700
    taosArrayDestroy(nodeList);
×
701
    return terrno;
×
702
  }
703

704
  tscDebug("0x%" PRIx64 " %s policy, use mnode list, num:%d", pRequest->requestId, policy, mnodeNum);
3,413,827✔
705

706
_return:
110,319✔
707

708
  *pNodeList = nodeList;
94,669,951✔
709

710
  return TSDB_CODE_SUCCESS;
94,670,247✔
711
}
712

713
int32_t buildQnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pQnodeList) {
415,042✔
714
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
415,042✔
715
  if (NULL == nodeList) {
415,042✔
716
    return terrno;
×
717
  }
718

719
  int32_t qNodeNum = taosArrayGetSize(pQnodeList);
415,042✔
720
  if (qNodeNum > 0) {
415,042✔
721
    void* pData = taosArrayGet(pQnodeList, 0);
328,665✔
722
    if (NULL == pData) {
328,665✔
723
      taosArrayDestroy(nodeList);
×
724
      return TSDB_CODE_OUT_OF_RANGE;
×
725
    }
726
    if (NULL == taosArrayAddBatch(nodeList, pData, qNodeNum)) {
328,665✔
727
      taosArrayDestroy(nodeList);
×
728
      return terrno;
×
729
    }
730
    tscDebug("0x%" PRIx64 " qnode policy, use qnode list, num:%d", pRequest->requestId, qNodeNum);
328,665✔
731
    goto _return;
328,665✔
732
  }
733

734
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
86,377✔
735
  if (mnodeNum <= 0) {
86,377✔
736
    tscDebug("0x%" PRIx64 " qnode policy, empty node list", pRequest->requestId);
2,966✔
737
    goto _return;
2,966✔
738
  }
739

740
  void* pData = taosArrayGet(pMnodeList, 0);
83,411✔
741
  if (NULL == pData) {
83,411✔
742
    taosArrayDestroy(nodeList);
×
743
    return TSDB_CODE_OUT_OF_RANGE;
×
744
  }
745
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
83,411✔
746
    taosArrayDestroy(nodeList);
×
747
    return terrno;
×
748
  }
749

750
  tscDebug("0x%" PRIx64 " qnode policy, use mnode list, num:%d", pRequest->requestId, mnodeNum);
83,411✔
751

752
_return:
×
753

754
  *pNodeList = nodeList;
415,042✔
755

756
  return TSDB_CODE_SUCCESS;
415,042✔
757
}
758

759
void freeVgList(void* list) {
11,707,882✔
760
  SArray* pList = *(SArray**)list;
11,707,882✔
761
  taosArrayDestroy(pList);
11,708,786✔
762
}
11,711,618✔
763

764
int32_t buildAsyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SMetaData* pResultMeta) {
83,322,789✔
765
  SArray* pDbVgList = NULL;
83,322,789✔
766
  SArray* pQnodeList = NULL;
83,322,789✔
767
  FDelete fp = NULL;
83,322,789✔
768
  int32_t code = 0;
83,322,789✔
769

770
  switch (tsQueryPolicy) {
83,322,789✔
771
    case QUERY_POLICY_VNODE:
82,908,398✔
772
    case QUERY_POLICY_CLIENT: {
773
      if (pResultMeta) {
82,908,398✔
774
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
82,908,836✔
775
        if (NULL == pDbVgList) {
82,908,500✔
776
          code = terrno;
×
777
          goto _return;
×
778
        }
779
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
82,908,500✔
780
        for (int32_t i = 0; i < dbNum; ++i) {
163,439,252✔
781
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
80,530,423✔
782
          if (pRes->code || NULL == pRes->pRes) {
80,531,143✔
783
            continue;
1,060✔
784
          }
785

786
          if (NULL == taosArrayPush(pDbVgList, &pRes->pRes)) {
161,057,699✔
787
            code = terrno;
×
788
            goto _return;
×
789
          }
790
        }
791
      } else {
792
        fp = freeVgList;
×
793

794
        int32_t dbNum = taosArrayGetSize(pRequest->dbList);
×
795
        if (dbNum > 0) {
×
796
          SCatalog*     pCtg = NULL;
×
797
          SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
×
798
          code = catalogGetHandle(pInst->clusterId, &pCtg);
×
799
          if (code != TSDB_CODE_SUCCESS) {
×
800
            goto _return;
×
801
          }
802

803
          pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
×
804
          if (NULL == pDbVgList) {
×
805
            code = terrno;
×
806
            goto _return;
×
807
          }
808
          SArray* pVgList = NULL;
×
809
          for (int32_t i = 0; i < dbNum; ++i) {
×
810
            char*            dbFName = taosArrayGet(pRequest->dbList, i);
×
811
            SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
×
812
                                     .requestId = pRequest->requestId,
×
813
                                     .requestObjRefId = pRequest->self,
×
814
                                     .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
×
815

816
            // catalogGetDBVgList will handle dbFName == null.
817
            code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
×
818
            if (code) {
×
819
              goto _return;
×
820
            }
821

822
            if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
×
823
              code = terrno;
×
824
              goto _return;
×
825
            }
826
          }
827
        }
828
      }
829

830
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
82,908,829✔
831
      break;
82,910,195✔
832
    }
833
    case QUERY_POLICY_HYBRID:
415,042✔
834
    case QUERY_POLICY_QNODE: {
835
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
508,626✔
836
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
93,584✔
837
        if (pRes->code) {
93,584✔
838
          pQnodeList = NULL;
×
839
        } else {
840
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
93,584✔
841
          if (NULL == pQnodeList) {
93,584✔
842
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
843
            goto _return;
×
844
          }
845
        }
846
      } else {
847
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
321,458✔
848
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
321,458✔
849
        if (pInst->pQnodeList) {
321,458✔
850
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
321,458✔
851
          if (NULL == pQnodeList) {
321,458✔
852
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
853
            goto _return;
×
854
          }
855
        }
856
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
321,458✔
857
      }
858

859
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
415,042✔
860
      break;
415,042✔
861
    }
862
    default:
2✔
863
      tscError("unknown query policy: %d", tsQueryPolicy);
2✔
864
      return TSDB_CODE_APP_ERROR;
×
865
  }
866

867
_return:
83,325,237✔
868
  taosArrayDestroyEx(pDbVgList, fp);
83,325,237✔
869
  taosArrayDestroy(pQnodeList);
83,324,024✔
870

871
  return code;
83,324,518✔
872
}
873

874
int32_t buildSyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList) {
11,757,407✔
875
  SArray* pDbVgList = NULL;
11,757,407✔
876
  SArray* pQnodeList = NULL;
11,757,407✔
877
  int32_t code = 0;
11,756,789✔
878

879
  switch (tsQueryPolicy) {
11,756,789✔
880
    case QUERY_POLICY_VNODE:
11,754,443✔
881
    case QUERY_POLICY_CLIENT: {
882
      int32_t dbNum = taosArrayGetSize(pRequest->dbList);
11,754,443✔
883
      if (dbNum > 0) {
11,759,198✔
884
        SCatalog*     pCtg = NULL;
11,711,208✔
885
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
11,711,463✔
886
        code = catalogGetHandle(pInst->clusterId, &pCtg);
11,710,764✔
887
        if (code != TSDB_CODE_SUCCESS) {
11,709,916✔
888
          goto _return;
×
889
        }
890

891
        pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
11,709,916✔
892
        if (NULL == pDbVgList) {
11,712,184✔
893
          code = terrno;
×
894
          goto _return;
×
895
        }
896
        SArray* pVgList = NULL;
11,712,647✔
897
        for (int32_t i = 0; i < dbNum; ++i) {
23,423,005✔
898
          char*            dbFName = taosArrayGet(pRequest->dbList, i);
11,708,395✔
899
          SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
11,711,608✔
900
                                   .requestId = pRequest->requestId,
11,712,139✔
901
                                   .requestObjRefId = pRequest->self,
11,711,274✔
902
                                   .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
11,711,580✔
903

904
          // catalogGetDBVgList will handle dbFName == null.
905
          code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
11,714,652✔
906
          if (code) {
11,711,403✔
907
            goto _return;
×
908
          }
909

910
          if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
11,712,829✔
911
            code = terrno;
×
912
            goto _return;
×
913
          }
914
        }
915
      }
916

917
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
11,764,123✔
918
      break;
11,759,802✔
919
    }
920
    case QUERY_POLICY_HYBRID:
×
921
    case QUERY_POLICY_QNODE: {
922
      TSC_ERR_JRET(getQnodeList(pRequest, &pQnodeList));
×
923

924
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
×
925
      break;
×
926
    }
927
    default:
2,378✔
928
      tscError("unknown query policy: %d", tsQueryPolicy);
2,378✔
929
      return TSDB_CODE_APP_ERROR;
×
930
  }
931

932
_return:
11,758,425✔
933

934
  taosArrayDestroyEx(pDbVgList, freeVgList);
11,759,070✔
935
  taosArrayDestroy(pQnodeList);
11,758,286✔
936

937
  return code;
11,760,070✔
938
}
939

940
int32_t scheduleQuery(SRequestObj* pRequest, SQueryPlan* pDag, SArray* pNodeList) {
11,754,479✔
941
  void* pTransporter = pRequest->pTscObj->pAppInfo->pTransporter;
11,754,479✔
942

943
  SExecResult      res = {0};
11,756,667✔
944
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
11,755,965✔
945
                           .requestId = pRequest->requestId,
11,755,200✔
946
                           .requestObjRefId = pRequest->self};
11,755,278✔
947
  SSchedulerReq    req = {
18,016,451✔
948
         .syncReq = true,
949
         .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
11,755,287✔
950
         .pConn = &conn,
951
         .pNodeList = pNodeList,
952
         .pDag = pDag,
953
         .sql = pRequest->sqlstr,
11,755,287✔
954
         .startTs = pRequest->metric.start,
11,753,979✔
955
         .execFp = NULL,
956
         .cbParam = NULL,
957
         .chkKillFp = chkRequestKilled,
958
         .chkKillParam = (void*)pRequest->self,
11,754,537✔
959
         .pExecRes = &res,
960
         .source = pRequest->source,
11,755,425✔
961
         .pWorkerCb = getTaskPoolWorkerCb(),
11,755,660✔
962
  };
963

964
  int32_t code = schedulerExecJob(&req, &pRequest->body.queryJob);
11,756,188✔
965

966
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
11,762,661✔
967
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
11,761,819✔
968

969
  if (code != TSDB_CODE_SUCCESS) {
11,761,263✔
970
    schedulerFreeJob(&pRequest->body.queryJob, 0);
×
971

972
    pRequest->code = code;
×
973
    terrno = code;
×
974
    return pRequest->code;
×
975
  }
976

977
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_DELETE == pRequest->type ||
11,761,263✔
978
      TDMT_VND_CREATE_TABLE == pRequest->type) {
15,354✔
979
    pRequest->body.resInfo.numOfRows = res.numOfRows;
11,750,684✔
980
    if (TDMT_VND_SUBMIT == pRequest->type) {
11,750,937✔
981
      STscObj*            pTscObj = pRequest->pTscObj;
11,746,969✔
982
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
11,746,228✔
983
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
11,746,700✔
984
    }
985

986
    schedulerFreeJob(&pRequest->body.queryJob, 0);
11,751,887✔
987
  }
988

989
  pRequest->code = res.code;
11,762,314✔
990
  terrno = res.code;
11,762,371✔
991
  return pRequest->code;
11,762,266✔
992
}
993

994
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
456,595,378✔
995
  SArray*      pArray = NULL;
456,595,378✔
996
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
456,595,378✔
997
  if (NULL == pRsp->aCreateTbRsp) {
456,595,378✔
998
    return TSDB_CODE_SUCCESS;
447,782,988✔
999
  }
1000

1001
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
8,820,246✔
1002
  for (int32_t i = 0; i < tbNum; ++i) {
21,240,462✔
1003
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
12,417,512✔
1004
    if (pTbRsp->pMeta) {
12,417,541✔
1005
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
11,712,436✔
1006
    }
1007
  }
1008

1009
  return TSDB_CODE_SUCCESS;
8,822,950✔
1010
}
1011

1012
int32_t handleQueryExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
69,542,594✔
1013
  int32_t code = 0;
69,542,594✔
1014
  SArray* pArray = NULL;
69,542,594✔
1015
  SArray* pTbArray = (SArray*)res;
69,542,594✔
1016
  int32_t tbNum = taosArrayGetSize(pTbArray);
69,542,594✔
1017
  if (tbNum <= 0) {
69,542,876✔
1018
    return TSDB_CODE_SUCCESS;
×
1019
  }
1020

1021
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
69,542,876✔
1022
  if (NULL == pArray) {
69,541,652✔
1023
    return terrno;
×
1024
  }
1025

1026
  for (int32_t i = 0; i < tbNum; ++i) {
185,611,663✔
1027
    STbVerInfo* tbInfo = taosArrayGet(pTbArray, i);
116,069,578✔
1028
    if (NULL == tbInfo) {
116,070,031✔
1029
      code = terrno;
×
1030
      goto _return;
×
1031
    }
1032
    STbSVersion tbSver = {
116,070,031✔
1033
        .tbFName = tbInfo->tbFName, .sver = tbInfo->sversion, .tver = tbInfo->tversion, .rver = tbInfo->rversion};
116,070,284✔
1034
    if (NULL == taosArrayPush(pArray, &tbSver)) {
116,071,013✔
1035
      code = terrno;
×
1036
      goto _return;
×
1037
    }
1038
  }
1039

1040
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
69,542,085✔
1041
                           .requestId = pRequest->requestId,
69,543,098✔
1042
                           .requestObjRefId = pRequest->self,
69,541,665✔
1043
                           .mgmtEps = *epset};
1044

1045
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
69,541,425✔
1046

1047
_return:
69,541,405✔
1048

1049
  taosArrayDestroy(pArray);
69,540,512✔
1050
  return code;
69,541,988✔
1051
}
1052

1053
int32_t handleAlterTbExecRes(void* res, SCatalog* pCatalog) {
8,695,982✔
1054
  return catalogUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
8,695,982✔
1055
}
1056

1057
int32_t handleCreateTbExecRes(void* res, SCatalog* pCatalog) {
54,713,876✔
1058
  return catalogAsyncUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
54,713,876✔
1059
}
1060

1061
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
591,879,055✔
1062
  if (NULL == pRequest->body.resInfo.execRes.res) {
591,879,055✔
1063
    return pRequest->code;
25,139,659✔
1064
  }
1065

1066
  SCatalog*     pCatalog = NULL;
566,735,943✔
1067
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
566,737,562✔
1068

1069
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
566,756,370✔
1070
  if (code) {
566,740,826✔
1071
    return code;
×
1072
  }
1073

1074
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
566,740,826✔
1075
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
566,757,307✔
1076

1077
  switch (pRes->msgType) {
566,759,989✔
1078
    case TDMT_VND_ALTER_TABLE:
3,792,882✔
1079
    case TDMT_MND_ALTER_STB: {
1080
      code = handleAlterTbExecRes(pRes->res, pCatalog);
3,792,882✔
1081
      break;
3,792,882✔
1082
    }
1083
    case TDMT_VND_CREATE_TABLE: {
36,446,413✔
1084
      SArray* pList = (SArray*)pRes->res;
36,446,413✔
1085
      int32_t num = taosArrayGetSize(pList);
36,460,034✔
1086
      for (int32_t i = 0; i < num; ++i) {
77,490,074✔
1087
        void* res = taosArrayGetP(pList, i);
41,026,876✔
1088
        // handleCreateTbExecRes will handle res == null
1089
        code = handleCreateTbExecRes(res, pCatalog);
41,030,862✔
1090
      }
1091
      break;
36,463,198✔
1092
    }
1093
    case TDMT_MND_CREATE_STB: {
351,953✔
1094
      code = handleCreateTbExecRes(pRes->res, pCatalog);
351,953✔
1095
      break;
351,953✔
1096
    }
1097
    case TDMT_VND_SUBMIT: {
456,596,951✔
1098
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
456,596,951✔
1099

1100
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
456,607,345✔
1101
      break;
456,599,131✔
1102
    }
1103
    case TDMT_SCH_QUERY:
69,540,482✔
1104
    case TDMT_SCH_MERGE_QUERY: {
1105
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
69,540,482✔
1106
      break;
69,540,066✔
1107
    }
1108
    default:
1,474✔
1109
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self,
1,474✔
1110
               pRequest->type, pRequest->requestId);
1111
      code = TSDB_CODE_APP_ERROR;
×
1112
  }
1113

1114
  return code;
566,747,230✔
1115
}
1116

1117
static bool incompletaFileParsing(SNode* pStmt) {
578,782,368✔
1118
  return QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pStmt) ? false : ((SVnodeModifyOpStmt*)pStmt)->fileProcessing;
578,782,368✔
1119
}
1120

1121
void continuePostSubQuery(SRequestObj* pRequest, SSDataBlock* pBlock) {
×
1122
  SSqlCallbackWrapper* pWrapper = pRequest->pWrapper;
×
1123

1124
  int32_t code = nodesAcquireAllocator(pWrapper->pParseCtx->allocatorId);
×
1125
  if (TSDB_CODE_SUCCESS == code) {
×
1126
    int64_t analyseStart = taosGetTimestampUs();
×
1127
    code = qContinueParsePostQuery(pWrapper->pParseCtx, pRequest->pQuery, pBlock);
×
1128
    pRequest->metric.analyseCostUs += taosGetTimestampUs() - analyseStart;
×
1129
  }
1130

1131
  if (TSDB_CODE_SUCCESS == code) {
×
1132
    code = qContinuePlanPostQuery(pRequest->pPostPlan);
×
1133
  }
1134

1135
  code = nodesReleaseAllocator(pWrapper->pParseCtx->allocatorId);
×
1136
  handleQueryAnslyseRes(pWrapper, NULL, code);
×
1137
}
×
1138

1139
void returnToUser(SRequestObj* pRequest) {
12,351,489✔
1140
  if (pRequest->relation.userRefId == pRequest->self || 0 == pRequest->relation.userRefId) {
12,351,489✔
1141
    // return to client
1142
    doRequestCallback(pRequest, pRequest->code);
12,351,489✔
1143
    return;
12,351,489✔
1144
  }
1145

1146
  SRequestObj* pUserReq = acquireRequest(pRequest->relation.userRefId);
×
1147
  if (pUserReq) {
×
1148
    pUserReq->code = pRequest->code;
×
1149
    // return to client
1150
    doRequestCallback(pUserReq, pUserReq->code);
×
1151
    (void)releaseRequest(pRequest->relation.userRefId);
×
1152
    return;
×
1153
  } else {
1154
    tscError("req:0x%" PRIx64 ", user ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1155
             pRequest->relation.userRefId, pRequest->requestId);
1156
  }
1157
}
1158

1159
static int32_t createResultBlock(TAOS_RES* pRes, int32_t numOfRows, SSDataBlock** pBlock) {
×
1160
  int64_t     lastTs = 0;
×
1161
  TAOS_FIELD* pResFields = taos_fetch_fields(pRes);
×
1162
  int32_t     numOfFields = taos_num_fields(pRes);
×
1163

1164
  int32_t code = createDataBlock(pBlock);
×
1165
  if (code) {
×
1166
    return code;
×
1167
  }
1168

1169
  for (int32_t i = 0; i < numOfFields; ++i) {
×
1170
    SColumnInfoData colInfoData = createColumnInfoData(pResFields[i].type, pResFields[i].bytes, i + 1);
×
1171
    code = blockDataAppendColInfo(*pBlock, &colInfoData);
×
1172
    if (TSDB_CODE_SUCCESS != code) {
×
1173
      blockDataDestroy(*pBlock);
×
1174
      return code;
×
1175
    }
1176
  }
1177

1178
  code = blockDataEnsureCapacity(*pBlock, numOfRows);
×
1179
  if (TSDB_CODE_SUCCESS != code) {
×
1180
    blockDataDestroy(*pBlock);
×
1181
    return code;
×
1182
  }
1183

1184
  for (int32_t i = 0; i < numOfRows; ++i) {
×
1185
    TAOS_ROW pRow = taos_fetch_row(pRes);
×
1186
    if (NULL == pRow[0] || NULL == pRow[1] || NULL == pRow[2]) {
×
1187
      tscError("invalid data from vnode");
×
1188
      blockDataDestroy(*pBlock);
×
1189
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1190
    }
1191
    int64_t ts = *(int64_t*)pRow[0];
×
1192
    if (lastTs < ts) {
×
1193
      lastTs = ts;
×
1194
    }
1195

1196
    for (int32_t j = 0; j < numOfFields; ++j) {
×
1197
      SColumnInfoData* pColInfoData = taosArrayGet((*pBlock)->pDataBlock, j);
×
1198
      code = colDataSetVal(pColInfoData, i, pRow[j], false);
×
1199
      if (TSDB_CODE_SUCCESS != code) {
×
1200
        blockDataDestroy(*pBlock);
×
1201
        return code;
×
1202
      }
1203
    }
1204

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

1209
  (*pBlock)->info.window.ekey = lastTs;
×
1210
  (*pBlock)->info.rows = numOfRows;
×
1211

1212
  tscInfo("[create stream with histroy] lastKey:%" PRId64 " numOfRows:%d from all vgroups", lastTs, numOfRows);
×
1213
  return TSDB_CODE_SUCCESS;
×
1214
}
1215

1216
void postSubQueryFetchCb(void* param, TAOS_RES* res, int32_t rowNum) {
×
1217
  SRequestObj* pRequest = (SRequestObj*)res;
×
1218
  if (pRequest->code) {
×
1219
    returnToUser(pRequest);
×
1220
    return;
×
1221
  }
1222

1223
  SSDataBlock* pBlock = NULL;
×
1224
  pRequest->code = createResultBlock(res, rowNum, &pBlock);
×
1225
  if (TSDB_CODE_SUCCESS != pRequest->code) {
×
1226
    tscError("req:0x%" PRIx64 ", create result block failed, QID:0x%" PRIx64 " %s", pRequest->self, pRequest->requestId,
×
1227
             tstrerror(pRequest->code));
1228
    returnToUser(pRequest);
×
1229
    return;
×
1230
  }
1231

1232
  SRequestObj* pNextReq = acquireRequest(pRequest->relation.nextRefId);
×
1233
  if (pNextReq) {
×
1234
    continuePostSubQuery(pNextReq, pBlock);
×
1235
    (void)releaseRequest(pRequest->relation.nextRefId);
×
1236
  } else {
1237
    tscError("req:0x%" PRIx64 ", next req ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1238
             pRequest->relation.nextRefId, pRequest->requestId);
1239
  }
1240

1241
  blockDataDestroy(pBlock);
×
1242
}
1243

1244
void handlePostSubQuery(SSqlCallbackWrapper* pWrapper) {
×
1245
  SRequestObj* pRequest = pWrapper->pRequest;
×
1246
  if (TD_RES_QUERY(pRequest)) {
×
1247
    taosAsyncFetchImpl(pRequest, postSubQueryFetchCb, pWrapper);
×
1248
    return;
×
1249
  }
1250

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

1261
// todo refacto the error code  mgmt
1262
void schedulerExecCb(SExecResult* pResult, void* param, int32_t code) {
579,784,692✔
1263
  SSqlCallbackWrapper* pWrapper = param;
579,784,692✔
1264
  SRequestObj*         pRequest = pWrapper->pRequest;
579,784,692✔
1265
  STscObj*             pTscObj = pRequest->pTscObj;
579,798,018✔
1266

1267
  pRequest->code = code;
579,800,035✔
1268
  if (pResult) {
579,801,694✔
1269
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
579,765,605✔
1270
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
579,771,014✔
1271
  }
1272

1273
  int32_t type = pRequest->type;
579,775,297✔
1274
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
579,765,887✔
1275
    if (pResult) {
484,797,145✔
1276
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
484,791,424✔
1277

1278
      // record the insert rows
1279
      if (TDMT_VND_SUBMIT == type) {
484,797,148✔
1280
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
444,995,119✔
1281
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
444,999,672✔
1282
      }
1283
    }
1284
    schedulerFreeJob(&pRequest->body.queryJob, 0);
484,805,559✔
1285
  }
1286

1287
  taosMemoryFree(pResult);
579,788,779✔
1288
  tscDebug("req:0x%" PRIx64 ", enter scheduler exec cb, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
579,779,150✔
1289
           pRequest->requestId);
1290

1291
  if (code != TSDB_CODE_SUCCESS && NEED_CLIENT_HANDLE_ERROR(code) && pRequest->sqlstr != NULL &&
579,777,874✔
1292
      pRequest->stmtBindVersion == 0) {
46,235✔
1293
    tscDebug("req:0x%" PRIx64 ", client retry to handle the error, code:%s, tryCount:%d, QID:0x%" PRIx64,
46,235✔
1294
             pRequest->self, tstrerror(code), pRequest->retry, pRequest->requestId);
1295
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
46,235✔
1296
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1297
    }
1298
    restartAsyncQuery(pRequest, code);
46,235✔
1299
    return;
46,235✔
1300
  }
1301

1302
  tscTrace("req:0x%" PRIx64 ", scheduler exec cb, request type:%s", pRequest->self, TMSG_INFO(pRequest->type));
579,731,639✔
1303
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
579,731,639✔
1304
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
2,846,222✔
1305
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1306
    }
1307
  }
1308

1309
  pRequest->metric.execCostUs = taosGetTimestampUs() - pRequest->metric.execStart;
579,733,765✔
1310
  int32_t code1 = handleQueryExecRsp(pRequest);
579,741,676✔
1311
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
579,749,860✔
1312
    pRequest->code = code1;
×
1313
  }
1314

1315
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
1,158,533,022✔
1316
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
578,776,273✔
1317
    continueInsertFromCsv(pWrapper, pRequest);
11,440✔
1318
    return;
11,440✔
1319
  }
1320

1321
  if (pRequest->relation.nextRefId) {
579,749,780✔
1322
    handlePostSubQuery(pWrapper);
×
1323
  } else {
1324
    destorySqlCallbackWrapper(pWrapper);
579,744,930✔
1325
    pRequest->pWrapper = NULL;
579,723,476✔
1326

1327
    // return to client
1328
    doRequestCallback(pRequest, code);
579,726,534✔
1329
  }
1330
}
1331

1332
void launchQueryImpl(SRequestObj* pRequest, SQuery* pQuery, bool keepQuery, void** res) {
12,144,095✔
1333
  int32_t code = 0;
12,144,095✔
1334
  int32_t subplanNum = 0;
12,144,095✔
1335

1336
  if (pQuery->pRoot) {
12,144,095✔
1337
    pRequest->stmtType = pQuery->pRoot->type;
11,761,682✔
1338
  }
1339

1340
  if (pQuery->pRoot && !pRequest->inRetry) {
12,145,778✔
1341
    STscObj*            pTscObj = pRequest->pTscObj;
11,762,014✔
1342
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
11,762,249✔
1343
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type) {
11,761,309✔
1344
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
11,750,905✔
1345
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
10,507✔
1346
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
10,425✔
1347
    }
1348
  }
1349

1350
  pRequest->body.execMode = pQuery->execMode;
12,145,558✔
1351
  switch (pQuery->execMode) {
12,146,411✔
1352
    case QUERY_EXEC_MODE_LOCAL:
×
1353
      if (!pRequest->validateOnly) {
×
1354
        if (NULL == pQuery->pRoot) {
×
1355
          terrno = TSDB_CODE_INVALID_PARA;
×
1356
          code = terrno;
×
1357
        } else {
1358
          code = execLocalCmd(pRequest, pQuery);
×
1359
        }
1360
      }
1361
      break;
×
1362
    case QUERY_EXEC_MODE_RPC:
385,060✔
1363
      if (!pRequest->validateOnly) {
385,060✔
1364
        code = execDdlQuery(pRequest, pQuery);
385,060✔
1365
      }
1366
      break;
385,218✔
1367
    case QUERY_EXEC_MODE_SCHEDULE: {
11,760,074✔
1368
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
11,760,074✔
1369
      if (NULL == pMnodeList) {
11,762,212✔
1370
        code = terrno;
×
1371
        break;
×
1372
      }
1373
      SQueryPlan* pDag = NULL;
11,762,212✔
1374
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
11,762,178✔
1375
      if (TSDB_CODE_SUCCESS == code) {
11,758,643✔
1376
        pRequest->body.subplanNum = pDag->numOfSubplans;
11,759,257✔
1377
        if (!pRequest->validateOnly) {
11,758,408✔
1378
          SArray* pNodeList = NULL;
11,756,669✔
1379
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
11,756,977✔
1380
          if (TSDB_CODE_SUCCESS == code) {
11,760,082✔
1381
            code = scheduleQuery(pRequest, pDag, pNodeList);
11,761,371✔
1382
          }
1383
          taosArrayDestroy(pNodeList);
11,759,512✔
1384
        }
1385
      }
1386
      taosArrayDestroy(pMnodeList);
11,762,647✔
1387
      break;
11,762,166✔
1388
    }
1389
    case QUERY_EXEC_MODE_EMPTY_RESULT:
×
1390
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
1391
      break;
×
1392
    default:
×
1393
      break;
×
1394
  }
1395

1396
  if (!keepQuery) {
12,147,502✔
1397
    qDestroyQuery(pQuery);
×
1398
  }
1399

1400
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
12,147,502✔
1401
    int ret = removeMeta(pRequest->pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type));
33,399✔
1402
    if (TSDB_CODE_SUCCESS != ret) {
33,399✔
1403
      tscError("req:0x%" PRIx64 ", remove meta failed,code:%d, QID:0x%" PRIx64, pRequest->self, ret,
×
1404
               pRequest->requestId);
1405
    }
1406
  }
1407

1408
  if (TSDB_CODE_SUCCESS == code) {
12,147,044✔
1409
    code = handleQueryExecRsp(pRequest);
12,146,088✔
1410
  }
1411

1412
  if (TSDB_CODE_SUCCESS != code) {
12,146,327✔
1413
    pRequest->code = code;
29,065✔
1414
  }
1415

1416
  if (res) {
12,146,327✔
1417
    *res = pRequest->body.resInfo.execRes.res;
×
1418
    pRequest->body.resInfo.execRes.res = NULL;
×
1419
  }
1420
}
12,146,327✔
1421

1422
static int32_t asyncExecSchQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta,
580,193,997✔
1423
                                 SSqlCallbackWrapper* pWrapper) {
1424
  int32_t code = TSDB_CODE_SUCCESS;
580,193,997✔
1425
  pRequest->type = pQuery->msgType;
580,193,997✔
1426
  SArray*     pMnodeList = NULL;
580,248,917✔
1427
  SQueryPlan* pDag = NULL;
580,248,917✔
1428
  int64_t     st = taosGetTimestampUs();
580,229,589✔
1429

1430
  if (!pRequest->parseOnly) {
580,229,589✔
1431
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
580,242,242✔
1432
    if (NULL == pMnodeList) {
580,235,010✔
1433
      code = terrno;
×
1434
    }
1435
    SPlanContext cxt = {.queryId = pRequest->requestId,
623,508,950✔
1436
                        .acctId = pRequest->pTscObj->acctId,
580,268,272✔
1437
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
580,284,855✔
1438
                        .pAstRoot = pQuery->pRoot,
580,292,869✔
1439
                        .showRewrite = pQuery->showRewrite,
580,296,404✔
1440
                        .isView = pWrapper->pParseCtx->isView,
580,291,468✔
1441
                        .isAudit = pWrapper->pParseCtx->isAudit,
580,288,389✔
1442
                        .pMsg = pRequest->msgBuf,
580,279,398✔
1443
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1444
                        .pUser = pRequest->pTscObj->user,
580,276,596✔
1445
                        .sysInfo = pRequest->pTscObj->sysInfo,
580,268,154✔
1446
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
580,251,517✔
1447
                        .allocatorId = pRequest->stmtBindVersion > 0 ? 0 : pRequest->allocatorRefId};
580,264,789✔
1448
    if (TSDB_CODE_SUCCESS == code) {
580,272,887✔
1449
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
580,273,583✔
1450
    }
1451
    if (code) {
580,237,356✔
1452
      tscError("req:0x%" PRIx64 ", failed to create query plan, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
264,916✔
1453
               pRequest->requestId);
1454
    } else {
1455
      pRequest->body.subplanNum = pDag->numOfSubplans;
579,972,440✔
1456
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
580,001,341✔
1457
    }
1458
  }
1459

1460
  pRequest->metric.execStart = taosGetTimestampUs();
580,262,902✔
1461
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
580,267,756✔
1462

1463
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
601,871,564✔
1464
    SArray* pNodeList = NULL;
579,753,243✔
1465
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
579,738,128✔
1466
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
83,323,283✔
1467
    }
1468

1469
    SRequestConnInfo conn = {.pTrans = getAppInfo(pRequest)->pTransporter,
579,777,228✔
1470
                             .requestId = pRequest->requestId,
579,776,679✔
1471
                             .requestObjRefId = pRequest->self};
579,784,815✔
1472
    SSchedulerReq    req = {
601,402,757✔
1473
           .syncReq = false,
1474
           .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
579,753,518✔
1475
           .pConn = &conn,
1476
           .pNodeList = pNodeList,
1477
           .pDag = pDag,
1478
           .allocatorRefId = pRequest->allocatorRefId,
579,753,518✔
1479
           .sql = pRequest->sqlstr,
579,747,256✔
1480
           .startTs = pRequest->metric.start,
579,769,262✔
1481
           .execFp = schedulerExecCb,
1482
           .cbParam = pWrapper,
1483
           .chkKillFp = chkRequestKilled,
1484
           .chkKillParam = (void*)pRequest->self,
579,759,713✔
1485
           .pExecRes = NULL,
1486
           .source = pRequest->source,
579,754,485✔
1487
           .pWorkerCb = getTaskPoolWorkerCb(),
579,740,953✔
1488
    };
1489
    if (TSDB_CODE_SUCCESS == code) {
579,758,063✔
1490
      code = schedulerExecJob(&req, &pRequest->body.queryJob);
579,796,740✔
1491
    }
1492

1493
    taosArrayDestroy(pNodeList);
579,752,992✔
1494
  } else {
1495
    qDestroyQueryPlan(pDag);
509,928✔
1496
    tscDebug("req:0x%" PRIx64 ", plan not executed, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
491,438✔
1497
             pRequest->requestId);
1498
    destorySqlCallbackWrapper(pWrapper);
491,438✔
1499
    pRequest->pWrapper = NULL;
491,438✔
1500
    if (TSDB_CODE_SUCCESS != code) {
491,438✔
1501
      pRequest->code = terrno;
264,916✔
1502
    }
1503

1504
    doRequestCallback(pRequest, code);
491,438✔
1505
  }
1506

1507
  // todo not to be released here
1508
  taosArrayDestroy(pMnodeList);
580,290,507✔
1509

1510
  return code;
580,278,720✔
1511
}
1512

1513
void launchAsyncQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta, SSqlCallbackWrapper* pWrapper) {
603,864,023✔
1514
  int32_t code = 0;
603,864,023✔
1515

1516
  if (pRequest->parseOnly) {
603,864,023✔
1517
    doRequestCallback(pRequest, 0);
287,630✔
1518
    return;
287,630✔
1519
  }
1520

1521
  pRequest->body.execMode = pQuery->execMode;
603,593,132✔
1522
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
603,571,983✔
1523
    destorySqlCallbackWrapper(pWrapper);
23,324,038✔
1524
    pRequest->pWrapper = NULL;
23,324,104✔
1525
  }
1526

1527
  if (pQuery->pRoot && !pRequest->inRetry) {
603,557,390✔
1528
    STscObj*            pTscObj = pRequest->pTscObj;
603,561,590✔
1529
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
603,563,391✔
1530
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
603,575,619✔
1531
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
496,456,253✔
1532
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
444,958,140✔
1533
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
158,607,900✔
1534
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
77,760,248✔
1535
    }
1536
  }
1537

1538
  switch (pQuery->execMode) {
603,559,173✔
1539
    case QUERY_EXEC_MODE_LOCAL:
5,314,808✔
1540
      asyncExecLocalCmd(pRequest, pQuery);
5,314,808✔
1541
      break;
5,315,596✔
1542
    case QUERY_EXEC_MODE_RPC:
17,653,763✔
1543
      code = asyncExecDdlQuery(pRequest, pQuery);
17,653,763✔
1544
      break;
17,653,936✔
1545
    case QUERY_EXEC_MODE_SCHEDULE: {
580,221,544✔
1546
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
580,221,544✔
1547
      break;
580,280,972✔
1548
    }
1549
    case QUERY_EXEC_MODE_EMPTY_RESULT:
354,746✔
1550
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
354,746✔
1551
      doRequestCallback(pRequest, 0);
354,746✔
1552
      break;
354,746✔
1553
    default:
×
1554
      tscError("req:0x%" PRIx64 ", invalid execMode %d", pRequest->self, pQuery->execMode);
×
1555
      doRequestCallback(pRequest, -1);
×
1556
      break;
×
1557
  }
1558
}
1559

1560
int32_t refreshMeta(STscObj* pTscObj, SRequestObj* pRequest) {
11,594✔
1561
  SCatalog* pCatalog = NULL;
11,594✔
1562
  int32_t   code = 0;
11,594✔
1563
  int32_t   dbNum = taosArrayGetSize(pRequest->dbList);
11,594✔
1564
  int32_t   tblNum = taosArrayGetSize(pRequest->tableList);
11,594✔
1565

1566
  if (dbNum <= 0 && tblNum <= 0) {
11,594✔
1567
    return TSDB_CODE_APP_ERROR;
11,436✔
1568
  }
1569

1570
  code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
158✔
1571
  if (code != TSDB_CODE_SUCCESS) {
158✔
1572
    return code;
×
1573
  }
1574

1575
  SRequestConnInfo conn = {.pTrans = pTscObj->pAppInfo->pTransporter,
158✔
1576
                           .requestId = pRequest->requestId,
158✔
1577
                           .requestObjRefId = pRequest->self,
158✔
1578
                           .mgmtEps = getEpSet_s(&pTscObj->pAppInfo->mgmtEp)};
158✔
1579

1580
  for (int32_t i = 0; i < dbNum; ++i) {
316✔
1581
    char* dbFName = taosArrayGet(pRequest->dbList, i);
158✔
1582

1583
    // catalogRefreshDBVgInfo will handle dbFName == null.
1584
    code = catalogRefreshDBVgInfo(pCatalog, &conn, dbFName);
158✔
1585
    if (code != TSDB_CODE_SUCCESS) {
158✔
1586
      return code;
×
1587
    }
1588
  }
1589

1590
  for (int32_t i = 0; i < tblNum; ++i) {
316✔
1591
    SName* tableName = taosArrayGet(pRequest->tableList, i);
158✔
1592

1593
    // catalogRefreshTableMeta will handle tableName == null.
1594
    code = catalogRefreshTableMeta(pCatalog, &conn, tableName, -1);
158✔
1595
    if (code != TSDB_CODE_SUCCESS) {
158✔
1596
      return code;
×
1597
    }
1598
  }
1599

1600
  return code;
158✔
1601
}
1602

1603
int32_t removeMeta(STscObj* pTscObj, SArray* tbList, bool isView) {
4,159,876✔
1604
  SCatalog* pCatalog = NULL;
4,159,876✔
1605
  int32_t   tbNum = taosArrayGetSize(tbList);
4,159,876✔
1606
  int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
4,159,876✔
1607
  if (code != TSDB_CODE_SUCCESS) {
4,159,876✔
1608
    return code;
×
1609
  }
1610

1611
  if (isView) {
4,159,876✔
1612
    for (int32_t i = 0; i < tbNum; ++i) {
818,288✔
1613
      SName* pViewName = taosArrayGet(tbList, i);
409,144✔
1614
      char   dbFName[TSDB_DB_FNAME_LEN];
399,464✔
1615
      if (NULL == pViewName) {
409,144✔
1616
        continue;
×
1617
      }
1618
      (void)tNameGetFullDbName(pViewName, dbFName);
409,144✔
1619
      TSC_ERR_RET(catalogRemoveViewMeta(pCatalog, dbFName, 0, pViewName->tname, 0));
409,144✔
1620
    }
1621
  } else {
1622
    for (int32_t i = 0; i < tbNum; ++i) {
5,552,107✔
1623
      SName* pTbName = taosArrayGet(tbList, i);
1,801,375✔
1624
      TSC_ERR_RET(catalogRemoveTableMeta(pCatalog, pTbName));
1,801,375✔
1625
    }
1626
  }
1627

1628
  return TSDB_CODE_SUCCESS;
4,159,876✔
1629
}
1630

1631
int32_t initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet) {
3,155,701✔
1632
  pEpSet->version = 0;
3,155,701✔
1633

1634
  // init mnode ip set
1635
  SEpSet* mgmtEpSet = &(pEpSet->epSet);
3,155,701✔
1636
  mgmtEpSet->numOfEps = 0;
3,155,675✔
1637
  mgmtEpSet->inUse = 0;
3,155,175✔
1638

1639
  if (firstEp && firstEp[0] != 0) {
3,155,428✔
1640
    if (strlen(firstEp) >= TSDB_EP_LEN) {
3,155,628✔
1641
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1642
      return -1;
×
1643
    }
1644

1645
    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
3,155,628✔
1646
    if (code != TSDB_CODE_SUCCESS) {
3,154,799✔
1647
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1648
      return terrno;
×
1649
    }
1650
    // uint32_t addr = 0;
1651
    SIpAddr addr = {0};
3,154,799✔
1652
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
3,154,799✔
1653
    if (code) {
3,153,438✔
1654
      tscError("failed to resolve firstEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
924✔
1655
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1656
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
765✔
1657
    } else {
1658
      mgmtEpSet->numOfEps++;
3,152,564✔
1659
    }
1660
  }
1661

1662
  if (secondEp && secondEp[0] != 0) {
3,152,623✔
1663
    if (strlen(secondEp) >= TSDB_EP_LEN) {
2,029,790✔
1664
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1665
      return terrno;
×
1666
    }
1667

1668
    int32_t code = taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
2,029,790✔
1669
    if (code != TSDB_CODE_SUCCESS) {
2,030,055✔
1670
      return code;
×
1671
    }
1672
    SIpAddr addr = {0};
2,030,055✔
1673
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
2,030,055✔
1674
    if (code) {
2,030,309✔
1675
      tscError("failed to resolve secondEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
374✔
1676
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1677
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
×
1678
    } else {
1679
      mgmtEpSet->numOfEps++;
2,030,035✔
1680
    }
1681
  }
1682

1683
  if (mgmtEpSet->numOfEps == 0) {
3,153,113✔
1684
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
765✔
1685
    return TSDB_CODE_RPC_NETWORK_UNAVAIL;
765✔
1686
  }
1687

1688
  return 0;
3,151,855✔
1689
}
1690

1691
int32_t taosConnectImpl(const char* user, const char* auth, const char* db, __taos_async_fn_t fp, void* param,
3,155,910✔
1692
                        SAppInstInfo* pAppInfo, int connType, STscObj** pTscObj) {
1693
  *pTscObj = NULL;
3,155,910✔
1694
  int32_t code = createTscObj(user, auth, db, connType, pAppInfo, pTscObj);
3,155,910✔
1695
  if (TSDB_CODE_SUCCESS != code) {
3,155,910✔
1696
    return code;
×
1697
  }
1698

1699
  SRequestObj* pRequest = NULL;
3,155,910✔
1700
  code = createRequest((*pTscObj)->id, TDMT_MND_CONNECT, 0, &pRequest);
3,155,910✔
1701
  if (TSDB_CODE_SUCCESS != code) {
3,155,617✔
1702
    destroyTscObj(*pTscObj);
×
1703
    return code;
×
1704
  }
1705

1706
  pRequest->sqlstr = taosStrdup("taos_connect");
3,155,617✔
1707
  if (pRequest->sqlstr) {
3,155,906✔
1708
    pRequest->sqlLen = strlen(pRequest->sqlstr);
3,155,662✔
1709
  } else {
1710
    return terrno;
×
1711
  }
1712

1713
  SMsgSendInfo* body = NULL;
3,155,906✔
1714
  code = buildConnectMsg(pRequest, &body);
3,155,906✔
1715
  if (TSDB_CODE_SUCCESS != code) {
3,154,502✔
1716
    destroyTscObj(*pTscObj);
×
1717
    return code;
×
1718
  }
1719

1720
  // int64_t transporterId = 0;
1721
  SEpSet epset = getEpSet_s(&(*pTscObj)->pAppInfo->mgmtEp);
3,154,502✔
1722
  code = asyncSendMsgToServer((*pTscObj)->pAppInfo->pTransporter, &epset, NULL, body);
3,155,910✔
1723
  if (TSDB_CODE_SUCCESS != code) {
3,155,910✔
1724
    destroyTscObj(*pTscObj);
×
1725
    tscError("failed to send connect msg to server, code:%s", tstrerror(code));
×
1726
    return code;
×
1727
  }
1728
  if (TSDB_CODE_SUCCESS != tsem_wait(&pRequest->body.rspSem)) {
3,155,910✔
1729
    destroyTscObj(*pTscObj);
×
1730
    tscError("failed to wait sem, code:%s", terrstr());
×
1731
    return terrno;
×
1732
  }
1733
  if (pRequest->code != TSDB_CODE_SUCCESS) {
3,155,910✔
1734
    const char* errorMsg = (code == TSDB_CODE_RPC_FQDN_ERROR) ? taos_errstr(pRequest) : tstrerror(pRequest->code);
19,406✔
1735
    tscError("failed to connect to server, reason: %s", errorMsg);
19,406✔
1736

1737
    terrno = pRequest->code;
19,406✔
1738
    destroyRequest(pRequest);
19,406✔
1739
    taos_close_internal(*pTscObj);
19,406✔
1740
    *pTscObj = NULL;
19,406✔
1741
    return terrno;
19,406✔
1742
  } else {
1743
    tscInfo("conn:0x%" PRIx64 ", connection is opening, connId:%u, dnodeConn:%p, QID:0x%" PRIx64, (*pTscObj)->id,
3,136,504✔
1744
            (*pTscObj)->connId, (*pTscObj)->pAppInfo->pTransporter, pRequest->requestId);
1745
    destroyRequest(pRequest);
3,136,504✔
1746
  }
1747
  return code;
3,136,504✔
1748
}
1749

1750
static int32_t buildConnectMsg(SRequestObj* pRequest, SMsgSendInfo** pMsgSendInfo) {
3,154,882✔
1751
  *pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
3,154,882✔
1752
  if (*pMsgSendInfo == NULL) {
3,155,666✔
1753
    return terrno;
×
1754
  }
1755

1756
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
3,155,272✔
1757

1758
  (*pMsgSendInfo)->requestObjRefId = pRequest->self;
3,155,910✔
1759
  (*pMsgSendInfo)->requestId = pRequest->requestId;
3,155,272✔
1760
  (*pMsgSendInfo)->fp = getMsgRspHandle((*pMsgSendInfo)->msgType);
3,155,516✔
1761
  (*pMsgSendInfo)->param = taosMemoryCalloc(1, sizeof(pRequest->self));
3,155,410✔
1762
  if (NULL == (*pMsgSendInfo)->param) {
3,155,507✔
1763
    taosMemoryFree(*pMsgSendInfo);
×
1764
    return terrno;
×
1765
  }
1766

1767
  *(int64_t*)(*pMsgSendInfo)->param = pRequest->self;
3,154,869✔
1768

1769
  SConnectReq connectReq = {0};
3,155,263✔
1770
  STscObj*    pObj = pRequest->pTscObj;
3,155,263✔
1771

1772
  char* db = getDbOfConnection(pObj);
3,154,864✔
1773
  if (db != NULL) {
3,155,910✔
1774
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
1,447,712✔
1775
  } else if (terrno) {
1,708,198✔
1776
    taosMemoryFree(*pMsgSendInfo);
×
1777
    return terrno;
×
1778
  }
1779
  taosMemoryFreeClear(db);
3,155,908✔
1780

1781
  connectReq.connType = pObj->connType;
3,156,166✔
1782
  connectReq.pid = appInfo.pid;
3,156,016✔
1783
  connectReq.startTime = appInfo.startTime;
3,155,772✔
1784

1785
  tstrncpy(connectReq.app, appInfo.appName, sizeof(connectReq.app));
3,155,772✔
1786
  tstrncpy(connectReq.user, pObj->user, sizeof(connectReq.user));
3,155,373✔
1787
  tstrncpy(connectReq.passwd, pObj->pass, sizeof(connectReq.passwd));
3,156,016✔
1788
  tstrncpy(connectReq.sVer, td_version, sizeof(connectReq.sVer));
3,156,016✔
1789

1790
  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connectReq);
3,156,016✔
1791
  void*   pReq = taosMemoryMalloc(contLen);
3,154,571✔
1792
  if (NULL == pReq) {
3,155,388✔
1793
    taosMemoryFree(*pMsgSendInfo);
×
1794
    return terrno;
×
1795
  }
1796

1797
  if (-1 == tSerializeSConnectReq(pReq, contLen, &connectReq)) {
3,155,388✔
1798
    taosMemoryFree(*pMsgSendInfo);
379✔
1799
    taosMemoryFree(pReq);
×
1800
    return terrno;
×
1801
  }
1802

1803
  (*pMsgSendInfo)->msgInfo.len = contLen;
3,155,235✔
1804
  (*pMsgSendInfo)->msgInfo.pData = pReq;
3,154,991✔
1805
  return TSDB_CODE_SUCCESS;
3,154,986✔
1806
}
1807

1808
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,012,337,086✔
1809
  if (NULL == pEpSet) {
1,012,337,086✔
1810
    return;
1,000,217,163✔
1811
  }
1812

1813
  switch (pSendInfo->target.type) {
12,119,923✔
1814
    case TARGET_TYPE_MNODE:
640✔
1815
      if (NULL == pTscObj) {
640✔
1816
        tscError("mnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1817
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1818
        return;
×
1819
      }
1820

1821
      SEpSet  originEpset = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
640✔
1822
      SEpSet* pOrig = &originEpset;
640✔
1823
      SEp*    pOrigEp = &pOrig->eps[pOrig->inUse];
640✔
1824
      SEp*    pNewEp = &pEpSet->eps[pEpSet->inUse];
640✔
1825
      tscDebug("mnode epset updated from %d/%d=>%s:%d to %d/%d=>%s:%d in client", pOrig->inUse, pOrig->numOfEps,
640✔
1826
               pOrigEp->fqdn, pOrigEp->port, pEpSet->inUse, pEpSet->numOfEps, pNewEp->fqdn, pNewEp->port);
1827
      updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
640✔
1828
      break;
8,313,062✔
1829
    case TARGET_TYPE_VNODE: {
11,867,588✔
1830
      if (NULL == pTscObj) {
11,867,588✔
1831
        tscError("vnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1832
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1833
        return;
×
1834
      }
1835

1836
      SCatalog* pCatalog = NULL;
11,867,588✔
1837
      int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
11,867,588✔
1838
      if (code != TSDB_CODE_SUCCESS) {
11,867,245✔
1839
        tscError("fail to get catalog handle, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1840
                 tstrerror(code));
1841
        return;
×
1842
      }
1843

1844
      code = catalogUpdateVgEpSet(pCatalog, pSendInfo->target.dbFName, pSendInfo->target.vgId, pEpSet);
11,867,245✔
1845
      if (code != TSDB_CODE_SUCCESS) {
11,868,925✔
1846
        tscError("fail to update catalog vg epset, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1847
                 tstrerror(code));
1848
        return;
×
1849
      }
1850
      taosMemoryFreeClear(pSendInfo->target.dbFName);
11,868,925✔
1851
      break;
11,869,121✔
1852
    }
1853
    default:
252,287✔
1854
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
252,287✔
1855
      break;
252,294✔
1856
  }
1857
}
1858

1859
int32_t doProcessMsgFromServerImpl(SRpcMsg* pMsg, SEpSet* pEpSet) {
1,012,923,566✔
1860
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
1,012,923,566✔
1861
  if (pMsg->info.ahandle == NULL) {
1,012,924,808✔
1862
    tscError("doProcessMsgFromServer pMsg->info.ahandle == NULL");
579,898✔
1863
    rpcFreeCont(pMsg->pCont);
579,898✔
1864
    taosMemoryFree(pEpSet);
579,898✔
1865
    return TSDB_CODE_TSC_INTERNAL_ERROR;
579,898✔
1866
  }
1867

1868
  STscObj* pTscObj = NULL;
1,012,342,716✔
1869

1870
  STraceId* trace = &pMsg->info.traceId;
1,012,342,716✔
1871
  char      tbuf[40] = {0};
1,012,344,410✔
1872
  TRACE_TO_STR(trace, tbuf);
1,012,345,607✔
1873

1874
  tscDebug("QID:%s, process message from server, handle:%p, message:%s, size:%d, code:%s", tbuf, pMsg->info.handle,
1,012,347,275✔
1875
           TMSG_INFO(pMsg->msgType), pMsg->contLen, tstrerror(pMsg->code));
1876

1877
  if (pSendInfo->requestObjRefId != 0) {
1,012,348,369✔
1878
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
871,768,021✔
1879
    if (pRequest) {
871,766,320✔
1880
      if (pRequest->self != pSendInfo->requestObjRefId) {
871,506,768✔
1881
        tscError("doProcessMsgFromServer req:0x%" PRId64 " != pSendInfo->requestObjRefId:0x%" PRId64, pRequest->self,
×
1882
                 pSendInfo->requestObjRefId);
1883

1884
        if (TSDB_CODE_SUCCESS != taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId)) {
×
1885
          tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1886
        }
1887
        rpcFreeCont(pMsg->pCont);
×
1888
        taosMemoryFree(pEpSet);
×
1889
        destroySendMsgInfo(pSendInfo);
×
1890
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1891
      }
1892
      pTscObj = pRequest->pTscObj;
871,506,662✔
1893
    }
1894
  }
1895

1896
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
1,012,346,550✔
1897

1898
  SDataBuf buf = {.msgType = pMsg->msgType,
1,012,339,114✔
1899
                  .len = pMsg->contLen,
1,012,339,665✔
1900
                  .pData = NULL,
1901
                  .handle = pMsg->info.handle,
1,012,340,783✔
1902
                  .handleRefId = pMsg->info.refId,
1,012,340,829✔
1903
                  .pEpSet = pEpSet};
1904

1905
  if (pMsg->contLen > 0) {
1,012,341,818✔
1906
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
989,683,002✔
1907
    if (buf.pData == NULL) {
989,684,409✔
1908
      pMsg->code = terrno;
×
1909
    } else {
1910
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
989,684,409✔
1911
    }
1912
  }
1913

1914
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
1,012,347,381✔
1915

1916
  if (pTscObj) {
1,012,315,611✔
1917
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
871,486,274✔
1918
    if (TSDB_CODE_SUCCESS != code) {
871,507,237✔
1919
      tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1920
      terrno = code;
×
1921
      pMsg->code = code;
×
1922
    }
1923
  }
1924

1925
  rpcFreeCont(pMsg->pCont);
1,012,336,574✔
1926
  destroySendMsgInfo(pSendInfo);
1,012,321,995✔
1927
  return TSDB_CODE_SUCCESS;
1,012,316,103✔
1928
}
1929

1930
int32_t doProcessMsgFromServer(void* param) {
1,012,925,953✔
1931
  AsyncArg* arg = (AsyncArg*)param;
1,012,925,953✔
1932
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
1,012,925,953✔
1933
  taosMemoryFree(arg);
1,012,885,965✔
1934
  return code;
1,012,890,261✔
1935
}
1936

1937
void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,012,914,635✔
1938
  int32_t code = 0;
1,012,914,635✔
1939
  SEpSet* tEpSet = NULL;
1,012,914,635✔
1940

1941
  tscDebug("msg callback, ahandle %p", pMsg->info.ahandle);
1,012,914,635✔
1942

1943
  if (pEpSet != NULL) {
1,012,914,880✔
1944
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
12,121,170✔
1945
    if (NULL == tEpSet) {
12,120,118✔
1946
      code = terrno;
×
1947
      pMsg->code = terrno;
×
1948
      goto _exit;
×
1949
    }
1950
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
12,120,118✔
1951
  }
1952

1953
  // pMsg is response msg
1954
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
1,012,913,828✔
1955
    // restore origin code
1956
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
3,155,796✔
1957
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1958
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
3,155,545✔
1959
      pMsg->code = TSDB_CODE_RPC_BROKEN_LINK;
×
1960
    }
1961
  } else {
1962
    // uniform to one error code: TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED
1963
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
1,009,760,657✔
1964
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
1965
    }
1966
  }
1967

1968
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
1,012,918,603✔
1969
  if (NULL == arg) {
1,012,906,074✔
1970
    code = terrno;
×
1971
    pMsg->code = code;
×
1972
    goto _exit;
×
1973
  }
1974

1975
  arg->msg = *pMsg;
1,012,906,074✔
1976
  arg->pEpset = tEpSet;
1,012,912,148✔
1977

1978
  if ((code = taosAsyncExec(doProcessMsgFromServer, arg, NULL)) != 0) {
1,012,915,621✔
1979
    pMsg->code = code;
78✔
1980
    taosMemoryFree(arg);
78✔
1981
    goto _exit;
×
1982
  }
1983
  return;
1,012,918,560✔
1984

1985
_exit:
×
1986
  tscError("failed to sched msg to tsc since %s", tstrerror(code));
×
1987
  code = doProcessMsgFromServerImpl(pMsg, tEpSet);
×
1988
  if (code != 0) {
×
1989
    tscError("failed to sched msg to tsc, tsc ready quit");
×
1990
  }
1991
}
1992

1993
TAOS* taos_connect_auth(const char* ip, const char* user, const char* auth, const char* db, uint16_t port) {
759✔
1994
  tscInfo("try to connect to %s:%u by auth, user:%s db:%s", ip, port, user, db);
759✔
1995
  if (user == NULL) {
759✔
1996
    user = TSDB_DEFAULT_USER;
×
1997
  }
1998

1999
  if (auth == NULL) {
759✔
2000
    tscError("No auth info is given, failed to connect to server");
×
2001
    return NULL;
×
2002
  }
2003

2004
  STscObj* pObj = NULL;
759✔
2005
  int32_t  code = taos_connect_internal(ip, user, NULL, auth, db, port, CONN_TYPE__QUERY, &pObj);
759✔
2006
  if (TSDB_CODE_SUCCESS == code) {
759✔
2007
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
133✔
2008
    if (NULL == rid) {
133✔
2009
      tscError("out of memory when taos connect to %s:%u, user:%s db:%s", ip, port, user, db);
×
2010
    }
2011
    *rid = pObj->id;
133✔
2012
    return (TAOS*)rid;
133✔
2013
  }
2014

2015
  return NULL;
626✔
2016
}
2017

2018
// TAOS* taos_connect_l(const char* ip, int ipLen, const char* user, int userLen, const char* pass, int passLen,
2019
//                      const char* db, int dbLen, uint16_t port) {
2020
//   char ipStr[TSDB_EP_LEN] = {0};
2021
//   char dbStr[TSDB_DB_NAME_LEN] = {0};
2022
//   char userStr[TSDB_USER_LEN] = {0};
2023
//   char passStr[TSDB_PASSWORD_LEN] = {0};
2024
//
2025
//   tstrncpy(ipStr, ip, TMIN(TSDB_EP_LEN - 1, ipLen));
2026
//   tstrncpy(userStr, user, TMIN(TSDB_USER_LEN - 1, userLen));
2027
//   tstrncpy(passStr, pass, TMIN(TSDB_PASSWORD_LEN - 1, passLen));
2028
//   tstrncpy(dbStr, db, TMIN(TSDB_DB_NAME_LEN - 1, dbLen));
2029
//   return taos_connect(ipStr, userStr, passStr, dbStr, port);
2030
// }
2031

2032
void doSetOneRowPtr(SReqResultInfo* pResultInfo) {
2,147,483,647✔
2033
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
2,147,483,647✔
2034
    SResultColumn* pCol = &pResultInfo->pCol[i];
2,147,483,647✔
2035

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

2039
    if (IS_VAR_DATA_TYPE(type)) {
2,147,483,647✔
2040
      if (!IS_VAR_NULL_TYPE(type, schemaBytes) && pCol->offset[pResultInfo->current] != -1) {
2,147,483,647✔
2041
        char* pStart = pResultInfo->pCol[i].offset[pResultInfo->current] + pResultInfo->pCol[i].pData;
1,919,720,576✔
2042

2043
        if (IS_STR_DATA_BLOB(type)) {
1,919,866,139✔
2044
          pResultInfo->length[i] = blobDataLen(pStart);
42,671✔
2045
          pResultInfo->row[i] = blobDataVal(pStart);
×
2046
        } else {
2047
          pResultInfo->length[i] = varDataLen(pStart);
1,919,823,468✔
2048
          pResultInfo->row[i] = varDataVal(pStart);
1,919,483,933✔
2049
        }
2050
      } else {
2051
        pResultInfo->row[i] = NULL;
46,014,749✔
2052
        pResultInfo->length[i] = 0;
46,190,338✔
2053
      }
2054
    } else {
2055
      if (!colDataIsNull_f(pCol, pResultInfo->current)) {
2,147,483,647✔
2056
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + schemaBytes * pResultInfo->current;
2,147,483,647✔
2057
        pResultInfo->length[i] = schemaBytes;
2,147,483,647✔
2058
      } else {
2059
        pResultInfo->row[i] = NULL;
216,864,767✔
2060
        pResultInfo->length[i] = 0;
218,981,862✔
2061
      }
2062
    }
2063
  }
2064
}
2,147,483,647✔
2065

2066
void* doFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
×
2067
  if (pRequest == NULL) {
×
2068
    return NULL;
×
2069
  }
2070

2071
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
×
2072
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
×
2073
    // All data has returned to App already, no need to try again
2074
    if (pResultInfo->completed) {
×
2075
      pResultInfo->numOfRows = 0;
×
2076
      return NULL;
×
2077
    }
2078

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

2082
    pRequest->code = schedulerFetchRows(pRequest->body.queryJob, &req);
×
2083
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2084
      pResultInfo->numOfRows = 0;
×
2085
      return NULL;
×
2086
    }
2087

2088
    pRequest->code = setQueryResultFromRsp(&pRequest->body.resInfo, (const SRetrieveTableRsp*)pResInfo->pData,
×
2089
                                           convertUcs4, pRequest->stmtBindVersion > 0);
×
2090
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2091
      pResultInfo->numOfRows = 0;
×
2092
      return NULL;
×
2093
    }
2094

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

2099
    STscObj*            pTscObj = pRequest->pTscObj;
×
2100
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
×
2101
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
×
2102

2103
    if (pResultInfo->numOfRows == 0) {
×
2104
      return NULL;
×
2105
    }
2106
  }
2107

2108
  if (setupOneRowPtr) {
×
2109
    doSetOneRowPtr(pResultInfo);
×
2110
    pResultInfo->current += 1;
×
2111
  }
2112

2113
  return pResultInfo->row;
×
2114
}
2115

2116
static void syncFetchFn(void* param, TAOS_RES* res, int32_t numOfRows) {
95,621,412✔
2117
  tsem_t* sem = param;
95,621,412✔
2118
  if (TSDB_CODE_SUCCESS != tsem_post(sem)) {
95,621,412✔
2119
    tscError("failed to post sem, code:%s", terrstr());
×
2120
  }
2121
}
95,621,908✔
2122

2123
void* doAsyncFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
1,096,227,183✔
2124
  if (pRequest == NULL) {
1,096,227,183✔
2125
    return NULL;
×
2126
  }
2127

2128
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
1,096,227,183✔
2129
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
1,096,281,387✔
2130
    // All data has returned to App already, no need to try again
2131
    if (pResultInfo->completed) {
167,732,943✔
2132
      pResultInfo->numOfRows = 0;
72,124,083✔
2133
      return NULL;
72,124,532✔
2134
    }
2135

2136
    // convert ucs4 to native multi-bytes string
2137
    pResultInfo->convertUcs4 = convertUcs4;
95,622,357✔
2138
    tsem_t sem;
86,771,217✔
2139
    if (TSDB_CODE_SUCCESS != tsem_init(&sem, 0, 0)) {
95,621,660✔
2140
      tscError("failed to init sem, code:%s", terrstr());
×
2141
    }
2142
    taos_fetch_rows_a(pRequest, syncFetchFn, &sem);
95,621,660✔
2143
    if (TSDB_CODE_SUCCESS != tsem_wait(&sem)) {
95,621,908✔
2144
      tscError("failed to wait sem, code:%s", terrstr());
×
2145
    }
2146
    if (TSDB_CODE_SUCCESS != tsem_destroy(&sem)) {
95,621,660✔
2147
      tscError("failed to destroy sem, code:%s", terrstr());
×
2148
    }
2149
    pRequest->inCallback = false;
95,621,908✔
2150
  }
2151

2152
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
1,024,180,324✔
2153
    return NULL;
6,878,823✔
2154
  } else {
2155
    if (setupOneRowPtr) {
1,017,261,542✔
2156
      doSetOneRowPtr(pResultInfo);
930,283,458✔
2157
      pResultInfo->current += 1;
930,305,905✔
2158
    }
2159

2160
    return pResultInfo->row;
1,017,286,657✔
2161
  }
2162
}
2163

2164
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
127,224,422✔
2165
  if (pResInfo->row == NULL) {
127,224,422✔
2166
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
108,841,846✔
2167
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
108,842,241✔
2168
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
108,839,540✔
2169
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
108,841,206✔
2170

2171
    if (pResInfo->row == NULL || pResInfo->pCol == NULL || pResInfo->length == NULL || pResInfo->convertBuf == NULL) {
108,840,919✔
2172
      taosMemoryFree(pResInfo->row);
×
2173
      taosMemoryFree(pResInfo->pCol);
×
2174
      taosMemoryFree(pResInfo->length);
×
2175
      taosMemoryFree(pResInfo->convertBuf);
×
2176
      return terrno;
×
2177
    }
2178
  }
2179

2180
  return TSDB_CODE_SUCCESS;
127,225,930✔
2181
}
2182

2183
static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength, bool isStmt) {
126,013,124✔
2184
  int32_t idx = -1;
126,013,124✔
2185
  iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt);
126,014,294✔
2186
  if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR;
126,010,873✔
2187

2188
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
705,626,650✔
2189
    int32_t type = pResultInfo->fields[i].type;
579,622,436✔
2190
    int32_t schemaBytes =
2191
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
579,623,377✔
2192

2193
    if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) {
579,617,427✔
2194
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
20,404,577✔
2195
      if (p == NULL) {
20,404,577✔
2196
        taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
×
2197
        return terrno;
×
2198
      }
2199

2200
      pResultInfo->convertBuf[i] = p;
20,404,577✔
2201

2202
      SResultColumn* pCol = &pResultInfo->pCol[i];
20,404,577✔
2203
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
2,147,483,647✔
2204
        if (pCol->offset[j] != -1) {
2,147,483,647✔
2205
          char* pStart = pCol->offset[j] + pCol->pData;
2,147,483,647✔
2206

2207
          int32_t len = taosUcs4ToMbsEx((TdUcs4*)varDataVal(pStart), varDataLen(pStart), varDataVal(p), conv);
2,147,483,647✔
2208
          if (len < 0 || len > schemaBytes || (p + len) >= (pResultInfo->convertBuf[i] + colLength[i])) {
2,147,483,647✔
2209
            tscError(
400✔
2210
                "doConvertUCS4 error, invalid data. len:%d, bytes:%d, (p + len):%p, (pResultInfo->convertBuf[i] + "
2211
                "colLength[i]):%p",
2212
                len, schemaBytes, (p + len), (pResultInfo->convertBuf[i] + colLength[i]));
2213
            taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
400✔
2214
            return TSDB_CODE_TSC_INTERNAL_ERROR;
328✔
2215
          }
2216

2217
          varDataSetLen(p, len);
2,147,483,647✔
2218
          pCol->offset[j] = (p - pResultInfo->convertBuf[i]);
2,147,483,647✔
2219
          p += (len + VARSTR_HEADER_SIZE);
2,147,483,647✔
2220
        }
2221
      }
2222

2223
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
20,404,249✔
2224
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
20,404,249✔
2225
    }
2226
  }
2227
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
126,012,265✔
2228
  return TSDB_CODE_SUCCESS;
126,013,163✔
2229
}
2230

2231
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
126,012,195✔
2232
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
705,617,625✔
2233
    TAOS_FIELD_E* pFieldE = pResultInfo->fields + i;
579,612,794✔
2234
    TAOS_FIELD*   pField = pResultInfo->userFields + i;
579,608,021✔
2235
    int32_t       type = pFieldE->type;
579,610,392✔
2236
    int32_t       bufLen = 0;
579,605,914✔
2237
    char*         p = NULL;
579,605,914✔
2238
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
579,605,914✔
2239
      continue;
577,972,077✔
2240
    } else {
2241
      bufLen = 64;
1,635,129✔
2242
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
1,635,129✔
2243
      pFieldE->bytes = bufLen;
1,635,129✔
2244
      pField->bytes = bufLen;
1,635,129✔
2245
    }
2246
    if (!p) return terrno;
1,635,129✔
2247
    pResultInfo->convertBuf[i] = p;
1,635,129✔
2248

2249
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
1,004,107,653✔
2250
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
1,002,472,524✔
2251
                                  pFieldE->precision, pFieldE->scale, p, bufLen);
1,002,472,524✔
2252
      p += bufLen;
1,002,472,524✔
2253
      if (TSDB_CODE_SUCCESS != code) {
1,002,472,524✔
2254
        return code;
×
2255
      }
2256
    }
2257
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
1,635,129✔
2258
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
1,635,129✔
2259
  }
2260
  return 0;
126,010,903✔
2261
}
2262

2263
int32_t getVersion1BlockMetaSize(const char* p, int32_t numOfCols) {
382,032✔
2264
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) * 3 + sizeof(uint64_t) +
764,064✔
2265
         numOfCols * (sizeof(int8_t) + sizeof(int32_t));
382,032✔
2266
}
2267

2268
static int32_t estimateJsonLen(SReqResultInfo* pResultInfo) {
191,016✔
2269
  char*   p = (char*)pResultInfo->pData;
191,016✔
2270
  int32_t blockVersion = *(int32_t*)p;
191,016✔
2271

2272
  int32_t numOfRows = pResultInfo->numOfRows;
191,016✔
2273
  int32_t numOfCols = pResultInfo->numOfCols;
191,016✔
2274

2275
  // | version | total length | total rows | total columns | flag seg| block group id | column schema | each column
2276
  // length |
2277
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
191,016✔
2278
  if (numOfCols != cols) {
191,016✔
2279
    tscError("estimateJsonLen error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2280
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2281
  }
2282

2283
  int32_t  len = getVersion1BlockMetaSize(p, numOfCols);
191,016✔
2284
  int32_t* colLength = (int32_t*)(p + len);
191,016✔
2285
  len += sizeof(int32_t) * numOfCols;
191,016✔
2286

2287
  char* pStart = p + len;
191,016✔
2288
  for (int32_t i = 0; i < numOfCols; ++i) {
830,477✔
2289
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
639,461✔
2290

2291
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
639,461✔
2292
      int32_t* offset = (int32_t*)pStart;
226,336✔
2293
      int32_t  lenTmp = numOfRows * sizeof(int32_t);
226,336✔
2294
      len += lenTmp;
226,336✔
2295
      pStart += lenTmp;
226,336✔
2296

2297
      int32_t estimateColLen = 0;
226,336✔
2298
      for (int32_t j = 0; j < numOfRows; ++j) {
1,183,513✔
2299
        if (offset[j] == -1) {
957,177✔
2300
          continue;
48,114✔
2301
        }
2302
        char* data = offset[j] + pStart;
909,063✔
2303

2304
        int32_t jsonInnerType = *data;
909,063✔
2305
        char*   jsonInnerData = data + CHAR_BYTES;
909,063✔
2306
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
909,063✔
2307
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
12,792✔
2308
        } else if (tTagIsJson(data)) {
896,271✔
2309
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
210,786✔
2310
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
685,485✔
2311
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
637,515✔
2312
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
47,970✔
2313
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
35,178✔
2314
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
12,792✔
2315
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
12,792✔
2316
        } else if (IS_STR_DATA_BLOB(jsonInnerType)) {
×
2317
          estimateColLen += (BLOBSTR_HEADER_SIZE + 32);
×
2318
        } else {
2319
          tscError("estimateJsonLen error: invalid type:%d", jsonInnerType);
×
2320
          return -1;
×
2321
        }
2322
      }
2323
      len += TMAX(colLen, estimateColLen);
226,336✔
2324
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
413,125✔
2325
      int32_t lenTmp = numOfRows * sizeof(int32_t);
53,300✔
2326
      len += (lenTmp + colLen);
53,300✔
2327
      pStart += lenTmp;
53,300✔
2328
    } else {
2329
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
359,825✔
2330
      len += (lenTmp + colLen);
359,825✔
2331
      pStart += lenTmp;
359,825✔
2332
    }
2333
    pStart += colLen;
639,461✔
2334
  }
2335

2336
  // Ensure the complete structure of the block, including the blankfill field,
2337
  // even though it is not used on the client side.
2338
  len += sizeof(bool);
191,016✔
2339
  return len;
191,016✔
2340
}
2341

2342
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
127,224,329✔
2343
  int32_t numOfRows = pResultInfo->numOfRows;
127,224,329✔
2344
  int32_t numOfCols = pResultInfo->numOfCols;
127,225,270✔
2345
  bool    needConvert = false;
127,224,867✔
2346
  for (int32_t i = 0; i < numOfCols; ++i) {
713,813,966✔
2347
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
586,778,416✔
2348
      needConvert = true;
191,016✔
2349
      break;
191,016✔
2350
    }
2351
  }
2352

2353
  if (!needConvert) {
127,226,566✔
2354
    return TSDB_CODE_SUCCESS;
127,035,550✔
2355
  }
2356

2357
  tscDebug("start to convert form json format string");
191,016✔
2358

2359
  char*   p = (char*)pResultInfo->pData;
191,016✔
2360
  int32_t blockVersion = *(int32_t*)p;
191,016✔
2361
  int32_t dataLen = estimateJsonLen(pResultInfo);
191,016✔
2362
  if (dataLen <= 0) {
191,016✔
2363
    tscError("doConvertJson error: estimateJsonLen failed");
×
2364
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2365
  }
2366

2367
  taosMemoryFreeClear(pResultInfo->convertJson);
191,016✔
2368
  pResultInfo->convertJson = taosMemoryCalloc(1, dataLen);
191,016✔
2369
  if (pResultInfo->convertJson == NULL) return terrno;
191,016✔
2370
  char* p1 = pResultInfo->convertJson;
191,016✔
2371

2372
  int32_t totalLen = 0;
191,016✔
2373
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
191,016✔
2374
  if (numOfCols != cols) {
191,016✔
2375
    tscError("doConvertJson error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2376
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2377
  }
2378

2379
  int32_t len = getVersion1BlockMetaSize(p, numOfCols);
191,016✔
2380
  (void)memcpy(p1, p, len);
191,016✔
2381

2382
  p += len;
191,016✔
2383
  p1 += len;
191,016✔
2384
  totalLen += len;
191,016✔
2385

2386
  len = sizeof(int32_t) * numOfCols;
191,016✔
2387
  int32_t* colLength = (int32_t*)p;
191,016✔
2388
  int32_t* colLength1 = (int32_t*)p1;
191,016✔
2389
  (void)memcpy(p1, p, len);
191,016✔
2390
  p += len;
191,016✔
2391
  p1 += len;
191,016✔
2392
  totalLen += len;
191,016✔
2393

2394
  char* pStart = p;
191,016✔
2395
  char* pStart1 = p1;
191,016✔
2396
  for (int32_t i = 0; i < numOfCols; ++i) {
830,477✔
2397
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
639,461✔
2398
    int32_t colLen1 = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength1[i]) : colLength1[i];
639,461✔
2399
    if (colLen >= dataLen) {
639,461✔
2400
      tscError("doConvertJson error: colLen:%d >= dataLen:%d", colLen, dataLen);
×
2401
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2402
    }
2403
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
639,461✔
2404
      int32_t* offset = (int32_t*)pStart;
226,336✔
2405
      int32_t* offset1 = (int32_t*)pStart1;
226,336✔
2406
      len = numOfRows * sizeof(int32_t);
226,336✔
2407
      (void)memcpy(pStart1, pStart, len);
226,336✔
2408
      pStart += len;
226,336✔
2409
      pStart1 += len;
226,336✔
2410
      totalLen += len;
226,336✔
2411

2412
      len = 0;
226,336✔
2413
      for (int32_t j = 0; j < numOfRows; ++j) {
1,183,513✔
2414
        if (offset[j] == -1) {
957,177✔
2415
          continue;
48,114✔
2416
        }
2417
        char* data = offset[j] + pStart;
909,063✔
2418

2419
        int32_t jsonInnerType = *data;
909,063✔
2420
        char*   jsonInnerData = data + CHAR_BYTES;
909,063✔
2421
        char    dst[TSDB_MAX_JSON_TAG_LEN] = {0};
909,063✔
2422
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
909,063✔
2423
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s", TSDB_DATA_NULL_STR_L);
12,792✔
2424
          varDataSetLen(dst, strlen(varDataVal(dst)));
12,792✔
2425
        } else if (tTagIsJson(data)) {
896,271✔
2426
          char* jsonString = NULL;
210,786✔
2427
          parseTagDatatoJson(data, &jsonString, pResultInfo->charsetCxt);
210,786✔
2428
          if (jsonString == NULL) {
210,786✔
2429
            tscError("doConvertJson error: parseTagDatatoJson failed");
×
2430
            return terrno;
×
2431
          }
2432
          STR_TO_VARSTR(dst, jsonString);
210,786✔
2433
          taosMemoryFree(jsonString);
210,786✔
2434
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
685,485✔
2435
          *(char*)varDataVal(dst) = '\"';
637,515✔
2436
          char    tmp[TSDB_MAX_JSON_TAG_LEN] = {0};
637,515✔
2437
          int32_t length = taosUcs4ToMbs((TdUcs4*)varDataVal(jsonInnerData), varDataLen(jsonInnerData),
637,515✔
2438
                                         varDataVal(tmp), pResultInfo->charsetCxt);
2439
          if (length <= 0) {
637,515✔
2440
            tscError("charset:%s to %s. convert failed.", DEFAULT_UNICODE_ENCODEC,
533✔
2441
                     pResultInfo->charsetCxt != NULL ? ((SConvInfo*)(pResultInfo->charsetCxt))->charset : tsCharset);
2442
            length = 0;
533✔
2443
          }
2444
          int32_t escapeLength = escapeToPrinted(varDataVal(dst) + CHAR_BYTES, TSDB_MAX_JSON_TAG_LEN - CHAR_BYTES * 2,varDataVal(tmp), length);
637,515✔
2445
          varDataSetLen(dst, escapeLength + CHAR_BYTES * 2);
637,515✔
2446
          *(char*)POINTER_SHIFT(varDataVal(dst), escapeLength + CHAR_BYTES) = '\"';
637,515✔
2447
          tscError("value:%s.", varDataVal(dst));
637,515✔
2448
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
47,970✔
2449
          double jsonVd = *(double*)(jsonInnerData);
35,178✔
2450
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%.9lf", jsonVd);
35,178✔
2451
          varDataSetLen(dst, strlen(varDataVal(dst)));
35,178✔
2452
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
12,792✔
2453
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s",
12,792✔
2454
                         (*((char*)jsonInnerData) == 1) ? "true" : "false");
12,792✔
2455
          varDataSetLen(dst, strlen(varDataVal(dst)));
12,792✔
2456
        } else {
2457
          tscError("doConvertJson error: invalid type:%d", jsonInnerType);
×
2458
          return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2459
        }
2460

2461
        offset1[j] = len;
909,063✔
2462
        (void)memcpy(pStart1 + len, dst, varDataTLen(dst));
909,063✔
2463
        len += varDataTLen(dst);
909,063✔
2464
      }
2465
      colLen1 = len;
226,336✔
2466
      totalLen += colLen1;
226,336✔
2467
      colLength1[i] = (blockVersion == BLOCK_VERSION_1) ? htonl(len) : len;
226,336✔
2468
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
413,125✔
2469
      len = numOfRows * sizeof(int32_t);
53,300✔
2470
      (void)memcpy(pStart1, pStart, len);
53,300✔
2471
      pStart += len;
53,300✔
2472
      pStart1 += len;
53,300✔
2473
      totalLen += len;
53,300✔
2474
      totalLen += colLen;
53,300✔
2475
      (void)memcpy(pStart1, pStart, colLen);
53,300✔
2476
    } else {
2477
      len = BitmapLen(pResultInfo->numOfRows);
359,825✔
2478
      (void)memcpy(pStart1, pStart, len);
359,825✔
2479
      pStart += len;
359,825✔
2480
      pStart1 += len;
359,825✔
2481
      totalLen += len;
359,825✔
2482
      totalLen += colLen;
359,825✔
2483
      (void)memcpy(pStart1, pStart, colLen);
359,825✔
2484
    }
2485
    pStart += colLen;
639,461✔
2486
    pStart1 += colLen1;
639,461✔
2487
  }
2488

2489
  // Ensure the complete structure of the block, including the blankfill field,
2490
  // even though it is not used on the client side.
2491
  // (void)memcpy(pStart1, pStart, sizeof(bool));
2492
  totalLen += sizeof(bool);
191,016✔
2493

2494
  *(int32_t*)(pResultInfo->convertJson + 4) = totalLen;
191,016✔
2495
  pResultInfo->pData = pResultInfo->convertJson;
191,016✔
2496
  return TSDB_CODE_SUCCESS;
191,016✔
2497
}
2498

2499
int32_t setResultDataPtr(SReqResultInfo* pResultInfo, bool convertUcs4, bool isStmt) {
134,199,452✔
2500
  bool convertForDecimal = convertUcs4;
134,199,452✔
2501
  if (pResultInfo == NULL || pResultInfo->numOfCols <= 0 || pResultInfo->fields == NULL) {
134,199,452✔
2502
    tscError("setResultDataPtr paras error");
×
2503
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2504
  }
2505

2506
  if (pResultInfo->numOfRows == 0) {
134,199,133✔
2507
    return TSDB_CODE_SUCCESS;
6,974,023✔
2508
  }
2509

2510
  if (pResultInfo->pData == NULL) {
127,225,863✔
2511
    tscError("setResultDataPtr error: pData is NULL");
×
2512
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2513
  }
2514

2515
  int32_t code = doPrepareResPtr(pResultInfo);
127,223,544✔
2516
  if (code != TSDB_CODE_SUCCESS) {
127,225,058✔
2517
    return code;
×
2518
  }
2519
  code = doConvertJson(pResultInfo);
127,225,058✔
2520
  if (code != TSDB_CODE_SUCCESS) {
127,223,735✔
2521
    return code;
×
2522
  }
2523

2524
  char* p = (char*)pResultInfo->pData;
127,223,735✔
2525

2526
  // version:
2527
  int32_t blockVersion = *(int32_t*)p;
127,223,983✔
2528
  p += sizeof(int32_t);
127,224,295✔
2529

2530
  int32_t dataLen = *(int32_t*)p;
127,225,654✔
2531
  p += sizeof(int32_t);
127,225,431✔
2532

2533
  int32_t rows = *(int32_t*)p;
127,226,468✔
2534
  p += sizeof(int32_t);
127,225,480✔
2535

2536
  int32_t cols = *(int32_t*)p;
127,225,512✔
2537
  p += sizeof(int32_t);
127,226,220✔
2538

2539
  if (rows != pResultInfo->numOfRows || cols != pResultInfo->numOfCols) {
127,224,634✔
2540
    tscError("setResultDataPtr paras error:rows;%d numOfRows:%" PRId64 " cols:%d numOfCols:%d", rows,
1,627✔
2541
             pResultInfo->numOfRows, cols, pResultInfo->numOfCols);
2542
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2543
  }
2544

2545
  int32_t hasColumnSeg = *(int32_t*)p;
127,224,498✔
2546
  p += sizeof(int32_t);
127,226,086✔
2547

2548
  uint64_t groupId = taosGetUInt64Aligned((uint64_t*)p);
127,225,274✔
2549
  p += sizeof(uint64_t);
127,225,274✔
2550

2551
  // check fields
2552
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
714,042,329✔
2553
    int8_t type = *(int8_t*)p;
586,822,236✔
2554
    p += sizeof(int8_t);
586,819,431✔
2555

2556
    int32_t bytes = *(int32_t*)p;
586,820,081✔
2557
    p += sizeof(int32_t);
586,819,045✔
2558

2559
    if (IS_DECIMAL_TYPE(type) && pResultInfo->fields[i].precision == 0) {
586,820,953✔
2560
      extractDecimalTypeInfoFromBytes(&bytes, &pResultInfo->fields[i].precision, &pResultInfo->fields[i].scale);
310,186✔
2561
    }
2562
  }
2563

2564
  int32_t* colLength = (int32_t*)p;
127,223,665✔
2565
  p += sizeof(int32_t) * pResultInfo->numOfCols;
127,223,665✔
2566

2567
  char* pStart = p;
127,223,798✔
2568
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
714,060,556✔
2569
    if ((pStart - pResultInfo->pData) >= dataLen) {
586,832,114✔
2570
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2571
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2572
    }
2573
    if (blockVersion == BLOCK_VERSION_1) {
586,830,358✔
2574
      colLength[i] = htonl(colLength[i]);
433,318,354✔
2575
    }
2576
    if (colLength[i] >= dataLen) {
586,832,063✔
2577
      tscError("invalid colLength %d, dataLen %d", colLength[i], dataLen);
×
2578
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2579
    }
2580
    if (IS_INVALID_TYPE(pResultInfo->fields[i].type)) {
586,833,009✔
2581
      tscError("invalid type %d", pResultInfo->fields[i].type);
327✔
2582
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2583
    }
2584
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
586,833,746✔
2585
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
145,826,110✔
2586
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
145,820,494✔
2587
    } else {
2588
      pResultInfo->pCol[i].nullbitmap = pStart;
441,015,586✔
2589
      pStart += BitmapLen(pResultInfo->numOfRows);
441,015,286✔
2590
    }
2591

2592
    pResultInfo->pCol[i].pData = pStart;
586,837,852✔
2593
    pResultInfo->length[i] =
1,173,671,408✔
2594
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
1,112,980,877✔
2595
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
586,835,196✔
2596

2597
    pStart += colLength[i];
586,836,563✔
2598
  }
2599

2600
  p = pStart;
127,227,328✔
2601
  // bool blankFill = *(bool*)p;
2602
  p += sizeof(bool);
127,227,328✔
2603
  int32_t offset = p - pResultInfo->pData;
127,227,328✔
2604
  if (offset > dataLen) {
127,225,217✔
2605
    tscError("invalid offset %d, dataLen %d", offset, dataLen);
×
2606
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2607
  }
2608

2609
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
2610
  if (convertUcs4) {
127,225,217✔
2611
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
126,012,251✔
2612
  }
2613
#endif
2614
  if (TSDB_CODE_SUCCESS == code && convertForDecimal) {
127,226,147✔
2615
    code = convertDecimalType(pResultInfo);
126,012,853✔
2616
  }
2617
  return code;
127,223,728✔
2618
}
2619

2620
char* getDbOfConnection(STscObj* pObj) {
630,664,198✔
2621
  terrno = TSDB_CODE_SUCCESS;
630,664,198✔
2622
  char* p = NULL;
630,668,387✔
2623
  (void)taosThreadMutexLock(&pObj->mutex);
630,668,387✔
2624
  size_t len = strlen(pObj->db);
630,674,921✔
2625
  if (len > 0) {
630,675,689✔
2626
    p = taosStrndup(pObj->db, tListLen(pObj->db));
564,735,113✔
2627
    if (p == NULL) {
564,723,308✔
2628
      tscError("failed to taosStrndup db name");
×
2629
    }
2630
  }
2631

2632
  (void)taosThreadMutexUnlock(&pObj->mutex);
630,663,884✔
2633
  return p;
630,659,300✔
2634
}
2635

2636
void setConnectionDB(STscObj* pTscObj, const char* db) {
2,952,976✔
2637
  if (db == NULL || pTscObj == NULL) {
2,952,976✔
2638
    tscError("setConnectionDB para is NULL");
×
2639
    return;
×
2640
  }
2641

2642
  (void)taosThreadMutexLock(&pTscObj->mutex);
2,953,137✔
2643
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
2,953,223✔
2644
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
2,953,223✔
2645
}
2646

2647
void resetConnectDB(STscObj* pTscObj) {
×
2648
  if (pTscObj == NULL) {
×
2649
    return;
×
2650
  }
2651

2652
  (void)taosThreadMutexLock(&pTscObj->mutex);
×
2653
  pTscObj->db[0] = 0;
×
2654
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
×
2655
}
2656

2657
int32_t setQueryResultFromRsp(SReqResultInfo* pResultInfo, const SRetrieveTableRsp* pRsp, bool convertUcs4,
100,137,699✔
2658
                              bool isStmt) {
2659
  if (pResultInfo == NULL || pRsp == NULL) {
100,137,699✔
2660
    tscError("setQueryResultFromRsp paras is null");
×
2661
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2662
  }
2663

2664
  taosMemoryFreeClear(pResultInfo->pRspMsg);
100,137,706✔
2665
  pResultInfo->pRspMsg = (const char*)pRsp;
100,137,954✔
2666
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
100,137,451✔
2667
  pResultInfo->current = 0;
100,137,699✔
2668
  pResultInfo->completed = (pRsp->completed == 1);
100,137,954✔
2669
  pResultInfo->precision = pRsp->precision;
100,136,451✔
2670

2671
  // decompress data if needed
2672
  int32_t payloadLen = htonl(pRsp->payloadLen);
100,136,754✔
2673

2674
  if (pRsp->compressed) {
100,136,723✔
2675
    if (pResultInfo->decompBuf == NULL) {
×
2676
      pResultInfo->decompBuf = taosMemoryMalloc(payloadLen);
×
2677
      if (pResultInfo->decompBuf == NULL) {
×
2678
        tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2679
        return terrno;
×
2680
      }
2681
      pResultInfo->decompBufSize = payloadLen;
×
2682
    } else {
2683
      if (pResultInfo->decompBufSize < payloadLen) {
×
2684
        char* p = taosMemoryRealloc(pResultInfo->decompBuf, payloadLen);
×
2685
        if (p == NULL) {
×
2686
          tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2687
          return terrno;
×
2688
        }
2689

2690
        pResultInfo->decompBuf = p;
×
2691
        pResultInfo->decompBufSize = payloadLen;
×
2692
      }
2693
    }
2694
  }
2695

2696
  if (payloadLen > 0) {
100,136,950✔
2697
    int32_t compLen = *(int32_t*)pRsp->data;
93,164,066✔
2698
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
93,163,567✔
2699

2700
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
93,164,073✔
2701

2702
    if (pRsp->compressed && compLen < rawLen) {
93,162,374✔
2703
      int32_t len = tsDecompressString(pStart, compLen, 1, pResultInfo->decompBuf, rawLen, ONE_STAGE_COMP, NULL, 0);
×
2704
      if (len < 0) {
×
2705
        tscError("tsDecompressString failed");
×
2706
        return terrno ? terrno : TSDB_CODE_FAILED;
×
2707
      }
2708
      if (len != rawLen) {
×
2709
        tscError("tsDecompressString failed, len:%d != rawLen:%d", len, rawLen);
×
2710
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2711
      }
2712
      pResultInfo->pData = pResultInfo->decompBuf;
×
2713
      pResultInfo->payloadLen = rawLen;
×
2714
    } else {
2715
      pResultInfo->pData = pStart;
93,162,622✔
2716
      pResultInfo->payloadLen = htonl(pRsp->compLen);
93,163,371✔
2717
      if (pRsp->compLen != pRsp->payloadLen) {
93,163,149✔
2718
        tscError("pRsp->compLen:%d != pRsp->payloadLen:%d", pRsp->compLen, pRsp->payloadLen);
×
2719
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2720
      }
2721
    }
2722
  }
2723

2724
  // TODO handle the compressed case
2725
  pResultInfo->totalRows += pResultInfo->numOfRows;
100,136,449✔
2726

2727
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
100,135,759✔
2728
  return code;
100,135,248✔
2729
}
2730

2731
TSDB_SERVER_STATUS taos_check_server_status(const char* fqdn, int port, char* details, int maxlen) {
904✔
2732
  TSDB_SERVER_STATUS code = TSDB_SRV_STATUS_UNAVAILABLE;
904✔
2733
  void*              clientRpc = NULL;
904✔
2734
  SServerStatusRsp   statusRsp = {0};
904✔
2735
  SEpSet             epSet = {.inUse = 0, .numOfEps = 1};
904✔
2736
  SRpcMsg  rpcMsg = {.info.ahandle = (void*)0x9527, .info.notFreeAhandle = 1, .msgType = TDMT_DND_SERVER_STATUS};
904✔
2737
  SRpcMsg  rpcRsp = {0};
904✔
2738
  SRpcInit rpcInit = {0};
904✔
2739
  char     pass[TSDB_PASSWORD_LEN + 1] = {0};
904✔
2740

2741
  rpcInit.label = "CHK";
904✔
2742
  rpcInit.numOfThreads = 1;
904✔
2743
  rpcInit.cfp = NULL;
904✔
2744
  rpcInit.sessions = 16;
904✔
2745
  rpcInit.connType = TAOS_CONN_CLIENT;
904✔
2746
  rpcInit.idleTime = tsShellActivityTimer * 1000;
904✔
2747
  rpcInit.compressSize = tsCompressMsgSize;
904✔
2748
  rpcInit.user = "_dnd";
904✔
2749

2750
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
904✔
2751
  connLimitNum = TMAX(connLimitNum, 10);
904✔
2752
  connLimitNum = TMIN(connLimitNum, 500);
904✔
2753
  rpcInit.connLimitNum = connLimitNum;
904✔
2754
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
904✔
2755
  rpcInit.readTimeout = tsReadTimeout;
904✔
2756
  rpcInit.ipv6 = tsEnableIpv6;
904✔
2757
  rpcInit.enableSSL = tsEnableTLS;
904✔
2758

2759
  memcpy(rpcInit.caPath, tsTLSCaPath, strlen(tsTLSCaPath));
904✔
2760
  memcpy(rpcInit.certPath, tsTLSSvrCertPath, strlen(tsTLSSvrCertPath));
904✔
2761
  memcpy(rpcInit.keyPath, tsTLSSvrKeyPath, strlen(tsTLSSvrKeyPath));
904✔
2762
  memcpy(rpcInit.cliCertPath, tsTLSCliCertPath, strlen(tsTLSCliCertPath));
904✔
2763
  memcpy(rpcInit.cliKeyPath, tsTLSCliKeyPath, strlen(tsTLSCliKeyPath));
904✔
2764

2765
  if (TSDB_CODE_SUCCESS != taosVersionStrToInt(td_version, &rpcInit.compatibilityVer)) {
904✔
2766
    tscError("faild to convert taos version from str to int, errcode:%s", terrstr());
×
2767
    goto _OVER;
×
2768
  }
2769

2770
  clientRpc = rpcOpen(&rpcInit);
904✔
2771
  if (clientRpc == NULL) {
904✔
2772
    code = terrno;
×
2773
    tscError("failed to init server status client since %s", tstrerror(code));
×
2774
    goto _OVER;
×
2775
  }
2776

2777
  if (fqdn == NULL) {
904✔
2778
    fqdn = tsLocalFqdn;
904✔
2779
  }
2780

2781
  if (port == 0) {
904✔
2782
    port = tsServerPort;
904✔
2783
  }
2784

2785
  tstrncpy(epSet.eps[0].fqdn, fqdn, TSDB_FQDN_LEN);
904✔
2786
  epSet.eps[0].port = (uint16_t)port;
904✔
2787
  int32_t ret = rpcSendRecv(clientRpc, &epSet, &rpcMsg, &rpcRsp);
904✔
2788
  if (TSDB_CODE_SUCCESS != ret) {
904✔
2789
    tscError("failed to send recv since %s", tstrerror(ret));
×
2790
    goto _OVER;
×
2791
  }
2792

2793
  if (rpcRsp.code != 0 || rpcRsp.contLen <= 0 || rpcRsp.pCont == NULL) {
904✔
2794
    tscError("failed to send server status req since %s", terrstr());
131✔
2795
    goto _OVER;
131✔
2796
  }
2797

2798
  if (tDeserializeSServerStatusRsp(rpcRsp.pCont, rpcRsp.contLen, &statusRsp) != 0) {
773✔
2799
    tscError("failed to parse server status rsp since %s", terrstr());
×
2800
    goto _OVER;
×
2801
  }
2802

2803
  code = statusRsp.statusCode;
773✔
2804
  if (details != NULL) {
773✔
2805
    tstrncpy(details, statusRsp.details, maxlen);
773✔
2806
  }
2807

2808
_OVER:
658✔
2809
  if (clientRpc != NULL) {
904✔
2810
    rpcClose(clientRpc);
904✔
2811
  }
2812
  if (rpcRsp.pCont != NULL) {
904✔
2813
    rpcFreeCont(rpcRsp.pCont);
773✔
2814
  }
2815
  return code;
904✔
2816
}
2817

2818
int32_t appendTbToReq(SHashObj* pHash, int32_t pos1, int32_t len1, int32_t pos2, int32_t len2, const char* str,
1,232✔
2819
                      int32_t acctId, char* db) {
2820
  SName name = {0};
1,232✔
2821

2822
  if (len1 <= 0) {
1,232✔
2823
    return -1;
×
2824
  }
2825

2826
  const char* dbName = db;
1,232✔
2827
  const char* tbName = NULL;
1,232✔
2828
  int32_t     dbLen = 0;
1,232✔
2829
  int32_t     tbLen = 0;
1,232✔
2830
  if (len2 > 0) {
1,232✔
2831
    dbName = str + pos1;
×
2832
    dbLen = len1;
×
2833
    tbName = str + pos2;
×
2834
    tbLen = len2;
×
2835
  } else {
2836
    dbLen = strlen(db);
1,232✔
2837
    tbName = str + pos1;
1,232✔
2838
    tbLen = len1;
1,232✔
2839
  }
2840

2841
  if (dbLen <= 0 || tbLen <= 0) {
1,232✔
2842
    return -1;
×
2843
  }
2844

2845
  if (tNameSetDbName(&name, acctId, dbName, dbLen)) {
1,232✔
2846
    return -1;
×
2847
  }
2848

2849
  if (tNameAddTbName(&name, tbName, tbLen)) {
1,232✔
2850
    return -1;
×
2851
  }
2852

2853
  char dbFName[TSDB_DB_FNAME_LEN] = {0};
1,232✔
2854
  (void)snprintf(dbFName, TSDB_DB_FNAME_LEN, "%d.%.*s", acctId, dbLen, dbName);
1,232✔
2855

2856
  STablesReq* pDb = taosHashGet(pHash, dbFName, strlen(dbFName));
1,232✔
2857
  if (pDb) {
1,232✔
2858
    if (NULL == taosArrayPush(pDb->pTables, &name)) {
×
2859
      return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
2860
    }
2861
  } else {
2862
    STablesReq db;
1,232✔
2863
    db.pTables = taosArrayInit(20, sizeof(SName));
1,232✔
2864
    if (NULL == db.pTables) {
1,232✔
2865
      return terrno;
×
2866
    }
2867
    tstrncpy(db.dbFName, dbFName, TSDB_DB_FNAME_LEN);
1,232✔
2868
    if (NULL == taosArrayPush(db.pTables, &name)) {
2,464✔
2869
      return terrno;
×
2870
    }
2871
    TSC_ERR_RET(taosHashPut(pHash, dbFName, strlen(dbFName), &db, sizeof(db)));
1,232✔
2872
  }
2873

2874
  return TSDB_CODE_SUCCESS;
1,232✔
2875
}
2876

2877
int32_t transferTableNameList(const char* tbList, int32_t acctId, char* dbName, SArray** pReq) {
1,232✔
2878
  SHashObj* pHash = taosHashInit(3, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
1,232✔
2879
  if (NULL == pHash) {
1,232✔
2880
    return terrno;
×
2881
  }
2882

2883
  bool    inEscape = false;
1,232✔
2884
  int32_t code = 0;
1,232✔
2885
  void*   pIter = NULL;
1,232✔
2886

2887
  int32_t vIdx = 0;
1,232✔
2888
  int32_t vPos[2];
1,232✔
2889
  int32_t vLen[2];
1,232✔
2890

2891
  (void)memset(vPos, -1, sizeof(vPos));
1,232✔
2892
  (void)memset(vLen, 0, sizeof(vLen));
1,232✔
2893

2894
  for (int32_t i = 0;; ++i) {
6,160✔
2895
    if (0 == *(tbList + i)) {
6,160✔
2896
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
1,232✔
2897
        vLen[vIdx] = i - vPos[vIdx];
1,232✔
2898
      }
2899

2900
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
1,232✔
2901
      if (code) {
1,232✔
2902
        goto _return;
×
2903
      }
2904

2905
      break;
1,232✔
2906
    }
2907

2908
    if ('`' == *(tbList + i)) {
4,928✔
2909
      inEscape = !inEscape;
×
2910
      if (!inEscape) {
×
2911
        if (vPos[vIdx] >= 0) {
×
2912
          vLen[vIdx] = i - vPos[vIdx];
×
2913
        } else {
2914
          goto _return;
×
2915
        }
2916
      }
2917

2918
      continue;
×
2919
    }
2920

2921
    if (inEscape) {
4,928✔
2922
      if (vPos[vIdx] < 0) {
×
2923
        vPos[vIdx] = i;
×
2924
      }
2925
      continue;
×
2926
    }
2927

2928
    if ('.' == *(tbList + i)) {
4,928✔
2929
      if (vPos[vIdx] < 0) {
×
2930
        goto _return;
×
2931
      }
2932
      if (vLen[vIdx] <= 0) {
×
2933
        vLen[vIdx] = i - vPos[vIdx];
×
2934
      }
2935
      vIdx++;
×
2936
      if (vIdx >= 2) {
×
2937
        goto _return;
×
2938
      }
2939
      continue;
×
2940
    }
2941

2942
    if (',' == *(tbList + i)) {
4,928✔
2943
      if (vPos[vIdx] < 0) {
×
2944
        goto _return;
×
2945
      }
2946
      if (vLen[vIdx] <= 0) {
×
2947
        vLen[vIdx] = i - vPos[vIdx];
×
2948
      }
2949

2950
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
×
2951
      if (code) {
×
2952
        goto _return;
×
2953
      }
2954

2955
      (void)memset(vPos, -1, sizeof(vPos));
×
2956
      (void)memset(vLen, 0, sizeof(vLen));
×
2957
      vIdx = 0;
×
2958
      continue;
×
2959
    }
2960

2961
    if (' ' == *(tbList + i) || '\r' == *(tbList + i) || '\t' == *(tbList + i) || '\n' == *(tbList + i)) {
4,928✔
2962
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
×
2963
        vLen[vIdx] = i - vPos[vIdx];
×
2964
      }
2965
      continue;
×
2966
    }
2967

2968
    if (('a' <= *(tbList + i) && 'z' >= *(tbList + i)) || ('A' <= *(tbList + i) && 'Z' >= *(tbList + i)) ||
4,928✔
2969
        ('0' <= *(tbList + i) && '9' >= *(tbList + i)) || ('_' == *(tbList + i))) {
616✔
2970
      if (vLen[vIdx] > 0) {
4,928✔
2971
        goto _return;
×
2972
      }
2973
      if (vPos[vIdx] < 0) {
4,928✔
2974
        vPos[vIdx] = i;
1,232✔
2975
      }
2976
      continue;
4,928✔
2977
    }
2978

2979
    goto _return;
×
2980
  }
2981

2982
  int32_t dbNum = taosHashGetSize(pHash);
1,232✔
2983
  *pReq = taosArrayInit(dbNum, sizeof(STablesReq));
1,232✔
2984
  if (NULL == pReq) {
1,232✔
2985
    TSC_ERR_JRET(terrno);
×
2986
  }
2987
  pIter = taosHashIterate(pHash, NULL);
1,232✔
2988
  while (pIter) {
2,464✔
2989
    STablesReq* pDb = (STablesReq*)pIter;
1,232✔
2990
    if (NULL == taosArrayPush(*pReq, pDb)) {
2,464✔
2991
      TSC_ERR_JRET(terrno);
×
2992
    }
2993
    pIter = taosHashIterate(pHash, pIter);
1,232✔
2994
  }
2995

2996
  taosHashCleanup(pHash);
1,232✔
2997

2998
  return TSDB_CODE_SUCCESS;
1,232✔
2999

3000
_return:
×
3001

3002
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
3003

3004
  pIter = taosHashIterate(pHash, NULL);
×
3005
  while (pIter) {
×
3006
    STablesReq* pDb = (STablesReq*)pIter;
×
3007
    taosArrayDestroy(pDb->pTables);
×
3008
    pIter = taosHashIterate(pHash, pIter);
×
3009
  }
3010

3011
  taosHashCleanup(pHash);
×
3012

3013
  return terrno;
×
3014
}
3015

3016
void syncCatalogFn(SMetaData* pResult, void* param, int32_t code) {
1,232✔
3017
  SSyncQueryParam* pParam = param;
1,232✔
3018
  pParam->pRequest->code = code;
1,232✔
3019

3020
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
1,232✔
3021
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3022
  }
3023
}
1,232✔
3024

3025
void syncQueryFn(void* param, void* res, int32_t code) {
622,277,158✔
3026
  SSyncQueryParam* pParam = param;
622,277,158✔
3027
  pParam->pRequest = res;
622,277,158✔
3028

3029
  if (pParam->pRequest) {
622,280,097✔
3030
    pParam->pRequest->code = code;
622,256,782✔
3031
    clientOperateReport(pParam->pRequest);
622,258,913✔
3032
  }
3033

3034
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
622,256,421✔
3035
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3036
  }
3037
}
622,287,657✔
3038

3039
void taosAsyncQueryImpl(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
621,815,994✔
3040
                        int8_t source) {
3041
  if (sql == NULL || NULL == fp) {
621,815,994✔
3042
    terrno = TSDB_CODE_INVALID_PARA;
×
3043
    if (fp) {
×
3044
      fp(param, NULL, terrno);
×
3045
    }
3046

3047
    return;
×
3048
  }
3049

3050
  size_t sqlLen = strlen(sql);
621,818,260✔
3051
  if (sqlLen > (size_t)tsMaxSQLLength) {
621,818,260✔
3052
    tscError("conn:0x%" PRIx64 ", sql string exceeds max length:%d", connId, tsMaxSQLLength);
1,256✔
3053
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
1,256✔
3054
    fp(param, NULL, terrno);
1,256✔
3055
    return;
1,256✔
3056
  }
3057

3058
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, sql:%s", connId, sql);
621,817,004✔
3059

3060
  SRequestObj* pRequest = NULL;
621,817,537✔
3061
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
621,816,944✔
3062
  if (code != TSDB_CODE_SUCCESS) {
621,814,684✔
3063
    terrno = code;
×
3064
    fp(param, NULL, terrno);
×
3065
    return;
×
3066
  }
3067

3068
  pRequest->source = source;
621,814,684✔
3069
  pRequest->body.queryFp = fp;
621,818,277✔
3070
  doAsyncQuery(pRequest, false);
621,814,127✔
3071
}
3072

3073
void taosAsyncQueryImplWithReqid(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
6,763✔
3074
                                 int64_t reqid) {
3075
  if (sql == NULL || NULL == fp) {
6,763✔
3076
    terrno = TSDB_CODE_INVALID_PARA;
×
3077
    if (fp) {
×
3078
      fp(param, NULL, terrno);
×
3079
    }
3080

3081
    return;
×
3082
  }
3083

3084
  size_t sqlLen = strlen(sql);
6,763✔
3085
  if (sqlLen > (size_t)tsMaxSQLLength) {
6,763✔
3086
    tscError("conn:0x%" PRIx64 ", QID:0x%" PRIx64 ", sql string exceeds max length:%d", connId, reqid, tsMaxSQLLength);
×
3087
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
3088
    fp(param, NULL, terrno);
×
3089
    return;
×
3090
  }
3091

3092
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, QID:0x%" PRIx64 ", sql:%s", connId, reqid, sql);
6,763✔
3093

3094
  SRequestObj* pRequest = NULL;
6,763✔
3095
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, reqid);
6,763✔
3096
  if (code != TSDB_CODE_SUCCESS) {
6,763✔
3097
    terrno = code;
×
3098
    fp(param, NULL, terrno);
×
3099
    return;
×
3100
  }
3101

3102
  pRequest->body.queryFp = fp;
6,763✔
3103
  doAsyncQuery(pRequest, false);
6,763✔
3104
}
3105

3106
TAOS_RES* taosQueryImpl(TAOS* taos, const char* sql, bool validateOnly, int8_t source) {
621,715,416✔
3107
  if (NULL == taos) {
621,715,416✔
3108
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3109
    return NULL;
×
3110
  }
3111

3112
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
621,715,416✔
3113
  if (NULL == param) {
621,713,367✔
3114
    return NULL;
×
3115
  }
3116
  int32_t code = tsem_init(&param->sem, 0, 0);
621,713,367✔
3117
  if (TSDB_CODE_SUCCESS != code) {
621,707,785✔
3118
    taosMemoryFree(param);
×
3119
    return NULL;
×
3120
  }
3121

3122
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
621,707,785✔
3123
  code = tsem_wait(&param->sem);
621,708,069✔
3124
  if (TSDB_CODE_SUCCESS != code) {
621,718,097✔
3125
    taosMemoryFree(param);
×
3126
    return NULL;
×
3127
  }
3128
  code = tsem_destroy(&param->sem);
621,718,097✔
3129
  if (TSDB_CODE_SUCCESS != code) {
621,721,546✔
3130
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3131
  }
3132

3133
  SRequestObj* pRequest = NULL;
621,721,390✔
3134
  if (param->pRequest != NULL) {
621,721,390✔
3135
    param->pRequest->syncQuery = true;
621,721,911✔
3136
    pRequest = param->pRequest;
621,721,119✔
3137
    param->pRequest->inCallback = false;
621,719,445✔
3138
  }
3139
  taosMemoryFree(param);
621,718,980✔
3140

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

3144
  return pRequest;
621,720,078✔
3145
}
3146

3147
TAOS_RES* taosQueryImplWithReqid(TAOS* taos, const char* sql, bool validateOnly, int64_t reqid) {
6,763✔
3148
  if (NULL == taos) {
6,763✔
3149
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3150
    return NULL;
×
3151
  }
3152

3153
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
6,763✔
3154
  if (param == NULL) {
6,763✔
3155
    return NULL;
×
3156
  }
3157
  int32_t code = tsem_init(&param->sem, 0, 0);
6,763✔
3158
  if (TSDB_CODE_SUCCESS != code) {
6,763✔
3159
    taosMemoryFree(param);
×
3160
    return NULL;
×
3161
  }
3162

3163
  taosAsyncQueryImplWithReqid(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, reqid);
6,763✔
3164
  code = tsem_wait(&param->sem);
6,763✔
3165
  if (TSDB_CODE_SUCCESS != code) {
6,763✔
3166
    taosMemoryFree(param);
×
3167
    return NULL;
×
3168
  }
3169
  SRequestObj* pRequest = NULL;
6,763✔
3170
  if (param->pRequest != NULL) {
6,763✔
3171
    param->pRequest->syncQuery = true;
6,763✔
3172
    pRequest = param->pRequest;
6,763✔
3173
  }
3174
  taosMemoryFree(param);
6,763✔
3175

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

3179
  return pRequest;
6,763✔
3180
}
3181

3182
static void fetchCallback(void* pResult, void* param, int32_t code) {
97,285,665✔
3183
  SRequestObj* pRequest = (SRequestObj*)param;
97,285,665✔
3184

3185
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
97,285,665✔
3186

3187
  tscDebug("req:0x%" PRIx64 ", enter scheduler fetch cb, code:%d - %s, QID:0x%" PRIx64, pRequest->self, code,
97,285,665✔
3188
           tstrerror(code), pRequest->requestId);
3189

3190
  pResultInfo->pData = pResult;
97,285,665✔
3191
  pResultInfo->numOfRows = 0;
97,285,665✔
3192

3193
  if (code != TSDB_CODE_SUCCESS) {
97,284,193✔
3194
    pRequest->code = code;
×
3195
    taosMemoryFreeClear(pResultInfo->pData);
×
3196
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
×
3197
    return;
×
3198
  }
3199

3200
  if (pRequest->code != TSDB_CODE_SUCCESS) {
97,284,193✔
3201
    taosMemoryFreeClear(pResultInfo->pData);
×
3202
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pRequest->code);
×
3203
    return;
×
3204
  }
3205

3206
  pRequest->code = setQueryResultFromRsp(pResultInfo, (const SRetrieveTableRsp*)pResultInfo->pData,
106,152,522✔
3207
                                         pResultInfo->convertUcs4, pRequest->stmtBindVersion > 0);
97,284,696✔
3208
  if (pRequest->code != TSDB_CODE_SUCCESS) {
97,283,323✔
3209
    pResultInfo->numOfRows = 0;
328✔
3210
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self,
328✔
3211
             tstrerror(pRequest->code), pRequest->requestId);
3212
  } else {
3213
    tscDebug(
97,282,999✔
3214
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
3215
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
3216

3217
    STscObj*            pTscObj = pRequest->pTscObj;
97,282,999✔
3218
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
97,283,865✔
3219
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
97,284,869✔
3220
  }
3221

3222
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
97,285,419✔
3223
}
3224

3225
void taosAsyncFetchImpl(SRequestObj* pRequest, __taos_async_fn_t fp, void* param) {
100,362,961✔
3226
  pRequest->body.fetchFp = fp;
100,362,961✔
3227
  ((SSyncQueryParam*)pRequest->body.interParam)->userParam = param;
100,363,214✔
3228

3229
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
100,363,214✔
3230

3231
  // this query has no results or error exists, return directly
3232
  if (taos_num_fields(pRequest) == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
100,362,961✔
3233
    pResultInfo->numOfRows = 0;
253✔
3234
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
×
3235
    return;
4,199✔
3236
  }
3237

3238
  // all data has returned to App already, no need to try again
3239
  if (pResultInfo->completed) {
100,362,961✔
3240
    // it is a local executed query, no need to do async fetch
3241
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
3,077,294✔
3242
      if (pResultInfo->localResultFetched) {
1,515,540✔
3243
        pResultInfo->numOfRows = 0;
757,770✔
3244
        pResultInfo->current = 0;
757,770✔
3245
      } else {
3246
        pResultInfo->localResultFetched = true;
757,770✔
3247
      }
3248
    } else {
3249
      pResultInfo->numOfRows = 0;
1,561,754✔
3250
    }
3251

3252
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
3,077,294✔
3253
    return;
3,077,294✔
3254
  }
3255

3256
  SSchedulerReq req = {
97,285,667✔
3257
      .syncReq = false,
3258
      .fetchFp = fetchCallback,
3259
      .cbParam = pRequest,
3260
  };
3261

3262
  int32_t code = schedulerFetchRows(pRequest->body.queryJob, &req);
97,285,667✔
3263
  if (TSDB_CODE_SUCCESS != code) {
97,285,228✔
3264
    tscError("0x%" PRIx64 " failed to schedule fetch rows", pRequest->requestId);
×
3265
    // pRequest->body.fetchFp(param, pRequest, code);
3266
  }
3267
}
3268

3269
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
622,293,204✔
3270
  pRequest->inCallback = true;
622,293,204✔
3271
  int64_t this = pRequest->self;
622,310,096✔
3272
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
622,282,352✔
3273
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
82,350✔
3274
    code = TSDB_CODE_SUCCESS;
×
3275
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3276
  }
3277

3278
  tscDebug("QID:0x%" PRIx64 ", taos_query end, req:0x%" PRIx64 ", res:%p", pRequest->requestId, pRequest->self,
622,282,352✔
3279
           pRequest);
3280

3281
  if (pRequest->body.queryFp != NULL) {
622,282,715✔
3282
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
622,299,759✔
3283
  }
3284

3285
  SRequestObj* pReq = acquireRequest(this);
622,311,165✔
3286
  if (pReq != NULL) {
622,315,190✔
3287
    pReq->inCallback = false;
621,371,068✔
3288
    (void)releaseRequest(this);
621,371,068✔
3289
  }
3290
}
622,309,244✔
3291

3292
int32_t clientParseSql(void* param, const char* dbName, const char* sql, bool parseOnly, const char* effectiveUser,
557,421✔
3293
                       SParseSqlRes* pRes) {
3294
#ifndef TD_ENTERPRISE
3295
  return TSDB_CODE_SUCCESS;
3296
#else
3297
  return clientParseSqlImpl(param, dbName, sql, parseOnly, effectiveUser, pRes);
557,421✔
3298
#endif
3299
}
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