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

taosdata / TDengine / #4811

16 Oct 2025 11:40AM UTC coverage: 58.693% (+0.2%) from 58.518%
#4811

push

travis-ci

web-flow
fix(tref): increase TSDB_REF_OBJECTS from 100 to 2000 for improved reference handling (#33281)

139835 of 303532 branches covered (46.07%)

Branch coverage included in aggregate %.

211576 of 295200 relevant lines covered (71.67%)

16841075.92 hits per line

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

50.77
/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) {
142,815✔
39
  SRequestObj* pReq = acquireRequest(rId);
142,815✔
40
  if (pReq != NULL) {
142,832✔
41
    pReq->isQuery = true;
142,831✔
42
    (void)releaseRequest(rId);
142,831✔
43
  }
44
}
142,824✔
45

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

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

56
  return true;
28,679✔
57
}
58

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

61
static bool validatePassword(const char* passwd) { return stringLengthCheck(passwd, TSDB_PASSWORD_MAX_LEN); }
11,310✔
62

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

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

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

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

125
  return dstLength;
×
126
}
127

128
bool chkRequestKilled(void* param) {
24,553,247✔
129
  bool         killed = false;
24,553,247✔
130
  SRequestObj* pRequest = acquireRequest((int64_t)param);
24,553,247✔
131
  if (NULL == pRequest || pRequest->killed) {
25,001,259!
132
    killed = true;
×
133
  }
134

135
  (void)releaseRequest((int64_t)param);
25,001,259✔
136

137
  return killed;
24,917,826✔
138
}
139

140
void cleanupAppInfo() {
4,534✔
141
  taosHashCleanup(appInfo.pInstMap);
4,534✔
142
  taosHashCleanup(appInfo.pInstMapByClusterId);
4,534✔
143
  tscInfo("cluster instance map cleaned");
4,534!
144
}
4,534✔
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,
11,318✔
150
                              uint16_t port, int connType, STscObj** pObj) {
151
  TSC_ERR_RET(taos_init());
11,318!
152
  if (!validateUserName(user)) {
11,332!
153
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
154
  }
155
  int32_t code = 0;
11,312✔
156

157
  char localDb[TSDB_DB_NAME_LEN] = {0};
11,312✔
158
  if (db != NULL && strlen(db) > 0) {
11,312✔
159
    if (!validateDbName(db)) {
6,088!
160
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_DB_LENGTH);
×
161
    }
162

163
    tstrncpy(localDb, db, sizeof(localDb));
6,101✔
164
    (void)strdequote(localDb);
6,101✔
165
  }
166

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

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

178
  SCorEpSet epSet = {0};
11,215✔
179
  if (ip) {
11,215✔
180
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
4,510✔
181
  } else {
182
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
6,705!
183
  }
184

185
  if (port) {
11,232✔
186
    epSet.epSet.eps[0].port = port;
101✔
187
    epSet.epSet.eps[1].port = port;
101✔
188
  }
189

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

247
    pInst = &p;
4,559✔
248
  } else {
249
    if (NULL == *pInst || NULL == (*pInst)->pAppHbMgr) {
6,777!
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);
6,777✔
255
  }
256

257
_return:
11,336✔
258

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

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

299
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
8,237,100!
300
  if ((*pRequest)->sqlstr == NULL) {
8,221,861!
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);
8,221,861✔
308
  (*pRequest)->sqlstr[sqlLen] = 0;
8,234,908✔
309
  (*pRequest)->sqlLen = sqlLen;
8,234,908✔
310
  (*pRequest)->validateOnly = validateSql;
8,234,908✔
311
  (*pRequest)->stmtBindVersion = 0;
8,234,908✔
312

313
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
8,234,908✔
314

315
  STscObj* pTscObj = (*pRequest)->pTscObj;
8,234,908✔
316
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
8,234,908✔
317
                             sizeof((*pRequest)->self));
318
  if (err) {
8,218,852!
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;
8,218,852✔
327
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
8,218,852!
328
    if (TSDB_CODE_SUCCESS !=
236,151!
329
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
236,154✔
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);
8,229,277✔
339
  return TSDB_CODE_SUCCESS;
8,226,758✔
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) {
11,709✔
355
  STscObj* pTscObj = pRequest->pTscObj;
11,709✔
356

357
  SParseContext cxt = {
11,709✔
358
      .requestId = pRequest->requestId,
11,709✔
359
      .requestRid = pRequest->self,
11,709✔
360
      .acctId = pTscObj->acctId,
11,709✔
361
      .db = pRequest->pDb,
11,709✔
362
      .topicQuery = topicQuery,
363
      .pSql = pRequest->sqlstr,
11,709✔
364
      .sqlLen = pRequest->sqlLen,
11,709✔
365
      .pMsg = pRequest->msgBuf,
11,709✔
366
      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
367
      .pTransporter = pTscObj->pAppInfo->pTransporter,
11,709✔
368
      .pStmtCb = pStmtCb,
369
      .pUser = pTscObj->user,
11,709✔
370
      .isSuperUser = (0 == strcmp(pTscObj->user, TSDB_DEFAULT_USER)),
11,709✔
371
      .enableSysInfo = pTscObj->sysInfo,
11,709✔
372
      .svrVer = pTscObj->sVer,
11,709✔
373
      .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes),
11,709✔
374
      .stmtBindVersion = pRequest->stmtBindVersion,
11,709✔
375
      .setQueryFp = setQueryRequest,
376
      .timezone = pTscObj->optionInfo.timezone,
11,709✔
377
      .charsetCxt = pTscObj->optionInfo.charsetCxt,
11,709✔
378
  };
379

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

386
  code = qParseSql(&cxt, pQuery);
11,720✔
387
  if (TSDB_CODE_SUCCESS == code) {
11,705✔
388
    if ((*pQuery)->haveResultSet) {
11,678!
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)) {
11,705!
396
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
11,698✔
397
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
11,698✔
398
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
11,698✔
399
  }
400

401
  taosArrayDestroy(cxt.pTableMetaPos);
11,705✔
402
  taosArrayDestroy(cxt.pTableVgroupPos);
11,716✔
403

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

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

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

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

440
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
16,295,473✔
441

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

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

456
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
3,736✔
457
  pRequest->code = code;
3,736✔
458

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

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

478
  // drop table if exists not_exists_table
479
  if (NULL == pQuery->pCmdMsg) {
11,778!
480
    doRequestCallback(pRequest, 0);
×
481
    return TSDB_CODE_SUCCESS;
×
482
  }
483

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

489
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
11,778✔
490
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
11,765✔
491

492
  int32_t code = asyncSendMsgToServer(pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg);
11,788✔
493
  if (code) {
11,816!
494
    doRequestCallback(pRequest, code);
×
495
  }
496
  return code;
11,817✔
497
}
498

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

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

507
  return node1->load > node2->load;
136,944✔
508
}
509

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

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

526
  return TSDB_CODE_SUCCESS;
38,096✔
527
}
528

529
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
8,218,464✔
530
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
8,218,464!
531
    *required = false;
8,218,464✔
532
    return TSDB_CODE_SUCCESS;
8,218,464✔
533
  }
534

535
  int32_t       code = TSDB_CODE_SUCCESS;
×
536
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
×
537
  *required = false;
×
538

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

581
  SPlanContext cxt = {.queryId = pRequest->requestId,
43,345✔
582
                      .acctId = pRequest->pTscObj->acctId,
21,666✔
583
                      .mgmtEpSet = getEpSet_s(&pAppInfo->mgmtEp),
21,666✔
584
                      .pAstRoot = pQuery->pRoot,
21,679✔
585
                      .showRewrite = pQuery->showRewrite,
21,679✔
586
                      .pMsg = pRequest->msgBuf,
21,679✔
587
                      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
588
                      .pUser = pRequest->pTscObj->user,
21,679✔
589
                      .timezone = pRequest->pTscObj->optionInfo.timezone,
21,679✔
590
                      .sysInfo = pRequest->pTscObj->sysInfo};
21,679✔
591

592
  return qCreateQueryPlan(&cxt, pPlan, pNodeList);
21,679✔
593
}
594

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

602
  pResInfo->numOfCols = numOfCols;
137,063✔
603
  if (pResInfo->fields != NULL) {
137,063!
604
    taosMemoryFree(pResInfo->fields);
×
605
  }
606
  if (pResInfo->userFields != NULL) {
137,063!
607
    taosMemoryFree(pResInfo->userFields);
×
608
  }
609
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD_E));
137,063!
610
  if (NULL == pResInfo->fields) return terrno;
137,031!
611
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
137,031!
612
  if (NULL == pResInfo->userFields) {
137,018!
613
    taosMemoryFree(pResInfo->fields);
×
614
    return terrno;
×
615
  }
616
  if (numOfCols != pResInfo->numOfCols) {
137,018!
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) {
363,320✔
622
    pResInfo->fields[i].type = pSchema[i].type;
226,253✔
623

624
    pResInfo->userFields[i].type = pSchema[i].type;
226,253✔
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);
226,253✔
627
    pResInfo->fields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, isStmt);
226,270✔
628
    if (IS_DECIMAL_TYPE(pSchema[i].type) && pExtSchema) {
226,294!
629
      decimalFromTypeMod(pExtSchema[i].typeMod, &pResInfo->fields[i].precision, &pResInfo->fields[i].scale);
1,781✔
630
    }
631

632
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
226,302✔
633
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
226,302✔
634
  }
635
  return TSDB_CODE_SUCCESS;
137,067✔
636
}
637

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

644
  pResInfo->precision = precision;
136,972✔
645
}
646

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

654
  int32_t dbNum = taosArrayGetSize(pDbVgList);
208,411✔
655
  for (int32_t i = 0; i < dbNum; ++i) {
416,224✔
656
    SArray* pVg = taosArrayGetP(pDbVgList, i);
207,810✔
657
    if (NULL == pVg) {
207,839!
658
      continue;
×
659
    }
660
    int32_t vgNum = taosArrayGetSize(pVg);
207,839✔
661
    if (vgNum <= 0) {
207,835✔
662
      continue;
141✔
663
    }
664

665
    for (int32_t j = 0; j < vgNum; ++j) {
1,925,583✔
666
      SVgroupInfo* pInfo = taosArrayGet(pVg, j);
1,717,923✔
667
      if (NULL == pInfo) {
1,717,902!
668
        taosArrayDestroy(nodeList);
×
669
        return TSDB_CODE_OUT_OF_RANGE;
×
670
      }
671
      SQueryNodeLoad load = {0};
1,717,902✔
672
      load.addr.nodeId = pInfo->vgId;
1,717,902✔
673
      load.addr.epSet = pInfo->epSet;
1,717,902✔
674

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

682
  int32_t vnodeNum = taosArrayGetSize(nodeList);
208,414✔
683
  if (vnodeNum > 0) {
208,463✔
684
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
207,429✔
685
    goto _return;
207,434✔
686
  }
687

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

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

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

706
_return:
330✔
707

708
  *pNodeList = nodeList;
208,450✔
709

710
  return TSDB_CODE_SUCCESS;
208,450✔
711
}
712

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

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

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

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

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

752
_return:
×
753

754
  *pNodeList = nodeList;
×
755

756
  return TSDB_CODE_SUCCESS;
×
757
}
758

759
void freeVgList(void* list) {
21,409✔
760
  SArray* pList = *(SArray**)list;
21,409✔
761
  taosArrayDestroy(pList);
21,409✔
762
}
21,437✔
763

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

770
  switch (tsQueryPolicy) {
186,716!
771
    case QUERY_POLICY_VNODE:
186,745✔
772
    case QUERY_POLICY_CLIENT: {
773
      if (pResultMeta) {
186,745✔
774
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
186,786✔
775
        if (NULL == pDbVgList) {
186,754!
776
          code = terrno;
×
777
          goto _return;
×
778
        }
779
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
186,754✔
780
        for (int32_t i = 0; i < dbNum; ++i) {
373,154✔
781
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
186,400✔
782
          if (pRes->code || NULL == pRes->pRes) {
186,387!
783
            continue;
×
784
          }
785

786
          if (NULL == taosArrayPush(pDbVgList, &pRes->pRes)) {
372,817!
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);
186,758✔
831
      break;
186,787✔
832
    }
833
    case QUERY_POLICY_HYBRID:
×
834
    case QUERY_POLICY_QNODE: {
835
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
×
836
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
×
837
        if (pRes->code) {
×
838
          pQnodeList = NULL;
×
839
        } else {
840
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
×
841
          if (NULL == pQnodeList) {
×
842
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
843
            goto _return;
×
844
          }
845
        }
846
      } else {
847
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
×
848
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
×
849
        if (pInst->pQnodeList) {
×
850
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
×
851
          if (NULL == pQnodeList) {
×
852
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
853
            goto _return;
×
854
          }
855
        }
856
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
×
857
      }
858

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

867
_return:
186,787✔
868
  taosArrayDestroyEx(pDbVgList, fp);
186,787✔
869
  taosArrayDestroy(pQnodeList);
186,793✔
870

871
  return code;
186,795✔
872
}
873

874
int32_t buildSyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList) {
21,630✔
875
  SArray* pDbVgList = NULL;
21,630✔
876
  SArray* pQnodeList = NULL;
21,630✔
877
  int32_t code = 0;
21,630✔
878

879
  switch (tsQueryPolicy) {
21,630!
880
    case QUERY_POLICY_VNODE:
21,641✔
881
    case QUERY_POLICY_CLIENT: {
882
      int32_t dbNum = taosArrayGetSize(pRequest->dbList);
21,641✔
883
      if (dbNum > 0) {
21,669✔
884
        SCatalog*     pCtg = NULL;
21,422✔
885
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
21,422✔
886
        code = catalogGetHandle(pInst->clusterId, &pCtg);
21,422✔
887
        if (code != TSDB_CODE_SUCCESS) {
21,410!
888
          goto _return;
×
889
        }
890

891
        pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
21,410✔
892
        if (NULL == pDbVgList) {
21,403!
893
          code = terrno;
×
894
          goto _return;
×
895
        }
896
        SArray* pVgList = NULL;
21,404✔
897
        for (int32_t i = 0; i < dbNum; ++i) {
42,838✔
898
          char*            dbFName = taosArrayGet(pRequest->dbList, i);
21,387✔
899
          SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
21,400✔
900
                                   .requestId = pRequest->requestId,
21,400✔
901
                                   .requestObjRefId = pRequest->self,
21,400✔
902
                                   .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
21,400✔
903

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

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

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

932
_return:
21,663✔
933

934
  taosArrayDestroyEx(pDbVgList, freeVgList);
21,663✔
935
  taosArrayDestroy(pQnodeList);
21,666✔
936

937
  return code;
21,678✔
938
}
939

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

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

964
  int32_t code = schedulerExecJob(&req, &pRequest->body.queryJob);
21,647✔
965

966
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
21,675✔
967
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
21,675✔
968

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

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

977
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_DELETE == pRequest->type ||
21,675!
978
      TDMT_VND_CREATE_TABLE == pRequest->type) {
159✔
979
    pRequest->body.resInfo.numOfRows = res.numOfRows;
21,643✔
980
    if (TDMT_VND_SUBMIT == pRequest->type) {
21,643✔
981
      STscObj*            pTscObj = pRequest->pTscObj;
21,523✔
982
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
21,523✔
983
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
21,523✔
984
    }
985

986
    schedulerFreeJob(&pRequest->body.queryJob, 0);
21,650✔
987
  }
988

989
  pRequest->code = res.code;
21,683✔
990
  terrno = res.code;
21,683✔
991
  return pRequest->code;
21,678✔
992
}
993

994
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
8,000,945✔
995
  SArray*      pArray = NULL;
8,000,945✔
996
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
8,000,945✔
997
  if (NULL == pRsp->aCreateTbRsp) {
8,000,945✔
998
    return TSDB_CODE_SUCCESS;
7,993,459✔
999
  }
1000

1001
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
7,486✔
1002
  for (int32_t i = 0; i < tbNum; ++i) {
24,682✔
1003
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
13,493✔
1004
    if (pTbRsp->pMeta) {
13,492✔
1005
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
11,264!
1006
    }
1007
  }
1008

1009
  return TSDB_CODE_SUCCESS;
11,189✔
1010
}
1011

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

1021
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
129,183✔
1022
  if (NULL == pArray) {
129,198!
1023
    return terrno;
×
1024
  }
1025

1026
  for (int32_t i = 0; i < tbNum; ++i) {
275,368✔
1027
    STbVerInfo* tbInfo = taosArrayGet(pTbArray, i);
146,169✔
1028
    if (NULL == tbInfo) {
146,163!
1029
      code = terrno;
×
1030
      goto _return;
×
1031
    }
1032
    STbSVersion tbSver = {
146,163✔
1033
        .tbFName = tbInfo->tbFName, .sver = tbInfo->sversion, .tver = tbInfo->tversion, .rver = tbInfo->rversion};
146,163✔
1034
    if (NULL == taosArrayPush(pArray, &tbSver)) {
146,170!
1035
      code = terrno;
×
1036
      goto _return;
×
1037
    }
1038
  }
1039

1040
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
129,199✔
1041
                           .requestId = pRequest->requestId,
129,199✔
1042
                           .requestObjRefId = pRequest->self,
129,199✔
1043
                           .mgmtEps = *epset};
1044

1045
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
129,199✔
1046

1047
_return:
129,184✔
1048

1049
  taosArrayDestroy(pArray);
129,184✔
1050
  return code;
129,203✔
1051
}
1052

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

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

1061
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
8,193,560✔
1062
  if (NULL == pRequest->body.resInfo.execRes.res) {
8,193,560✔
1063
    return pRequest->code;
60,557✔
1064
  }
1065

1066
  SCatalog*     pCatalog = NULL;
8,133,003✔
1067
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
8,133,003✔
1068

1069
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
8,133,810✔
1070
  if (code) {
8,145,865!
1071
    return code;
×
1072
  }
1073

1074
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
8,145,865✔
1075
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
8,165,316✔
1076

1077
  switch (pRes->msgType) {
8,165,316✔
1078
    case TDMT_VND_ALTER_TABLE:
889✔
1079
    case TDMT_MND_ALTER_STB: {
1080
      code = handleAlterTbExecRes(pRes->res, pCatalog);
889✔
1081
      break;
889✔
1082
    }
1083
    case TDMT_VND_CREATE_TABLE: {
27,548✔
1084
      SArray* pList = (SArray*)pRes->res;
27,548✔
1085
      int32_t num = taosArrayGetSize(pList);
27,548✔
1086
      for (int32_t i = 0; i < num; ++i) {
76,980✔
1087
        void* res = taosArrayGetP(pList, i);
49,425✔
1088
        // handleCreateTbExecRes will handle res == null
1089
        code = handleCreateTbExecRes(res, pCatalog);
49,426✔
1090
      }
1091
      break;
27,555✔
1092
    }
1093
    case TDMT_MND_CREATE_STB: {
220✔
1094
      code = handleCreateTbExecRes(pRes->res, pCatalog);
220✔
1095
      break;
220✔
1096
    }
1097
    case TDMT_VND_SUBMIT: {
8,005,320✔
1098
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
8,005,320✔
1099

1100
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
8,008,746✔
1101
      break;
8,002,363✔
1102
    }
1103
    case TDMT_SCH_QUERY:
129,195✔
1104
    case TDMT_SCH_MERGE_QUERY: {
1105
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
129,195✔
1106
      break;
129,187✔
1107
    }
1108
    default:
2,144✔
1109
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self,
2,144!
1110
               pRequest->type, pRequest->requestId);
1111
      code = TSDB_CODE_APP_ERROR;
×
1112
  }
1113

1114
  return code;
8,160,214✔
1115
}
1116

1117
static bool incompletaFileParsing(SNode* pStmt) {
8,204,210✔
1118
  return QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pStmt) ? false : ((SVnodeModifyOpStmt*)pStmt)->fileProcessing;
8,204,210!
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) {
720✔
1140
  if (pRequest->relation.userRefId == pRequest->self || 0 == pRequest->relation.userRefId) {
720!
1141
    // return to client
1142
    doRequestCallback(pRequest, pRequest->code);
720✔
1143
    return;
720✔
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) {
8,184,060✔
1263
  SSqlCallbackWrapper* pWrapper = param;
8,184,060✔
1264
  SRequestObj*         pRequest = pWrapper->pRequest;
8,184,060✔
1265
  STscObj*             pTscObj = pRequest->pTscObj;
8,184,060✔
1266

1267
  pRequest->code = code;
8,184,060✔
1268
  if (pResult) {
8,184,060!
1269
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
8,192,109✔
1270
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
8,192,702✔
1271
  }
1272

1273
  int32_t type = pRequest->type;
8,184,653✔
1274
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
8,184,653✔
1275
    if (pResult) {
8,049,353!
1276
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
8,052,730✔
1277

1278
      // record the insert rows
1279
      if (TDMT_VND_SUBMIT == type) {
8,052,730✔
1280
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
7,974,978✔
1281
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
7,974,978✔
1282
      }
1283
    }
1284
    schedulerFreeJob(&pRequest->body.queryJob, 0);
8,066,063✔
1285
  }
1286

1287
  taosMemoryFree(pResult);
8,193,585!
1288
  tscDebug("req:0x%" PRIx64 ", enter scheduler exec cb, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
8,205,464✔
1289
           pRequest->requestId);
1290

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

1302
  tscTrace("req:0x%" PRIx64 ", scheduler exec cb, request type:%s", pRequest->self, TMSG_INFO(pRequest->type));
8,189,200!
1303
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
8,189,200!
1304
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
1,444!
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;
8,191,579✔
1310
  int32_t code1 = handleQueryExecRsp(pRequest);
8,191,579✔
1311
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
8,194,493!
1312
    pRequest->code = code1;
×
1313
  }
1314

1315
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
16,398,720!
1316
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
8,202,193✔
1317
    continueInsertFromCsv(pWrapper, pRequest);
×
1318
    return;
×
1319
  }
1320

1321
  if (pRequest->relation.nextRefId) {
8,205,366!
1322
    handlePostSubQuery(pWrapper);
×
1323
  } else {
1324
    destorySqlCallbackWrapper(pWrapper);
8,205,366✔
1325
    pRequest->pWrapper = NULL;
8,206,458✔
1326

1327
    // return to client
1328
    doRequestCallback(pRequest, code);
8,206,458✔
1329
  }
1330
}
1331

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

1336
  if (pQuery->pRoot) {
22,034✔
1337
    pRequest->stmtType = pQuery->pRoot->type;
21,669✔
1338
  }
1339

1340
  if (pQuery->pRoot && !pRequest->inRetry) {
22,034!
1341
    STscObj*            pTscObj = pRequest->pTscObj;
21,680✔
1342
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
21,680✔
1343
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type) {
21,680✔
1344
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
21,669✔
1345
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
11✔
1346
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
9✔
1347
    }
1348
  }
1349

1350
  pRequest->body.execMode = pQuery->execMode;
22,072✔
1351
  switch (pQuery->execMode) {
22,072!
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:
393✔
1363
      if (!pRequest->validateOnly) {
393!
1364
        code = execDdlQuery(pRequest, pQuery);
393✔
1365
      }
1366
      break;
393✔
1367
    case QUERY_EXEC_MODE_SCHEDULE: {
21,679✔
1368
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
21,679✔
1369
      if (NULL == pMnodeList) {
21,658!
1370
        code = terrno;
×
1371
        break;
×
1372
      }
1373
      SQueryPlan* pDag = NULL;
21,658✔
1374
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
21,658✔
1375
      if (TSDB_CODE_SUCCESS == code) {
21,630!
1376
        pRequest->body.subplanNum = pDag->numOfSubplans;
21,640✔
1377
        if (!pRequest->validateOnly) {
21,640!
1378
          SArray* pNodeList = NULL;
21,659✔
1379
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
21,659✔
1380
          if (TSDB_CODE_SUCCESS == code) {
21,662!
1381
            code = scheduleQuery(pRequest, pDag, pNodeList);
21,671✔
1382
          }
1383
          taosArrayDestroy(pNodeList);
21,661✔
1384
        }
1385
      }
1386
      taosArrayDestroy(pMnodeList);
21,644✔
1387
      break;
21,683✔
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) {
22,076!
1397
    qDestroyQuery(pQuery);
×
1398
  }
1399

1400
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
22,076!
1401
    int ret = removeMeta(pRequest->pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type));
176!
1402
    if (TSDB_CODE_SUCCESS != ret) {
176!
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) {
22,076✔
1409
    code = handleQueryExecRsp(pRequest);
22,072✔
1410
  }
1411

1412
  if (TSDB_CODE_SUCCESS != code) {
22,073✔
1413
    pRequest->code = code;
109✔
1414
  }
1415

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

1422
static int32_t asyncExecSchQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta,
8,196,111✔
1423
                                 SSqlCallbackWrapper* pWrapper) {
1424
  int32_t code = TSDB_CODE_SUCCESS;
8,196,111✔
1425
  pRequest->type = pQuery->msgType;
8,196,111✔
1426
  SArray*     pMnodeList = NULL;
8,196,111✔
1427
  SQueryPlan* pDag = NULL;
8,196,111✔
1428
  int64_t     st = taosGetTimestampUs();
8,192,001✔
1429

1430
  if (!pRequest->parseOnly) {
8,192,001!
1431
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
8,194,616✔
1432
    if (NULL == pMnodeList) {
8,175,269!
1433
      code = terrno;
×
1434
    }
1435
    SPlanContext cxt = {.queryId = pRequest->requestId,
24,578,779✔
1436
                        .acctId = pRequest->pTscObj->acctId,
8,175,269✔
1437
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
8,175,269✔
1438
                        .pAstRoot = pQuery->pRoot,
8,201,755✔
1439
                        .showRewrite = pQuery->showRewrite,
8,201,755✔
1440
                        .isView = pWrapper->pParseCtx->isView,
8,201,755✔
1441
                        .isAudit = pWrapper->pParseCtx->isAudit,
8,201,755✔
1442
                        .pMsg = pRequest->msgBuf,
8,201,755✔
1443
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1444
                        .pUser = pRequest->pTscObj->user,
8,201,755✔
1445
                        .sysInfo = pRequest->pTscObj->sysInfo,
8,201,755✔
1446
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
8,201,755✔
1447
                        .allocatorId = pRequest->stmtBindVersion > 0 ? 0 : pRequest->allocatorRefId};
8,201,755✔
1448
    if (TSDB_CODE_SUCCESS == code) {
8,201,755✔
1449
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
8,183,759✔
1450
    }
1451
    if (code) {
8,166,588!
1452
      tscError("req:0x%" PRIx64 ", failed to create query plan, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
×
1453
               pRequest->requestId);
1454
    } else {
1455
      pRequest->body.subplanNum = pDag->numOfSubplans;
8,166,588✔
1456
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
8,166,588✔
1457
    }
1458
  }
1459

1460
  pRequest->metric.execStart = taosGetTimestampUs();
8,178,970✔
1461
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
8,178,970✔
1462

1463
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
16,350,512✔
1464
    SArray* pNodeList = NULL;
8,156,948✔
1465
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
8,156,948✔
1466
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
186,783✔
1467
    }
1468

1469
    SRequestConnInfo conn = {.pTrans = getAppInfo(pRequest)->pTransporter,
8,156,964✔
1470
                             .requestId = pRequest->requestId,
8,138,555✔
1471
                             .requestObjRefId = pRequest->self};
8,138,555✔
1472
    SSchedulerReq    req = {
16,273,878✔
1473
           .syncReq = false,
1474
           .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
8,138,555✔
1475
           .pConn = &conn,
1476
           .pNodeList = pNodeList,
1477
           .pDag = pDag,
1478
           .allocatorRefId = pRequest->allocatorRefId,
8,138,555✔
1479
           .sql = pRequest->sqlstr,
8,138,555✔
1480
           .startTs = pRequest->metric.start,
8,138,555✔
1481
           .execFp = schedulerExecCb,
1482
           .cbParam = pWrapper,
1483
           .chkKillFp = chkRequestKilled,
1484
           .chkKillParam = (void*)pRequest->self,
8,138,555✔
1485
           .pExecRes = NULL,
1486
           .source = pRequest->source,
8,138,555✔
1487
           .pWorkerCb = getTaskPoolWorkerCb(),
8,138,555✔
1488
    };
1489
    if (TSDB_CODE_SUCCESS == code) {
8,135,323!
1490
      code = schedulerExecJob(&req, &pRequest->body.queryJob);
8,155,341✔
1491
    }
1492

1493
    taosArrayDestroy(pNodeList);
8,156,952✔
1494
  } else {
1495
    qDestroyQueryPlan(pDag);
22,022✔
1496
    tscDebug("req:0x%" PRIx64 ", plan not executed, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
66!
1497
             pRequest->requestId);
1498
    destorySqlCallbackWrapper(pWrapper);
66✔
1499
    pRequest->pWrapper = NULL;
66✔
1500
    if (TSDB_CODE_SUCCESS != code) {
66!
1501
      pRequest->code = terrno;
×
1502
    }
1503

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

1507
  // todo not to be released here
1508
  taosArrayDestroy(pMnodeList);
8,171,608✔
1509

1510
  return code;
8,166,347✔
1511
}
1512

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

1516
  if (pRequest->parseOnly) {
8,137,952✔
1517
    doRequestCallback(pRequest, 0);
42✔
1518
    return;
42✔
1519
  }
1520

1521
  pRequest->body.execMode = pQuery->execMode;
8,137,910✔
1522
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
8,137,910✔
1523
    destorySqlCallbackWrapper(pWrapper);
15,539✔
1524
    pRequest->pWrapper = NULL;
15,526✔
1525
  }
1526

1527
  if (pQuery->pRoot && !pRequest->inRetry) {
8,137,897!
1528
    STscObj*            pTscObj = pRequest->pTscObj;
8,172,491✔
1529
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
8,172,491✔
1530
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
8,172,491✔
1531
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
7,995,705✔
1532
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
7,965,296✔
1533
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
207,195✔
1534
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
136,006✔
1535
    }
1536
  }
1537

1538
  switch (pQuery->execMode) {
8,219,839!
1539
    case QUERY_EXEC_MODE_LOCAL:
3,737✔
1540
      asyncExecLocalCmd(pRequest, pQuery);
3,737✔
1541
      break;
3,737✔
1542
    case QUERY_EXEC_MODE_RPC:
11,786✔
1543
      code = asyncExecDdlQuery(pRequest, pQuery);
11,786✔
1544
      break;
11,817✔
1545
    case QUERY_EXEC_MODE_SCHEDULE: {
8,204,306✔
1546
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
8,204,306✔
1547
      break;
8,161,375✔
1548
    }
1549
    case QUERY_EXEC_MODE_EMPTY_RESULT:
10✔
1550
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
10✔
1551
      doRequestCallback(pRequest, 0);
10✔
1552
      break;
10✔
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) {
×
1561
  SCatalog* pCatalog = NULL;
×
1562
  int32_t   code = 0;
×
1563
  int32_t   dbNum = taosArrayGetSize(pRequest->dbList);
×
1564
  int32_t   tblNum = taosArrayGetSize(pRequest->tableList);
×
1565

1566
  if (dbNum <= 0 && tblNum <= 0) {
×
1567
    return TSDB_CODE_APP_ERROR;
×
1568
  }
1569

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

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

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

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

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

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

1600
  return code;
×
1601
}
1602

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

1611
  if (isView) {
2,079✔
1612
    for (int32_t i = 0; i < tbNum; ++i) {
132✔
1613
      SName* pViewName = taosArrayGet(tbList, i);
66✔
1614
      char   dbFName[TSDB_DB_FNAME_LEN];
1615
      if (NULL == pViewName) {
66!
1616
        continue;
×
1617
      }
1618
      (void)tNameGetFullDbName(pViewName, dbFName);
66✔
1619
      TSC_ERR_RET(catalogRemoveViewMeta(pCatalog, dbFName, 0, pViewName->tname, 0));
66!
1620
    }
1621
  } else {
1622
    for (int32_t i = 0; i < tbNum; ++i) {
2,294✔
1623
      SName* pTbName = taosArrayGet(tbList, i);
281✔
1624
      TSC_ERR_RET(catalogRemoveTableMeta(pCatalog, pTbName));
281!
1625
    }
1626
  }
1627

1628
  return TSDB_CODE_SUCCESS;
2,079✔
1629
}
1630

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

1634
  // init mnode ip set
1635
  SEpSet* mgmtEpSet = &(pEpSet->epSet);
11,091✔
1636
  mgmtEpSet->numOfEps = 0;
11,091✔
1637
  mgmtEpSet->inUse = 0;
11,091✔
1638

1639
  if (firstEp && firstEp[0] != 0) {
11,091!
1640
    if (strlen(firstEp) >= TSDB_EP_LEN) {
11,263!
1641
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1642
      return -1;
×
1643
    }
1644

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

1662
  if (secondEp && secondEp[0] != 0) {
11,094✔
1663
    if (strlen(secondEp) >= TSDB_EP_LEN) {
6,690!
1664
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1665
      return terrno;
×
1666
    }
1667

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

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

1688
  return 0;
11,090✔
1689
}
1690

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

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

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

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

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

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

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

1756
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
11,334✔
1757

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

1767
  *(int64_t*)(*pMsgSendInfo)->param = pRequest->self;
11,326✔
1768

1769
  SConnectReq connectReq = {0};
11,326✔
1770
  STscObj*    pObj = pRequest->pTscObj;
11,326✔
1771

1772
  char* db = getDbOfConnection(pObj);
11,326✔
1773
  if (db != NULL) {
11,334✔
1774
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
6,113✔
1775
  } else if (terrno) {
5,221!
1776
    taosMemoryFree(*pMsgSendInfo);
×
1777
    return terrno;
×
1778
  }
1779
  taosMemoryFreeClear(db);
11,331!
1780

1781
  connectReq.connType = pObj->connType;
11,335✔
1782
  connectReq.pid = appInfo.pid;
11,335✔
1783
  connectReq.startTime = appInfo.startTime;
11,335✔
1784

1785
  tstrncpy(connectReq.app, appInfo.appName, sizeof(connectReq.app));
11,335✔
1786
  tstrncpy(connectReq.user, pObj->user, sizeof(connectReq.user));
11,335✔
1787
  tstrncpy(connectReq.passwd, pObj->pass, sizeof(connectReq.passwd));
11,335✔
1788
  tstrncpy(connectReq.sVer, td_version, sizeof(connectReq.sVer));
11,335✔
1789

1790
  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connectReq);
11,335✔
1791
  void*   pReq = taosMemoryMalloc(contLen);
11,307!
1792
  if (NULL == pReq) {
11,319!
1793
    taosMemoryFree(*pMsgSendInfo);
×
1794
    return terrno;
×
1795
  }
1796

1797
  if (-1 == tSerializeSConnectReq(pReq, contLen, &connectReq)) {
11,319✔
1798
    taosMemoryFree(*pMsgSendInfo);
9!
1799
    taosMemoryFree(pReq);
×
1800
    return terrno;
×
1801
  }
1802

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

1808
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
8,693,133✔
1809
  if (NULL == pEpSet) {
8,693,133✔
1810
    return;
8,679,341✔
1811
  }
1812

1813
  switch (pSendInfo->target.type) {
13,792!
1814
    case TARGET_TYPE_MNODE:
×
1815
      if (NULL == pTscObj) {
×
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);
×
1822
      SEpSet* pOrig = &originEpset;
×
1823
      SEp*    pOrigEp = &pOrig->eps[pOrig->inUse];
×
1824
      SEp*    pNewEp = &pEpSet->eps[pEpSet->inUse];
×
1825
      tscDebug("mnode epset updated from %d/%d=>%s:%d to %d/%d=>%s:%d in client", pOrig->inUse, pOrig->numOfEps,
×
1826
               pOrigEp->fqdn, pOrigEp->port, pEpSet->inUse, pEpSet->numOfEps, pNewEp->fqdn, pNewEp->port);
1827
      updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
×
1828
      break;
14,728✔
1829
    case TARGET_TYPE_VNODE: {
14,624✔
1830
      if (NULL == pTscObj) {
14,624!
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;
14,624✔
1837
      int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
14,624✔
1838
      if (code != TSDB_CODE_SUCCESS) {
14,621!
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);
14,621✔
1845
      if (code != TSDB_CODE_SUCCESS) {
14,627!
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);
14,629!
1851
      break;
14,627✔
1852
    }
1853
    default:
33✔
1854
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
33!
1855
      break;
101✔
1856
  }
1857
}
1858

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

1868
  STscObj* pTscObj = NULL;
8,701,411✔
1869

1870
  STraceId* trace = &pMsg->info.traceId;
8,701,411✔
1871
  char      tbuf[40] = {0};
8,701,411✔
1872
  TRACE_TO_STR(trace, tbuf);
8,701,411!
1873

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

1877
  if (pSendInfo->requestObjRefId != 0) {
8,697,776✔
1878
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
8,499,805✔
1879
    if (pRequest) {
8,499,461✔
1880
      if (pRequest->self != pSendInfo->requestObjRefId) {
8,499,160!
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;
8,499,160✔
1893
    }
1894
  }
1895

1896
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
8,697,432✔
1897

1898
  SDataBuf buf = {.msgType = pMsg->msgType,
8,693,067✔
1899
                  .len = pMsg->contLen,
8,693,067✔
1900
                  .pData = NULL,
1901
                  .handle = pMsg->info.handle,
8,693,067✔
1902
                  .handleRefId = pMsg->info.refId,
8,693,067✔
1903
                  .pEpSet = pEpSet};
1904

1905
  if (pMsg->contLen > 0) {
8,693,067✔
1906
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
8,631,247!
1907
    if (buf.pData == NULL) {
8,630,385!
1908
      pMsg->code = terrno;
×
1909
    } else {
1910
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
8,630,385✔
1911
    }
1912
  }
1913

1914
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
8,692,205✔
1915

1916
  if (pTscObj) {
8,685,315✔
1917
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
8,487,152✔
1918
    if (TSDB_CODE_SUCCESS != code) {
8,496,718!
1919
      tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1920
      terrno = code;
×
1921
      pMsg->code = code;
×
1922
    }
1923
  }
1924

1925
  rpcFreeCont(pMsg->pCont);
8,694,881✔
1926
  destroySendMsgInfo(pSendInfo);
8,698,594✔
1927
  return TSDB_CODE_SUCCESS;
8,698,868✔
1928
}
1929

1930
int32_t doProcessMsgFromServer(void* param) {
8,702,946✔
1931
  AsyncArg* arg = (AsyncArg*)param;
8,702,946✔
1932
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
8,702,946✔
1933
  taosMemoryFree(arg);
8,697,775!
1934
  return code;
8,700,476✔
1935
}
1936

1937
void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
8,673,995✔
1938
  int32_t code = 0;
8,673,995✔
1939
  SEpSet* tEpSet = NULL;
8,673,995✔
1940

1941
  tscDebug("msg callback, ahandle %p", pMsg->info.ahandle);
8,673,995✔
1942

1943
  if (pEpSet != NULL) {
8,674,247✔
1944
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
14,720!
1945
    if (NULL == tEpSet) {
14,713!
1946
      code = terrno;
×
1947
      pMsg->code = terrno;
×
1948
      goto _exit;
×
1949
    }
1950
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
14,713✔
1951
  }
1952

1953
  // pMsg is response msg
1954
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
8,674,240✔
1955
    // restore origin code
1956
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
11,327!
1957
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1958
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
11,327!
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) {
8,662,913!
1964
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
1965
    }
1966
  }
1967

1968
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
8,674,240!
1969
  if (NULL == arg) {
8,680,455!
1970
    code = terrno;
×
1971
    pMsg->code = code;
×
1972
    goto _exit;
×
1973
  }
1974

1975
  arg->msg = *pMsg;
8,680,455✔
1976
  arg->pEpset = tEpSet;
8,680,455✔
1977

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

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

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

2015
  return NULL;
2✔
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) {
3,242,391✔
2033
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
12,369,368✔
2034
    SResultColumn* pCol = &pResultInfo->pCol[i];
9,126,913✔
2035

2036
    int32_t type = pResultInfo->fields[i].type;
9,126,913✔
2037
    int32_t schemaBytes = calcSchemaBytesFromTypeBytes(type, pResultInfo->userFields[i].bytes, false);
9,126,913✔
2038

2039
    if (IS_VAR_DATA_TYPE(type)) {
9,126,977!
2040
      if (!IS_VAR_NULL_TYPE(type, schemaBytes) && pCol->offset[pResultInfo->current] != -1) {
2,885,225!
2041
        char* pStart = pResultInfo->pCol[i].offset[pResultInfo->current] + pResultInfo->pCol[i].pData;
1,241,110✔
2042

2043
        if (IS_STR_DATA_BLOB(type)) {
1,241,110!
2044
          pResultInfo->length[i] = blobDataLen(pStart);
×
2045
          pResultInfo->row[i] = blobDataVal(pStart);
×
2046
        } else {
2047
          pResultInfo->length[i] = varDataLen(pStart);
1,241,122✔
2048
          pResultInfo->row[i] = varDataVal(pStart);
1,241,122✔
2049
        }
2050
      } else {
2051
        pResultInfo->row[i] = NULL;
403,005✔
2052
        pResultInfo->length[i] = 0;
403,005✔
2053
      }
2054
    } else {
2055
      if (!colDataIsNull_f(pCol, pResultInfo->current)) {
7,482,862!
2056
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + schemaBytes * pResultInfo->current;
6,280,377✔
2057
        pResultInfo->length[i] = schemaBytes;
6,280,377✔
2058
      } else {
2059
        pResultInfo->row[i] = NULL;
1,202,485✔
2060
        pResultInfo->length[i] = 0;
1,202,485✔
2061
      }
2062
    }
2063
  }
2064
}
3,242,455✔
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) {
125,074✔
2117
  tsem_t* sem = param;
125,074✔
2118
  if (TSDB_CODE_SUCCESS != tsem_post(sem)) {
125,074!
2119
    tscError("failed to post sem, code:%s", terrstr());
×
2120
  }
2121
}
125,083✔
2122

2123
void* doAsyncFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
3,264,392✔
2124
  if (pRequest == NULL) {
3,264,392!
2125
    return NULL;
×
2126
  }
2127

2128
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
3,264,392✔
2129
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
3,264,392✔
2130
    // All data has returned to App already, no need to try again
2131
    if (pResultInfo->completed) {
140,776✔
2132
      pResultInfo->numOfRows = 0;
15,702✔
2133
      return NULL;
15,702✔
2134
    }
2135

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

2152
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
3,248,691!
2153
    return NULL;
1,503✔
2154
  } else {
2155
    if (setupOneRowPtr) {
3,247,188✔
2156
      doSetOneRowPtr(pResultInfo);
3,241,175✔
2157
      pResultInfo->current += 1;
3,241,136✔
2158
    }
2159

2160
    return pResultInfo->row;
3,247,149✔
2161
  }
2162
}
2163

2164
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
137,168✔
2165
  if (pResInfo->row == NULL) {
137,168✔
2166
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
134,579!
2167
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
134,600!
2168
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
134,603!
2169
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
134,606!
2170

2171
    if (pResInfo->row == NULL || pResInfo->pCol == NULL || pResInfo->length == NULL || pResInfo->convertBuf == NULL) {
134,604!
2172
      taosMemoryFree(pResInfo->row);
2!
2173
      taosMemoryFree(pResInfo->pCol);
×
2174
      taosMemoryFree(pResInfo->length);
×
2175
      taosMemoryFree(pResInfo->convertBuf);
×
2176
      return terrno;
×
2177
    }
2178
  }
2179

2180
  return TSDB_CODE_SUCCESS;
137,191✔
2181
}
2182

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

2188
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
360,387✔
2189
    int32_t type = pResultInfo->fields[i].type;
223,297✔
2190
    int32_t schemaBytes =
2191
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
223,297✔
2192

2193
    if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) {
223,302✔
2194
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
3,163!
2195
      if (p == NULL) {
3,163!
2196
        taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
×
2197
        return terrno;
×
2198
      }
2199

2200
      pResultInfo->convertBuf[i] = p;
3,163✔
2201

2202
      SResultColumn* pCol = &pResultInfo->pCol[i];
3,163✔
2203
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
671,627✔
2204
        if (pCol->offset[j] != -1) {
668,463✔
2205
          char* pStart = pCol->offset[j] + pCol->pData;
492,634✔
2206

2207
          int32_t len = taosUcs4ToMbsEx((TdUcs4*)varDataVal(pStart), varDataLen(pStart), varDataVal(p), conv);
492,634✔
2208
          if (len < 0 || len > schemaBytes || (p + len) >= (pResultInfo->convertBuf[i] + colLength[i])) {
492,634!
2209
            tscError(
×
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);
×
2214
            return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2215
          }
2216

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

2223
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
3,164✔
2224
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
3,164✔
2225
    }
2226
  }
2227
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
137,090✔
2228
  return TSDB_CODE_SUCCESS;
137,081✔
2229
}
2230

2231
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
137,070✔
2232
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
360,356✔
2233
    TAOS_FIELD_E* pFieldE = pResultInfo->fields + i;
223,286✔
2234
    TAOS_FIELD*   pField = pResultInfo->userFields + i;
223,286✔
2235
    int32_t       type = pFieldE->type;
223,286✔
2236
    int32_t       bufLen = 0;
223,286✔
2237
    char*         p = NULL;
223,286✔
2238
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
223,286!
2239
      continue;
221,580✔
2240
    } else {
2241
      bufLen = 64;
1,706✔
2242
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
1,706!
2243
      pFieldE->bytes = bufLen;
1,706✔
2244
      pField->bytes = bufLen;
1,706✔
2245
    }
2246
    if (!p) return terrno;
1,706!
2247
    pResultInfo->convertBuf[i] = p;
1,706✔
2248

2249
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
1,309,932✔
2250
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
1,308,226✔
2251
                                  pFieldE->precision, pFieldE->scale, p, bufLen);
1,308,226✔
2252
      p += bufLen;
1,308,226✔
2253
      if (TSDB_CODE_SUCCESS != code) {
1,308,226!
2254
        return code;
×
2255
      }
2256
    }
2257
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
1,706✔
2258
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
1,706✔
2259
  }
2260
  return 0;
137,070✔
2261
}
2262

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

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

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

2287
  char* pStart = p + len;
2✔
2288
  for (int32_t i = 0; i < numOfCols; ++i) {
4✔
2289
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
2!
2290

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

2297
      int32_t estimateColLen = 0;
2✔
2298
      for (int32_t j = 0; j < numOfRows; ++j) {
4✔
2299
        if (offset[j] == -1) {
2!
2300
          continue;
×
2301
        }
2302
        char* data = offset[j] + pStart;
2✔
2303

2304
        int32_t jsonInnerType = *data;
2✔
2305
        char*   jsonInnerData = data + CHAR_BYTES;
2✔
2306
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
2!
2307
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
×
2308
        } else if (tTagIsJson(data)) {
2!
2309
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
2✔
2310
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
×
2311
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
×
2312
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
×
2313
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
×
2314
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
×
2315
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
×
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);
2✔
2324
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
×
2325
      int32_t lenTmp = numOfRows * sizeof(int32_t);
×
2326
      len += (lenTmp + colLen);
×
2327
      pStart += lenTmp;
×
2328
    } else {
2329
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
×
2330
      len += (lenTmp + colLen);
×
2331
      pStart += lenTmp;
×
2332
    }
2333
    pStart += colLen;
2✔
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);
2✔
2339
  return len;
2✔
2340
}
2341

2342
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
137,197✔
2343
  int32_t numOfRows = pResultInfo->numOfRows;
137,197✔
2344
  int32_t numOfCols = pResultInfo->numOfCols;
137,197✔
2345
  bool    needConvert = false;
137,197✔
2346
  for (int32_t i = 0; i < numOfCols; ++i) {
361,054✔
2347
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
223,859✔
2348
      needConvert = true;
2✔
2349
      break;
2✔
2350
    }
2351
  }
2352

2353
  if (!needConvert) {
137,197✔
2354
    return TSDB_CODE_SUCCESS;
137,195✔
2355
  }
2356

2357
  tscDebug("start to convert form json format string");
2!
2358

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

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

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

2382
  p += len;
2✔
2383
  p1 += len;
2✔
2384
  totalLen += len;
2✔
2385

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

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

2412
      len = 0;
2✔
2413
      for (int32_t j = 0; j < numOfRows; ++j) {
4✔
2414
        if (offset[j] == -1) {
2!
2415
          continue;
×
2416
        }
2417
        char* data = offset[j] + pStart;
2✔
2418

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

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

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

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

2506
  if (pResultInfo->numOfRows == 0) {
139,480✔
2507
    return TSDB_CODE_SUCCESS;
2,303✔
2508
  }
2509

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

2515
  int32_t code = doPrepareResPtr(pResultInfo);
137,177✔
2516
  if (code != TSDB_CODE_SUCCESS) {
137,192!
2517
    return code;
×
2518
  }
2519
  code = doConvertJson(pResultInfo);
137,192✔
2520
  if (code != TSDB_CODE_SUCCESS) {
137,197!
2521
    return code;
×
2522
  }
2523

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

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

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

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

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

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

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

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

2551
  // check fields
2552
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
361,060✔
2553
    int8_t type = *(int8_t*)p;
223,861✔
2554
    p += sizeof(int8_t);
223,861✔
2555

2556
    int32_t bytes = *(int32_t*)p;
223,861✔
2557
    p += sizeof(int32_t);
223,861✔
2558

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

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

2567
  char* pStart = p;
137,199✔
2568
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
361,060✔
2569
    if ((pStart - pResultInfo->pData) >= dataLen) {
223,859!
2570
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2571
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2572
    }
2573
    if (blockVersion == BLOCK_VERSION_1) {
223,859✔
2574
      colLength[i] = htonl(colLength[i]);
223,407✔
2575
    }
2576
    if (colLength[i] >= dataLen) {
223,859!
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)) {
223,859✔
2581
      tscError("invalid type %d", pResultInfo->fields[i].type);
4!
2582
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2583
    }
2584
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
223,855!
2585
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
33,618✔
2586
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
33,618✔
2587
    } else {
2588
      pResultInfo->pCol[i].nullbitmap = pStart;
190,237✔
2589
      pStart += BitmapLen(pResultInfo->numOfRows);
190,237✔
2590
    }
2591

2592
    pResultInfo->pCol[i].pData = pStart;
223,855✔
2593
    pResultInfo->length[i] =
447,716✔
2594
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
223,855✔
2595
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
223,861✔
2596

2597
    pStart += colLength[i];
223,861✔
2598
  }
2599

2600
  p = pStart;
137,201✔
2601
  // bool blankFill = *(bool*)p;
2602
  p += sizeof(bool);
137,201✔
2603
  int32_t offset = p - pResultInfo->pData;
137,201✔
2604
  if (offset > dataLen) {
137,201!
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,201✔
2611
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
137,084✔
2612
  }
2613
#endif
2614
  if (TSDB_CODE_SUCCESS == code && convertForDecimal) {
137,199✔
2615
    code = convertDecimalType(pResultInfo);
137,082✔
2616
  }
2617
  return code;
137,189✔
2618
}
2619

2620
char* getDbOfConnection(STscObj* pObj) {
8,251,961✔
2621
  terrno = TSDB_CODE_SUCCESS;
8,251,961✔
2622
  char* p = NULL;
8,249,096✔
2623
  (void)taosThreadMutexLock(&pObj->mutex);
8,249,096✔
2624
  size_t len = strlen(pObj->db);
8,257,132✔
2625
  if (len > 0) {
8,257,132✔
2626
    p = taosStrndup(pObj->db, tListLen(pObj->db));
8,231,099!
2627
    if (p == NULL) {
8,223,898!
2628
      tscError("failed to taosStrndup db name");
×
2629
    }
2630
  }
2631

2632
  (void)taosThreadMutexUnlock(&pObj->mutex);
8,249,931✔
2633
  return p;
8,258,676✔
2634
}
2635

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

2642
  (void)taosThreadMutexLock(&pTscObj->mutex);
5,052✔
2643
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
5,049✔
2644
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
5,049✔
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,
139,443✔
2658
                              bool isStmt) {
2659
  if (pResultInfo == NULL || pRsp == NULL) {
139,443!
2660
    tscError("setQueryResultFromRsp paras is null");
×
2661
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2662
  }
2663

2664
  taosMemoryFreeClear(pResultInfo->pRspMsg);
139,450!
2665
  pResultInfo->pRspMsg = (const char*)pRsp;
139,450✔
2666
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
139,450✔
2667
  pResultInfo->current = 0;
139,449✔
2668
  pResultInfo->completed = (pRsp->completed == 1);
139,449✔
2669
  pResultInfo->precision = pRsp->precision;
139,449✔
2670

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

2674
  if (pRsp->compressed) {
139,449!
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) {
139,449✔
2697
    int32_t compLen = *(int32_t*)pRsp->data;
137,136✔
2698
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
137,136✔
2699

2700
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
137,136✔
2701

2702
    if (pRsp->compressed && compLen < rawLen) {
137,136!
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;
137,136✔
2716
      pResultInfo->payloadLen = htonl(pRsp->compLen);
137,136✔
2717
      if (pRsp->compLen != pRsp->payloadLen) {
137,136!
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;
139,449✔
2726

2727
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
139,449✔
2728
  return code;
139,449✔
2729
}
2730

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2874
  return TSDB_CODE_SUCCESS;
×
2875
}
2876

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

2883
  bool    inEscape = false;
×
2884
  int32_t code = 0;
×
2885
  void*   pIter = NULL;
×
2886

2887
  int32_t vIdx = 0;
×
2888
  int32_t vPos[2];
2889
  int32_t vLen[2];
2890

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

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

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

2905
      break;
×
2906
    }
2907

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

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

2979
    goto _return;
×
2980
  }
2981

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

2996
  taosHashCleanup(pHash);
×
2997

2998
  return TSDB_CODE_SUCCESS;
×
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) {
×
3017
  SSyncQueryParam* pParam = param;
×
3018
  pParam->pRequest->code = code;
×
3019

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

3025
void syncQueryFn(void* param, void* res, int32_t code) {
8,214,186✔
3026
  SSyncQueryParam* pParam = param;
8,214,186✔
3027
  pParam->pRequest = res;
8,214,186✔
3028

3029
  if (pParam->pRequest) {
8,214,186✔
3030
    pParam->pRequest->code = code;
8,213,170✔
3031
    clientOperateReport(pParam->pRequest);
8,213,170✔
3032
  }
3033

3034
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
8,216,136!
3035
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3036
  }
3037
}
8,221,897✔
3038

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

3047
    return;
×
3048
  }
3049

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

3058
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, sql:%s", connId, sql);
8,216,260✔
3059

3060
  SRequestObj* pRequest = NULL;
8,216,260✔
3061
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
8,216,260✔
3062
  if (code != TSDB_CODE_SUCCESS) {
8,210,256!
3063
    terrno = code;
×
3064
    fp(param, NULL, terrno);
×
3065
    return;
×
3066
  }
3067

3068
  pRequest->source = source;
8,210,256✔
3069
  pRequest->body.queryFp = fp;
8,210,256✔
3070
  doAsyncQuery(pRequest, false);
8,210,256✔
3071
}
3072

3073
void taosAsyncQueryImplWithReqid(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
×
3074
                                 int64_t reqid) {
3075
  if (sql == NULL || NULL == fp) {
×
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);
×
3085
  if (sqlLen > (size_t)TSDB_MAX_ALLOWED_SQL_LEN) {
×
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);
×
3094

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

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

3107
TAOS_RES* taosQueryImpl(TAOS* taos, const char* sql, bool validateOnly, int8_t source) {
8,205,902✔
3108
  if (NULL == taos) {
8,205,902✔
3109
    terrno = TSDB_CODE_TSC_DISCONNECTED;
1✔
3110
    return NULL;
1✔
3111
  }
3112

3113
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
8,205,901!
3114
  if (NULL == param) {
8,216,075!
3115
    return NULL;
×
3116
  }
3117
  int32_t code = tsem_init(&param->sem, 0, 0);
8,216,075✔
3118
  if (TSDB_CODE_SUCCESS != code) {
8,215,399!
3119
    taosMemoryFree(param);
×
3120
    return NULL;
×
3121
  }
3122

3123
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
8,215,399✔
3124
  code = tsem_wait(&param->sem);
8,165,816✔
3125
  if (TSDB_CODE_SUCCESS != code) {
8,219,487!
3126
    taosMemoryFree(param);
×
3127
    return NULL;
×
3128
  }
3129
  code = tsem_destroy(&param->sem);
8,219,487✔
3130
  if (TSDB_CODE_SUCCESS != code) {
8,217,340!
3131
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3132
  }
3133

3134
  SRequestObj* pRequest = NULL;
8,217,897✔
3135
  if (param->pRequest != NULL) {
8,217,897!
3136
    param->pRequest->syncQuery = true;
8,217,897✔
3137
    pRequest = param->pRequest;
8,217,897✔
3138
    param->pRequest->inCallback = false;
8,217,897✔
3139
  }
3140
  taosMemoryFree(param);
8,217,897!
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;
8,212,864✔
3146
}
3147

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

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

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

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

3186
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
135,991✔
3187

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

3191
  pResultInfo->pData = pResult;
135,985✔
3192
  pResultInfo->numOfRows = 0;
135,985✔
3193

3194
  if (code != TSDB_CODE_SUCCESS) {
135,985!
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) {
135,985!
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,
271,979✔
3208
                                         pResultInfo->convertUcs4, pRequest->stmtBindVersion > 0);
135,985✔
3209
  if (pRequest->code != TSDB_CODE_SUCCESS) {
135,994!
3210
    pResultInfo->numOfRows = 0;
×
3211
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self,
×
3212
             tstrerror(pRequest->code), pRequest->requestId);
3213
  } else {
3214
    tscDebug(
135,994✔
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;
135,994✔
3219
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
135,994✔
3220
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
135,994✔
3221
  }
3222

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

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

3230
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
149,719✔
3231

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

3239
  // all data has returned to App already, no need to try again
3240
  if (pResultInfo->completed) {
149,717✔
3241
    // it is a local executed query, no need to do async fetch
3242
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
13,703✔
3243
      if (pResultInfo->localResultFetched) {
5,390✔
3244
        pResultInfo->numOfRows = 0;
2,695✔
3245
        pResultInfo->current = 0;
2,695✔
3246
      } else {
3247
        pResultInfo->localResultFetched = true;
2,695✔
3248
      }
3249
    } else {
3250
      pResultInfo->numOfRows = 0;
8,313✔
3251
    }
3252

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

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

3263
  int32_t code = schedulerFetchRows(pRequest->body.queryJob, &req);
136,014✔
3264
  if (TSDB_CODE_SUCCESS != code) {
136,015!
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) {
8,213,283✔
3271
  pRequest->inCallback = true;
8,213,283✔
3272
  int64_t this = pRequest->self;
8,213,283✔
3273
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
8,213,283!
3274
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
×
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,
8,213,283✔
3280
           pRequest);
3281

3282
  if (pRequest->body.queryFp != NULL) {
8,213,283!
3283
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
8,214,386✔
3284
  }
3285

3286
  SRequestObj* pReq = acquireRequest(this);
8,220,886✔
3287
  if (pReq != NULL) {
8,222,546✔
3288
    pReq->inCallback = false;
8,218,647✔
3289
    (void)releaseRequest(this);
8,218,647✔
3290
  }
3291
}
8,216,766✔
3292

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