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

taosdata / TDengine / #4807

17 Oct 2025 06:47AM UTC coverage: 61.121% (+0.03%) from 61.094%
#4807

push

travis-ci

web-flow
Merge pull request #33289 from taosdata/3.0

enh: Code Optimization (#33283)

155421 of 324369 branches covered (47.91%)

Branch coverage included in aggregate %.

1 of 1 new or added line in 1 file covered. (100.0%)

2727 existing lines in 120 files now uncovered.

207582 of 269535 relevant lines covered (77.01%)

127069383.69 hits per line

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

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

16
#include "cJSON.h"
17
#include "clientInt.h"
18
#include "clientLog.h"
19
#include "clientMonitor.h"
20
#include "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) {
151,937,663✔
39
  SRequestObj* pReq = acquireRequest(rId);
151,937,663✔
40
  if (pReq != NULL) {
151,938,718✔
41
    pReq->isQuery = true;
151,926,361✔
42
    (void)releaseRequest(rId);
151,926,361✔
43
  }
44
}
151,937,774✔
45

46
static bool stringLengthCheck(const char* str, size_t maxsize) {
8,598,208✔
47
  if (str == NULL) {
8,598,208!
48
    return false;
×
49
  }
50

51
  size_t len = strlen(str);
8,598,208!
52
  if (len <= 0 || len > maxsize) {
8,598,208✔
53
    return false;
46✔
54
  }
55

56
  return true;
8,598,247✔
57
}
58

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

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

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

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

71
static int32_t escapeToPrinted(char* dst, size_t maxDstLength, const char* src, size_t srcLength) {
1,198,823✔
72
  if (dst == NULL || src == NULL || srcLength == 0) {
1,198,823!
73
    return 0;
230✔
74
  }
75
  
76
  size_t escapeLength = 0;
1,198,593✔
77
  for(size_t i = 0; i < srcLength; ++i) {
37,132,572✔
78
    if( src[i] == '\"' || src[i] == '\\' || src[i] == '\b' || src[i] == '\f' || src[i] == '\n' ||
35,933,979!
79
        src[i] == '\r' || src[i] == '\t') {
35,931,843✔
80
      escapeLength += 1; 
3,560✔
81
    }    
82
  }
83

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

125
  return dstLength;
1,198,593✔
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,542,507✔
141
  taosHashCleanup(appInfo.pInstMap);
1,542,507✔
142
  taosHashCleanup(appInfo.pInstMapByClusterId);
1,542,507✔
143
  tscInfo("cluster instance map cleaned");
1,542,507!
144
}
1,542,507✔
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,497,354✔
150
                              uint16_t port, int connType, STscObj** pObj) {
151
  TSC_ERR_RET(taos_init());
3,497,354!
152
  if (!validateUserName(user)) {
3,497,483!
153
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
154
  }
155
  int32_t code = 0;
3,497,483✔
156

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

163
    tstrncpy(localDb, db, sizeof(localDb));
1,604,282!
164
    (void)strdequote(localDb);
1,604,282✔
165
  }
166

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

173
    taosEncryptPass_c((uint8_t*)pass, strlen(pass), secretEncrypt);
3,496,718!
174
  } else {
175
    tstrncpy(secretEncrypt, auth, tListLen(secretEncrypt));
850!
176
  }
177

178
  SCorEpSet epSet = {0};
3,496,217✔
179
  if (ip) {
3,495,789✔
180
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
1,203,707✔
181
  } else {
182
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
2,292,082!
183
  }
184

185
  if (port) {
3,495,160✔
186
    epSet.epSet.eps[0].port = port;
76,054✔
187
    epSet.epSet.eps[1].port = port;
76,054✔
188
  }
189

190
  char* key = getClusterKey(user, secretEncrypt, ip, port);
3,495,160✔
191
  if (NULL == key) {
3,495,781!
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,495,781!
195
          user, db, key);
196
  for (int32_t i = 0; i < epSet.epSet.numOfEps; ++i) {
9,287,276✔
197
    tscInfo("ep:%d, %s:%u", i, epSet.epSet.eps[i].fqdn, epSet.epSet.eps[i].port);
5,790,527!
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,496,749✔
209
  code = taosThreadMutexLock(&appInfo.mutex);
3,496,749✔
210
  if (TSDB_CODE_SUCCESS != code) {
3,496,749!
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,496,749!
216
  SAppInstInfo* p = NULL;
3,496,749✔
217
  if (pInst == NULL) {
3,496,749✔
218
    p = taosMemoryCalloc(1, sizeof(struct SAppInstInfo));
1,597,626!
219
    if (NULL == p) {
1,597,626!
220
      TSC_ERR_JRET(terrno);
×
221
    }
222
    p->mgmtEp = epSet;
1,597,626✔
223
    code = taosThreadMutexInit(&p->qnodeMutex, NULL);
1,597,626✔
224
    if (TSDB_CODE_SUCCESS != code) {
1,597,626!
225
      taosMemoryFree(p);
×
226
      TSC_ERR_JRET(code);
×
227
    }
228
    code = openTransporter(user, secretEncrypt, tsNumOfCores / 2, &p->pTransporter);
1,597,626!
229
    if (TSDB_CODE_SUCCESS != code) {
1,597,626!
230
      taosMemoryFree(p);
×
231
      TSC_ERR_JRET(code);
×
232
    }
233
    code = appHbMgrInit(p, key, &p->pAppHbMgr);
1,597,626✔
234
    if (TSDB_CODE_SUCCESS != code) {
1,597,626!
235
      destroyAppInst(&p);
×
236
      TSC_ERR_JRET(code);
×
237
    }
238
    code = taosHashPut(appInfo.pInstMap, key, strlen(key), &p, POINTER_BYTES);
1,597,626!
239
    if (TSDB_CODE_SUCCESS != code) {
1,597,626!
240
      destroyAppInst(&p);
×
241
      TSC_ERR_JRET(code);
×
242
    }
243
    p->instKey = key;
1,597,626✔
244
    key = NULL;
1,597,626✔
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,597,626!
246

247
    pInst = &p;
1,597,626✔
248
  } else {
249
    if (NULL == *pInst || NULL == (*pInst)->pAppHbMgr) {
1,899,123!
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,899,123✔
255
  }
256

257
_return:
3,496,749✔
258

259
  if (TSDB_CODE_SUCCESS != code) {
3,496,749!
260
    (void)taosThreadMutexUnlock(&appInfo.mutex);
×
261
    taosMemoryFreeClear(key);
×
262
    return code;
×
263
  } else {
264
    code = taosThreadMutexUnlock(&appInfo.mutex);
3,496,749✔
265
    taosMemoryFreeClear(key);
3,496,749!
266
    if (TSDB_CODE_SUCCESS != code) {
3,496,749!
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,496,749✔
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) {
601,586✔
284
  if (param == NULL) return;
601,586!
285
  if (TSDB_CODE_SUCCESS != tsem_destroy(&param->sem)) {
601,586!
286
    tscError("failed to destroy semaphore in freeQueryParam");
×
287
  }
288
  taosMemoryFree(param);
601,586!
289
}
290

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

299
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
718,904,252!
300
  if ((*pRequest)->sqlstr == NULL) {
718,901,475!
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);
718,902,176✔
308
  (*pRequest)->sqlstr[sqlLen] = 0;
718,915,813✔
309
  (*pRequest)->sqlLen = sqlLen;
718,916,894✔
310
  (*pRequest)->validateOnly = validateSql;
718,915,016✔
311
  (*pRequest)->stmtBindVersion = 0;
718,915,016✔
312

313
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
718,912,175✔
314

315
  STscObj* pTscObj = (*pRequest)->pTscObj;
718,914,611✔
316
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
718,912,261✔
317
                             sizeof((*pRequest)->self));
318
  if (err) {
718,910,726!
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;
718,910,726✔
327
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
718,916,996✔
328
    if (TSDB_CODE_SUCCESS !=
205,992,504!
329
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
205,982,913✔
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);
718,927,975✔
339
  return TSDB_CODE_SUCCESS;
718,906,638✔
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) {
881,112✔
355
  STscObj* pTscObj = pRequest->pTscObj;
881,112✔
356

357
  SParseContext cxt = {
881,399✔
358
      .requestId = pRequest->requestId,
880,803✔
359
      .requestRid = pRequest->self,
881,667✔
360
      .acctId = pTscObj->acctId,
880,653✔
361
      .db = pRequest->pDb,
880,142✔
362
      .topicQuery = topicQuery,
363
      .pSql = pRequest->sqlstr,
880,060✔
364
      .sqlLen = pRequest->sqlLen,
880,142✔
365
      .pMsg = pRequest->msgBuf,
880,806✔
366
      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
367
      .pTransporter = pTscObj->pAppInfo->pTransporter,
879,938✔
368
      .pStmtCb = pStmtCb,
369
      .pUser = pTscObj->user,
880,129✔
370
      .isSuperUser = (0 == strcmp(pTscObj->user, TSDB_DEFAULT_USER)),
880,883!
371
      .enableSysInfo = pTscObj->sysInfo,
881,088✔
372
      .svrVer = pTscObj->sVer,
879,937✔
373
      .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes),
880,293✔
374
      .stmtBindVersion = pRequest->stmtBindVersion,
880,495✔
375
      .setQueryFp = setQueryRequest,
376
      .timezone = pTscObj->optionInfo.timezone,
880,249✔
377
      .charsetCxt = pTscObj->optionInfo.charsetCxt,
879,937✔
378
  };
379

380
  cxt.mgmtEpSet = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
881,279✔
381
  int32_t code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &cxt.pCatalog);
881,438✔
382
  if (code != TSDB_CODE_SUCCESS) {
880,951!
383
    return code;
×
384
  }
385

386
  code = qParseSql(&cxt, pQuery);
880,951✔
387
  if (TSDB_CODE_SUCCESS == code) {
880,732✔
388
    if ((*pQuery)->haveResultSet) {
879,189!
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)) {
880,412!
396
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
878,101✔
397
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
877,836✔
398
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
877,289✔
399
  }
400

401
  taosArrayDestroy(cxt.pTableMetaPos);
879,930✔
402
  taosArrayDestroy(cxt.pTableVgroupPos);
879,622✔
403

404
  return code;
880,056✔
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) {
443,350✔
421
  // drop table if exists not_exists_table
422
  if (NULL == pQuery->pCmdMsg) {
443,350!
423
    return TSDB_CODE_SUCCESS;
×
424
  }
425

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

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

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

440
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
1,299,215,757✔
441

442
void asyncExecLocalCmd(SRequestObj* pRequest, SQuery* pQuery) {
6,294,349✔
443
  SRetrieveTableRsp* pRsp = NULL;
6,294,349✔
444
  if (pRequest->validateOnly) {
6,294,349!
445
    doRequestCallback(pRequest, 0);
15,876✔
446
    return;
15,876✔
447
  }
448

449
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp,
12,525,225✔
450
                              atomic_load_8(&pRequest->pTscObj->biMode), pRequest->pTscObj->optionInfo.charsetCxt);
12,525,225✔
451
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
6,278,473✔
452
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4,
3,696,289!
453
                                 pRequest->stmtBindVersion > 0);
3,696,289✔
454
  }
455

456
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
6,278,473✔
457
  pRequest->code = code;
6,278,473✔
458

459
  if (pRequest->code != TSDB_CODE_SUCCESS) {
6,278,473✔
460
    pResultInfo->numOfRows = 0;
2,531✔
461
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
2,531!
462
             pRequest->requestId);
463
  } else {
464
    tscDebug(
6,275,431!
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);
6,277,962✔
470
}
471

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

478
  // drop table if exists not_exists_table
479
  if (NULL == pQuery->pCmdMsg) {
14,873,409✔
480
    doRequestCallback(pRequest, 0);
9,363✔
481
    return TSDB_CODE_SUCCESS;
9,363✔
482
  }
483

484
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
14,863,647✔
485
  pRequest->type = pMsgInfo->msgType;
14,864,046✔
486
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
14,863,646✔
487
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
14,864,046✔
488

489
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
14,864,046✔
490
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
14,863,723✔
491

492
  int32_t code = asyncSendMsgToServer(pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg);
14,863,298✔
493
  if (code) {
14,864,046!
494
    doRequestCallback(pRequest, code);
×
495
  }
496
  return code;
14,864,046✔
497
}
498

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

503
  if (node1->load < node2->load) {
138,905!
504
    return -1;
×
505
  }
506

507
  return node1->load > node2->load;
138,905✔
508
}
509

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

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

526
  return TSDB_CODE_SUCCESS;
20,630✔
527
}
528

529
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
718,974,601✔
530
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
718,974,601✔
531
    *required = false;
718,724,622✔
532
    return TSDB_CODE_SUCCESS;
718,722,832✔
533
  }
534

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

539
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
249,979!
540
  *required = (NULL == pInfo->pQnodeList);
249,979✔
541
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
249,979!
542
  return TSDB_CODE_SUCCESS;
249,979✔
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) {
5,934,681✔
578
  pRequest->type = pQuery->msgType;
5,934,681✔
579
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
5,934,804✔
580

581
  SPlanContext cxt = {.queryId = pRequest->requestId,
6,857,349✔
582
                      .acctId = pRequest->pTscObj->acctId,
5,934,062✔
583
                      .mgmtEpSet = getEpSet_s(&pAppInfo->mgmtEp),
5,934,161✔
584
                      .pAstRoot = pQuery->pRoot,
5,934,031✔
585
                      .showRewrite = pQuery->showRewrite,
5,933,949!
586
                      .pMsg = pRequest->msgBuf,
5,934,113✔
587
                      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
588
                      .pUser = pRequest->pTscObj->user,
5,934,415✔
589
                      .timezone = pRequest->pTscObj->optionInfo.timezone,
5,934,374✔
590
                      .sysInfo = pRequest->pTscObj->sysInfo};
5,934,333✔
591

592
  return qCreateQueryPlan(&cxt, pPlan, pNodeList);
5,934,579✔
593
}
594

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

602
  pResInfo->numOfCols = numOfCols;
133,228,103✔
603
  if (pResInfo->fields != NULL) {
133,230,269✔
604
    taosMemoryFree(pResInfo->fields);
13,532!
605
  }
606
  if (pResInfo->userFields != NULL) {
133,226,835✔
607
    taosMemoryFree(pResInfo->userFields);
13,532!
608
  }
609
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD_E));
133,226,918!
610
  if (NULL == pResInfo->fields) return terrno;
133,222,675!
611
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
133,226,015!
612
  if (NULL == pResInfo->userFields) {
133,225,436!
613
    taosMemoryFree(pResInfo->fields);
×
614
    return terrno;
×
615
  }
616
  if (numOfCols != pResInfo->numOfCols) {
133,225,239!
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) {
797,411,018✔
622
    pResInfo->fields[i].type = pSchema[i].type;
664,191,436✔
623

624
    pResInfo->userFields[i].type = pSchema[i].type;
664,188,705✔
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);
664,190,923✔
627
    pResInfo->fields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, isStmt);
664,190,428✔
628
    if (IS_DECIMAL_TYPE(pSchema[i].type) && pExtSchema) {
664,190,604!
629
      decimalFromTypeMod(pExtSchema[i].typeMod, &pResInfo->fields[i].precision, &pResInfo->fields[i].scale);
511,278✔
630
    }
631

632
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
664,190,634!
633
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
664,191,744!
634
  }
635
  return TSDB_CODE_SUCCESS;
133,228,300✔
636
}
637

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

644
  pResInfo->precision = precision;
108,306,050✔
645
}
646

647
int32_t buildVnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pDbVgList) {
112,279,565✔
648
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
112,279,565✔
649
  if (NULL == nodeList) {
112,281,405!
650
    return terrno;
×
651
  }
652
  char* policy = (tsQueryPolicy == QUERY_POLICY_VNODE) ? "vnode" : "client";
112,283,076✔
653

654
  int32_t dbNum = taosArrayGetSize(pDbVgList);
112,283,076✔
655
  for (int32_t i = 0; i < dbNum; ++i) {
221,990,576✔
656
    SArray* pVg = taosArrayGetP(pDbVgList, i);
109,700,086✔
657
    if (NULL == pVg) {
109,700,642!
658
      continue;
×
659
    }
660
    int32_t vgNum = taosArrayGetSize(pVg);
109,700,642✔
661
    if (vgNum <= 0) {
109,701,715✔
662
      continue;
408,758✔
663
    }
664

665
    for (int32_t j = 0; j < vgNum; ++j) {
348,565,930✔
666
      SVgroupInfo* pInfo = taosArrayGet(pVg, j);
239,268,092✔
667
      if (NULL == pInfo) {
239,271,506!
668
        taosArrayDestroy(nodeList);
×
669
        return TSDB_CODE_OUT_OF_RANGE;
×
670
      }
671
      SQueryNodeLoad load = {0};
239,271,506✔
672
      load.addr.nodeId = pInfo->vgId;
239,272,167✔
673
      load.addr.epSet = pInfo->epSet;
239,274,300✔
674

675
      if (NULL == taosArrayPush(nodeList, &load)) {
239,267,021!
676
        taosArrayDestroy(nodeList);
×
677
        return terrno;
×
678
      }
679
    }
680
  }
681

682
  int32_t vnodeNum = taosArrayGetSize(nodeList);
112,290,490✔
683
  if (vnodeNum > 0) {
112,285,192✔
684
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
108,988,952✔
685
    goto _return;
108,989,701✔
686
  }
687

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

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

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

706
_return:
27,412✔
707

708
  *pNodeList = nodeList;
112,284,628✔
709

710
  return TSDB_CODE_SUCCESS;
112,282,883✔
711
}
712

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

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

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

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

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

752
_return:
×
753

754
  *pNodeList = nodeList;
137,781✔
755

756
  return TSDB_CODE_SUCCESS;
137,781✔
757
}
758

759
void freeVgList(void* list) {
5,909,328✔
760
  SArray* pList = *(SArray**)list;
5,909,328✔
761
  taosArrayDestroy(pList);
5,909,492✔
762
}
5,909,741✔
763

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

770
  switch (tsQueryPolicy) {
106,483,435✔
771
    case QUERY_POLICY_VNODE:
106,344,998✔
772
    case QUERY_POLICY_CLIENT: {
773
      if (pResultMeta) {
106,344,998✔
774
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
106,347,808✔
775
        if (NULL == pDbVgList) {
106,346,341!
776
          code = terrno;
×
777
          goto _return;
×
778
        }
779
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
106,346,341✔
780
        for (int32_t i = 0; i < dbNum; ++i) {
210,138,472✔
781
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
103,791,235✔
782
          if (pRes->code || NULL == pRes->pRes) {
103,789,805!
783
            continue;
×
784
          }
785

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

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

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

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

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

830
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
106,347,241✔
831
      break;
106,349,105✔
832
    }
833
    case QUERY_POLICY_HYBRID:
137,781✔
834
    case QUERY_POLICY_QNODE: {
835
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
274,977!
836
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
137,196✔
837
        if (pRes->code) {
137,196!
838
          pQnodeList = NULL;
×
839
        } else {
840
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
137,196✔
841
          if (NULL == pQnodeList) {
137,196!
842
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
843
            goto _return;
×
844
          }
845
        }
846
      } else {
847
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
585✔
848
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
585!
849
        if (pInst->pQnodeList) {
585!
850
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
585✔
851
          if (NULL == pQnodeList) {
585!
852
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
853
            goto _return;
×
854
          }
855
        }
856
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
585!
857
      }
858

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

867
_return:
106,486,886✔
868
  taosArrayDestroyEx(pDbVgList, fp);
106,486,886✔
869
  taosArrayDestroy(pQnodeList);
106,484,584✔
870

871
  return code;
106,486,321✔
872
}
873

874
int32_t buildSyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList) {
5,933,907✔
875
  SArray* pDbVgList = NULL;
5,933,907✔
876
  SArray* pQnodeList = NULL;
5,933,907✔
877
  int32_t code = 0;
5,934,153✔
878

879
  switch (tsQueryPolicy) {
5,934,153!
880
    case QUERY_POLICY_VNODE:
5,933,131✔
881
    case QUERY_POLICY_CLIENT: {
882
      int32_t dbNum = taosArrayGetSize(pRequest->dbList);
5,933,131✔
883
      if (dbNum > 0) {
5,933,789✔
884
        SCatalog*     pCtg = NULL;
5,909,050✔
885
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
5,909,420✔
886
        code = catalogGetHandle(pInst->clusterId, &pCtg);
5,909,420✔
887
        if (code != TSDB_CODE_SUCCESS) {
5,908,910!
888
          goto _return;
×
889
        }
890

891
        pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
5,908,910✔
892
        if (NULL == pDbVgList) {
5,909,346✔
893
          code = terrno;
177✔
894
          goto _return;
×
895
        }
896
        SArray* pVgList = NULL;
5,909,169✔
897
        for (int32_t i = 0; i < dbNum; ++i) {
11,818,363✔
898
          char*            dbFName = taosArrayGet(pRequest->dbList, i);
5,909,015✔
899
          SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
5,908,557✔
900
                                   .requestId = pRequest->requestId,
5,908,927✔
901
                                   .requestObjRefId = pRequest->self,
5,908,804✔
902
                                   .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
5,908,412✔
903

904
          // catalogGetDBVgList will handle dbFName == null.
905
          code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
5,910,254✔
906
          if (code) {
5,909,488!
907
            goto _return;
×
908
          }
909

910
          if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
5,909,865!
911
            code = terrno;
×
912
            goto _return;
×
913
          }
914
        }
915
      }
916

917
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
5,934,922✔
918
      break;
5,934,253✔
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:
1,171✔
928
      tscError("unknown query policy: %d", tsQueryPolicy);
1,171!
929
      return TSDB_CODE_APP_ERROR;
×
930
  }
931

932
_return:
5,934,294✔
933

934
  taosArrayDestroyEx(pDbVgList, freeVgList);
5,933,905✔
935
  taosArrayDestroy(pQnodeList);
5,934,113✔
936

937
  return code;
5,934,606✔
938
}
939

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

943
  SExecResult      res = {0};
5,934,266✔
944
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
5,934,266✔
945
                           .requestId = pRequest->requestId,
5,934,266✔
946
                           .requestObjRefId = pRequest->self};
5,934,020✔
947
  SSchedulerReq    req = {
6,857,386✔
948
         .syncReq = true,
949
         .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
5,934,143✔
950
         .pConn = &conn,
951
         .pNodeList = pNodeList,
952
         .pDag = pDag,
953
         .sql = pRequest->sqlstr,
5,934,143✔
954
         .startTs = pRequest->metric.start,
5,933,856✔
955
         .execFp = NULL,
956
         .cbParam = NULL,
957
         .chkKillFp = chkRequestKilled,
958
         .chkKillParam = (void*)pRequest->self,
5,934,143✔
959
         .pExecRes = &res,
960
         .source = pRequest->source,
5,934,061✔
961
         .pWorkerCb = getTaskPoolWorkerCb(),
5,934,266✔
962
  };
963

964
  int32_t code = schedulerExecJob(&req, &pRequest->body.queryJob);
5,933,510✔
965

966
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
5,934,377✔
967
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
5,934,725!
968

969
  if (code != TSDB_CODE_SUCCESS) {
5,934,766!
970
    schedulerFreeJob(&pRequest->body.queryJob, 0);
×
971

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

977
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_DELETE == pRequest->type ||
5,934,766!
978
      TDMT_VND_CREATE_TABLE == pRequest->type) {
17,532✔
979
    pRequest->body.resInfo.numOfRows = res.numOfRows;
5,921,842✔
980
    if (TDMT_VND_SUBMIT == pRequest->type) {
5,921,842✔
981
      STscObj*            pTscObj = pRequest->pTscObj;
5,917,175✔
982
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
5,917,134✔
983
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
5,917,525✔
984
    }
985

986
    schedulerFreeJob(&pRequest->body.queryJob, 0);
5,921,510✔
987
  }
988

989
  pRequest->code = res.code;
5,934,136✔
990
  terrno = res.code;
5,933,100✔
991
  return pRequest->code;
5,933,786✔
992
}
993

994
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
501,552,261✔
995
  SArray*      pArray = NULL;
501,552,261✔
996
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
501,552,261✔
997
  if (NULL == pRsp->aCreateTbRsp) {
501,552,261✔
998
    return TSDB_CODE_SUCCESS;
483,343,642✔
999
  }
1000

1001
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
18,213,256✔
1002
  for (int32_t i = 0; i < tbNum; ++i) {
43,109,531✔
1003
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
24,895,351✔
1004
    if (pTbRsp->pMeta) {
24,895,187✔
1005
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
23,909,685!
1006
    }
1007
  }
1008

1009
  return TSDB_CODE_SUCCESS;
18,214,180✔
1010
}
1011

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

1021
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
90,582,724✔
1022
  if (NULL == pArray) {
90,583,121!
1023
    return terrno;
×
1024
  }
1025

1026
  for (int32_t i = 0; i < tbNum; ++i) {
244,841,967✔
1027
    STbVerInfo* tbInfo = taosArrayGet(pTbArray, i);
154,260,190✔
1028
    if (NULL == tbInfo) {
154,259,460!
1029
      code = terrno;
×
1030
      goto _return;
×
1031
    }
1032
    STbSVersion tbSver = {
154,259,460✔
1033
        .tbFName = tbInfo->tbFName, .sver = tbInfo->sversion, .tver = tbInfo->tversion, .rver = tbInfo->rversion};
154,259,460✔
1034
    if (NULL == taosArrayPush(pArray, &tbSver)) {
154,259,897!
1035
      code = terrno;
×
1036
      goto _return;
×
1037
    }
1038
  }
1039

1040
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
90,581,777✔
1041
                           .requestId = pRequest->requestId,
90,584,268✔
1042
                           .requestObjRefId = pRequest->self,
90,583,927✔
1043
                           .mgmtEps = *epset};
1044

1045
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
90,582,828✔
1046

1047
_return:
90,583,169✔
1048

1049
  taosArrayDestroy(pArray);
90,581,817✔
1050
  return code;
90,582,843✔
1051
}
1052

1053
int32_t handleAlterTbExecRes(void* res, SCatalog* pCatalog) {
6,310,476✔
1054
  return catalogUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
6,310,476✔
1055
}
1056

1057
int32_t handleCreateTbExecRes(void* res, SCatalog* pCatalog) {
59,535,419✔
1058
  return catalogAsyncUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
59,535,419✔
1059
}
1060

1061
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
657,884,473✔
1062
  if (NULL == pRequest->body.resInfo.execRes.res) {
657,884,473✔
1063
    return pRequest->code;
30,979,926✔
1064
  }
1065

1066
  SCatalog*     pCatalog = NULL;
626,893,504✔
1067
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
626,896,179✔
1068

1069
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
626,906,469✔
1070
  if (code) {
626,906,398!
1071
    return code;
×
1072
  }
1073

1074
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
626,906,398✔
1075
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
626,912,548✔
1076

1077
  switch (pRes->msgType) {
626,913,407✔
1078
    case TDMT_VND_ALTER_TABLE:
4,322,302✔
1079
    case TDMT_MND_ALTER_STB: {
1080
      code = handleAlterTbExecRes(pRes->res, pCatalog);
4,322,302✔
1081
      break;
4,322,302✔
1082
    }
1083
    case TDMT_VND_CREATE_TABLE: {
30,028,086✔
1084
      SArray* pList = (SArray*)pRes->res;
30,028,086✔
1085
      int32_t num = taosArrayGetSize(pList);
30,041,183✔
1086
      for (int32_t i = 0; i < num; ++i) {
63,590,766✔
1087
        void* res = taosArrayGetP(pList, i);
33,547,298✔
1088
        // handleCreateTbExecRes will handle res == null
1089
        code = handleCreateTbExecRes(res, pCatalog);
33,546,701✔
1090
      }
1091
      break;
30,043,468✔
1092
    }
1093
    case TDMT_MND_CREATE_STB: {
408,479✔
1094
      code = handleCreateTbExecRes(pRes->res, pCatalog);
408,479✔
1095
      break;
408,479✔
1096
    }
1097
    case TDMT_VND_SUBMIT: {
501,550,699✔
1098
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
501,550,699✔
1099

1100
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
501,558,631✔
1101
      break;
501,553,121✔
1102
    }
1103
    case TDMT_SCH_QUERY:
90,583,980✔
1104
    case TDMT_SCH_MERGE_QUERY: {
1105
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
90,583,980✔
1106
      break;
90,580,373✔
1107
    }
1108
    default:
787✔
1109
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self,
787!
1110
               pRequest->type, pRequest->requestId);
1111
      code = TSDB_CODE_APP_ERROR;
×
1112
  }
1113

1114
  return code;
626,907,743✔
1115
}
1116

1117
static bool incompletaFileParsing(SNode* pStmt) {
650,657,462✔
1118
  return QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pStmt) ? false : ((SVnodeModifyOpStmt*)pStmt)->fileProcessing;
650,657,462!
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) {
19,386,026✔
1140
  if (pRequest->relation.userRefId == pRequest->self || 0 == pRequest->relation.userRefId) {
19,386,026!
1141
    // return to client
1142
    doRequestCallback(pRequest, pRequest->code);
19,386,026✔
1143
    return;
19,386,026✔
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) {
651,542,260✔
1263
  SSqlCallbackWrapper* pWrapper = param;
651,542,260✔
1264
  SRequestObj*         pRequest = pWrapper->pRequest;
651,542,260✔
1265
  STscObj*             pTscObj = pRequest->pTscObj;
651,544,947✔
1266

1267
  pRequest->code = code;
651,543,537✔
1268
  if (pResult) {
651,544,426✔
1269
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
651,513,171✔
1270
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
651,525,614!
1271
  }
1272

1273
  int32_t type = pRequest->type;
651,540,342✔
1274
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
651,525,091✔
1275
    if (pResult) {
530,924,494✔
1276
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
530,925,526✔
1277

1278
      // record the insert rows
1279
      if (TDMT_VND_SUBMIT == type) {
530,927,618✔
1280
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
495,795,499✔
1281
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
495,798,126✔
1282
      }
1283
    }
1284
    schedulerFreeJob(&pRequest->body.queryJob, 0);
530,930,633✔
1285
  }
1286

1287
  taosMemoryFree(pResult);
651,548,174!
1288
  tscDebug("req:0x%" PRIx64 ", enter scheduler exec cb, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
651,541,761✔
1289
           pRequest->requestId);
1290

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

1302
  tscTrace("req:0x%" PRIx64 ", scheduler exec cb, request type:%s", pRequest->self, TMSG_INFO(pRequest->type));
651,508,106!
1303
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
651,508,106!
1304
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
11,304,202!
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;
651,517,089✔
1310
  int32_t code1 = handleQueryExecRsp(pRequest);
651,506,936✔
1311
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
651,512,320!
1312
    pRequest->code = code1;
×
1313
  }
1314

1315
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
1,302,170,603✔
1316
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
650,649,502✔
1317
    continueInsertFromCsv(pWrapper, pRequest);
13,508✔
1318
    return;
13,480✔
1319
  }
1320

1321
  if (pRequest->relation.nextRefId) {
651,506,519!
1322
    handlePostSubQuery(pWrapper);
×
1323
  } else {
1324
    destorySqlCallbackWrapper(pWrapper);
651,505,101✔
1325
    pRequest->pWrapper = NULL;
651,489,074✔
1326

1327
    // return to client
1328
    doRequestCallback(pRequest, code);
651,491,461✔
1329
  }
1330
}
1331

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

1336
  if (pQuery->pRoot) {
6,375,112✔
1337
    pRequest->stmtType = pQuery->pRoot->type;
5,934,280✔
1338
  }
1339

1340
  if (pQuery->pRoot && !pRequest->inRetry) {
6,373,779!
1341
    STscObj*            pTscObj = pRequest->pTscObj;
5,934,650✔
1342
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
5,933,732✔
1343
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type) {
5,934,259✔
1344
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
5,921,952✔
1345
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
12,364!
1346
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
12,364✔
1347
    }
1348
  }
1349

1350
  pRequest->body.execMode = pQuery->execMode;
6,376,263✔
1351
  switch (pQuery->execMode) {
6,377,783!
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:
443,350✔
1363
      if (!pRequest->validateOnly) {
443,350!
1364
        code = execDdlQuery(pRequest, pQuery);
443,350✔
1365
      }
1366
      break;
443,350✔
1367
    case QUERY_EXEC_MODE_SCHEDULE: {
5,932,559✔
1368
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
5,932,559✔
1369
      if (NULL == pMnodeList) {
5,934,394!
1370
        code = terrno;
×
1371
        break;
×
1372
      }
1373
      SQueryPlan* pDag = NULL;
5,934,394✔
1374
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
5,934,394✔
1375
      if (TSDB_CODE_SUCCESS == code) {
5,934,534✔
1376
        pRequest->body.subplanNum = pDag->numOfSubplans;
5,934,370✔
1377
        if (!pRequest->validateOnly) {
5,934,780✔
1378
          SArray* pNodeList = NULL;
5,933,996✔
1379
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
5,933,402✔
1380
          if (TSDB_CODE_SUCCESS == code) {
5,934,305!
1381
            code = scheduleQuery(pRequest, pDag, pNodeList);
5,934,535✔
1382
          }
1383
          taosArrayDestroy(pNodeList);
5,933,316✔
1384
        }
1385
      }
1386
      taosArrayDestroy(pMnodeList);
5,934,913✔
1387
      break;
5,933,824✔
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) {
6,377,215!
1397
    qDestroyQuery(pQuery);
×
1398
  }
1399

1400
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
6,377,215!
1401
    int ret = removeMeta(pRequest->pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type));
34,996!
1402
    if (TSDB_CODE_SUCCESS != ret) {
34,996!
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) {
6,377,604✔
1409
    code = handleQueryExecRsp(pRequest);
6,376,655✔
1410
  }
1411

1412
  if (TSDB_CODE_SUCCESS != code) {
6,378,089✔
1413
    pRequest->code = code;
26,825✔
1414
  }
1415

1416
  if (res) {
6,378,089!
1417
    *res = pRequest->body.resInfo.execRes.res;
×
1418
    pRequest->body.resInfo.execRes.res = NULL;
×
1419
  }
1420
}
6,378,089✔
1421

1422
static int32_t asyncExecSchQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta,
652,050,268✔
1423
                                 SSqlCallbackWrapper* pWrapper) {
1424
  int32_t code = TSDB_CODE_SUCCESS;
652,050,268✔
1425
  pRequest->type = pQuery->msgType;
652,050,268✔
1426
  SArray*     pMnodeList = NULL;
652,027,690✔
1427
  SQueryPlan* pDag = NULL;
652,027,690✔
1428
  int64_t     st = taosGetTimestampUs();
652,043,707✔
1429

1430
  if (!pRequest->parseOnly) {
652,043,707✔
1431
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
652,042,889✔
1432
    if (NULL == pMnodeList) {
652,038,098!
1433
      code = terrno;
×
1434
    }
1435
    SPlanContext cxt = {.queryId = pRequest->requestId,
667,412,144✔
1436
                        .acctId = pRequest->pTscObj->acctId,
652,068,667✔
1437
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
652,056,109✔
1438
                        .pAstRoot = pQuery->pRoot,
652,082,946✔
1439
                        .showRewrite = pQuery->showRewrite,
652,082,785!
1440
                        .isView = pWrapper->pParseCtx->isView,
652,068,529!
1441
                        .isAudit = pWrapper->pParseCtx->isAudit,
652,071,529!
1442
                        .pMsg = pRequest->msgBuf,
652,059,059✔
1443
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1444
                        .pUser = pRequest->pTscObj->user,
652,067,416✔
1445
                        .sysInfo = pRequest->pTscObj->sysInfo,
652,063,629✔
1446
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
652,050,732✔
1447
                        .allocatorId = pRequest->stmtBindVersion > 0 ? 0 : pRequest->allocatorRefId};
652,060,533✔
1448
    if (TSDB_CODE_SUCCESS == code) {
652,065,452✔
1449
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
652,061,691✔
1450
    }
1451
    if (code) {
652,054,971✔
1452
      tscError("req:0x%" PRIx64 ", failed to create query plan, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
356,122!
1453
               pRequest->requestId);
1454
    } else {
1455
      pRequest->body.subplanNum = pDag->numOfSubplans;
651,698,849✔
1456
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
651,711,450✔
1457
    }
1458
  }
1459

1460
  pRequest->metric.execStart = taosGetTimestampUs();
652,070,958✔
1461
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
652,060,218✔
1462

1463
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
659,699,071✔
1464
    SArray* pNodeList = NULL;
651,517,562✔
1465
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
651,519,610✔
1466
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
106,485,524✔
1467
    }
1468

1469
    SRequestConnInfo conn = {.pTrans = getAppInfo(pRequest)->pTransporter,
651,514,559✔
1470
                             .requestId = pRequest->requestId,
651,526,261✔
1471
                             .requestObjRefId = pRequest->self};
651,518,742✔
1472
    SSchedulerReq    req = {
659,211,052✔
1473
           .syncReq = false,
1474
           .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
651,520,138✔
1475
           .pConn = &conn,
1476
           .pNodeList = pNodeList,
1477
           .pDag = pDag,
1478
           .allocatorRefId = pRequest->allocatorRefId,
651,520,138✔
1479
           .sql = pRequest->sqlstr,
651,494,645✔
1480
           .startTs = pRequest->metric.start,
651,515,917✔
1481
           .execFp = schedulerExecCb,
1482
           .cbParam = pWrapper,
1483
           .chkKillFp = chkRequestKilled,
1484
           .chkKillParam = (void*)pRequest->self,
651,516,259✔
1485
           .pExecRes = NULL,
1486
           .source = pRequest->source,
651,494,650✔
1487
           .pWorkerCb = getTaskPoolWorkerCb(),
651,501,773✔
1488
    };
1489
    if (TSDB_CODE_SUCCESS == code) {
651,520,092!
1490
      code = schedulerExecJob(&req, &pRequest->body.queryJob);
651,544,993✔
1491
    }
1492

1493
    taosArrayDestroy(pNodeList);
651,516,324✔
1494
  } else {
1495
    qDestroyQueryPlan(pDag);
507,104✔
1496
    tscDebug("req:0x%" PRIx64 ", plan not executed, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
535,585!
1497
             pRequest->requestId);
1498
    destorySqlCallbackWrapper(pWrapper);
535,585✔
1499
    pRequest->pWrapper = NULL;
535,585✔
1500
    if (TSDB_CODE_SUCCESS != code) {
535,585✔
1501
      pRequest->code = terrno;
356,122✔
1502
    }
1503

1504
    doRequestCallback(pRequest, code);
535,585✔
1505
  }
1506

1507
  // todo not to be released here
1508
  taosArrayDestroy(pMnodeList);
652,079,768✔
1509

1510
  return code;
652,075,799✔
1511
}
1512

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

1516
  if (pRequest->parseOnly) {
674,058,745✔
1517
    doRequestCallback(pRequest, 0);
369,807✔
1518
    return;
369,807✔
1519
  }
1520

1521
  pRequest->body.execMode = pQuery->execMode;
673,702,253✔
1522
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
673,699,784✔
1523
    destorySqlCallbackWrapper(pWrapper);
21,635,992✔
1524
    pRequest->pWrapper = NULL;
21,637,127✔
1525
  }
1526

1527
  if (pQuery->pRoot && !pRequest->inRetry) {
673,670,655✔
1528
    STscObj*            pTscObj = pRequest->pTscObj;
673,684,730✔
1529
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
673,697,321✔
1530
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
673,694,830✔
1531
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
545,041,990✔
1532
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
495,732,609✔
1533
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
177,963,273✔
1534
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
98,805,400✔
1535
    }
1536
  }
1537

1538
  switch (pQuery->execMode) {
673,706,492!
1539
    case QUERY_EXEC_MODE_LOCAL:
6,294,349✔
1540
      asyncExecLocalCmd(pRequest, pQuery);
6,294,349✔
1541
      break;
6,294,349✔
1542
    case QUERY_EXEC_MODE_RPC:
14,872,678✔
1543
      code = asyncExecDdlQuery(pRequest, pQuery);
14,872,678✔
1544
      break;
14,873,409✔
1545
    case QUERY_EXEC_MODE_SCHEDULE: {
652,053,740✔
1546
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
652,053,740✔
1547
      break;
652,070,854✔
1548
    }
1549
    case QUERY_EXEC_MODE_EMPTY_RESULT:
469,399✔
1550
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
469,399✔
1551
      doRequestCallback(pRequest, 0);
469,399✔
1552
      break;
469,399✔
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) {
21,182✔
1561
  SCatalog* pCatalog = NULL;
21,182✔
1562
  int32_t   code = 0;
21,182✔
1563
  int32_t   dbNum = taosArrayGetSize(pRequest->dbList);
21,182✔
1564
  int32_t   tblNum = taosArrayGetSize(pRequest->tableList);
21,182✔
1565

1566
  if (dbNum <= 0 && tblNum <= 0) {
21,182!
1567
    return TSDB_CODE_APP_ERROR;
21,182✔
1568
  }
1569

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

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

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

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

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

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

UNCOV
1600
  return code;
×
1601
}
1602

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

1611
  if (isView) {
12,664,689✔
1612
    for (int32_t i = 0; i < tbNum; ++i) {
636,904✔
1613
      SName* pViewName = taosArrayGet(tbList, i);
318,452✔
1614
      char   dbFName[TSDB_DB_FNAME_LEN];
314,782✔
1615
      if (NULL == pViewName) {
318,452!
1616
        continue;
×
1617
      }
1618
      (void)tNameGetFullDbName(pViewName, dbFName);
318,452✔
1619
      TSC_ERR_RET(catalogRemoveViewMeta(pCatalog, dbFName, 0, pViewName->tname, 0));
318,452!
1620
    }
1621
  } else {
1622
    for (int32_t i = 0; i < tbNum; ++i) {
22,433,646✔
1623
      SName* pTbName = taosArrayGet(tbList, i);
10,087,409✔
1624
      TSC_ERR_RET(catalogRemoveTableMeta(pCatalog, pTbName));
10,087,409!
1625
    }
1626
  }
1627

1628
  return TSDB_CODE_SUCCESS;
12,664,689✔
1629
}
1630

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

1634
  // init mnode ip set
1635
  SEpSet* mgmtEpSet = &(pEpSet->epSet);
3,496,556✔
1636
  mgmtEpSet->numOfEps = 0;
3,496,388✔
1637
  mgmtEpSet->inUse = 0;
3,495,813✔
1638

1639
  if (firstEp && firstEp[0] != 0) {
3,496,045!
1640
    if (strlen(firstEp) >= TSDB_EP_LEN) {
3,495,600!
1641
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1642
      return -1;
×
1643
    }
1644

1645
    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
3,495,600✔
1646
    if (code != TSDB_CODE_SUCCESS) {
3,494,349!
1647
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1648
      return terrno;
×
1649
    }
1650
    // uint32_t addr = 0;
1651
    SIpAddr addr = {0};
3,494,349✔
1652
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
3,495,300✔
1653
    if (code) {
3,496,059✔
1654
      tscError("failed to resolve firstEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
1,033✔
1655
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1656
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
819!
1657
    } else {
1658
      mgmtEpSet->numOfEps++;
3,495,026✔
1659
    }
1660
  }
1661

1662
  if (secondEp && secondEp[0] != 0) {
3,496,449✔
1663
    if (strlen(secondEp) >= TSDB_EP_LEN) {
2,293,457!
1664
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1665
      return terrno;
×
1666
    }
1667

1668
    int32_t code = taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
2,293,457✔
1669
    if (code != TSDB_CODE_SUCCESS) {
2,293,671!
1670
      return code;
×
1671
    }
1672
    SIpAddr addr = {0};
2,293,671✔
1673
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
2,293,671✔
1674
    if (code) {
2,293,457✔
1675
      tscError("failed to resolve secondEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
107!
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,293,350✔
1680
    }
1681
  }
1682

1683
  if (mgmtEpSet->numOfEps == 0) {
3,495,725✔
1684
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
819✔
1685
    return TSDB_CODE_RPC_NETWORK_UNAVAIL;
819✔
1686
  }
1687

1688
  return 0;
3,495,173✔
1689
}
1690

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

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

1706
  pRequest->sqlstr = taosStrdup("taos_connect");
3,496,635!
1707
  if (pRequest->sqlstr) {
3,496,635!
1708
    pRequest->sqlLen = strlen(pRequest->sqlstr);
3,496,635!
1709
  } else {
1710
    return terrno;
×
1711
  }
1712

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

1720
  // int64_t transporterId = 0;
1721
  SEpSet epset = getEpSet_s(&(*pTscObj)->pAppInfo->mgmtEp);
3,496,096✔
1722
  code = asyncSendMsgToServer((*pTscObj)->pAppInfo->pTransporter, &epset, NULL, body);
3,496,339✔
1723
  if (TSDB_CODE_SUCCESS != code) {
3,496,286!
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,496,286!
1729
    destroyTscObj(*pTscObj);
×
1730
    tscError("failed to wait sem, code:%s", terrstr());
×
1731
    return terrno;
×
1732
  }
1733
  if (pRequest->code != TSDB_CODE_SUCCESS) {
3,496,749✔
1734
    const char* errorMsg = (code == TSDB_CODE_RPC_FQDN_ERROR) ? taos_errstr(pRequest) : tstrerror(pRequest->code);
5,879!
1735
    tscError("failed to connect to server, reason: %s", errorMsg);
5,879!
1736

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

1750
static int32_t buildConnectMsg(SRequestObj* pRequest, SMsgSendInfo** pMsgSendInfo) {
3,496,528✔
1751
  *pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
3,496,528!
1752
  if (*pMsgSendInfo == NULL) {
3,496,749!
1753
    return terrno;
×
1754
  }
1755

1756
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
3,496,749✔
1757

1758
  (*pMsgSendInfo)->requestObjRefId = pRequest->self;
3,496,749✔
1759
  (*pMsgSendInfo)->requestId = pRequest->requestId;
3,496,749✔
1760
  (*pMsgSendInfo)->fp = getMsgRspHandle((*pMsgSendInfo)->msgType);
3,496,749✔
1761
  (*pMsgSendInfo)->param = taosMemoryCalloc(1, sizeof(pRequest->self));
3,496,619!
1762
  if (NULL == (*pMsgSendInfo)->param) {
3,496,619!
1763
    taosMemoryFree(*pMsgSendInfo);
×
1764
    return terrno;
×
1765
  }
1766

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

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

1772
  char* db = getDbOfConnection(pObj);
3,496,207✔
1773
  if (db != NULL) {
3,496,290✔
1774
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
1,603,823!
1775
  } else if (terrno) {
1,892,467!
1776
    taosMemoryFree(*pMsgSendInfo);
×
1777
    return terrno;
×
1778
  }
1779
  taosMemoryFreeClear(db);
3,496,290!
1780

1781
  connectReq.connType = pObj->connType;
3,496,749✔
1782
  connectReq.pid = appInfo.pid;
3,496,749✔
1783
  connectReq.startTime = appInfo.startTime;
3,496,749✔
1784

1785
  tstrncpy(connectReq.app, appInfo.appName, sizeof(connectReq.app));
3,496,749!
1786
  tstrncpy(connectReq.user, pObj->user, sizeof(connectReq.user));
3,496,749!
1787
  tstrncpy(connectReq.passwd, pObj->pass, sizeof(connectReq.passwd));
3,496,749!
1788
  tstrncpy(connectReq.sVer, td_version, sizeof(connectReq.sVer));
3,496,749!
1789

1790
  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connectReq);
3,496,749✔
1791
  void*   pReq = taosMemoryMalloc(contLen);
3,496,009!
1792
  if (NULL == pReq) {
3,496,633!
1793
    taosMemoryFree(*pMsgSendInfo);
×
1794
    return terrno;
×
1795
  }
1796

1797
  if (-1 == tSerializeSConnectReq(pReq, contLen, &connectReq)) {
3,496,633!
UNCOV
1798
    taosMemoryFree(*pMsgSendInfo);
×
1799
    taosMemoryFree(pReq);
×
1800
    return terrno;
×
1801
  }
1802

1803
  (*pMsgSendInfo)->msgInfo.len = contLen;
3,496,179✔
1804
  (*pMsgSendInfo)->msgInfo.pData = pReq;
3,496,504✔
1805
  return TSDB_CODE_SUCCESS;
3,496,504✔
1806
}
1807

1808
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,379,370,063✔
1809
  if (NULL == pEpSet) {
1,379,370,063✔
1810
    return;
1,319,673,059✔
1811
  }
1812

1813
  switch (pSendInfo->target.type) {
59,697,004✔
1814
    case TARGET_TYPE_MNODE:
1,288✔
1815
      if (NULL == pTscObj) {
1,288!
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);
1,288✔
1822
      SEpSet* pOrig = &originEpset;
1,288✔
1823
      SEp*    pOrigEp = &pOrig->eps[pOrig->inUse];
1,288✔
1824
      SEp*    pNewEp = &pEpSet->eps[pEpSet->inUse];
1,288✔
1825
      tscDebug("mnode epset updated from %d/%d=>%s:%d to %d/%d=>%s:%d in client", pOrig->inUse, pOrig->numOfEps,
1,288!
1826
               pOrigEp->fqdn, pOrigEp->port, pEpSet->inUse, pEpSet->numOfEps, pNewEp->fqdn, pNewEp->port);
1827
      updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
1,288✔
1828
      break;
348,485✔
1829
    case TARGET_TYPE_VNODE: {
59,478,014✔
1830
      if (NULL == pTscObj) {
59,478,014!
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;
59,478,014✔
1837
      int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
59,478,014✔
1838
      if (code != TSDB_CODE_SUCCESS) {
59,477,297!
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);
59,477,297✔
1845
      if (code != TSDB_CODE_SUCCESS) {
59,478,170!
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);
59,478,170!
1851
      break;
59,478,170✔
1852
    }
1853
    default:
217,035✔
1854
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
217,035!
1855
      break;
216,916✔
1856
  }
1857
}
1858

1859
int32_t doProcessMsgFromServerImpl(SRpcMsg* pMsg, SEpSet* pEpSet) {
1,383,834,986✔
1860
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
1,383,834,986✔
1861
  if (pMsg->info.ahandle == NULL) {
1,383,834,804✔
1862
    tscError("doProcessMsgFromServer pMsg->info.ahandle == NULL");
4,463,432!
1863
    rpcFreeCont(pMsg->pCont);
4,463,432✔
1864
    taosMemoryFree(pEpSet);
4,463,432!
1865
    return TSDB_CODE_TSC_INTERNAL_ERROR;
4,463,432✔
1866
  }
1867

1868
  STscObj* pTscObj = NULL;
1,379,372,432✔
1869

1870
  STraceId* trace = &pMsg->info.traceId;
1,379,372,432✔
1871
  char      tbuf[40] = {0};
1,379,373,356✔
1872
  TRACE_TO_STR(trace, tbuf);
1,379,372,947!
1873

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

1877
  if (pSendInfo->requestObjRefId != 0) {
1,379,374,146✔
1878
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
1,141,903,000✔
1879
    if (pRequest) {
1,141,901,461✔
1880
      if (pRequest->self != pSendInfo->requestObjRefId) {
1,141,720,674!
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;
1,141,720,780✔
1893
    }
1894
  }
1895

1896
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
1,379,373,958✔
1897

1898
  SDataBuf buf = {.msgType = pMsg->msgType,
1,379,368,451✔
1899
                  .len = pMsg->contLen,
1,379,369,945✔
1900
                  .pData = NULL,
1901
                  .handle = pMsg->info.handle,
1,379,371,303✔
1902
                  .handleRefId = pMsg->info.refId,
1,379,371,175✔
1903
                  .pEpSet = pEpSet};
1904

1905
  if (pMsg->contLen > 0) {
1,379,370,303✔
1906
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
1,229,568,519!
1907
    if (buf.pData == NULL) {
1,229,561,316!
1908
      pMsg->code = terrno;
×
1909
    } else {
1910
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
1,229,561,316!
1911
    }
1912
  }
1913

1914
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
1,379,370,855✔
1915

1916
  if (pTscObj) {
1,379,345,998✔
1917
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
1,141,701,623✔
1918
    if (TSDB_CODE_SUCCESS != code) {
1,141,721,005✔
1919
      tscError("doProcessMsgFromServer taosReleaseRef failed");
719!
1920
      terrno = code;
719✔
1921
      pMsg->code = code;
719✔
1922
    }
1923
  }
1924

1925
  rpcFreeCont(pMsg->pCont);
1,379,365,380✔
1926
  destroySendMsgInfo(pSendInfo);
1,379,346,633✔
1927
  return TSDB_CODE_SUCCESS;
1,379,338,124✔
1928
}
1929

1930
int32_t doProcessMsgFromServer(void* param) {
1,383,835,366✔
1931
  AsyncArg* arg = (AsyncArg*)param;
1,383,835,366✔
1932
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
1,383,835,366✔
1933
  taosMemoryFree(arg);
1,383,799,997!
1934
  return code;
1,383,815,958✔
1935
}
1936

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

1941
  tscDebug("msg callback, ahandle %p", pMsg->info.ahandle);
1,383,824,085✔
1942

1943
  if (pEpSet != NULL) {
1,383,821,708✔
1944
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
59,696,030!
1945
    if (NULL == tEpSet) {
59,696,030!
1946
      code = terrno;
×
1947
      pMsg->code = terrno;
×
1948
      goto _exit;
×
1949
    }
1950
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
59,696,030!
1951
  }
1952

1953
  // pMsg is response msg
1954
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
1,383,821,708✔
1955
    // restore origin code
1956
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
3,496,749!
1957
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1958
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
3,496,749!
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,380,333,513!
1964
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
1965
    }
1966
  }
1967

1968
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
1,383,834,045!
1969
  if (NULL == arg) {
1,383,823,138!
1970
    code = terrno;
×
1971
    pMsg->code = code;
×
1972
    goto _exit;
×
1973
  }
1974

1975
  arg->msg = *pMsg;
1,383,823,138✔
1976
  arg->pEpset = tEpSet;
1,383,823,793✔
1977

1978
  if ((code = taosAsyncExec(doProcessMsgFromServer, arg, NULL)) != 0) {
1,383,829,886✔
1979
    pMsg->code = code;
60✔
1980
    taosMemoryFree(arg);
60!
1981
    goto _exit;
×
1982
  }
1983
  return;
1,383,834,098✔
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) {
850✔
1994
  tscInfo("try to connect to %s:%u by auth, user:%s db:%s", ip, port, user, db);
850!
1995
  if (user == NULL) {
850!
1996
    user = TSDB_DEFAULT_USER;
×
1997
  }
1998

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

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

2015
  return NULL;
680✔
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,907,269,538✔
2042

2043
        if (IS_STR_DATA_BLOB(type)) {
1,907,248,861✔
2044
          pResultInfo->length[i] = blobDataLen(pStart);
19,134✔
2045
          pResultInfo->row[i] = blobDataVal(pStart);
18,501✔
2046
        } else {
2047
          pResultInfo->length[i] = varDataLen(pStart);
1,907,258,299✔
2048
          pResultInfo->row[i] = varDataVal(pStart);
1,907,257,120✔
2049
        }
2050
      } else {
2051
        pResultInfo->row[i] = NULL;
299,951,357✔
2052
        pResultInfo->length[i] = 0;
299,956,923✔
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;
930,138,495✔
2060
        pResultInfo->length[i] = 0;
930,019,397✔
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) {
110,587,370✔
2117
  tsem_t* sem = param;
110,587,370✔
2118
  if (TSDB_CODE_SUCCESS != tsem_post(sem)) {
110,587,370!
2119
    tscError("failed to post sem, code:%s", terrstr());
×
2120
  }
2121
}
110,588,367✔
2122

2123
void* doAsyncFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
1,274,714,491✔
2124
  if (pRequest == NULL) {
1,274,714,491!
2125
    return NULL;
×
2126
  }
2127

2128
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
1,274,714,491✔
2129
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
1,274,714,856✔
2130
    // All data has returned to App already, no need to try again
2131
    if (pResultInfo->completed) {
197,727,579✔
2132
      pResultInfo->numOfRows = 0;
87,140,681✔
2133
      return NULL;
87,140,681✔
2134
    }
2135

2136
    // convert ucs4 to native multi-bytes string
2137
    pResultInfo->convertUcs4 = convertUcs4;
110,587,950✔
2138
    tsem_t sem;
108,948,152✔
2139
    if (TSDB_CODE_SUCCESS != tsem_init(&sem, 0, 0)) {
110,588,295!
2140
      tscError("failed to init sem, code:%s", terrstr());
×
2141
    }
2142
    taos_fetch_rows_a(pRequest, syncFetchFn, &sem);
110,587,677✔
2143
    if (TSDB_CODE_SUCCESS != tsem_wait(&sem)) {
110,588,367!
2144
      tscError("failed to wait sem, code:%s", terrstr());
×
2145
    }
2146
    if (TSDB_CODE_SUCCESS != tsem_destroy(&sem)) {
110,588,367!
2147
      tscError("failed to destroy sem, code:%s", terrstr());
×
2148
    }
2149
    pRequest->inCallback = false;
110,588,367✔
2150
  }
2151

2152
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
1,187,575,299✔
2153
    return NULL;
8,334,813✔
2154
  } else {
2155
    if (setupOneRowPtr) {
1,179,240,486✔
2156
      doSetOneRowPtr(pResultInfo);
1,079,478,168✔
2157
      pResultInfo->current += 1;
1,079,455,685✔
2158
    }
2159

2160
    return pResultInfo->row;
1,179,217,662✔
2161
  }
2162
}
2163

2164
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
137,180,410✔
2165
  if (pResInfo->row == NULL) {
137,180,410✔
2166
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
119,577,410!
2167
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
119,579,355!
2168
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
119,578,170!
2169
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
119,577,725!
2170

2171
    if (pResInfo->row == NULL || pResInfo->pCol == NULL || pResInfo->length == NULL || pResInfo->convertBuf == NULL) {
119,578,420✔
2172
      taosMemoryFree(pResInfo->row);
3,180!
2173
      taosMemoryFree(pResInfo->pCol);
×
2174
      taosMemoryFree(pResInfo->length);
×
2175
      taosMemoryFree(pResInfo->convertBuf);
×
2176
      return terrno;
×
2177
    }
2178
  }
2179

2180
  return TSDB_CODE_SUCCESS;
137,181,528✔
2181
}
2182

2183
static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength, bool isStmt) {
137,079,966✔
2184
  int32_t idx = -1;
137,079,966✔
2185
  iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt);
137,080,311✔
2186
  if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR;
137,077,821!
2187

2188
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
786,398,885✔
2189
    int32_t type = pResultInfo->fields[i].type;
649,327,499✔
2190
    int32_t schemaBytes =
2191
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
649,325,582✔
2192

2193
    if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) {
649,324,035✔
2194
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
27,136,899!
2195
      if (p == NULL) {
27,136,980!
2196
        taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
×
2197
        return terrno;
×
2198
      }
2199

2200
      pResultInfo->convertBuf[i] = p;
27,136,980✔
2201

2202
      SResultColumn* pCol = &pResultInfo->pCol[i];
27,136,980✔
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(
729✔
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);
729✔
2214
            return TSDB_CODE_TSC_INTERNAL_ERROR;
36✔
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];
27,136,568✔
2224
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
27,136,487✔
2225
    }
2226
  }
2227
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
137,077,591✔
2228
  return TSDB_CODE_SUCCESS;
137,080,534✔
2229
}
2230

2231
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
137,078,550✔
2232
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
786,393,441✔
2233
    TAOS_FIELD_E* pFieldE = pResultInfo->fields + i;
649,321,654✔
2234
    TAOS_FIELD*   pField = pResultInfo->userFields + i;
649,320,001✔
2235
    int32_t       type = pFieldE->type;
649,319,598✔
2236
    int32_t       bufLen = 0;
649,319,785✔
2237
    char*         p = NULL;
649,319,785✔
2238
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
649,319,785✔
2239
      continue;
648,859,468✔
2240
    } else {
2241
      bufLen = 64;
454,033✔
2242
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
454,033!
2243
      pFieldE->bytes = bufLen;
454,033✔
2244
      pField->bytes = bufLen;
454,033✔
2245
    }
2246
    if (!p) return terrno;
454,033!
2247
    pResultInfo->convertBuf[i] = p;
454,033✔
2248

2249
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
312,196,026✔
2250
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
311,741,993✔
2251
                                  pFieldE->precision, pFieldE->scale, p, bufLen);
311,741,993✔
2252
      p += bufLen;
311,741,993✔
2253
      if (TSDB_CODE_SUCCESS != code) {
311,741,993!
2254
        return code;
×
2255
      }
2256
    }
2257
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
454,033✔
2258
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
454,033✔
2259
  }
2260
  return 0;
137,078,022✔
2261
}
2262

2263
int32_t getVersion1BlockMetaSize(const char* p, int32_t numOfCols) {
348,516✔
2264
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) * 3 + sizeof(uint64_t) +
696,440✔
2265
         numOfCols * (sizeof(int8_t) + sizeof(int32_t));
347,924✔
2266
}
2267

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

2272
  int32_t numOfRows = pResultInfo->numOfRows;
174,258✔
2273
  int32_t numOfCols = pResultInfo->numOfCols;
174,258✔
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);
174,258✔
2278
  if (numOfCols != cols) {
174,258!
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);
174,258✔
2284
  int32_t* colLength = (int32_t*)(p + len);
174,258✔
2285
  len += sizeof(int32_t) * numOfCols;
174,258✔
2286

2287
  char* pStart = p + len;
174,258✔
2288
  for (int32_t i = 0; i < numOfCols; ++i) {
767,894✔
2289
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
593,636!
2290

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

2297
      int32_t estimateColLen = 0;
238,366✔
2298
      for (int32_t j = 0; j < numOfRows; ++j) {
1,646,182✔
2299
        if (offset[j] == -1) {
1,407,816✔
2300
          continue;
36,652✔
2301
        }
2302
        char* data = offset[j] + pStart;
1,371,164✔
2303

2304
        int32_t jsonInnerType = *data;
1,371,164✔
2305
        char*   jsonInnerData = data + CHAR_BYTES;
1,371,164✔
2306
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
1,371,164✔
2307
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
4,140✔
2308
        } else if (tTagIsJson(data)) {
1,367,024✔
2309
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
151,181✔
2310
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
1,215,843✔
2311
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
1,198,823✔
2312
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
17,020✔
2313
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
12,420✔
2314
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
4,600!
2315
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
4,600✔
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);
238,366✔
2324
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
355,270!
2325
      int32_t lenTmp = numOfRows * sizeof(int32_t);
22,770✔
2326
      len += (lenTmp + colLen);
22,770✔
2327
      pStart += lenTmp;
22,770✔
2328
    } else {
2329
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
332,500✔
2330
      len += (lenTmp + colLen);
332,500✔
2331
      pStart += lenTmp;
332,500✔
2332
    }
2333
    pStart += colLen;
593,636✔
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);
174,258✔
2339
  return len;
174,258✔
2340
}
2341

2342
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
137,180,317✔
2343
  int32_t numOfRows = pResultInfo->numOfRows;
137,180,317✔
2344
  int32_t numOfCols = pResultInfo->numOfCols;
137,180,662✔
2345
  bool    needConvert = false;
137,182,207✔
2346
  for (int32_t i = 0; i < numOfCols; ++i) {
786,747,112✔
2347
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
649,738,580✔
2348
      needConvert = true;
174,258✔
2349
      break;
174,258✔
2350
    }
2351
  }
2352

2353
  if (!needConvert) {
137,182,790✔
2354
    return TSDB_CODE_SUCCESS;
137,008,604✔
2355
  }
2356

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

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

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

2372
  int32_t totalLen = 0;
174,258✔
2373
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
174,258✔
2374
  if (numOfCols != cols) {
174,258!
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);
174,258✔
2380
  (void)memcpy(p1, p, len);
174,258!
2381

2382
  p += len;
174,258✔
2383
  p1 += len;
174,258✔
2384
  totalLen += len;
174,258✔
2385

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

2394
  char* pStart = p;
174,258✔
2395
  char* pStart1 = p1;
174,258✔
2396
  for (int32_t i = 0; i < numOfCols; ++i) {
767,894✔
2397
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
593,636!
2398
    int32_t colLen1 = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength1[i]) : colLength1[i];
593,636!
2399
    if (colLen >= dataLen) {
593,636!
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) {
593,636✔
2404
      int32_t* offset = (int32_t*)pStart;
238,366✔
2405
      int32_t* offset1 = (int32_t*)pStart1;
238,366✔
2406
      len = numOfRows * sizeof(int32_t);
238,366✔
2407
      (void)memcpy(pStart1, pStart, len);
238,366!
2408
      pStart += len;
238,366✔
2409
      pStart1 += len;
238,366✔
2410
      totalLen += len;
238,366✔
2411

2412
      len = 0;
238,366✔
2413
      for (int32_t j = 0; j < numOfRows; ++j) {
1,646,182✔
2414
        if (offset[j] == -1) {
1,407,816✔
2415
          continue;
36,652✔
2416
        }
2417
        char* data = offset[j] + pStart;
1,371,164✔
2418

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

2461
        offset1[j] = len;
1,371,164✔
2462
        (void)memcpy(pStart1 + len, dst, varDataTLen(dst));
1,371,164!
2463
        len += varDataTLen(dst);
1,371,164✔
2464
      }
2465
      colLen1 = len;
238,366✔
2466
      totalLen += colLen1;
238,366✔
2467
      colLength1[i] = (blockVersion == BLOCK_VERSION_1) ? htonl(len) : len;
238,366!
2468
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
355,270!
2469
      len = numOfRows * sizeof(int32_t);
22,770✔
2470
      (void)memcpy(pStart1, pStart, len);
22,770!
2471
      pStart += len;
22,770✔
2472
      pStart1 += len;
22,770✔
2473
      totalLen += len;
22,770✔
2474
      totalLen += colLen;
22,770✔
2475
      (void)memcpy(pStart1, pStart, colLen);
22,770!
2476
    } else {
2477
      len = BitmapLen(pResultInfo->numOfRows);
332,500✔
2478
      (void)memcpy(pStart1, pStart, len);
332,500!
2479
      pStart += len;
332,500✔
2480
      pStart1 += len;
332,500✔
2481
      totalLen += len;
332,500✔
2482
      totalLen += colLen;
332,500✔
2483
      (void)memcpy(pStart1, pStart, colLen);
332,500!
2484
    }
2485
    pStart += colLen;
593,636✔
2486
    pStart1 += colLen1;
593,636✔
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);
174,258✔
2493

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

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

2506
  if (pResultInfo->numOfRows == 0) {
145,963,772✔
2507
    return TSDB_CODE_SUCCESS;
8,782,444✔
2508
  }
2509

2510
  if (pResultInfo->pData == NULL) {
137,181,777!
2511
    tscError("setResultDataPtr error: pData is NULL");
×
2512
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2513
  }
2514

2515
  int32_t code = doPrepareResPtr(pResultInfo);
137,178,668✔
2516
  if (code != TSDB_CODE_SUCCESS) {
137,181,038!
2517
    return code;
×
2518
  }
2519
  code = doConvertJson(pResultInfo);
137,181,038✔
2520
  if (code != TSDB_CODE_SUCCESS) {
137,181,528!
2521
    return code;
×
2522
  }
2523

2524
  char* p = (char*)pResultInfo->pData;
137,181,528✔
2525

2526
  // version:
2527
  int32_t blockVersion = *(int32_t*)p;
137,181,528✔
2528
  p += sizeof(int32_t);
137,181,810✔
2529

2530
  int32_t dataLen = *(int32_t*)p;
137,182,594✔
2531
  p += sizeof(int32_t);
137,182,594✔
2532

2533
  int32_t rows = *(int32_t*)p;
137,182,439✔
2534
  p += sizeof(int32_t);
137,182,439✔
2535

2536
  int32_t cols = *(int32_t*)p;
137,182,689✔
2537
  p += sizeof(int32_t);
137,182,348✔
2538

2539
  if (rows != pResultInfo->numOfRows || cols != pResultInfo->numOfCols) {
137,182,249!
2540
    tscError("setResultDataPtr paras error:rows;%d numOfRows:%" PRId64 " cols:%d numOfCols:%d", rows,
2,411!
2541
             pResultInfo->numOfRows, cols, pResultInfo->numOfCols);
2542
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2543
  }
2544

2545
  int32_t hasColumnSeg = *(int32_t*)p;
137,180,583✔
2546
  p += sizeof(int32_t);
137,180,940✔
2547

2548
  uint64_t groupId = taosGetUInt64Aligned((uint64_t*)p);
137,182,284✔
2549
  p += sizeof(uint64_t);
137,182,284✔
2550

2551
  // check fields
2552
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
786,992,698✔
2553
    int8_t type = *(int8_t*)p;
649,815,153✔
2554
    p += sizeof(int8_t);
649,812,054✔
2555

2556
    int32_t bytes = *(int32_t*)p;
649,813,844✔
2557
    p += sizeof(int32_t);
649,813,382✔
2558

2559
    if (IS_DECIMAL_TYPE(type) && pResultInfo->fields[i].precision == 0) {
649,811,951!
2560
      extractDecimalTypeInfoFromBytes(&bytes, &pResultInfo->fields[i].precision, &pResultInfo->fields[i].scale);
×
2561
    }
2562
  }
2563

2564
  int32_t* colLength = (int32_t*)p;
137,181,085✔
2565
  p += sizeof(int32_t) * pResultInfo->numOfCols;
137,181,085✔
2566

2567
  char* pStart = p;
137,181,689✔
2568
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
786,999,787✔
2569
    if ((pStart - pResultInfo->pData) >= dataLen) {
649,817,373!
2570
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2571
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2572
    }
2573
    if (blockVersion == BLOCK_VERSION_1) {
649,812,287✔
2574
      colLength[i] = htonl(colLength[i]);
526,717,561✔
2575
    }
2576
    if (colLength[i] >= dataLen) {
649,812,997!
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)) {
649,811,151✔
2581
      tscError("invalid type %d", pResultInfo->fields[i].type);
5,120!
2582
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2583
    }
2584
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
649,816,025✔
2585
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
161,670,904✔
2586
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
161,670,610✔
2587
    } else {
2588
      pResultInfo->pCol[i].nullbitmap = pStart;
488,149,957✔
2589
      pStart += BitmapLen(pResultInfo->numOfRows);
488,153,291✔
2590
    }
2591

2592
    pResultInfo->pCol[i].pData = pStart;
649,823,607✔
2593
    pResultInfo->length[i] =
1,299,640,445✔
2594
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
1,287,567,201✔
2595
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
649,820,917✔
2596

2597
    pStart += colLength[i];
649,818,458✔
2598
  }
2599

2600
  p = pStart;
137,182,184✔
2601
  // bool blankFill = *(bool*)p;
2602
  p += sizeof(bool);
137,182,184✔
2603
  int32_t offset = p - pResultInfo->pData;
137,182,890✔
2604
  if (offset > dataLen) {
137,182,464!
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) {
137,182,464✔
2611
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
137,080,156✔
2612
  }
2613
#endif
2614
  if (TSDB_CODE_SUCCESS == code && convertForDecimal) {
137,182,878!
2615
    code = convertDecimalType(pResultInfo);
137,080,534✔
2616
  }
2617
  return code;
137,179,907✔
2618
}
2619

2620
char* getDbOfConnection(STscObj* pObj) {
725,901,133✔
2621
  terrno = TSDB_CODE_SUCCESS;
725,901,133✔
2622
  char* p = NULL;
725,899,315✔
2623
  (void)taosThreadMutexLock(&pObj->mutex);
725,899,315✔
2624
  size_t len = strlen(pObj->db);
725,909,108!
2625
  if (len > 0) {
725,909,149✔
2626
    p = taosStrndup(pObj->db, tListLen(pObj->db));
636,859,747!
2627
    if (p == NULL) {
636,855,762!
2628
      tscError("failed to taosStrndup db name");
×
2629
    }
2630
  }
2631

2632
  (void)taosThreadMutexUnlock(&pObj->mutex);
725,905,164✔
2633
  return p;
725,899,012✔
2634
}
2635

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

2642
  (void)taosThreadMutexLock(&pTscObj->mutex);
3,007,804✔
2643
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
3,007,887!
2644
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
3,007,887✔
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,
121,042,725✔
2658
                              bool isStmt) {
2659
  if (pResultInfo == NULL || pRsp == NULL) {
121,042,725!
2660
    tscError("setQueryResultFromRsp paras is null");
361!
2661
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2662
  }
2663

2664
  taosMemoryFreeClear(pResultInfo->pRspMsg);
121,042,364!
2665
  pResultInfo->pRspMsg = (const char*)pRsp;
121,043,435✔
2666
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
121,042,725✔
2667
  pResultInfo->current = 0;
121,042,312✔
2668
  pResultInfo->completed = (pRsp->completed == 1);
121,042,312✔
2669
  pResultInfo->precision = pRsp->precision;
121,041,955✔
2670

2671
  // decompress data if needed
2672
  int32_t payloadLen = htonl(pRsp->payloadLen);
121,042,653✔
2673

2674
  if (pRsp->compressed) {
121,041,277!
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) {
121,041,622✔
2697
    int32_t compLen = *(int32_t*)pRsp->data;
112,260,765✔
2698
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
112,260,420✔
2699

2700
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
112,260,765✔
2701

2702
    if (pRsp->compressed && compLen < rawLen) {
112,260,769!
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;
112,260,103✔
2716
      pResultInfo->payloadLen = htonl(pRsp->compLen);
112,261,130✔
2717
      if (pRsp->compLen != pRsp->payloadLen) {
112,260,478!
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;
121,040,571✔
2726

2727
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
121,042,998✔
2728
  return code;
121,041,713✔
2729
}
2730

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

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

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

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

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

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

2777
  if (fqdn == NULL) {
1,039!
2778
    fqdn = tsLocalFqdn;
1,039✔
2779
  }
2780

2781
  if (port == 0) {
1,039!
2782
    port = tsServerPort;
1,039✔
2783
  }
2784

2785
  tstrncpy(epSet.eps[0].fqdn, fqdn, TSDB_FQDN_LEN);
1,039!
2786
  epSet.eps[0].port = (uint16_t)port;
1,039✔
2787
  int32_t ret = rpcSendRecv(clientRpc, &epSet, &rpcMsg, &rpcRsp);
1,039✔
2788
  if (TSDB_CODE_SUCCESS != ret) {
1,039!
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) {
1,039!
2794
    tscError("failed to send server status req since %s", terrstr());
169!
2795
    goto _OVER;
169✔
2796
  }
2797

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

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

2808
_OVER:
952✔
2809
  if (clientRpc != NULL) {
1,039!
2810
    rpcClose(clientRpc);
1,039✔
2811
  }
2812
  if (rpcRsp.pCont != NULL) {
1,039✔
2813
    rpcFreeCont(rpcRsp.pCont);
870✔
2814
  }
2815
  return code;
1,039✔
2816
}
2817

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

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

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

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

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

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

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

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

2874
  return TSDB_CODE_SUCCESS;
1,482✔
2875
}
2876

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

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

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

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

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

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

2905
      break;
1,482✔
2906
    }
2907

2908
    if ('`' == *(tbList + i)) {
5,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) {
5,928!
2922
      if (vPos[vIdx] < 0) {
×
2923
        vPos[vIdx] = i;
×
2924
      }
2925
      continue;
×
2926
    }
2927

2928
    if ('.' == *(tbList + i)) {
5,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)) {
5,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)) {
5,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)) ||
5,928!
2969
        ('0' <= *(tbList + i) && '9' >= *(tbList + i)) || ('_' == *(tbList + i))) {
741!
2970
      if (vLen[vIdx] > 0) {
5,928!
2971
        goto _return;
×
2972
      }
2973
      if (vPos[vIdx] < 0) {
5,928✔
2974
        vPos[vIdx] = i;
1,482✔
2975
      }
2976
      continue;
5,928✔
2977
    }
2978

2979
    goto _return;
×
2980
  }
2981

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

2996
  taosHashCleanup(pHash);
1,482✔
2997

2998
  return TSDB_CODE_SUCCESS;
1,482✔
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,482✔
3017
  SSyncQueryParam* pParam = param;
1,482✔
3018
  pParam->pRequest->code = code;
1,482✔
3019

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

3025
void syncQueryFn(void* param, void* res, int32_t code) {
716,546,064✔
3026
  SSyncQueryParam* pParam = param;
716,546,064✔
3027
  pParam->pRequest = res;
716,546,064✔
3028

3029
  if (pParam->pRequest) {
716,548,804!
3030
    pParam->pRequest->code = code;
716,529,489✔
3031
    clientOperateReport(pParam->pRequest);
716,540,834✔
3032
  }
3033

3034
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
716,528,471!
3035
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3036
  }
3037
}
716,554,506✔
3038

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

3047
    return;
×
3048
  }
3049

3050
  size_t sqlLen = strlen(sql);
715,979,091!
3051
  if (sqlLen > (size_t)TSDB_MAX_ALLOWED_SQL_LEN) {
715,979,091✔
3052
    tscError("conn:0x%" PRIx64 ", sql string exceeds max length:%d", connId, TSDB_MAX_ALLOWED_SQL_LEN);
484!
3053
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
484✔
3054
    fp(param, NULL, terrno);
484✔
3055
    return;
484✔
3056
  }
3057

3058
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, sql:%s", connId, sql);
715,978,607✔
3059

3060
  SRequestObj* pRequest = NULL;
715,979,046✔
3061
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
715,990,855✔
3062
  if (code != TSDB_CODE_SUCCESS) {
715,985,458!
3063
    terrno = code;
×
3064
    fp(param, NULL, terrno);
×
3065
    return;
×
3066
  }
3067

3068
  pRequest->source = source;
715,985,458✔
3069
  pRequest->body.queryFp = fp;
715,990,311✔
3070
  doAsyncQuery(pRequest, false);
715,986,446✔
3071
}
3072

3073
void taosAsyncQueryImplWithReqid(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
231✔
3074
                                 int64_t reqid) {
3075
  if (sql == NULL || NULL == fp) {
231!
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);
231!
3085
  if (sqlLen > (size_t)TSDB_MAX_ALLOWED_SQL_LEN) {
231!
3086
    tscError("conn:0x%" PRIx64 ", QID:0x%" PRIx64 ", sql string exceeds max length:%d", connId, reqid,
×
3087
             TSDB_MAX_ALLOWED_SQL_LEN);
3088
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
3089
    fp(param, NULL, terrno);
×
3090
    return;
×
3091
  }
3092

3093
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, QID:0x%" PRIx64 ", sql:%s", connId, reqid, sql);
231!
3094

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

3103
  pRequest->body.queryFp = fp;
231✔
3104
  doAsyncQuery(pRequest, false);
231✔
3105
}
3106

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

3113
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
715,943,621!
3114
  if (NULL == param) {
715,944,298!
3115
    return NULL;
×
3116
  }
3117
  int32_t code = tsem_init(&param->sem, 0, 0);
715,944,298✔
3118
  if (TSDB_CODE_SUCCESS != code) {
715,944,055!
3119
    taosMemoryFree(param);
×
3120
    return NULL;
×
3121
  }
3122

3123
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
715,944,055✔
3124
  code = tsem_wait(&param->sem);
715,934,651✔
3125
  if (TSDB_CODE_SUCCESS != code) {
715,950,514!
3126
    taosMemoryFree(param);
×
3127
    return NULL;
×
3128
  }
3129
  code = tsem_destroy(&param->sem);
715,950,514✔
3130
  if (TSDB_CODE_SUCCESS != code) {
715,953,227!
3131
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3132
  }
3133

3134
  SRequestObj* pRequest = NULL;
715,953,312✔
3135
  if (param->pRequest != NULL) {
715,953,312✔
3136
    param->pRequest->syncQuery = true;
715,951,744✔
3137
    pRequest = param->pRequest;
715,954,412✔
3138
    param->pRequest->inCallback = false;
715,952,189✔
3139
  }
3140
  taosMemoryFree(param);
715,951,958!
3141

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

3145
  return pRequest;
715,951,037✔
3146
}
3147

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

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

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

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

3180
  return pRequest;
231✔
3181
}
3182

3183
static void fetchCallback(void* pResult, void* param, int32_t code) {
117,270,764✔
3184
  SRequestObj* pRequest = (SRequestObj*)param;
117,270,764✔
3185

3186
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
117,270,764✔
3187

3188
  tscDebug("req:0x%" PRIx64 ", enter scheduler fetch cb, code:%d - %s, QID:0x%" PRIx64, pRequest->self, code,
117,271,109✔
3189
           tstrerror(code), pRequest->requestId);
3190

3191
  pResultInfo->pData = pResult;
117,271,037✔
3192
  pResultInfo->numOfRows = 0;
117,270,692✔
3193

3194
  if (code != TSDB_CODE_SUCCESS) {
117,268,578!
3195
    pRequest->code = code;
×
3196
    taosMemoryFreeClear(pResultInfo->pData);
×
3197
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
×
3198
    return;
×
3199
  }
3200

3201
  if (pRequest->code != TSDB_CODE_SUCCESS) {
117,268,578!
3202
    taosMemoryFreeClear(pResultInfo->pData);
×
3203
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pRequest->code);
×
3204
    return;
×
3205
  }
3206

3207
  pRequest->code = setQueryResultFromRsp(pResultInfo, (const SRetrieveTableRsp*)pResultInfo->pData,
118,910,829✔
3208
                                         pResultInfo->convertUcs4, pRequest->stmtBindVersion > 0);
117,270,692!
3209
  if (pRequest->code != TSDB_CODE_SUCCESS) {
117,269,752✔
3210
    pResultInfo->numOfRows = 0;
36✔
3211
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self,
36!
3212
             tstrerror(pRequest->code), pRequest->requestId);
3213
  } else {
3214
    tscDebug(
117,269,379!
3215
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
3216
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
3217

3218
    STscObj*            pTscObj = pRequest->pTscObj;
117,269,379✔
3219
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
117,270,291✔
3220
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
117,269,930✔
3221
  }
3222

3223
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
117,270,443✔
3224
}
3225

3226
void taosAsyncFetchImpl(SRequestObj* pRequest, __taos_async_fn_t fp, void* param) {
125,148,123✔
3227
  pRequest->body.fetchFp = fp;
125,148,123✔
3228
  ((SSyncQueryParam*)pRequest->body.interParam)->userParam = param;
125,148,123✔
3229

3230
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
125,148,123✔
3231

3232
  // this query has no results or error exists, return directly
3233
  if (taos_num_fields(pRequest) == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
125,148,123!
3234
    pResultInfo->numOfRows = 0;
×
3235
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
×
3236
    return;
986✔
3237
  }
3238

3239
  // all data has returned to App already, no need to try again
3240
  if (pResultInfo->completed) {
125,148,123✔
3241
    // it is a local executed query, no need to do async fetch
3242
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
7,876,649✔
3243
      if (pResultInfo->localResultFetched) {
2,955,354!
3244
        pResultInfo->numOfRows = 0;
1,477,677✔
3245
        pResultInfo->current = 0;
1,477,677✔
3246
      } else {
3247
        pResultInfo->localResultFetched = true;
1,477,677✔
3248
      }
3249
    } else {
3250
      pResultInfo->numOfRows = 0;
4,921,295✔
3251
    }
3252

3253
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
7,876,649✔
3254
    return;
7,876,649✔
3255
  }
3256

3257
  SSchedulerReq req = {
117,271,474✔
3258
      .syncReq = false,
3259
      .fetchFp = fetchCallback,
3260
      .cbParam = pRequest,
3261
  };
3262

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

3270
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
716,549,604✔
3271
  pRequest->inCallback = true;
716,549,604✔
3272
  int64_t this = pRequest->self;
716,559,508✔
3273
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
716,529,445!
3274
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
136,650!
3275
    code = TSDB_CODE_SUCCESS;
×
3276
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3277
  }
3278

3279
  tscDebug("QID:0x%" PRIx64 ", taos_query end, req:0x%" PRIx64 ", res:%p", pRequest->requestId, pRequest->self,
716,529,445✔
3280
           pRequest);
3281

3282
  if (pRequest->body.queryFp != NULL) {
716,530,640!
3283
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
716,555,004✔
3284
  }
3285

3286
  SRequestObj* pReq = acquireRequest(this);
716,563,852✔
3287
  if (pReq != NULL) {
716,563,912✔
3288
    pReq->inCallback = false;
715,722,468✔
3289
    (void)releaseRequest(this);
715,722,981✔
3290
  }
3291
}
716,563,449✔
3292

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