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

taosdata / TDengine / #4874

04 Dec 2025 01:55AM UTC coverage: 64.623% (+0.07%) from 64.558%
#4874

push

travis-ci

guanshengliang
Merge branch '3.0' into cover/3.0

865 of 2219 new or added lines in 36 files covered. (38.98%)

6317 existing lines in 143 files now uncovered.

159543 of 246882 relevant lines covered (64.62%)

106415537.4 hits per line

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

70.13
/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) {
115,914,977✔
39
  SRequestObj* pReq = acquireRequest(rId);
115,914,977✔
40
  if (pReq != NULL) {
115,916,920✔
41
    pReq->isQuery = true;
115,906,714✔
42
    (void)releaseRequest(rId);
115,904,874✔
43
  }
44
}
115,915,376✔
45

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

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

56
  return true;
7,975,837✔
57
}
58

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

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

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

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

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

84
  size_t dstLength = srcLength;
634,868✔
85
  if(escapeLength == 0) {
634,868✔
86
     (void)memcpy(dst, src, srcLength);
634,868✔
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;
634,868✔
126
}
127

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

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

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

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

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

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

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

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

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

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

178
  SCorEpSet epSet = {0};
3,238,463✔
179
  if (ip) {
3,237,853✔
180
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
1,140,995✔
181
  } else {
182
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
2,096,858✔
183
  }
184

185
  if (port) {
3,236,828✔
186
    epSet.epSet.eps[0].port = port;
148,577✔
187
    epSet.epSet.eps[1].port = port;
148,577✔
188
  }
189

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

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

215
  pInst = taosHashGet(appInfo.pInstMap, key, strlen(key));
3,238,509✔
216
  SAppInstInfo* p = NULL;
3,238,509✔
217
  if (pInst == NULL) {
3,238,509✔
218
    p = taosMemoryCalloc(1, sizeof(struct SAppInstInfo));
1,355,325✔
219
    if (NULL == p) {
1,355,325✔
220
      TSC_ERR_JRET(terrno);
×
221
    }
222
    p->mgmtEp = epSet;
1,355,325✔
223
    code = taosThreadMutexInit(&p->qnodeMutex, NULL);
1,355,325✔
224
    if (TSDB_CODE_SUCCESS != code) {
1,355,325✔
225
      taosMemoryFree(p);
×
226
      TSC_ERR_JRET(code);
×
227
    }
228
    code = openTransporter(user, secretEncrypt, tsNumOfCores / 2, &p->pTransporter);
1,355,325✔
229
    if (TSDB_CODE_SUCCESS != code) {
1,355,325✔
230
      taosMemoryFree(p);
×
231
      TSC_ERR_JRET(code);
×
232
    }
233
    code = appHbMgrInit(p, key, &p->pAppHbMgr);
1,355,325✔
234
    if (TSDB_CODE_SUCCESS != code) {
1,355,325✔
235
      destroyAppInst(&p);
×
236
      TSC_ERR_JRET(code);
×
237
    }
238
    code = taosHashPut(appInfo.pInstMap, key, strlen(key), &p, POINTER_BYTES);
1,355,325✔
239
    if (TSDB_CODE_SUCCESS != code) {
1,355,325✔
240
      destroyAppInst(&p);
×
241
      TSC_ERR_JRET(code);
×
242
    }
243
    p->instKey = key;
1,355,325✔
244
    key = NULL;
1,355,325✔
245
    tscInfo("new app inst mgr:%p, user:%s, ip:%s, port:%d", p, user, epSet.epSet.eps[0].fqdn, epSet.epSet.eps[0].port);
1,355,325✔
246

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

257
_return:
3,238,509✔
258

259
  if (TSDB_CODE_SUCCESS != code) {
3,238,509✔
260
    (void)taosThreadMutexUnlock(&appInfo.mutex);
×
261
    taosMemoryFreeClear(key);
×
262
    return code;
×
263
  } else {
264
    code = taosThreadMutexUnlock(&appInfo.mutex);
3,238,509✔
265
    taosMemoryFreeClear(key);
3,238,509✔
266
    if (TSDB_CODE_SUCCESS != code) {
3,238,509✔
267
      tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
268
      return code;
×
269
    }
270
    return taosConnectImpl(user, &secretEncrypt[0], localDb, NULL, NULL, *pInst, connType, pObj);
3,238,509✔
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) {
559,051✔
284
  if (param == NULL) return;
559,051✔
285
  if (TSDB_CODE_SUCCESS != tsem_destroy(&param->sem)) {
559,051✔
286
    tscError("failed to destroy semaphore in freeQueryParam");
×
287
  }
288
  taosMemoryFree(param);
559,051✔
289
}
290

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

299
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
625,515,569✔
300
  if ((*pRequest)->sqlstr == NULL) {
625,512,866✔
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);
625,507,910✔
308
  (*pRequest)->sqlstr[sqlLen] = 0;
625,524,085✔
309
  (*pRequest)->sqlLen = sqlLen;
625,525,107✔
310
  (*pRequest)->validateOnly = validateSql;
625,525,406✔
311
  (*pRequest)->stmtBindVersion = 0;
625,523,228✔
312

313
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
625,523,189✔
314

315
  STscObj* pTscObj = (*pRequest)->pTscObj;
625,520,902✔
316
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
625,520,274✔
317
                             sizeof((*pRequest)->self));
318
  if (err) {
625,518,043✔
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;
625,518,043✔
327
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
625,521,615✔
328
    if (TSDB_CODE_SUCCESS !=
177,716,780✔
329
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
177,706,657✔
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);
625,529,835✔
339
  return TSDB_CODE_SUCCESS;
625,516,217✔
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) {
786,976✔
355
  STscObj* pTscObj = pRequest->pTscObj;
786,976✔
356

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

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

386
  code = qParseSql(&cxt, pQuery);
786,980✔
387
  if (TSDB_CODE_SUCCESS == code) {
786,449✔
388
    if ((*pQuery)->haveResultSet) {
784,704✔
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)) {
786,520✔
396
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
784,375✔
397
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
784,893✔
398
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
784,315✔
399
  }
400

401
  taosArrayDestroy(cxt.pTableMetaPos);
785,782✔
402
  taosArrayDestroy(cxt.pTableVgroupPos);
785,355✔
403

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

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

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

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

440
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
1,177,636,237✔
441

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

449
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp,
10,519,915✔
450
                              atomic_load_8(&pRequest->pTscObj->biMode), pRequest->pTscObj->optionInfo.charsetCxt);
10,519,915✔
451
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
5,310,872✔
452
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4,
2,765,451✔
453
                                 pRequest->stmtBindVersion > 0);
2,765,451✔
454
  }
455

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

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

469
  doRequestCallback(pRequest, code);
5,310,872✔
470
}
471

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

478
  // drop table if exists not_exists_table
479
  if (NULL == pQuery->pCmdMsg) {
18,062,183✔
480
    doRequestCallback(pRequest, 0);
7,696✔
481
    return TSDB_CODE_SUCCESS;
7,696✔
482
  }
483

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

489
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
18,054,212✔
490
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
18,053,909✔
491

492
  int32_t code = asyncSendMsgToServer(pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg);
18,053,992✔
493
  if (code) {
18,054,699✔
494
    doRequestCallback(pRequest, code);
×
495
  }
496
  return code;
18,054,768✔
497
}
498

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

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

507
  return node1->load > node2->load;
392,053✔
508
}
509

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

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

526
  return TSDB_CODE_SUCCESS;
93,071✔
527
}
528

529
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
625,244,565✔
530
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
625,244,565✔
531
    *required = false;
624,739,666✔
532
    return TSDB_CODE_SUCCESS;
624,737,182✔
533
  }
534

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

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

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

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

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

574
  return code;
×
575
}
576

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

581
  SPlanContext cxt = {.queryId = pRequest->requestId,
17,875,834✔
582
                      .acctId = pRequest->pTscObj->acctId,
11,870,205✔
583
                      .mgmtEpSet = getEpSet_s(&pAppInfo->mgmtEp),
11,870,355✔
584
                      .pAstRoot = pQuery->pRoot,
11,871,751✔
585
                      .showRewrite = pQuery->showRewrite,
11,870,578✔
586
                      .pMsg = pRequest->msgBuf,
11,871,408✔
587
                      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
588
                      .pUser = pRequest->pTscObj->user,
11,871,270✔
589
                      .timezone = pRequest->pTscObj->optionInfo.timezone,
11,869,533✔
590
                      .sysInfo = pRequest->pTscObj->sysInfo};
11,870,676✔
591

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

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

602
  pResInfo->numOfCols = numOfCols;
120,348,719✔
603
  if (pResInfo->fields != NULL) {
120,349,349✔
604
    taosMemoryFree(pResInfo->fields);
21,662✔
605
  }
606
  if (pResInfo->userFields != NULL) {
120,344,489✔
607
    taosMemoryFree(pResInfo->userFields);
21,662✔
608
  }
609
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD_E));
120,347,232✔
610
  if (NULL == pResInfo->fields) return terrno;
120,345,916✔
611
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
120,346,213✔
612
  if (NULL == pResInfo->userFields) {
120,345,362✔
613
    taosMemoryFree(pResInfo->fields);
×
614
    return terrno;
×
615
  }
616
  if (numOfCols != pResInfo->numOfCols) {
120,345,007✔
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) {
714,730,758✔
622
    pResInfo->fields[i].type = pSchema[i].type;
594,382,409✔
623

624
    pResInfo->userFields[i].type = pSchema[i].type;
594,382,153✔
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);
594,380,432✔
627
    pResInfo->fields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, isStmt);
594,383,749✔
628
    if (IS_DECIMAL_TYPE(pSchema[i].type) && pExtSchema) {
594,382,349✔
629
      decimalFromTypeMod(pExtSchema[i].typeMod, &pResInfo->fields[i].precision, &pResInfo->fields[i].scale);
1,449,829✔
630
    }
631

632
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
594,381,087✔
633
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
594,384,176✔
634
  }
635
  return TSDB_CODE_SUCCESS;
120,350,258✔
636
}
637

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

644
  pResInfo->precision = precision;
85,258,396✔
645
}
646

647
int32_t buildVnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pDbVgList) {
94,533,722✔
648
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
94,533,722✔
649
  if (NULL == nodeList) {
94,538,793✔
UNCOV
650
    return terrno;
×
651
  }
652
  char* policy = (tsQueryPolicy == QUERY_POLICY_VNODE) ? "vnode" : "client";
94,539,253✔
653

654
  int32_t dbNum = taosArrayGetSize(pDbVgList);
94,539,253✔
655
  for (int32_t i = 0; i < dbNum; ++i) {
186,626,434✔
656
    SArray* pVg = taosArrayGetP(pDbVgList, i);
92,081,116✔
657
    if (NULL == pVg) {
92,083,488✔
658
      continue;
×
659
    }
660
    int32_t vgNum = taosArrayGetSize(pVg);
92,083,488✔
661
    if (vgNum <= 0) {
92,082,637✔
662
      continue;
685,688✔
663
    }
664

665
    for (int32_t j = 0; j < vgNum; ++j) {
300,460,556✔
666
      SVgroupInfo* pInfo = taosArrayGet(pVg, j);
209,060,031✔
667
      if (NULL == pInfo) {
209,061,316✔
668
        taosArrayDestroy(nodeList);
×
669
        return TSDB_CODE_OUT_OF_RANGE;
×
670
      }
671
      SQueryNodeLoad load = {0};
209,061,316✔
672
      load.addr.nodeId = pInfo->vgId;
209,061,988✔
673
      load.addr.epSet = pInfo->epSet;
209,060,265✔
674

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

682
  int32_t vnodeNum = taosArrayGetSize(nodeList);
94,545,318✔
683
  if (vnodeNum > 0) {
94,545,431✔
684
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
91,089,272✔
685
    goto _return;
91,086,289✔
686
  }
687

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

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

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

706
_return:
129,221✔
707

708
  *pNodeList = nodeList;
94,540,803✔
709

710
  return TSDB_CODE_SUCCESS;
94,539,827✔
711
}
712

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

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

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

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

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

752
_return:
×
753

754
  *pNodeList = nodeList;
403,831✔
755

756
  return TSDB_CODE_SUCCESS;
403,831✔
757
}
758

759
void freeVgList(void* list) {
11,804,480✔
760
  SArray* pList = *(SArray**)list;
11,804,480✔
761
  taosArrayDestroy(pList);
11,805,000✔
762
}
11,808,768✔
763

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

770
  switch (tsQueryPolicy) {
83,073,560✔
771
    case QUERY_POLICY_VNODE:
82,670,906✔
772
    case QUERY_POLICY_CLIENT: {
773
      if (pResultMeta) {
82,670,906✔
774
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
82,671,821✔
775
        if (NULL == pDbVgList) {
82,671,366✔
776
          code = terrno;
×
777
          goto _return;
×
778
        }
779
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
82,671,366✔
780
        for (int32_t i = 0; i < dbNum; ++i) {
162,946,574✔
781
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
80,273,927✔
782
          if (pRes->code || NULL == pRes->pRes) {
80,273,624✔
783
            continue;
341✔
784
          }
785

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

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

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

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

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

830
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
82,672,647✔
831
      break;
82,671,875✔
832
    }
833
    case QUERY_POLICY_HYBRID:
403,831✔
834
    case QUERY_POLICY_QNODE: {
835
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
497,383✔
836
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
93,552✔
837
        if (pRes->code) {
93,552✔
838
          pQnodeList = NULL;
×
839
        } else {
840
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
93,552✔
841
          if (NULL == pQnodeList) {
93,552✔
842
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
843
            goto _return;
×
844
          }
845
        }
846
      } else {
847
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
310,279✔
848
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
310,279✔
849
        if (pInst->pQnodeList) {
310,279✔
850
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
310,279✔
851
          if (NULL == pQnodeList) {
310,279✔
852
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
853
            goto _return;
×
854
          }
855
        }
856
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
310,279✔
857
      }
858

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

867
_return:
83,075,706✔
868
  taosArrayDestroyEx(pDbVgList, fp);
83,075,706✔
869
  taosArrayDestroy(pQnodeList);
83,075,457✔
870

871
  return code;
83,075,901✔
872
}
873

874
int32_t buildSyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList) {
11,862,968✔
875
  SArray* pDbVgList = NULL;
11,862,968✔
876
  SArray* pQnodeList = NULL;
11,862,968✔
877
  int32_t code = 0;
11,864,424✔
878

879
  switch (tsQueryPolicy) {
11,864,424✔
880
    case QUERY_POLICY_VNODE:
11,862,827✔
881
    case QUERY_POLICY_CLIENT: {
882
      int32_t dbNum = taosArrayGetSize(pRequest->dbList);
11,862,827✔
883
      if (dbNum > 0) {
11,868,683✔
884
        SCatalog*     pCtg = NULL;
11,807,415✔
885
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
11,807,713✔
886
        code = catalogGetHandle(pInst->clusterId, &pCtg);
11,806,856✔
887
        if (code != TSDB_CODE_SUCCESS) {
11,803,653✔
888
          goto _return;
×
889
        }
890

891
        pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
11,803,653✔
892
        if (NULL == pDbVgList) {
11,808,563✔
893
          code = terrno;
397✔
894
          goto _return;
×
895
        }
896
        SArray* pVgList = NULL;
11,808,166✔
897
        for (int32_t i = 0; i < dbNum; ++i) {
23,614,102✔
898
          char*            dbFName = taosArrayGet(pRequest->dbList, i);
11,802,543✔
899
          SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
11,807,340✔
900
                                   .requestId = pRequest->requestId,
11,807,237✔
901
                                   .requestObjRefId = pRequest->self,
11,805,721✔
902
                                   .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
11,806,433✔
903

904
          // catalogGetDBVgList will handle dbFName == null.
905
          code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
11,810,288✔
906
          if (code) {
11,807,134✔
907
            goto _return;
×
908
          }
909

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

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

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

932
_return:
11,866,161✔
933

934
  taosArrayDestroyEx(pDbVgList, freeVgList);
11,867,328✔
935
  taosArrayDestroy(pQnodeList);
11,868,634✔
936

937
  return code;
11,869,984✔
938
}
939

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

943
  SExecResult      res = {0};
11,868,136✔
944
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
11,868,247✔
945
                           .requestId = pRequest->requestId,
11,867,840✔
946
                           .requestObjRefId = pRequest->self};
11,867,049✔
947
  SSchedulerReq    req = {
17,868,473✔
948
         .syncReq = true,
949
         .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
11,866,837✔
950
         .pConn = &conn,
951
         .pNodeList = pNodeList,
952
         .pDag = pDag,
953
         .sql = pRequest->sqlstr,
11,866,837✔
954
         .startTs = pRequest->metric.start,
11,866,231✔
955
         .execFp = NULL,
956
         .cbParam = NULL,
957
         .chkKillFp = chkRequestKilled,
958
         .chkKillParam = (void*)pRequest->self,
11,866,761✔
959
         .pExecRes = &res,
960
         .source = pRequest->source,
11,867,124✔
961
         .pWorkerCb = getTaskPoolWorkerCb(),
11,867,000✔
962
  };
963

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

966
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
11,870,688✔
967
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
11,871,471✔
968

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

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

977
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_DELETE == pRequest->type ||
11,870,575✔
978
      TDMT_VND_CREATE_TABLE == pRequest->type) {
15,435✔
979
    pRequest->body.resInfo.numOfRows = res.numOfRows;
11,859,273✔
980
    if (TDMT_VND_SUBMIT == pRequest->type) {
11,859,538✔
981
      STscObj*            pTscObj = pRequest->pTscObj;
11,855,740✔
982
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
11,855,565✔
983
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
11,855,817✔
984
    }
985

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

989
  pRequest->code = res.code;
11,870,372✔
990
  terrno = res.code;
11,869,302✔
991
  return pRequest->code;
11,868,695✔
992
}
993

994
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
457,387,017✔
995
  SArray*      pArray = NULL;
457,387,017✔
996
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
457,387,017✔
997
  if (NULL == pRsp->aCreateTbRsp) {
457,387,017✔
998
    return TSDB_CODE_SUCCESS;
448,454,257✔
999
  }
1000

1001
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
8,940,614✔
1002
  for (int32_t i = 0; i < tbNum; ++i) {
21,470,533✔
1003
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
12,528,448✔
1004
    if (pTbRsp->pMeta) {
12,528,036✔
1005
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
11,816,753✔
1006
    }
1007
  }
1008

1009
  return TSDB_CODE_SUCCESS;
8,942,085✔
1010
}
1011

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

1021
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
69,116,273✔
1022
  if (NULL == pArray) {
69,115,350✔
UNCOV
1023
    return terrno;
×
1024
  }
1025

1026
  for (int32_t i = 0; i < tbNum; ++i) {
183,798,696✔
1027
    STbVerInfo* tbInfo = taosArrayGet(pTbArray, i);
114,683,595✔
1028
    if (NULL == tbInfo) {
114,684,041✔
1029
      code = terrno;
×
1030
      goto _return;
×
1031
    }
1032
    STbSVersion tbSver = {
114,684,041✔
1033
        .tbFName = tbInfo->tbFName, .sver = tbInfo->sversion, .tver = tbInfo->tversion, .rver = tbInfo->rversion};
114,683,570✔
1034
    if (NULL == taosArrayPush(pArray, &tbSver)) {
114,683,045✔
1035
      code = terrno;
×
1036
      goto _return;
×
1037
    }
1038
  }
1039

1040
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
69,115,101✔
1041
                           .requestId = pRequest->requestId,
69,116,381✔
1042
                           .requestObjRefId = pRequest->self,
69,115,821✔
1043
                           .mgmtEps = *epset};
1044

1045
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
69,116,055✔
1046

1047
_return:
69,115,414✔
1048

1049
  taosArrayDestroy(pArray);
69,115,066✔
1050
  return code;
69,115,271✔
1051
}
1052

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

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

1061
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
592,659,618✔
1062
  if (NULL == pRequest->body.resInfo.execRes.res) {
592,659,618✔
1063
    return pRequest->code;
25,360,093✔
1064
  }
1065

1066
  SCatalog*     pCatalog = NULL;
567,293,592✔
1067
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
567,296,282✔
1068

1069
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
567,305,486✔
1070
  if (code) {
567,296,103✔
1071
    return code;
×
1072
  }
1073

1074
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
567,296,103✔
1075
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
567,303,622✔
1076

1077
  switch (pRes->msgType) {
567,306,759✔
1078
    case TDMT_VND_ALTER_TABLE:
3,807,917✔
1079
    case TDMT_MND_ALTER_STB: {
1080
      code = handleAlterTbExecRes(pRes->res, pCatalog);
3,807,917✔
1081
      break;
3,807,917✔
1082
    }
1083
    case TDMT_VND_CREATE_TABLE: {
36,616,368✔
1084
      SArray* pList = (SArray*)pRes->res;
36,616,368✔
1085
      int32_t num = taosArrayGetSize(pList);
36,633,591✔
1086
      for (int32_t i = 0; i < num; ++i) {
77,872,214✔
1087
        void* res = taosArrayGetP(pList, i);
41,235,461✔
1088
        // handleCreateTbExecRes will handle res == null
1089
        code = handleCreateTbExecRes(res, pCatalog);
41,236,643✔
1090
      }
1091
      break;
36,636,753✔
1092
    }
1093
    case TDMT_MND_CREATE_STB: {
350,759✔
1094
      code = handleCreateTbExecRes(pRes->res, pCatalog);
350,759✔
1095
      break;
350,759✔
1096
    }
1097
    case TDMT_VND_SUBMIT: {
457,388,886✔
1098
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
457,388,886✔
1099

1100
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
457,396,836✔
1101
      break;
457,394,368✔
1102
    }
1103
    case TDMT_SCH_QUERY:
69,114,389✔
1104
    case TDMT_SCH_MERGE_QUERY: {
1105
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
69,114,389✔
1106
      break;
69,115,757✔
1107
    }
1108
    default:
1,569✔
1109
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self,
1,569✔
1110
               pRequest->type, pRequest->requestId);
1111
      code = TSDB_CODE_APP_ERROR;
×
1112
  }
1113

1114
  return code;
567,305,554✔
1115
}
1116

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

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

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

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

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

1139
void returnToUser(SRequestObj* pRequest) {
12,391,079✔
1140
  if (pRequest->relation.userRefId == pRequest->self || 0 == pRequest->relation.userRefId) {
12,391,079✔
1141
    // return to client
1142
    doRequestCallback(pRequest, pRequest->code);
12,391,079✔
1143
    return;
12,391,079✔
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) {
580,452,944✔
1263
  SSqlCallbackWrapper* pWrapper = param;
580,452,944✔
1264
  SRequestObj*         pRequest = pWrapper->pRequest;
580,452,944✔
1265
  STscObj*             pTscObj = pRequest->pTscObj;
580,457,264✔
1266

1267
  pRequest->code = code;
580,455,982✔
1268
  if (pResult) {
580,460,421✔
1269
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
580,423,082✔
1270
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
580,424,944✔
1271
  }
1272

1273
  int32_t type = pRequest->type;
580,440,877✔
1274
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
580,430,628✔
1275
    if (pResult) {
485,635,086✔
1276
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
485,624,091✔
1277

1278
      // record the insert rows
1279
      if (TDMT_VND_SUBMIT == type) {
485,636,371✔
1280
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
445,677,533✔
1281
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
445,678,944✔
1282
      }
1283
    }
1284
    schedulerFreeJob(&pRequest->body.queryJob, 0);
485,646,758✔
1285
  }
1286

1287
  taosMemoryFree(pResult);
580,460,507✔
1288
  tscDebug("req:0x%" PRIx64 ", enter scheduler exec cb, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
580,448,881✔
1289
           pRequest->requestId);
1290

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

1302
  tscTrace("req:0x%" PRIx64 ", scheduler exec cb, request type:%s", pRequest->self, TMSG_INFO(pRequest->type));
580,409,804✔
1303
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
580,409,804✔
1304
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
2,839,971✔
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;
580,407,496✔
1310
  int32_t code1 = handleQueryExecRsp(pRequest);
580,410,120✔
1311
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
580,414,539✔
1312
    pRequest->code = code1;
×
1313
  }
1314

1315
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
1,159,860,838✔
1316
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
579,434,346✔
1317
    continueInsertFromCsv(pWrapper, pRequest);
11,469✔
1318
    return;
11,469✔
1319
  }
1320

1321
  if (pRequest->relation.nextRefId) {
580,412,243✔
1322
    handlePostSubQuery(pWrapper);
×
1323
  } else {
1324
    destorySqlCallbackWrapper(pWrapper);
580,409,347✔
1325
    pRequest->pWrapper = NULL;
580,388,264✔
1326

1327
    // return to client
1328
    doRequestCallback(pRequest, code);
580,391,470✔
1329
  }
1330
}
1331

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

1336
  if (pQuery->pRoot) {
12,248,175✔
1337
    pRequest->stmtType = pQuery->pRoot->type;
11,869,625✔
1338
  }
1339

1340
  if (pQuery->pRoot && !pRequest->inRetry) {
12,249,579✔
1341
    STscObj*            pTscObj = pRequest->pTscObj;
11,869,152✔
1342
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
11,868,888✔
1343
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type) {
11,870,334✔
1344
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
11,860,256✔
1345
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
10,276✔
1346
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
10,430✔
1347
    }
1348
  }
1349

1350
  pRequest->body.execMode = pQuery->execMode;
12,250,143✔
1351
  switch (pQuery->execMode) {
12,251,444✔
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:
381,652✔
1363
      if (!pRequest->validateOnly) {
381,652✔
1364
        code = execDdlQuery(pRequest, pQuery);
381,652✔
1365
      }
1366
      break;
381,809✔
1367
    case QUERY_EXEC_MODE_SCHEDULE: {
11,867,415✔
1368
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
11,867,415✔
1369
      if (NULL == pMnodeList) {
11,869,596✔
1370
        code = terrno;
×
1371
        break;
×
1372
      }
1373
      SQueryPlan* pDag = NULL;
11,869,596✔
1374
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
11,869,298✔
1375
      if (TSDB_CODE_SUCCESS == code) {
11,865,372✔
1376
        pRequest->body.subplanNum = pDag->numOfSubplans;
11,866,372✔
1377
        if (!pRequest->validateOnly) {
11,865,265✔
1378
          SArray* pNodeList = NULL;
11,868,636✔
1379
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
11,869,006✔
1380
          if (TSDB_CODE_SUCCESS == code) {
11,867,607✔
1381
            code = scheduleQuery(pRequest, pDag, pNodeList);
11,869,318✔
1382
          }
1383
          taosArrayDestroy(pNodeList);
11,866,975✔
1384
        }
1385
      }
1386
      taosArrayDestroy(pMnodeList);
11,866,936✔
1387
      break;
11,870,321✔
1388
    }
1389
    case QUERY_EXEC_MODE_EMPTY_RESULT:
×
1390
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
1391
      break;
×
1392
    default:
×
1393
      break;
×
1394
  }
1395

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

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

1408
  if (TSDB_CODE_SUCCESS == code) {
12,251,389✔
1409
    code = handleQueryExecRsp(pRequest);
12,250,897✔
1410
  }
1411

1412
  if (TSDB_CODE_SUCCESS != code) {
12,250,495✔
1413
    pRequest->code = code;
25,341✔
1414
  }
1415

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

1422
static int32_t asyncExecSchQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta,
580,878,789✔
1423
                                 SSqlCallbackWrapper* pWrapper) {
1424
  int32_t code = TSDB_CODE_SUCCESS;
580,878,789✔
1425
  pRequest->type = pQuery->msgType;
580,878,789✔
1426
  SArray*     pMnodeList = NULL;
580,884,963✔
1427
  SQueryPlan* pDag = NULL;
580,884,963✔
1428
  int64_t     st = taosGetTimestampUs();
580,907,218✔
1429

1430
  if (!pRequest->parseOnly) {
580,907,218✔
1431
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
580,904,698✔
1432
    if (NULL == pMnodeList) {
580,895,042✔
1433
      code = terrno;
×
1434
    }
1435
    SPlanContext cxt = {.queryId = pRequest->requestId,
624,815,280✔
1436
                        .acctId = pRequest->pTscObj->acctId,
580,932,824✔
1437
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
580,940,777✔
1438
                        .pAstRoot = pQuery->pRoot,
580,949,757✔
1439
                        .showRewrite = pQuery->showRewrite,
580,952,939✔
1440
                        .isView = pWrapper->pParseCtx->isView,
580,943,489✔
1441
                        .isAudit = pWrapper->pParseCtx->isAudit,
580,942,530✔
1442
                        .pMsg = pRequest->msgBuf,
580,933,654✔
1443
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1444
                        .pUser = pRequest->pTscObj->user,
580,931,114✔
1445
                        .sysInfo = pRequest->pTscObj->sysInfo,
580,914,891✔
1446
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
580,926,383✔
1447
                        .allocatorId = pRequest->stmtBindVersion > 0 ? 0 : pRequest->allocatorRefId};
580,933,430✔
1448
    if (TSDB_CODE_SUCCESS == code) {
580,928,798✔
1449
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
580,937,023✔
1450
    }
1451
    if (code) {
580,905,866✔
1452
      tscError("req:0x%" PRIx64 ", failed to create query plan, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
265,110✔
1453
               pRequest->requestId);
1454
    } else {
1455
      pRequest->body.subplanNum = pDag->numOfSubplans;
580,640,756✔
1456
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
580,671,091✔
1457
    }
1458
  }
1459

1460
  pRequest->metric.execStart = taosGetTimestampUs();
580,932,279✔
1461
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
580,936,343✔
1462

1463
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
602,882,015✔
1464
    SArray* pNodeList = NULL;
580,428,975✔
1465
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
580,414,068✔
1466
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
83,074,949✔
1467
    }
1468

1469
    SRequestConnInfo conn = {.pTrans = getAppInfo(pRequest)->pTransporter,
580,441,574✔
1470
                             .requestId = pRequest->requestId,
580,434,444✔
1471
                             .requestObjRefId = pRequest->self};
580,436,763✔
1472
    SSchedulerReq    req = {
602,387,002✔
1473
           .syncReq = false,
1474
           .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
580,425,079✔
1475
           .pConn = &conn,
1476
           .pNodeList = pNodeList,
1477
           .pDag = pDag,
1478
           .allocatorRefId = pRequest->allocatorRefId,
580,425,079✔
1479
           .sql = pRequest->sqlstr,
580,407,660✔
1480
           .startTs = pRequest->metric.start,
580,435,424✔
1481
           .execFp = schedulerExecCb,
1482
           .cbParam = pWrapper,
1483
           .chkKillFp = chkRequestKilled,
1484
           .chkKillParam = (void*)pRequest->self,
580,431,702✔
1485
           .pExecRes = NULL,
1486
           .source = pRequest->source,
580,424,284✔
1487
           .pWorkerCb = getTaskPoolWorkerCb(),
580,395,169✔
1488
    };
1489
    if (TSDB_CODE_SUCCESS == code) {
580,416,758✔
1490
      code = schedulerExecJob(&req, &pRequest->body.queryJob);
580,449,538✔
1491
    }
1492

1493
    taosArrayDestroy(pNodeList);
580,421,099✔
1494
  } else {
1495
    qDestroyQueryPlan(pDag);
512,160✔
1496
    tscDebug("req:0x%" PRIx64 ", plan not executed, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
492,527✔
1497
             pRequest->requestId);
1498
    destorySqlCallbackWrapper(pWrapper);
492,527✔
1499
    pRequest->pWrapper = NULL;
492,527✔
1500
    if (TSDB_CODE_SUCCESS != code) {
492,527✔
1501
      pRequest->code = terrno;
265,110✔
1502
    }
1503

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

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

1510
  return code;
580,944,991✔
1511
}
1512

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

1516
  if (pRequest->parseOnly) {
604,934,521✔
1517
    doRequestCallback(pRequest, 0);
288,248✔
1518
    return;
288,248✔
1519
  }
1520

1521
  pRequest->body.execMode = pQuery->execMode;
604,664,020✔
1522
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
604,665,290✔
1523
    destorySqlCallbackWrapper(pWrapper);
23,733,082✔
1524
    pRequest->pWrapper = NULL;
23,732,072✔
1525
  }
1526

1527
  if (pQuery->pRoot && !pRequest->inRetry) {
604,636,593✔
1528
    STscObj*            pTscObj = pRequest->pTscObj;
604,643,141✔
1529
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
604,642,462✔
1530
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
604,668,628✔
1531
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
497,347,875✔
1532
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
445,636,992✔
1533
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
159,055,020✔
1534
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
77,504,662✔
1535
    }
1536
  }
1537

1538
  switch (pQuery->execMode) {
604,641,626✔
1539
    case QUERY_EXEC_MODE_LOCAL:
5,322,968✔
1540
      asyncExecLocalCmd(pRequest, pQuery);
5,322,968✔
1541
      break;
5,322,968✔
1542
    case QUERY_EXEC_MODE_RPC:
18,061,947✔
1543
      code = asyncExecDdlQuery(pRequest, pQuery);
18,061,947✔
1544
      break;
18,062,464✔
1545
    case QUERY_EXEC_MODE_SCHEDULE: {
580,905,987✔
1546
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
580,905,987✔
1547
      break;
580,945,856✔
1548
    }
1549
    case QUERY_EXEC_MODE_EMPTY_RESULT:
347,650✔
1550
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
347,650✔
1551
      doRequestCallback(pRequest, 0);
347,650✔
1552
      break;
347,650✔
1553
    default:
×
1554
      tscError("req:0x%" PRIx64 ", invalid execMode %d", pRequest->self, pQuery->execMode);
×
1555
      doRequestCallback(pRequest, -1);
×
1556
      break;
×
1557
  }
1558
}
1559

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

1566
  if (dbNum <= 0 && tblNum <= 0) {
11,808✔
1567
    return TSDB_CODE_APP_ERROR;
11,808✔
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) {
4,149,494✔
1604
  SCatalog* pCatalog = NULL;
4,149,494✔
1605
  int32_t   tbNum = taosArrayGetSize(tbList);
4,149,494✔
1606
  int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
4,149,494✔
1607
  if (code != TSDB_CODE_SUCCESS) {
4,149,494✔
1608
    return code;
×
1609
  }
1610

1611
  if (isView) {
4,149,494✔
1612
    for (int32_t i = 0; i < tbNum; ++i) {
822,454✔
1613
      SName* pViewName = taosArrayGet(tbList, i);
411,227✔
1614
      char   dbFName[TSDB_DB_FNAME_LEN];
401,577✔
1615
      if (NULL == pViewName) {
411,227✔
1616
        continue;
×
1617
      }
1618
      (void)tNameGetFullDbName(pViewName, dbFName);
411,227✔
1619
      TSC_ERR_RET(catalogRemoveViewMeta(pCatalog, dbFName, 0, pViewName->tname, 0));
411,227✔
1620
    }
1621
  } else {
1622
    for (int32_t i = 0; i < tbNum; ++i) {
5,543,966✔
1623
      SName* pTbName = taosArrayGet(tbList, i);
1,805,699✔
1624
      TSC_ERR_RET(catalogRemoveTableMeta(pCatalog, pTbName));
1,805,699✔
1625
    }
1626
  }
1627

1628
  return TSDB_CODE_SUCCESS;
4,149,494✔
1629
}
1630

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

1634
  // init mnode ip set
1635
  SEpSet* mgmtEpSet = &(pEpSet->epSet);
3,237,735✔
1636
  mgmtEpSet->numOfEps = 0;
3,237,994✔
1637
  mgmtEpSet->inUse = 0;
3,237,087✔
1638

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

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

1662
  if (secondEp && secondEp[0] != 0) {
3,237,531✔
1663
    if (strlen(secondEp) >= TSDB_EP_LEN) {
2,096,967✔
1664
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1665
      return terrno;
×
1666
    }
1667

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

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

1688
  return 0;
3,236,397✔
1689
}
1690

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

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

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

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

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

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

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

1756
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
3,238,352✔
1757

1758
  (*pMsgSendInfo)->requestObjRefId = pRequest->self;
3,238,352✔
1759
  (*pMsgSendInfo)->requestId = pRequest->requestId;
3,238,100✔
1760
  (*pMsgSendInfo)->fp = getMsgRspHandle((*pMsgSendInfo)->msgType);
3,238,100✔
1761
  (*pMsgSendInfo)->param = taosMemoryCalloc(1, sizeof(pRequest->self));
3,237,971✔
1762
  if (NULL == (*pMsgSendInfo)->param) {
3,237,970✔
1763
    taosMemoryFree(*pMsgSendInfo);
×
1764
    return terrno;
×
1765
  }
1766

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

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

1772
  char* db = getDbOfConnection(pObj);
3,237,970✔
1773
  if (db != NULL) {
3,238,509✔
1774
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
1,498,702✔
1775
  } else if (terrno) {
1,739,807✔
1776
    taosMemoryFree(*pMsgSendInfo);
×
1777
    return terrno;
×
1778
  }
1779
  taosMemoryFreeClear(db);
3,238,509✔
1780

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

1785
  tstrncpy(connectReq.app, appInfo.appName, sizeof(connectReq.app));
3,238,147✔
1786
  tstrncpy(connectReq.user, pObj->user, sizeof(connectReq.user));
3,237,895✔
1787
  tstrncpy(connectReq.passwd, pObj->pass, sizeof(connectReq.passwd));
3,238,147✔
1788
  tstrncpy(connectReq.sVer, td_version, sizeof(connectReq.sVer));
3,238,147✔
1789

1790
  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connectReq);
3,238,147✔
1791
  void*   pReq = taosMemoryMalloc(contLen);
3,236,240✔
1792
  if (NULL == pReq) {
3,237,095✔
1793
    taosMemoryFree(*pMsgSendInfo);
×
1794
    return terrno;
×
1795
  }
1796

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

1803
  (*pMsgSendInfo)->msgInfo.len = contLen;
3,237,295✔
1804
  (*pMsgSendInfo)->msgInfo.pData = pReq;
3,237,781✔
1805
  return TSDB_CODE_SUCCESS;
3,237,266✔
1806
}
1807

1808
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
1,013,679,071✔
1809
  if (NULL == pEpSet) {
1,013,679,071✔
1810
    return;
1,002,465,562✔
1811
  }
1812

1813
  switch (pSendInfo->target.type) {
11,213,509✔
1814
    case TARGET_TYPE_MNODE:
3,561✔
1815
      if (NULL == pTscObj) {
3,561✔
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);
3,561✔
1822
      SEpSet* pOrig = &originEpset;
3,561✔
1823
      SEp*    pOrigEp = &pOrig->eps[pOrig->inUse];
3,561✔
1824
      SEp*    pNewEp = &pEpSet->eps[pEpSet->inUse];
3,561✔
1825
      tscDebug("mnode epset updated from %d/%d=>%s:%d to %d/%d=>%s:%d in client", pOrig->inUse, pOrig->numOfEps,
3,561✔
1826
               pOrigEp->fqdn, pOrigEp->port, pEpSet->inUse, pEpSet->numOfEps, pNewEp->fqdn, pNewEp->port);
1827
      updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
3,561✔
1828
      break;
7,587,428✔
1829
    case TARGET_TYPE_VNODE: {
10,979,048✔
1830
      if (NULL == pTscObj) {
10,979,048✔
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;
10,979,048✔
1837
      int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
10,979,321✔
1838
      if (code != TSDB_CODE_SUCCESS) {
10,979,079✔
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);
10,979,079✔
1845
      if (code != TSDB_CODE_SUCCESS) {
10,980,114✔
1846
        tscError("fail to update catalog vg epset, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
71✔
1847
                 tstrerror(code));
1848
        return;
×
1849
      }
1850
      taosMemoryFreeClear(pSendInfo->target.dbFName);
10,980,043✔
1851
      break;
10,979,427✔
1852
    }
1853
    default:
231,408✔
1854
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
231,408✔
1855
      break;
231,511✔
1856
  }
1857
}
1858

1859
int32_t doProcessMsgFromServerImpl(SRpcMsg* pMsg, SEpSet* pEpSet) {
1,014,335,989✔
1860
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
1,014,335,989✔
1861
  if (pMsg->info.ahandle == NULL) {
1,014,337,919✔
1862
    tscError("doProcessMsgFromServer pMsg->info.ahandle == NULL");
653,234✔
1863
    rpcFreeCont(pMsg->pCont);
653,234✔
1864
    taosMemoryFree(pEpSet);
653,234✔
1865
    return TSDB_CODE_TSC_INTERNAL_ERROR;
653,234✔
1866
  }
1867

1868
  STscObj* pTscObj = NULL;
1,013,682,766✔
1869

1870
  STraceId* trace = &pMsg->info.traceId;
1,013,682,766✔
1871
  char      tbuf[40] = {0};
1,013,684,851✔
1872
  TRACE_TO_STR(trace, tbuf);
1,013,685,845✔
1873

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

1877
  if (pSendInfo->requestObjRefId != 0) {
1,013,687,278✔
1878
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
872,254,424✔
1879
    if (pRequest) {
872,253,838✔
1880
      if (pRequest->self != pSendInfo->requestObjRefId) {
871,997,725✔
1881
        tscError("doProcessMsgFromServer req:0x%" PRId64 " != pSendInfo->requestObjRefId:0x%" PRId64, pRequest->self,
×
1882
                 pSendInfo->requestObjRefId);
1883

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

1896
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
1,013,685,175✔
1897

1898
  SDataBuf buf = {.msgType = pMsg->msgType,
1,013,679,428✔
1899
                  .len = pMsg->contLen,
1,013,680,135✔
1900
                  .pData = NULL,
1901
                  .handle = pMsg->info.handle,
1,013,680,521✔
1902
                  .handleRefId = pMsg->info.refId,
1,013,681,037✔
1903
                  .pEpSet = pEpSet};
1904

1905
  if (pMsg->contLen > 0) {
1,013,681,292✔
1906
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
990,677,413✔
1907
    if (buf.pData == NULL) {
990,675,176✔
1908
      pMsg->code = terrno;
×
1909
    } else {
1910
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
990,675,176✔
1911
    }
1912
  }
1913

1914
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
1,013,683,948✔
1915

1916
  if (pTscObj) {
1,013,665,988✔
1917
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
871,984,930✔
1918
    if (TSDB_CODE_SUCCESS != code) {
871,997,200✔
UNCOV
1919
      tscError("doProcessMsgFromServer taosReleaseRef failed");
×
UNCOV
1920
      terrno = code;
×
UNCOV
1921
      pMsg->code = code;
×
1922
    }
1923
  }
1924

1925
  rpcFreeCont(pMsg->pCont);
1,013,678,258✔
1926
  destroySendMsgInfo(pSendInfo);
1,013,653,794✔
1927
  return TSDB_CODE_SUCCESS;
1,013,653,613✔
1928
}
1929

1930
int32_t doProcessMsgFromServer(void* param) {
1,014,339,232✔
1931
  AsyncArg* arg = (AsyncArg*)param;
1,014,339,232✔
1932
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
1,014,339,232✔
1933
  taosMemoryFree(arg);
1,014,301,301✔
1934
  return code;
1,014,294,590✔
1935
}
1936

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

1941
  tscDebug("msg callback, ahandle %p", pMsg->info.ahandle);
1,014,325,354✔
1942

1943
  if (pEpSet != NULL) {
1,014,325,020✔
1944
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
11,214,135✔
1945
    if (NULL == tEpSet) {
11,213,118✔
1946
      code = terrno;
×
1947
      pMsg->code = terrno;
×
1948
      goto _exit;
×
1949
    }
1950
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
11,213,118✔
1951
  }
1952

1953
  // pMsg is response msg
1954
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
1,014,324,003✔
1955
    // restore origin code
1956
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
3,238,509✔
1957
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1958
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
3,238,472✔
1959
      pMsg->code = TSDB_CODE_RPC_BROKEN_LINK;
×
1960
    }
1961
  } else {
1962
    // uniform to one error code: TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED
1963
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
1,011,090,486✔
1964
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
1965
    }
1966
  }
1967

1968
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
1,014,332,241✔
1969
  if (NULL == arg) {
1,014,321,779✔
1970
    code = terrno;
×
1971
    pMsg->code = code;
×
1972
    goto _exit;
×
1973
  }
1974

1975
  arg->msg = *pMsg;
1,014,321,779✔
1976
  arg->pEpset = tEpSet;
1,014,323,952✔
1977

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

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

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

2015
  return NULL;
627✔
2016
}
2017

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

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

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

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

2043
        if (IS_STR_DATA_BLOB(type)) {
2,147,483,647✔
2044
          pResultInfo->length[i] = blobDataLen(pStart);
10,831✔
2045
          pResultInfo->row[i] = blobDataVal(pStart);
×
2046
        } else {
2047
          pResultInfo->length[i] = varDataLen(pStart);
2,147,483,647✔
2048
          pResultInfo->row[i] = varDataVal(pStart);
2,147,483,647✔
2049
        }
2050
      } else {
2051
        pResultInfo->row[i] = NULL;
40,652,465✔
2052
        pResultInfo->length[i] = 0;
41,471,251✔
2053
      }
2054
    } else {
2055
      if (!colDataIsNull_f(pCol, pResultInfo->current)) {
2,147,483,647✔
2056
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + schemaBytes * pResultInfo->current;
2,147,483,647✔
2057
        pResultInfo->length[i] = schemaBytes;
2,147,483,647✔
2058
      } else {
2059
        pResultInfo->row[i] = NULL;
253,186,386✔
2060
        pResultInfo->length[i] = 0;
254,182,525✔
2061
      }
2062
    }
2063
  }
2064
}
2,147,483,647✔
2065

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

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

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

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

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

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

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

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

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

2113
  return pResultInfo->row;
×
2114
}
2115

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

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

2128
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
1,243,389,209✔
2129
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
1,243,421,375✔
2130
    // All data has returned to App already, no need to try again
2131
    if (pResultInfo->completed) {
168,550,742✔
2132
      pResultInfo->numOfRows = 0;
72,090,389✔
2133
      return NULL;
72,089,891✔
2134
    }
2135

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

2152
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
1,171,404,232✔
2153
    return NULL;
6,926,738✔
2154
  } else {
2155
    if (setupOneRowPtr) {
1,164,459,030✔
2156
      doSetOneRowPtr(pResultInfo);
1,076,692,894✔
2157
      pResultInfo->current += 1;
1,076,708,140✔
2158
    }
2159

2160
    return pResultInfo->row;
1,164,473,457✔
2161
  }
2162
}
2163

2164
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
128,864,930✔
2165
  if (pResInfo->row == NULL) {
128,864,930✔
2166
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
109,614,959✔
2167
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
109,615,273✔
2168
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
109,614,028✔
2169
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
109,614,986✔
2170

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

2180
  return TSDB_CODE_SUCCESS;
128,864,930✔
2181
}
2182

2183
static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength, bool isStmt) {
127,512,832✔
2184
  int32_t idx = -1;
127,512,832✔
2185
  iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt);
127,513,054✔
2186
  if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR;
127,510,967✔
2187

2188
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
711,318,501✔
2189
    int32_t type = pResultInfo->fields[i].type;
583,810,720✔
2190
    int32_t schemaBytes =
2191
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
583,808,862✔
2192

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

2200
      pResultInfo->convertBuf[i] = p;
20,743,323✔
2201

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

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

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

2223
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
20,742,995✔
2224
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
20,742,995✔
2225
    }
2226
  }
2227
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
127,513,108✔
2228
  return TSDB_CODE_SUCCESS;
127,512,139✔
2229
}
2230

2231
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
127,511,849✔
2232
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
711,309,619✔
2233
    TAOS_FIELD_E* pFieldE = pResultInfo->fields + i;
583,802,537✔
2234
    TAOS_FIELD*   pField = pResultInfo->userFields + i;
583,800,336✔
2235
    int32_t       type = pFieldE->type;
583,802,277✔
2236
    int32_t       bufLen = 0;
583,799,924✔
2237
    char*         p = NULL;
583,799,924✔
2238
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
583,799,924✔
2239
      continue;
582,151,001✔
2240
    } else {
2241
      bufLen = 64;
1,648,953✔
2242
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
1,648,953✔
2243
      pFieldE->bytes = bufLen;
1,648,953✔
2244
      pField->bytes = bufLen;
1,648,953✔
2245
    }
2246
    if (!p) return terrno;
1,648,953✔
2247
    pResultInfo->convertBuf[i] = p;
1,648,953✔
2248

2249
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
997,359,056✔
2250
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
995,710,103✔
2251
                                  pFieldE->precision, pFieldE->scale, p, bufLen);
995,710,103✔
2252
      p += bufLen;
995,710,103✔
2253
      if (TSDB_CODE_SUCCESS != code) {
995,710,103✔
2254
        return code;
×
2255
      }
2256
    }
2257
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
1,648,953✔
2258
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
1,648,953✔
2259
  }
2260
  return 0;
127,511,706✔
2261
}
2262

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

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

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

2287
  char* pStart = p + len;
186,595✔
2288
  for (int32_t i = 0; i < numOfCols; ++i) {
817,785✔
2289
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
631,190✔
2290

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

2297
      int32_t estimateColLen = 0;
221,962✔
2298
      for (int32_t j = 0; j < numOfRows; ++j) {
1,145,826✔
2299
        if (offset[j] == -1) {
923,864✔
2300
          continue;
42,856✔
2301
        }
2302
        char* data = offset[j] + pStart;
881,008✔
2303

2304
        int32_t jsonInnerType = *data;
881,008✔
2305
        char*   jsonInnerData = data + CHAR_BYTES;
881,008✔
2306
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
881,008✔
2307
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
9,630✔
2308
        } else if (tTagIsJson(data)) {
871,378✔
2309
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
196,385✔
2310
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
674,993✔
2311
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
635,403✔
2312
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
39,590✔
2313
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
28,890✔
2314
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
10,700✔
2315
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
10,700✔
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);
221,962✔
2324
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
409,228✔
2325
      int32_t lenTmp = numOfRows * sizeof(int32_t);
52,965✔
2326
      len += (lenTmp + colLen);
52,965✔
2327
      pStart += lenTmp;
52,965✔
2328
    } else {
2329
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
356,263✔
2330
      len += (lenTmp + colLen);
356,263✔
2331
      pStart += lenTmp;
356,263✔
2332
    }
2333
    pStart += colLen;
631,190✔
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);
186,595✔
2339
  return len;
186,595✔
2340
}
2341

2342
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
128,863,647✔
2343
  int32_t numOfRows = pResultInfo->numOfRows;
128,863,647✔
2344
  int32_t numOfCols = pResultInfo->numOfCols;
128,863,869✔
2345
  bool    needConvert = false;
128,864,367✔
2346
  for (int32_t i = 0; i < numOfCols; ++i) {
720,476,948✔
2347
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
591,798,548✔
2348
      needConvert = true;
186,595✔
2349
      break;
186,595✔
2350
    }
2351
  }
2352

2353
  if (!needConvert) {
128,864,995✔
2354
    return TSDB_CODE_SUCCESS;
128,678,400✔
2355
  }
2356

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

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

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

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

2382
  p += len;
186,595✔
2383
  p1 += len;
186,595✔
2384
  totalLen += len;
186,595✔
2385

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

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

2412
      len = 0;
221,962✔
2413
      for (int32_t j = 0; j < numOfRows; ++j) {
1,145,826✔
2414
        if (offset[j] == -1) {
923,864✔
2415
          continue;
42,856✔
2416
        }
2417
        char* data = offset[j] + pStart;
881,008✔
2418

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

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

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

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

2506
  if (pResultInfo->numOfRows == 0) {
135,825,983✔
2507
    return TSDB_CODE_SUCCESS;
6,961,275✔
2508
  }
2509

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

2515
  int32_t code = doPrepareResPtr(pResultInfo);
128,864,118✔
2516
  if (code != TSDB_CODE_SUCCESS) {
128,865,152✔
2517
    return code;
×
2518
  }
2519
  code = doConvertJson(pResultInfo);
128,865,152✔
2520
  if (code != TSDB_CODE_SUCCESS) {
128,863,395✔
2521
    return code;
×
2522
  }
2523

2524
  char* p = (char*)pResultInfo->pData;
128,863,395✔
2525

2526
  // version:
2527
  int32_t blockVersion = *(int32_t*)p;
128,863,617✔
2528
  p += sizeof(int32_t);
128,863,617✔
2529

2530
  int32_t dataLen = *(int32_t*)p;
128,863,869✔
2531
  p += sizeof(int32_t);
128,864,497✔
2532

2533
  int32_t rows = *(int32_t*)p;
128,863,999✔
2534
  p += sizeof(int32_t);
128,863,593✔
2535

2536
  int32_t cols = *(int32_t*)p;
128,864,562✔
2537
  p += sizeof(int32_t);
128,864,091✔
2538

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

2545
  int32_t hasColumnSeg = *(int32_t*)p;
128,862,689✔
2546
  p += sizeof(int32_t);
128,862,556✔
2547

2548
  uint64_t groupId = taosGetUInt64Aligned((uint64_t*)p);
128,864,340✔
2549
  p += sizeof(uint64_t);
128,864,340✔
2550

2551
  // check fields
2552
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
720,703,664✔
2553
    int8_t type = *(int8_t*)p;
591,843,249✔
2554
    p += sizeof(int8_t);
591,841,598✔
2555

2556
    int32_t bytes = *(int32_t*)p;
591,841,690✔
2557
    p += sizeof(int32_t);
591,843,720✔
2558

2559
    if (IS_DECIMAL_TYPE(type) && pResultInfo->fields[i].precision == 0) {
591,841,698✔
2560
      extractDecimalTypeInfoFromBytes(&bytes, &pResultInfo->fields[i].precision, &pResultInfo->fields[i].scale);
310,664✔
2561
    }
2562
  }
2563

2564
  int32_t* colLength = (int32_t*)p;
128,863,613✔
2565
  p += sizeof(int32_t) * pResultInfo->numOfCols;
128,863,613✔
2566

2567
  char* pStart = p;
128,863,613✔
2568
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
720,714,191✔
2569
    if ((pStart - pResultInfo->pData) >= dataLen) {
591,850,861✔
2570
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2571
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2572
    }
2573
    if (blockVersion == BLOCK_VERSION_1) {
591,849,589✔
2574
      colLength[i] = htonl(colLength[i]);
434,026,658✔
2575
    }
2576
    if (colLength[i] >= dataLen) {
591,849,088✔
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)) {
591,850,490✔
2581
      tscError("invalid type %d", pResultInfo->fields[i].type);
×
2582
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2583
    }
2584
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
591,850,889✔
2585
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
146,425,871✔
2586
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
146,423,538✔
2587
    } else {
2588
      pResultInfo->pCol[i].nullbitmap = pStart;
445,426,753✔
2589
      pStart += BitmapLen(pResultInfo->numOfRows);
445,428,312✔
2590
    }
2591

2592
    pResultInfo->pCol[i].pData = pStart;
591,851,471✔
2593
    pResultInfo->length[i] =
1,183,702,730✔
2594
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
1,120,020,386✔
2595
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
591,851,837✔
2596

2597
    pStart += colLength[i];
591,850,814✔
2598
  }
2599

2600
  p = pStart;
128,865,152✔
2601
  // bool blankFill = *(bool*)p;
2602
  p += sizeof(bool);
128,865,152✔
2603
  int32_t offset = p - pResultInfo->pData;
128,865,152✔
2604
  if (offset > dataLen) {
128,863,736✔
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) {
128,863,736✔
2611
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
127,512,399✔
2612
  }
2613
#endif
2614
  if (TSDB_CODE_SUCCESS == code && convertForDecimal) {
128,863,712✔
2615
    code = convertDecimalType(pResultInfo);
127,512,047✔
2616
  }
2617
  return code;
128,863,712✔
2618
}
2619

2620
char* getDbOfConnection(STscObj* pObj) {
631,989,865✔
2621
  terrno = TSDB_CODE_SUCCESS;
631,989,865✔
2622
  char* p = NULL;
631,996,056✔
2623
  (void)taosThreadMutexLock(&pObj->mutex);
631,996,056✔
2624
  size_t len = strlen(pObj->db);
631,999,102✔
2625
  if (len > 0) {
632,000,545✔
2626
    p = taosStrndup(pObj->db, tListLen(pObj->db));
565,781,341✔
2627
    if (p == NULL) {
565,775,629✔
2628
      tscError("failed to taosStrndup db name");
×
2629
    }
2630
  }
2631

2632
  (void)taosThreadMutexUnlock(&pObj->mutex);
631,994,833✔
2633
  return p;
631,988,529✔
2634
}
2635

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

2642
  (void)taosThreadMutexLock(&pTscObj->mutex);
2,977,039✔
2643
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
2,977,039✔
2644
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
2,976,776✔
2645
}
2646

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

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

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

2664
  taosMemoryFreeClear(pResultInfo->pRspMsg);
100,738,030✔
2665
  pResultInfo->pRspMsg = (const char*)pRsp;
100,738,030✔
2666
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
100,738,003✔
2667
  pResultInfo->current = 0;
100,738,252✔
2668
  pResultInfo->completed = (pRsp->completed == 1);
100,737,754✔
2669
  pResultInfo->precision = pRsp->precision;
100,737,781✔
2670

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

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

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

2696
  if (payloadLen > 0) {
100,737,754✔
2697
    int32_t compLen = *(int32_t*)pRsp->data;
93,777,116✔
2698
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
93,776,867✔
2699

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

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

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

2727
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
100,737,061✔
2728
  return code;
100,736,785✔
2729
}
2730

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2874
  return TSDB_CODE_SUCCESS;
1,236✔
2875
}
2876

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

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

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

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

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

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

2905
      break;
1,236✔
2906
    }
2907

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

2918
      continue;
×
2919
    }
2920

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

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

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

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

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

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

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

2979
    goto _return;
×
2980
  }
2981

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

2996
  taosHashCleanup(pHash);
1,236✔
2997

2998
  return TSDB_CODE_SUCCESS;
1,236✔
2999

3000
_return:
×
3001

3002
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
3003

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

3011
  taosHashCleanup(pHash);
×
3012

3013
  return terrno;
×
3014
}
3015

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

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

3025
void syncQueryFn(void* param, void* res, int32_t code) {
623,402,023✔
3026
  SSyncQueryParam* pParam = param;
623,402,023✔
3027
  pParam->pRequest = res;
623,402,023✔
3028

3029
  if (pParam->pRequest) {
623,404,483✔
3030
    pParam->pRequest->code = code;
623,382,868✔
3031
    clientOperateReport(pParam->pRequest);
623,386,495✔
3032
  }
3033

3034
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
623,382,119✔
3035
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
3036
  }
3037
}
623,406,934✔
3038

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

3047
    return;
×
3048
  }
3049

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

3058
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, sql:%s", connId, sql);
622,933,493✔
3059

3060
  SRequestObj* pRequest = NULL;
622,934,233✔
3061
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
622,935,924✔
3062
  if (code != TSDB_CODE_SUCCESS) {
622,936,025✔
3063
    terrno = code;
×
3064
    fp(param, NULL, terrno);
×
3065
    return;
×
3066
  }
3067

3068
  pRequest->source = source;
622,936,025✔
3069
  pRequest->body.queryFp = fp;
622,938,169✔
3070
  doAsyncQuery(pRequest, false);
622,934,756✔
3071
}
3072

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

UNCOV
3081
    return;
×
3082
  }
3083

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

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

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

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

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

3112
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
622,827,518✔
3113
  if (NULL == param) {
622,833,906✔
UNCOV
3114
    return NULL;
×
3115
  }
3116
  int32_t code = tsem_init(&param->sem, 0, 0);
622,833,906✔
3117
  if (TSDB_CODE_SUCCESS != code) {
622,820,365✔
3118
    taosMemoryFree(param);
×
UNCOV
3119
    return NULL;
×
3120
  }
3121

3122
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
622,820,365✔
3123
  code = tsem_wait(&param->sem);
622,826,531✔
3124
  if (TSDB_CODE_SUCCESS != code) {
622,838,319✔
3125
    taosMemoryFree(param);
×
UNCOV
3126
    return NULL;
×
3127
  }
3128
  code = tsem_destroy(&param->sem);
622,838,319✔
3129
  if (TSDB_CODE_SUCCESS != code) {
622,842,303✔
UNCOV
3130
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3131
  }
3132

3133
  SRequestObj* pRequest = NULL;
622,842,303✔
3134
  if (param->pRequest != NULL) {
622,842,303✔
3135
    param->pRequest->syncQuery = true;
622,840,515✔
3136
    pRequest = param->pRequest;
622,840,383✔
3137
    param->pRequest->inCallback = false;
622,841,041✔
3138
  }
3139
  taosMemoryFree(param);
622,838,208✔
3140

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

3144
  return pRequest;
622,835,991✔
3145
}
3146

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

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

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

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

3179
  return pRequest;
6,817✔
3180
}
3181

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

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

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

3190
  pResultInfo->pData = pResult;
97,869,042✔
3191
  pResultInfo->numOfRows = 0;
97,868,820✔
3192

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

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

3206
  pRequest->code = setQueryResultFromRsp(pResultInfo, (const SRetrieveTableRsp*)pResultInfo->pData,
107,547,959✔
3207
                                         pResultInfo->convertUcs4, pRequest->stmtBindVersion > 0);
97,868,571✔
3208
  if (pRequest->code != TSDB_CODE_SUCCESS) {
97,868,073✔
3209
    pResultInfo->numOfRows = 0;
328✔
3210
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self,
328✔
3211
             tstrerror(pRequest->code), pRequest->requestId);
3212
  } else {
3213
    tscDebug(
97,866,381✔
3214
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
3215
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
3216

3217
    STscObj*            pTscObj = pRequest->pTscObj;
97,867,049✔
3218
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
97,868,714✔
3219
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
97,868,714✔
3220
  }
3221

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

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

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

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

3238
  // all data has returned to App already, no need to try again
3239
  if (pResultInfo->completed) {
100,726,385✔
3240
    // it is a local executed query, no need to do async fetch
3241
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
2,857,343✔
3242
      if (pResultInfo->localResultFetched) {
1,512,562✔
3243
        pResultInfo->numOfRows = 0;
756,281✔
3244
        pResultInfo->current = 0;
756,281✔
3245
      } else {
3246
        pResultInfo->localResultFetched = true;
756,281✔
3247
      }
3248
    } else {
3249
      pResultInfo->numOfRows = 0;
1,344,781✔
3250
    }
3251

3252
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
2,857,343✔
3253
    return;
2,857,343✔
3254
  }
3255

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

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

3269
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
623,425,184✔
3270
  pRequest->inCallback = true;
623,425,184✔
3271
  int64_t this = pRequest->self;
623,432,910✔
3272
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
623,401,332✔
3273
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
83,250✔
3274
    code = TSDB_CODE_SUCCESS;
×
UNCOV
3275
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3276
  }
3277

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

3281
  if (pRequest->body.queryFp != NULL) {
623,402,888✔
3282
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
623,425,499✔
3283
  }
3284

3285
  SRequestObj* pReq = acquireRequest(this);
623,436,539✔
3286
  if (pReq != NULL) {
623,435,410✔
3287
    pReq->inCallback = false;
622,553,928✔
3288
    (void)releaseRequest(this);
622,553,396✔
3289
  }
3290
}
623,433,116✔
3291

3292
int32_t clientParseSql(void* param, const char* dbName, const char* sql, bool parseOnly, const char* effectiveUser,
559,051✔
3293
                       SParseSqlRes* pRes) {
3294
#ifndef TD_ENTERPRISE
3295
  return TSDB_CODE_SUCCESS;
3296
#else
3297
  return clientParseSqlImpl(param, dbName, sql, parseOnly, effectiveUser, pRes);
559,051✔
3298
#endif
3299
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc