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

taosdata / TDengine / #4361

25 Jun 2025 09:25AM UTC coverage: 62.074% (-0.4%) from 62.521%
#4361

push

travis-ci

GitHub
docs: add OpenMetrics support and configuration details to taosAdapter documentation (#31427)

155314 of 319947 branches covered (48.54%)

Branch coverage included in aggregate %.

241251 of 318911 relevant lines covered (75.65%)

6190992.11 hits per line

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

63.84
/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 "tmsgtype.h"
28
#include "tpagedbuf.h"
29
#include "tref.h"
30
#include "tsched.h"
31
#include "tversion.h"
32

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

36
void setQueryRequest(int64_t rId) {
1,466,248✔
37
  SRequestObj* pReq = acquireRequest(rId);
1,466,248✔
38
  if (pReq != NULL) {
1,466,253✔
39
    pReq->isQuery = true;
1,466,249✔
40
    (void)releaseRequest(rId);
1,466,249✔
41
  }
42
}
1,466,247✔
43

44
static bool stringLengthCheck(const char* str, size_t maxsize) {
58,406✔
45
  if (str == NULL) {
58,406!
46
    return false;
×
47
  }
48

49
  size_t len = strlen(str);
58,406✔
50
  if (len <= 0 || len > maxsize) {
58,406!
51
    return false;
×
52
  }
53

54
  return true;
58,409✔
55
}
56

57
static bool validateUserName(const char* user) { return stringLengthCheck(user, TSDB_USER_LEN - 1); }
28,432✔
58

59
static bool validatePassword(const char* passwd) { return stringLengthCheck(passwd, TSDB_PASSWORD_MAX_LEN); }
28,429✔
60

61
static bool validateDbName(const char* db) { return stringLengthCheck(db, TSDB_DB_NAME_LEN - 1); }
1,547✔
62

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

69
bool chkRequestKilled(void* param) {
11,980,952✔
70
  bool         killed = false;
11,980,952✔
71
  SRequestObj* pRequest = acquireRequest((int64_t)param);
11,980,952✔
72
  if (NULL == pRequest || pRequest->killed) {
12,007,695!
73
    killed = true;
×
74
  }
75

76
  (void)releaseRequest((int64_t)param);
12,007,695✔
77

78
  return killed;
12,007,483✔
79
}
80

81
void cleanupAppInfo() {
17,207✔
82
  taosHashCleanup(appInfo.pInstMap);
17,207✔
83
  taosHashCleanup(appInfo.pInstMapByClusterId);
17,207✔
84
  tscInfo("cluster instance map cleaned");
17,207!
85
}
17,207✔
86

87
static int32_t taosConnectImpl(const char* user, const char* auth, const char* db, __taos_async_fn_t fp, void* param,
88
                               SAppInstInfo* pAppInfo, int connType, STscObj** pTscObj);
89

90
int32_t taos_connect_internal(const char* ip, const char* user, const char* pass, const char* auth, const char* db,
28,434✔
91
                              uint16_t port, int connType, STscObj** pObj) {
92
  TSC_ERR_RET(taos_init());
28,434!
93
  if (!validateUserName(user)) {
28,432!
94
    TSC_ERR_RET(TSDB_CODE_TSC_INVALID_USER_LENGTH);
×
95
  }
96
  int32_t code = 0;
28,433✔
97

98
  char localDb[TSDB_DB_NAME_LEN] = {0};
28,433✔
99
  if (db != NULL && strlen(db) > 0) {
28,433✔
100
    if (!validateDbName(db)) {
1,547!
101
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_DB_LENGTH);
×
102
    }
103

104
    tstrncpy(localDb, db, sizeof(localDb));
1,547✔
105
    (void)strdequote(localDb);
1,547✔
106
  }
107

108
  char secretEncrypt[TSDB_PASSWORD_LEN + 1] = {0};
28,433✔
109
  if (auth == NULL) {
28,433✔
110
    if (!validatePassword(pass)) {
28,429!
111
      TSC_ERR_RET(TSDB_CODE_TSC_INVALID_PASS_LENGTH);
×
112
    }
113

114
    taosEncryptPass_c((uint8_t*)pass, strlen(pass), secretEncrypt);
28,430✔
115
  } else {
116
    tstrncpy(secretEncrypt, auth, tListLen(secretEncrypt));
4✔
117
  }
118

119
  SCorEpSet epSet = {0};
28,435✔
120
  if (ip) {
28,435✔
121
    TSC_ERR_RET(initEpSetFromCfg(ip, NULL, &epSet));
6,869✔
122
  } else {
123
    TSC_ERR_RET(initEpSetFromCfg(tsFirst, tsSecond, &epSet));
21,566!
124
  }
125

126
  if (port) {
28,426✔
127
    epSet.epSet.eps[0].port = port;
606✔
128
    epSet.epSet.eps[1].port = port;
606✔
129
  }
130

131
  char* key = getClusterKey(user, secretEncrypt, ip, port);
28,426✔
132
  if (NULL == key) {
28,431!
133
    TSC_ERR_RET(terrno);
×
134
  }
135
  tscInfo("connecting to server, numOfEps:%d inUse:%d user:%s db:%s key:%s", epSet.epSet.numOfEps, epSet.epSet.inUse,
28,431✔
136
          user, db, key);
137
  for (int32_t i = 0; i < epSet.epSet.numOfEps; ++i) {
78,434✔
138
    tscInfo("ep:%d, %s:%u", i, epSet.epSet.eps[i].fqdn, epSet.epSet.eps[i].port);
50,000!
139
  }
140
  // for (int32_t i = 0; i < epSet.epSet.numOfEps; i++) {
141
  //   if ((code = taosValidFqdn(tsEnableIpv6, epSet.epSet.eps[i].fqdn)) != 0) {
142
  //     taosMemFree(key);
143
  //     tscError("ipv6 flag %d, the local FQDN %s does not resolve to the ip address since %s", tsEnableIpv6,
144
  //              epSet.epSet.eps[i].fqdn, tstrerror(code));
145
  //     TSC_ERR_RET(code);
146
  //   }
147
  // }
148

149
  SAppInstInfo** pInst = NULL;
28,434✔
150
  code = taosThreadMutexLock(&appInfo.mutex);
28,434✔
151
  if (TSDB_CODE_SUCCESS != code) {
28,434!
152
    tscError("failed to lock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
153
    TSC_ERR_RET(code);
×
154
  }
155

156
  pInst = taosHashGet(appInfo.pInstMap, key, strlen(key));
28,434✔
157
  SAppInstInfo* p = NULL;
28,434✔
158
  if (pInst == NULL) {
28,434✔
159
    p = taosMemoryCalloc(1, sizeof(struct SAppInstInfo));
17,443!
160
    if (NULL == p) {
17,443!
161
      TSC_ERR_JRET(terrno);
×
162
    }
163
    p->mgmtEp = epSet;
17,443✔
164
    code = taosThreadMutexInit(&p->qnodeMutex, NULL);
17,443✔
165
    if (TSDB_CODE_SUCCESS != code) {
17,443!
166
      taosMemoryFree(p);
×
167
      TSC_ERR_JRET(code);
×
168
    }
169
    code = openTransporter(user, secretEncrypt, tsNumOfCores / 2, &p->pTransporter);
17,443✔
170
    if (TSDB_CODE_SUCCESS != code) {
17,443!
171
      taosMemoryFree(p);
×
172
      TSC_ERR_JRET(code);
×
173
    }
174
    code = appHbMgrInit(p, key, &p->pAppHbMgr);
17,443✔
175
    if (TSDB_CODE_SUCCESS != code) {
17,443!
176
      destroyAppInst(&p);
×
177
      TSC_ERR_JRET(code);
×
178
    }
179
    code = taosHashPut(appInfo.pInstMap, key, strlen(key), &p, POINTER_BYTES);
17,443✔
180
    if (TSDB_CODE_SUCCESS != code) {
17,443!
181
      destroyAppInst(&p);
×
182
      TSC_ERR_JRET(code);
×
183
    }
184
    p->instKey = key;
17,443✔
185
    key = NULL;
17,443✔
186
    tscInfo("new app inst mgr:%p, user:%s, ip:%s, port:%d", p, user, epSet.epSet.eps[0].fqdn, epSet.epSet.eps[0].port);
17,443!
187

188
    pInst = &p;
17,443✔
189
  } else {
190
    if (NULL == *pInst || NULL == (*pInst)->pAppHbMgr) {
10,991!
191
      tscError("*pInst:%p, pAppHgMgr:%p", *pInst, (*pInst) ? (*pInst)->pAppHbMgr : NULL);
×
192
      TSC_ERR_JRET(TSDB_CODE_TSC_INTERNAL_ERROR);
×
193
    }
194
    // reset to 0 in case of conn with duplicated user key but its user has ever been dropped.
195
    atomic_store_8(&(*pInst)->pAppHbMgr->connHbFlag, 0);
10,991✔
196
  }
197

198
_return:
28,434✔
199

200
  if (TSDB_CODE_SUCCESS != code) {
28,434!
201
    (void)taosThreadMutexUnlock(&appInfo.mutex);
×
202
    taosMemoryFreeClear(key);
×
203
    return code;
×
204
  } else {
205
    code = taosThreadMutexUnlock(&appInfo.mutex);
28,434✔
206
    taosMemoryFreeClear(key);
28,434!
207
    if (TSDB_CODE_SUCCESS != code) {
28,434!
208
      tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
209
      return code;
×
210
    }
211
    return taosConnectImpl(user, &secretEncrypt[0], localDb, NULL, NULL, *pInst, connType, pObj);
28,434✔
212
  }
213
}
214

215
// SAppInstInfo* getAppInstInfo(const char* clusterKey) {
216
//   SAppInstInfo** ppAppInstInfo = taosHashGet(appInfo.pInstMap, clusterKey, strlen(clusterKey));
217
//   if (ppAppInstInfo != NULL && *ppAppInstInfo != NULL) {
218
//     return *ppAppInstInfo;
219
//   } else {
220
//     return NULL;
221
//   }
222
// }
223

224
void freeQueryParam(SSyncQueryParam* param) {
941✔
225
  if (param == NULL) return;
941!
226
  if (TSDB_CODE_SUCCESS != tsem_destroy(&param->sem)) {
941!
227
    tscError("failed to destroy semaphore in freeQueryParam");
×
228
  }
229
  taosMemoryFree(param);
941!
230
}
231

232
int32_t buildRequest(uint64_t connId, const char* sql, int sqlLen, void* param, bool validateSql,
2,956,236✔
233
                     SRequestObj** pRequest, int64_t reqid) {
234
  int32_t code = createRequest(connId, TSDB_SQL_SELECT, reqid, pRequest);
2,956,236✔
235
  if (TSDB_CODE_SUCCESS != code) {
2,956,350!
236
    tscError("failed to malloc sqlObj, %s", sql);
×
237
    return code;
×
238
  }
239

240
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
2,956,350!
241
  if ((*pRequest)->sqlstr == NULL) {
2,956,316!
242
    tscError("req:0x%" PRIx64 ", failed to prepare sql string buffer, %s", (*pRequest)->self, sql);
×
243
    destroyRequest(*pRequest);
×
244
    *pRequest = NULL;
×
245
    return terrno;
×
246
  }
247

248
  (void)strntolower((*pRequest)->sqlstr, sql, (int32_t)sqlLen);
2,956,316✔
249
  (*pRequest)->sqlstr[sqlLen] = 0;
2,956,350✔
250
  (*pRequest)->sqlLen = sqlLen;
2,956,350✔
251
  (*pRequest)->validateOnly = validateSql;
2,956,350✔
252
  (*pRequest)->isStmtBind = false;
2,956,350✔
253

254
  ((SSyncQueryParam*)(*pRequest)->body.interParam)->userParam = param;
2,956,350✔
255

256
  STscObj* pTscObj = (*pRequest)->pTscObj;
2,956,350✔
257
  int32_t  err = taosHashPut(pTscObj->pRequests, &(*pRequest)->self, sizeof((*pRequest)->self), &(*pRequest)->self,
2,956,350✔
258
                             sizeof((*pRequest)->self));
259
  if (err) {
2,956,391!
260
    tscError("req:0x%" PRId64 ", failed to add to request container, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
261
             (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
262
    destroyRequest(*pRequest);
×
263
    *pRequest = NULL;
×
264
    return terrno;
×
265
  }
266

267
  (*pRequest)->allocatorRefId = -1;
2,956,391✔
268
  if (tsQueryUseNodeAllocator && !qIsInsertValuesSql((*pRequest)->sqlstr, (*pRequest)->sqlLen)) {
2,956,391✔
269
    if (TSDB_CODE_SUCCESS !=
1,187,683!
270
        nodesCreateAllocator((*pRequest)->requestId, tsQueryNodeChunkSize, &((*pRequest)->allocatorRefId))) {
1,187,659✔
271
      tscError("req:0x%" PRId64 ", failed to create node allocator, QID:0x%" PRIx64 ", conn:%" PRId64 ", %s",
×
272
               (*pRequest)->self, (*pRequest)->requestId, pTscObj->id, sql);
273
      destroyRequest(*pRequest);
×
274
      *pRequest = NULL;
×
275
      return terrno;
×
276
    }
277
  }
278

279
  tscDebug("req:0x%" PRIx64 ", build request, QID:0x%" PRIx64, (*pRequest)->self, (*pRequest)->requestId);
2,956,431✔
280
  return TSDB_CODE_SUCCESS;
2,956,308✔
281
}
282

283
int32_t buildPreviousRequest(SRequestObj* pRequest, const char* sql, SRequestObj** pNewRequest) {
458✔
284
  int32_t code =
285
      buildRequest(pRequest->pTscObj->id, sql, strlen(sql), pRequest, pRequest->validateOnly, pNewRequest, 0);
458✔
286
  if (TSDB_CODE_SUCCESS == code) {
458!
287
    pRequest->relation.prevRefId = (*pNewRequest)->self;
458✔
288
    (*pNewRequest)->relation.nextRefId = pRequest->self;
458✔
289
    (*pNewRequest)->relation.userRefId = pRequest->self;
458✔
290
    (*pNewRequest)->isSubReq = true;
458✔
291
  }
292
  return code;
458✔
293
}
294

295
int32_t parseSql(SRequestObj* pRequest, bool topicQuery, SQuery** pQuery, SStmtCallback* pStmtCb) {
20,880✔
296
  STscObj* pTscObj = pRequest->pTscObj;
20,880✔
297

298
  SParseContext cxt = {
20,880✔
299
      .requestId = pRequest->requestId,
20,880✔
300
      .requestRid = pRequest->self,
20,880✔
301
      .acctId = pTscObj->acctId,
20,880✔
302
      .db = pRequest->pDb,
20,880✔
303
      .topicQuery = topicQuery,
304
      .pSql = pRequest->sqlstr,
20,880✔
305
      .sqlLen = pRequest->sqlLen,
20,880✔
306
      .pMsg = pRequest->msgBuf,
20,880✔
307
      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
308
      .pTransporter = pTscObj->pAppInfo->pTransporter,
20,880✔
309
      .pStmtCb = pStmtCb,
310
      .pUser = pTscObj->user,
20,880✔
311
      .isSuperUser = (0 == strcmp(pTscObj->user, TSDB_DEFAULT_USER)),
20,880✔
312
      .enableSysInfo = pTscObj->sysInfo,
20,880✔
313
      .svrVer = pTscObj->sVer,
20,880✔
314
      .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes),
20,880✔
315
      .isStmtBind = pRequest->isStmtBind,
20,880✔
316
      .setQueryFp = setQueryRequest,
317
      .timezone = pTscObj->optionInfo.timezone,
20,880✔
318
      .charsetCxt = pTscObj->optionInfo.charsetCxt,
20,880✔
319
  };
320

321
  cxt.mgmtEpSet = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
20,880✔
322
  int32_t code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &cxt.pCatalog);
20,914✔
323
  if (code != TSDB_CODE_SUCCESS) {
20,906!
324
    return code;
×
325
  }
326

327
  code = qParseSql(&cxt, pQuery);
20,906✔
328
  if (TSDB_CODE_SUCCESS == code) {
20,881✔
329
    if ((*pQuery)->haveResultSet) {
20,859!
330
      code = setResSchemaInfo(&pRequest->body.resInfo, (*pQuery)->pResSchema, (*pQuery)->numOfResCols,
×
331
                              (*pQuery)->pResExtSchema, pRequest->isStmtBind);
×
332
      setResPrecision(&pRequest->body.resInfo, (*pQuery)->precision);
×
333
    }
334
  }
335

336
  if (TSDB_CODE_SUCCESS == code || NEED_CLIENT_HANDLE_ERROR(code)) {
20,902!
337
    TSWAP(pRequest->dbList, (*pQuery)->pDbList);
20,865✔
338
    TSWAP(pRequest->tableList, (*pQuery)->pTableList);
20,865✔
339
    TSWAP(pRequest->targetTableList, (*pQuery)->pTargetTableList);
20,865✔
340
  }
341

342
  taosArrayDestroy(cxt.pTableMetaPos);
20,902✔
343
  taosArrayDestroy(cxt.pTableVgroupPos);
20,890✔
344

345
  return code;
20,900✔
346
}
347

348
int32_t execLocalCmd(SRequestObj* pRequest, SQuery* pQuery) {
×
349
  SRetrieveTableRsp* pRsp = NULL;
×
350
  int8_t             biMode = atomic_load_8(&pRequest->pTscObj->biMode);
×
351
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp, biMode,
×
352
                              pRequest->pTscObj->optionInfo.charsetCxt);
×
353
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
×
354
    code =
355
        setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4, pRequest->isStmtBind);
×
356
  }
357

358
  return code;
×
359
}
360

361
int32_t execDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
653✔
362
  // drop table if exists not_exists_table
363
  if (NULL == pQuery->pCmdMsg) {
653!
364
    return TSDB_CODE_SUCCESS;
×
365
  }
366

367
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
653✔
368
  pRequest->type = pMsgInfo->msgType;
653✔
369
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
653✔
370
  pMsgInfo->pMsg = NULL;  // pMsg transferred to SMsgSendInfo management
653✔
371

372
  STscObj*      pTscObj = pRequest->pTscObj;
653✔
373
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
653✔
374

375
  // int64_t transporterId = 0;
376
  TSC_ERR_RET(asyncSendMsgToServer(pTscObj->pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg));
653!
377
  TSC_ERR_RET(tsem_wait(&pRequest->body.rspSem));
654!
378
  return TSDB_CODE_SUCCESS;
654✔
379
}
380

381
static SAppInstInfo* getAppInfo(SRequestObj* pRequest) { return pRequest->pTscObj->pAppInfo; }
5,269,620✔
382

383
void asyncExecLocalCmd(SRequestObj* pRequest, SQuery* pQuery) {
133,067✔
384
  SRetrieveTableRsp* pRsp = NULL;
133,067✔
385
  if (pRequest->validateOnly) {
133,067✔
386
    doRequestCallback(pRequest, 0);
27✔
387
    return;
27✔
388
  }
389

390
  int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp,
133,040✔
391
                              atomic_load_8(&pRequest->pTscObj->biMode), pRequest->pTscObj->optionInfo.charsetCxt);
133,040✔
392
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
133,040✔
393
    code =
394
        setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4, pRequest->isStmtBind);
122,927✔
395
  }
396

397
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
133,038✔
398
  pRequest->code = code;
133,038✔
399

400
  if (pRequest->code != TSDB_CODE_SUCCESS) {
133,038✔
401
    pResultInfo->numOfRows = 0;
8✔
402
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
8!
403
             pRequest->requestId);
404
  } else {
405
    tscDebug(
133,030✔
406
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
407
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
408
  }
409

410
  doRequestCallback(pRequest, code);
133,038✔
411
}
412

413
int32_t asyncExecDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
33,542✔
414
  if (pRequest->validateOnly) {
33,542!
415
    doRequestCallback(pRequest, 0);
×
416
    return TSDB_CODE_SUCCESS;
×
417
  }
418

419
  // drop table if exists not_exists_table
420
  if (NULL == pQuery->pCmdMsg) {
33,542✔
421
    doRequestCallback(pRequest, 0);
1✔
422
    return TSDB_CODE_SUCCESS;
1✔
423
  }
424

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

430
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
33,541✔
431
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
33,538✔
432

433
  int32_t code = asyncSendMsgToServer(pAppInfo->pTransporter, &pMsgInfo->epSet, NULL, pSendMsg);
33,537✔
434
  if (code) {
33,547!
435
    doRequestCallback(pRequest, code);
×
436
  }
437
  return code;
33,547✔
438
}
439

440
int compareQueryNodeLoad(const void* elem1, const void* elem2) {
308✔
441
  SQueryNodeLoad* node1 = (SQueryNodeLoad*)elem1;
308✔
442
  SQueryNodeLoad* node2 = (SQueryNodeLoad*)elem2;
308✔
443

444
  if (node1->load < node2->load) {
308!
445
    return -1;
×
446
  }
447

448
  return node1->load > node2->load;
308✔
449
}
450

451
int32_t updateQnodeList(SAppInstInfo* pInfo, SArray* pNodeList) {
19,470✔
452
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
19,470!
453
  if (pInfo->pQnodeList) {
19,470✔
454
    taosArrayDestroy(pInfo->pQnodeList);
18,880✔
455
    pInfo->pQnodeList = NULL;
18,880✔
456
    tscDebug("QnodeList cleared in cluster 0x%" PRIx64, pInfo->clusterId);
18,880✔
457
  }
458

459
  if (pNodeList) {
19,470!
460
    pInfo->pQnodeList = taosArrayDup(pNodeList, NULL);
19,470✔
461
    taosArraySort(pInfo->pQnodeList, compareQueryNodeLoad);
19,470✔
462
    tscDebug("QnodeList updated in cluster 0x%" PRIx64 ", num:%ld", pInfo->clusterId,
19,470✔
463
             taosArrayGetSize(pInfo->pQnodeList));
464
  }
465
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
19,470!
466

467
  return TSDB_CODE_SUCCESS;
19,470✔
468
}
469

470
int32_t qnodeRequired(SRequestObj* pRequest, bool* required) {
2,923,882✔
471
  if (QUERY_POLICY_VNODE == tsQueryPolicy || QUERY_POLICY_CLIENT == tsQueryPolicy) {
2,923,882✔
472
    *required = false;
2,272,715✔
473
    return TSDB_CODE_SUCCESS;
2,272,715✔
474
  }
475

476
  int32_t       code = TSDB_CODE_SUCCESS;
651,167✔
477
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
651,167✔
478
  *required = false;
651,167✔
479

480
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
651,167!
481
  *required = (NULL == pInfo->pQnodeList);
651,167✔
482
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
651,167!
483
  return TSDB_CODE_SUCCESS;
651,167✔
484
}
485

486
int32_t getQnodeList(SRequestObj* pRequest, SArray** pNodeList) {
×
487
  SAppInstInfo* pInfo = pRequest->pTscObj->pAppInfo;
×
488
  int32_t       code = 0;
×
489

490
  TSC_ERR_RET(taosThreadMutexLock(&pInfo->qnodeMutex));
×
491
  if (pInfo->pQnodeList) {
×
492
    *pNodeList = taosArrayDup(pInfo->pQnodeList, NULL);
×
493
  }
494
  TSC_ERR_RET(taosThreadMutexUnlock(&pInfo->qnodeMutex));
×
495
  if (NULL == *pNodeList) {
×
496
    SCatalog* pCatalog = NULL;
×
497
    code = catalogGetHandle(pRequest->pTscObj->pAppInfo->clusterId, &pCatalog);
×
498
    if (TSDB_CODE_SUCCESS == code) {
×
499
      *pNodeList = taosArrayInit(5, sizeof(SQueryNodeLoad));
×
500
      if (NULL == pNodeList) {
×
501
        TSC_ERR_RET(terrno);
×
502
      }
503
      SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
×
504
                               .requestId = pRequest->requestId,
×
505
                               .requestObjRefId = pRequest->self,
×
506
                               .mgmtEps = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp)};
×
507
      code = catalogGetQnodeList(pCatalog, &conn, *pNodeList);
×
508
    }
509

510
    if (TSDB_CODE_SUCCESS == code && *pNodeList) {
×
511
      code = updateQnodeList(pInfo, *pNodeList);
×
512
    }
513
  }
514

515
  return code;
×
516
}
517

518
int32_t getPlan(SRequestObj* pRequest, SQuery* pQuery, SQueryPlan** pPlan, SArray* pNodeList) {
64,503✔
519
  pRequest->type = pQuery->msgType;
64,503✔
520
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
64,503✔
521

522
  SPlanContext cxt = {.queryId = pRequest->requestId,
129,118✔
523
                      .acctId = pRequest->pTscObj->acctId,
64,536✔
524
                      .mgmtEpSet = getEpSet_s(&pAppInfo->mgmtEp),
64,536✔
525
                      .pAstRoot = pQuery->pRoot,
64,582✔
526
                      .showRewrite = pQuery->showRewrite,
64,582✔
527
                      .pMsg = pRequest->msgBuf,
64,582✔
528
                      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
529
                      .pUser = pRequest->pTscObj->user,
64,582✔
530
                      .timezone = pRequest->pTscObj->optionInfo.timezone,
64,582✔
531
                      .sysInfo = pRequest->pTscObj->sysInfo};
64,582✔
532

533
  return qCreateQueryPlan(&cxt, pPlan, pNodeList);
64,582✔
534
}
535

536
int32_t setResSchemaInfo(SReqResultInfo* pResInfo, const SSchema* pSchema, int32_t numOfCols,
1,243,037✔
537
                         const SExtSchema* pExtSchema, bool isStmt) {
538
  if (pResInfo == NULL || pSchema == NULL || numOfCols <= 0) {
1,243,037!
539
    tscError("invalid paras, pResInfo == NULL || pSchema == NULL || numOfCols <= 0");
×
540
    return TSDB_CODE_INVALID_PARA;
×
541
  }
542

543
  pResInfo->numOfCols = numOfCols;
1,243,046✔
544
  if (pResInfo->fields != NULL) {
1,243,046✔
545
    taosMemoryFree(pResInfo->fields);
47!
546
  }
547
  if (pResInfo->userFields != NULL) {
1,243,046✔
548
    taosMemoryFree(pResInfo->userFields);
47!
549
  }
550
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD_E));
1,243,046!
551
  if (NULL == pResInfo->fields) return terrno;
1,243,044!
552
  pResInfo->userFields = taosMemoryCalloc(numOfCols, sizeof(TAOS_FIELD));
1,243,044!
553
  if (NULL == pResInfo->userFields) {
1,243,036!
554
    taosMemoryFree(pResInfo->fields);
×
555
    return terrno;
×
556
  }
557
  if (numOfCols != pResInfo->numOfCols) {
1,243,036!
558
    tscError("numOfCols:%d != pResInfo->numOfCols:%d", numOfCols, pResInfo->numOfCols);
×
559
    return TSDB_CODE_FAILED;
×
560
  }
561

562
  for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
5,405,384✔
563
    pResInfo->fields[i].type = pSchema[i].type;
4,162,429✔
564

565
    pResInfo->userFields[i].type = pSchema[i].type;
4,162,429✔
566
    // userFields must convert to type bytes, no matter isStmt or not
567
    pResInfo->userFields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, false);
4,162,429✔
568
    pResInfo->fields[i].bytes = calcTypeBytesFromSchemaBytes(pSchema[i].type, pSchema[i].bytes, isStmt);
4,162,355✔
569
    if (IS_DECIMAL_TYPE(pSchema[i].type) && pExtSchema) {
4,162,303!
570
      decimalFromTypeMod(pExtSchema[i].typeMod, &pResInfo->fields[i].precision, &pResInfo->fields[i].scale);
8,827✔
571
    }
572

573
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
4,162,348✔
574
    tstrncpy(pResInfo->userFields[i].name, pSchema[i].name, tListLen(pResInfo->userFields[i].name));
4,162,348✔
575
  }
576
  return TSDB_CODE_SUCCESS;
1,242,955✔
577
}
578

579
void setResPrecision(SReqResultInfo* pResInfo, int32_t precision) {
906,530✔
580
  if (precision != TSDB_TIME_PRECISION_MILLI && precision != TSDB_TIME_PRECISION_MICRO &&
906,530!
581
      precision != TSDB_TIME_PRECISION_NANO) {
582
    return;
×
583
  }
584

585
  pResInfo->precision = precision;
906,530✔
586
}
587

588
int32_t buildVnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pDbVgList) {
556,104✔
589
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
556,104✔
590
  if (NULL == nodeList) {
556,175!
591
    return terrno;
×
592
  }
593
  char* policy = (tsQueryPolicy == QUERY_POLICY_VNODE) ? "vnode" : "client";
556,191✔
594

595
  int32_t dbNum = taosArrayGetSize(pDbVgList);
556,191✔
596
  for (int32_t i = 0; i < dbNum; ++i) {
1,088,274✔
597
    SArray* pVg = taosArrayGetP(pDbVgList, i);
532,026✔
598
    if (NULL == pVg) {
532,055!
599
      continue;
×
600
    }
601
    int32_t vgNum = taosArrayGetSize(pVg);
532,055✔
602
    if (vgNum <= 0) {
532,058✔
603
      continue;
616✔
604
    }
605

606
    for (int32_t j = 0; j < vgNum; ++j) {
1,906,057✔
607
      SVgroupInfo* pInfo = taosArrayGet(pVg, j);
1,374,580✔
608
      if (NULL == pInfo) {
1,374,569!
609
        taosArrayDestroy(nodeList);
×
610
        return TSDB_CODE_OUT_OF_RANGE;
×
611
      }
612
      SQueryNodeLoad load = {0};
1,374,569✔
613
      load.addr.nodeId = pInfo->vgId;
1,374,569✔
614
      load.addr.epSet = pInfo->epSet;
1,374,569✔
615

616
      if (NULL == taosArrayPush(nodeList, &load)) {
1,374,615!
617
        taosArrayDestroy(nodeList);
×
618
        return terrno;
×
619
      }
620
    }
621
  }
622

623
  int32_t vnodeNum = taosArrayGetSize(nodeList);
556,248✔
624
  if (vnodeNum > 0) {
556,224✔
625
    tscDebug("0x%" PRIx64 " %s policy, use vnode list, num:%d", pRequest->requestId, policy, vnodeNum);
530,633✔
626
    goto _return;
530,638✔
627
  }
628

629
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
25,591✔
630
  if (mnodeNum <= 0) {
25,577!
631
    tscDebug("0x%" PRIx64 " %s policy, empty node list", pRequest->requestId, policy);
×
632
    goto _return;
×
633
  }
634

635
  void* pData = taosArrayGet(pMnodeList, 0);
25,577✔
636
  if (NULL == pData) {
25,573!
637
    taosArrayDestroy(nodeList);
×
638
    return TSDB_CODE_OUT_OF_RANGE;
×
639
  }
640
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
25,573!
641
    taosArrayDestroy(nodeList);
×
642
    return terrno;
×
643
  }
644

645
  tscDebug("0x%" PRIx64 " %s policy, use mnode list, num:%d", pRequest->requestId, policy, mnodeNum);
25,575✔
646

647
_return:
21,552✔
648

649
  *pNodeList = nodeList;
556,185✔
650

651
  return TSDB_CODE_SUCCESS;
556,185✔
652
}
653

654
int32_t buildQnodePolicyNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SArray* pQnodeList) {
295,374✔
655
  SArray* nodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
295,374✔
656
  if (NULL == nodeList) {
295,374!
657
    return terrno;
×
658
  }
659

660
  int32_t qNodeNum = taosArrayGetSize(pQnodeList);
295,374✔
661
  if (qNodeNum > 0) {
295,374✔
662
    void* pData = taosArrayGet(pQnodeList, 0);
295,052✔
663
    if (NULL == pData) {
295,052!
664
      taosArrayDestroy(nodeList);
×
665
      return TSDB_CODE_OUT_OF_RANGE;
×
666
    }
667
    if (NULL == taosArrayAddBatch(nodeList, pData, qNodeNum)) {
295,052!
668
      taosArrayDestroy(nodeList);
×
669
      return terrno;
×
670
    }
671
    tscDebug("0x%" PRIx64 " qnode policy, use qnode list, num:%d", pRequest->requestId, qNodeNum);
295,052✔
672
    goto _return;
295,052✔
673
  }
674

675
  int32_t mnodeNum = taosArrayGetSize(pMnodeList);
322✔
676
  if (mnodeNum <= 0) {
322✔
677
    tscDebug("0x%" PRIx64 " qnode policy, empty node list", pRequest->requestId);
4!
678
    goto _return;
4✔
679
  }
680

681
  void* pData = taosArrayGet(pMnodeList, 0);
318✔
682
  if (NULL == pData) {
318!
683
    taosArrayDestroy(nodeList);
×
684
    return TSDB_CODE_OUT_OF_RANGE;
×
685
  }
686
  if (NULL == taosArrayAddBatch(nodeList, pData, mnodeNum)) {
318!
687
    taosArrayDestroy(nodeList);
×
688
    return terrno;
×
689
  }
690

691
  tscDebug("0x%" PRIx64 " qnode policy, use mnode list, num:%d", pRequest->requestId, mnodeNum);
318!
692

693
_return:
×
694

695
  *pNodeList = nodeList;
295,374✔
696

697
  return TSDB_CODE_SUCCESS;
295,374✔
698
}
699

700
void freeVgList(void* list) {
44,216✔
701
  SArray* pList = *(SArray**)list;
44,216✔
702
  taosArrayDestroy(pList);
44,216✔
703
}
44,267✔
704

705
int32_t buildAsyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList, SMetaData* pResultMeta) {
786,987✔
706
  SArray* pDbVgList = NULL;
786,987✔
707
  SArray* pQnodeList = NULL;
786,987✔
708
  FDelete fp = NULL;
786,987✔
709
  int32_t code = 0;
786,987✔
710

711
  switch (tsQueryPolicy) {
786,987!
712
    case QUERY_POLICY_VNODE:
491,630✔
713
    case QUERY_POLICY_CLIENT: {
714
      if (pResultMeta) {
491,630!
715
        pDbVgList = taosArrayInit(4, POINTER_BYTES);
491,646✔
716
        if (NULL == pDbVgList) {
491,643!
717
          code = terrno;
×
718
          goto _return;
×
719
        }
720
        int32_t dbNum = taosArrayGetSize(pResultMeta->pDbVgroup);
491,643✔
721
        for (int32_t i = 0; i < dbNum; ++i) {
979,453✔
722
          SMetaRes* pRes = taosArrayGet(pResultMeta->pDbVgroup, i);
487,817✔
723
          if (pRes->code || NULL == pRes->pRes) {
487,811!
724
            continue;
×
725
          }
726

727
          if (NULL == taosArrayPush(pDbVgList, &pRes->pRes)) {
975,623!
728
            code = terrno;
×
729
            goto _return;
×
730
          }
731
        }
732
      } else {
733
        fp = freeVgList;
×
734

735
        int32_t dbNum = taosArrayGetSize(pRequest->dbList);
×
736
        if (dbNum > 0) {
×
737
          SCatalog*     pCtg = NULL;
×
738
          SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
×
739
          code = catalogGetHandle(pInst->clusterId, &pCtg);
×
740
          if (code != TSDB_CODE_SUCCESS) {
×
741
            goto _return;
×
742
          }
743

744
          pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
×
745
          if (NULL == pDbVgList) {
×
746
            code = terrno;
×
747
            goto _return;
×
748
          }
749
          SArray* pVgList = NULL;
×
750
          for (int32_t i = 0; i < dbNum; ++i) {
×
751
            char*            dbFName = taosArrayGet(pRequest->dbList, i);
×
752
            SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
×
753
                                     .requestId = pRequest->requestId,
×
754
                                     .requestObjRefId = pRequest->self,
×
755
                                     .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
×
756

757
            // catalogGetDBVgList will handle dbFName == null.
758
            code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
×
759
            if (code) {
×
760
              goto _return;
×
761
            }
762

763
            if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
×
764
              code = terrno;
×
765
              goto _return;
×
766
            }
767
          }
768
        }
769
      }
770

771
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
491,636✔
772
      break;
491,647✔
773
    }
774
    case QUERY_POLICY_HYBRID:
295,361✔
775
    case QUERY_POLICY_QNODE: {
776
      if (pResultMeta && taosArrayGetSize(pResultMeta->pQnodeList) > 0) {
300,749✔
777
        SMetaRes* pRes = taosArrayGet(pResultMeta->pQnodeList, 0);
5,388✔
778
        if (pRes->code) {
5,388!
779
          pQnodeList = NULL;
×
780
        } else {
781
          pQnodeList = taosArrayDup((SArray*)pRes->pRes, NULL);
5,388✔
782
          if (NULL == pQnodeList) {
5,388!
783
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
784
            goto _return;
×
785
          }
786
        }
787
      } else {
788
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
289,985✔
789
        TSC_ERR_JRET(taosThreadMutexLock(&pInst->qnodeMutex));
289,985!
790
        if (pInst->pQnodeList) {
289,986!
791
          pQnodeList = taosArrayDup(pInst->pQnodeList, NULL);
289,986✔
792
          if (NULL == pQnodeList) {
289,986!
793
            code = terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
794
            goto _return;
×
795
          }
796
        }
797
        TSC_ERR_JRET(taosThreadMutexUnlock(&pInst->qnodeMutex));
289,986!
798
      }
799

800
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
295,374✔
801
      break;
295,374✔
802
    }
803
    default:
×
804
      tscError("unknown query policy: %d", tsQueryPolicy);
×
805
      return TSDB_CODE_APP_ERROR;
×
806
  }
807

808
_return:
787,021✔
809
  taosArrayDestroyEx(pDbVgList, fp);
787,021✔
810
  taosArrayDestroy(pQnodeList);
787,025✔
811

812
  return code;
787,026✔
813
}
814

815
int32_t buildSyncExecNodeList(SRequestObj* pRequest, SArray** pNodeList, SArray* pMnodeList) {
64,455✔
816
  SArray* pDbVgList = NULL;
64,455✔
817
  SArray* pQnodeList = NULL;
64,455✔
818
  int32_t code = 0;
64,455✔
819

820
  switch (tsQueryPolicy) {
64,455!
821
    case QUERY_POLICY_VNODE:
64,495✔
822
    case QUERY_POLICY_CLIENT: {
823
      int32_t dbNum = taosArrayGetSize(pRequest->dbList);
64,495✔
824
      if (dbNum > 0) {
64,551✔
825
        SCatalog*     pCtg = NULL;
44,257✔
826
        SAppInstInfo* pInst = pRequest->pTscObj->pAppInfo;
44,257✔
827
        code = catalogGetHandle(pInst->clusterId, &pCtg);
44,257✔
828
        if (code != TSDB_CODE_SUCCESS) {
44,225!
829
          goto _return;
×
830
        }
831

832
        pDbVgList = taosArrayInit(dbNum, POINTER_BYTES);
44,225✔
833
        if (NULL == pDbVgList) {
44,263✔
834
          code = terrno;
4✔
835
          goto _return;
×
836
        }
837
        SArray* pVgList = NULL;
44,259✔
838
        for (int32_t i = 0; i < dbNum; ++i) {
88,519✔
839
          char*            dbFName = taosArrayGet(pRequest->dbList, i);
44,178✔
840
          SRequestConnInfo conn = {.pTrans = pInst->pTransporter,
44,210✔
841
                                   .requestId = pRequest->requestId,
44,210✔
842
                                   .requestObjRefId = pRequest->self,
44,210✔
843
                                   .mgmtEps = getEpSet_s(&pInst->mgmtEp)};
44,210✔
844

845
          // catalogGetDBVgList will handle dbFName == null.
846
          code = catalogGetDBVgList(pCtg, &conn, dbFName, &pVgList);
44,276✔
847
          if (code) {
44,245!
848
            goto _return;
×
849
          }
850

851
          if (NULL == taosArrayPush(pDbVgList, &pVgList)) {
44,260!
852
            code = terrno;
×
853
            goto _return;
×
854
          }
855
        }
856
      }
857

858
      code = buildVnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pDbVgList);
64,635✔
859
      break;
64,535✔
860
    }
861
    case QUERY_POLICY_HYBRID:
×
862
    case QUERY_POLICY_QNODE: {
863
      TSC_ERR_JRET(getQnodeList(pRequest, &pQnodeList));
×
864

865
      code = buildQnodePolicyNodeList(pRequest, pNodeList, pMnodeList, pQnodeList);
×
866
      break;
×
867
    }
868
    default:
×
869
      tscError("unknown query policy: %d", tsQueryPolicy);
×
870
      return TSDB_CODE_APP_ERROR;
×
871
  }
872

873
_return:
64,535✔
874

875
  taosArrayDestroyEx(pDbVgList, freeVgList);
64,535✔
876
  taosArrayDestroy(pQnodeList);
64,530✔
877

878
  return code;
64,552✔
879
}
880

881
int32_t scheduleQuery(SRequestObj* pRequest, SQueryPlan* pDag, SArray* pNodeList) {
64,490✔
882
  void* pTransporter = pRequest->pTscObj->pAppInfo->pTransporter;
64,490✔
883

884
  SExecResult      res = {0};
64,490✔
885
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
64,490✔
886
                           .requestId = pRequest->requestId,
64,490✔
887
                           .requestObjRefId = pRequest->self};
64,490✔
888
  SSchedulerReq    req = {
129,001✔
889
         .syncReq = true,
890
         .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
64,490✔
891
         .pConn = &conn,
892
         .pNodeList = pNodeList,
893
         .pDag = pDag,
894
         .sql = pRequest->sqlstr,
64,490✔
895
         .startTs = pRequest->metric.start,
64,490✔
896
         .execFp = NULL,
897
         .cbParam = NULL,
898
         .chkKillFp = chkRequestKilled,
899
         .chkKillParam = (void*)pRequest->self,
64,490✔
900
         .pExecRes = &res,
901
         .source = pRequest->source,
64,490✔
902
         .pWorkerCb = getTaskPoolWorkerCb(),
64,490✔
903
  };
904

905
  int32_t code = schedulerExecJob(&req, &pRequest->body.queryJob);
64,511✔
906

907
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
64,547✔
908
  (void)memcpy(&pRequest->body.resInfo.execRes, &res, sizeof(res));
64,552✔
909

910
  if (code != TSDB_CODE_SUCCESS) {
64,552!
911
    schedulerFreeJob(&pRequest->body.queryJob, 0);
×
912

913
    pRequest->code = code;
×
914
    terrno = code;
×
915
    return pRequest->code;
13✔
916
  }
917

918
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_DELETE == pRequest->type ||
64,552!
919
      TDMT_VND_CREATE_TABLE == pRequest->type) {
158✔
920
    pRequest->body.resInfo.numOfRows = res.numOfRows;
64,520✔
921
    if (TDMT_VND_SUBMIT == pRequest->type) {
64,520✔
922
      STscObj*            pTscObj = pRequest->pTscObj;
64,411✔
923
      SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
64,411✔
924
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, res.numOfRows);
64,411✔
925
    }
926

927
    schedulerFreeJob(&pRequest->body.queryJob, 0);
64,533✔
928
  }
929

930
  pRequest->code = res.code;
64,575✔
931
  terrno = res.code;
64,575✔
932
  return pRequest->code;
64,547✔
933
}
934

935
int32_t handleSubmitExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
1,788,900✔
936
  SArray*      pArray = NULL;
1,788,900✔
937
  SSubmitRsp2* pRsp = (SSubmitRsp2*)res;
1,788,900✔
938
  if (NULL == pRsp->aCreateTbRsp) {
1,788,900✔
939
    return TSDB_CODE_SUCCESS;
1,722,934✔
940
  }
941

942
  int32_t tbNum = taosArrayGetSize(pRsp->aCreateTbRsp);
65,966✔
943
  for (int32_t i = 0; i < tbNum; ++i) {
138,101✔
944
    SVCreateTbRsp* pTbRsp = (SVCreateTbRsp*)taosArrayGet(pRsp->aCreateTbRsp, i);
72,070✔
945
    if (pTbRsp->pMeta) {
72,071✔
946
      TSC_ERR_RET(handleCreateTbExecRes(pTbRsp->pMeta, pCatalog));
50,792!
947
    }
948
  }
949

950
  return TSDB_CODE_SUCCESS;
66,031✔
951
}
952

953
int32_t handleQueryExecRes(SRequestObj* pRequest, void* res, SCatalog* pCatalog, SEpSet* epset) {
643,427✔
954
  int32_t code = 0;
643,427✔
955
  SArray* pArray = NULL;
643,427✔
956
  SArray* pTbArray = (SArray*)res;
643,427✔
957
  int32_t tbNum = taosArrayGetSize(pTbArray);
643,427✔
958
  if (tbNum <= 0) {
643,428!
959
    return TSDB_CODE_SUCCESS;
×
960
  }
961

962
  pArray = taosArrayInit(tbNum, sizeof(STbSVersion));
643,428✔
963
  if (NULL == pArray) {
643,433✔
964
    return terrno;
4✔
965
  }
966

967
  for (int32_t i = 0; i < tbNum; ++i) {
1,896,521✔
968
    STbVerInfo* tbInfo = taosArrayGet(pTbArray, i);
1,253,089✔
969
    if (NULL == tbInfo) {
1,253,088!
970
      code = terrno;
×
971
      goto _return;
×
972
    }
973
    STbSVersion tbSver = {
1,253,088✔
974
        .tbFName = tbInfo->tbFName, .sver = tbInfo->sversion, .tver = tbInfo->tversion, .rver = tbInfo->rversion};
1,253,088✔
975
    if (NULL == taosArrayPush(pArray, &tbSver)) {
1,253,092!
976
      code = terrno;
×
977
      goto _return;
×
978
    }
979
  }
980

981
  SRequestConnInfo conn = {.pTrans = pRequest->pTscObj->pAppInfo->pTransporter,
643,432✔
982
                           .requestId = pRequest->requestId,
643,432✔
983
                           .requestObjRefId = pRequest->self,
643,432✔
984
                           .mgmtEps = *epset};
985

986
  code = catalogChkTbMetaVersion(pCatalog, &conn, pArray);
643,432✔
987

988
_return:
643,430✔
989

990
  taosArrayDestroy(pArray);
643,430✔
991
  return code;
643,433✔
992
}
993

994
int32_t handleAlterTbExecRes(void* res, SCatalog* pCatalog) {
4,076✔
995
  return catalogUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
4,076✔
996
}
997

998
int32_t handleCreateTbExecRes(void* res, SCatalog* pCatalog) {
183,731✔
999
  return catalogAsyncUpdateTableMeta(pCatalog, (STableMetaRsp*)res);
183,731✔
1000
}
1001

1002
int32_t handleQueryExecRsp(SRequestObj* pRequest) {
2,697,173✔
1003
  if (NULL == pRequest->body.resInfo.execRes.res) {
2,697,173✔
1004
    return pRequest->code;
157,555✔
1005
  }
1006

1007
  SCatalog*     pCatalog = NULL;
2,539,618✔
1008
  SAppInstInfo* pAppInfo = getAppInfo(pRequest);
2,539,618✔
1009

1010
  int32_t code = catalogGetHandle(pAppInfo->clusterId, &pCatalog);
2,539,677✔
1011
  if (code) {
2,539,677!
1012
    return code;
×
1013
  }
1014

1015
  SEpSet       epset = getEpSet_s(&pAppInfo->mgmtEp);
2,539,677✔
1016
  SExecResult* pRes = &pRequest->body.resInfo.execRes;
2,539,801✔
1017

1018
  switch (pRes->msgType) {
2,539,801✔
1019
    case TDMT_VND_ALTER_TABLE:
745✔
1020
    case TDMT_MND_ALTER_STB: {
1021
      code = handleAlterTbExecRes(pRes->res, pCatalog);
745✔
1022
      break;
745✔
1023
    }
1024
    case TDMT_VND_CREATE_TABLE: {
106,145✔
1025
      SArray* pList = (SArray*)pRes->res;
106,145✔
1026
      int32_t num = taosArrayGetSize(pList);
106,145✔
1027
      for (int32_t i = 0; i < num; ++i) {
232,495✔
1028
        void* res = taosArrayGetP(pList, i);
126,354✔
1029
        // handleCreateTbExecRes will handle res == null
1030
        code = handleCreateTbExecRes(res, pCatalog);
126,343✔
1031
      }
1032
      break;
106,141✔
1033
    }
1034
    case TDMT_MND_CREATE_STB: {
453✔
1035
      code = handleCreateTbExecRes(pRes->res, pCatalog);
453✔
1036
      break;
453✔
1037
    }
1038
    case TDMT_VND_SUBMIT: {
1,788,940✔
1039
      (void)atomic_add_fetch_64((int64_t*)&pAppInfo->summary.insertBytes, pRes->numOfBytes);
1,788,940✔
1040

1041
      code = handleSubmitExecRes(pRequest, pRes->res, pCatalog, &epset);
1,788,974✔
1042
      break;
1,788,960✔
1043
    }
1044
    case TDMT_SCH_QUERY:
643,434✔
1045
    case TDMT_SCH_MERGE_QUERY: {
1046
      code = handleQueryExecRes(pRequest, pRes->res, pCatalog, &epset);
643,434✔
1047
      break;
643,430✔
1048
    }
1049
    default:
84✔
1050
      tscError("req:0x%" PRIx64 ", invalid exec result for request type:%d, QID:0x%" PRIx64, pRequest->self,
84!
1051
               pRequest->type, pRequest->requestId);
1052
      code = TSDB_CODE_APP_ERROR;
×
1053
  }
1054

1055
  return code;
2,539,729✔
1056
}
1057

1058
static bool incompletaFileParsing(SNode* pStmt) {
2,630,989✔
1059
  return QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pStmt) ? false : ((SVnodeModifyOpStmt*)pStmt)->fileProcessing;
2,630,989✔
1060
}
1061

1062
void continuePostSubQuery(SRequestObj* pRequest, SSDataBlock* pBlock) {
435✔
1063
  SSqlCallbackWrapper* pWrapper = pRequest->pWrapper;
435✔
1064

1065
  int32_t code = nodesAcquireAllocator(pWrapper->pParseCtx->allocatorId);
435✔
1066
  if (TSDB_CODE_SUCCESS == code) {
435!
1067
    int64_t analyseStart = taosGetTimestampUs();
435✔
1068
    code = qContinueParsePostQuery(pWrapper->pParseCtx, pRequest->pQuery, pBlock);
435✔
1069
    pRequest->metric.analyseCostUs += taosGetTimestampUs() - analyseStart;
435✔
1070
  }
1071

1072
  if (TSDB_CODE_SUCCESS == code) {
435!
1073
    code = qContinuePlanPostQuery(pRequest->pPostPlan);
435✔
1074
  }
1075

1076
  code = nodesReleaseAllocator(pWrapper->pParseCtx->allocatorId);
435✔
1077
  handleQueryAnslyseRes(pWrapper, NULL, code);
435✔
1078
}
435✔
1079

1080
void returnToUser(SRequestObj* pRequest) {
72,435✔
1081
  if (pRequest->relation.userRefId == pRequest->self || 0 == pRequest->relation.userRefId) {
72,435!
1082
    // return to client
1083
    doRequestCallback(pRequest, pRequest->code);
72,434✔
1084
    return;
72,434✔
1085
  }
1086

1087
  SRequestObj* pUserReq = acquireRequest(pRequest->relation.userRefId);
1✔
1088
  if (pUserReq) {
1!
1089
    pUserReq->code = pRequest->code;
1✔
1090
    // return to client
1091
    doRequestCallback(pUserReq, pUserReq->code);
1✔
1092
    (void)releaseRequest(pRequest->relation.userRefId);
1✔
1093
    return;
1✔
1094
  } else {
1095
    tscError("req:0x%" PRIx64 ", user ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1096
             pRequest->relation.userRefId, pRequest->requestId);
1097
  }
1098
}
1099

1100
static int32_t createResultBlock(TAOS_RES* pRes, int32_t numOfRows, SSDataBlock** pBlock) {
435✔
1101
  int64_t     lastTs = 0;
435✔
1102
  TAOS_FIELD* pResFields = taos_fetch_fields(pRes);
435✔
1103
  int32_t     numOfFields = taos_num_fields(pRes);
435✔
1104

1105
  int32_t code = createDataBlock(pBlock);
435✔
1106
  if (code) {
435!
1107
    return code;
×
1108
  }
1109

1110
  for (int32_t i = 0; i < numOfFields; ++i) {
1,740✔
1111
    SColumnInfoData colInfoData = createColumnInfoData(pResFields[i].type, pResFields[i].bytes, i + 1);
1,305✔
1112
    code = blockDataAppendColInfo(*pBlock, &colInfoData);
1,305✔
1113
    if (TSDB_CODE_SUCCESS != code) {
1,305!
1114
      blockDataDestroy(*pBlock);
×
1115
      return code;
×
1116
    }
1117
  }
1118

1119
  code = blockDataEnsureCapacity(*pBlock, numOfRows);
435✔
1120
  if (TSDB_CODE_SUCCESS != code) {
435!
1121
    blockDataDestroy(*pBlock);
×
1122
    return code;
×
1123
  }
1124

1125
  for (int32_t i = 0; i < numOfRows; ++i) {
1,320✔
1126
    TAOS_ROW pRow = taos_fetch_row(pRes);
885✔
1127
    if (NULL == pRow[0] || NULL == pRow[1] || NULL == pRow[2]) {
885!
1128
      tscError("invalid data from vnode");
×
1129
      blockDataDestroy(*pBlock);
×
1130
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1131
    }
1132
    int64_t ts = *(int64_t*)pRow[0];
885✔
1133
    if (lastTs < ts) {
885✔
1134
      lastTs = ts;
499✔
1135
    }
1136

1137
    for (int32_t j = 0; j < numOfFields; ++j) {
3,540✔
1138
      SColumnInfoData* pColInfoData = taosArrayGet((*pBlock)->pDataBlock, j);
2,655✔
1139
      code = colDataSetVal(pColInfoData, i, pRow[j], false);
2,655✔
1140
      if (TSDB_CODE_SUCCESS != code) {
2,655!
1141
        blockDataDestroy(*pBlock);
×
1142
        return code;
×
1143
      }
1144
    }
1145

1146
    tscInfo("[create stream with histroy] lastKey:%" PRId64 " vgId:%d, vgVer:%" PRId64, ts, *(int32_t*)pRow[1],
885!
1147
            *(int64_t*)pRow[2]);
1148
  }
1149

1150
  (*pBlock)->info.window.ekey = lastTs;
435✔
1151
  (*pBlock)->info.rows = numOfRows;
435✔
1152

1153
  tscInfo("[create stream with histroy] lastKey:%" PRId64 " numOfRows:%d from all vgroups", lastTs, numOfRows);
435!
1154
  return TSDB_CODE_SUCCESS;
435✔
1155
}
1156

1157
void postSubQueryFetchCb(void* param, TAOS_RES* res, int32_t rowNum) {
436✔
1158
  SRequestObj* pRequest = (SRequestObj*)res;
436✔
1159
  if (pRequest->code) {
436✔
1160
    returnToUser(pRequest);
1✔
1161
    return;
1✔
1162
  }
1163

1164
  SSDataBlock* pBlock = NULL;
435✔
1165
  pRequest->code = createResultBlock(res, rowNum, &pBlock);
435✔
1166
  if (TSDB_CODE_SUCCESS != pRequest->code) {
435!
1167
    tscError("req:0x%" PRIx64 ", create result block failed, QID:0x%" PRIx64 " %s", pRequest->self, pRequest->requestId,
×
1168
             tstrerror(pRequest->code));
1169
    returnToUser(pRequest);
×
1170
    return;
×
1171
  }
1172

1173
  SRequestObj* pNextReq = acquireRequest(pRequest->relation.nextRefId);
435✔
1174
  if (pNextReq) {
435!
1175
    continuePostSubQuery(pNextReq, pBlock);
435✔
1176
    (void)releaseRequest(pRequest->relation.nextRefId);
435✔
1177
  } else {
1178
    tscError("req:0x%" PRIx64 ", next req ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1179
             pRequest->relation.nextRefId, pRequest->requestId);
1180
  }
1181

1182
  blockDataDestroy(pBlock);
435✔
1183
}
1184

1185
void handlePostSubQuery(SSqlCallbackWrapper* pWrapper) {
436✔
1186
  SRequestObj* pRequest = pWrapper->pRequest;
436✔
1187
  if (TD_RES_QUERY(pRequest)) {
436!
1188
    taosAsyncFetchImpl(pRequest, postSubQueryFetchCb, pWrapper);
436✔
1189
    return;
436✔
1190
  }
1191

1192
  SRequestObj* pNextReq = acquireRequest(pRequest->relation.nextRefId);
×
1193
  if (pNextReq) {
×
1194
    continuePostSubQuery(pNextReq, NULL);
×
1195
    (void)releaseRequest(pRequest->relation.nextRefId);
×
1196
  } else {
1197
    tscError("req:0x%" PRIx64 ", next req ref 0x%" PRIx64 " is not there, QID:0x%" PRIx64, pRequest->self,
×
1198
             pRequest->relation.nextRefId, pRequest->requestId);
1199
  }
1200
}
1201

1202
// todo refacto the error code  mgmt
1203
void schedulerExecCb(SExecResult* pResult, void* param, int32_t code) {
2,632,219✔
1204
  SSqlCallbackWrapper* pWrapper = param;
2,632,219✔
1205
  SRequestObj*         pRequest = pWrapper->pRequest;
2,632,219✔
1206
  STscObj*             pTscObj = pRequest->pTscObj;
2,632,219✔
1207

1208
  pRequest->code = code;
2,632,219✔
1209
  if (pResult) {
2,632,219✔
1210
    destroyQueryExecRes(&pRequest->body.resInfo.execRes);
2,632,188✔
1211
    (void)memcpy(&pRequest->body.resInfo.execRes, pResult, sizeof(*pResult));
2,632,151✔
1212
  }
1213

1214
  int32_t type = pRequest->type;
2,632,182✔
1215
  if (TDMT_VND_SUBMIT == type || TDMT_VND_DELETE == type || TDMT_VND_CREATE_TABLE == type) {
2,632,182✔
1216
    if (pResult) {
1,847,697✔
1217
      pRequest->body.resInfo.numOfRows += pResult->numOfRows;
1,847,664✔
1218

1219
      // record the insert rows
1220
      if (TDMT_VND_SUBMIT == type) {
1,847,664✔
1221
        SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
1,724,826✔
1222
        (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertRows, pResult->numOfRows);
1,724,826✔
1223
      }
1224
    }
1225
    schedulerFreeJob(&pRequest->body.queryJob, 0);
1,847,729✔
1226
  }
1227

1228
  taosMemoryFree(pResult);
2,632,295!
1229
  tscDebug("req:0x%" PRIx64 ", enter scheduler exec cb, code:%s, QID:0x%" PRIx64, pRequest->self, tstrerror(code),
2,632,270✔
1230
           pRequest->requestId);
1231

1232
  if (code != TSDB_CODE_SUCCESS && NEED_CLIENT_HANDLE_ERROR(code) && pRequest->sqlstr != NULL) {
2,632,241!
1233
    tscDebug("req:0x%" PRIx64 ", client retry to handle the error, code:%s, tryCount:%d, QID:0x%" PRIx64,
217✔
1234
             pRequest->self, tstrerror(code), pRequest->retry, pRequest->requestId);
1235
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
217!
1236
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1237
    }
1238
    restartAsyncQuery(pRequest, code);
217✔
1239
    return;
217✔
1240
  }
1241

1242
  tscTrace("req:0x%" PRIx64 ", scheduler exec cb, request type:%s", pRequest->self, TMSG_INFO(pRequest->type));
2,632,024!
1243
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
2,632,024!
1244
    if (TSDB_CODE_SUCCESS != removeMeta(pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type))) {
12,911!
1245
      tscError("req:0x%" PRIx64 ", remove meta failed, QID:0x%" PRIx64, pRequest->self, pRequest->requestId);
×
1246
    }
1247
  }
1248

1249
  pRequest->metric.execCostUs = taosGetTimestampUs() - pRequest->metric.execStart;
2,632,015✔
1250
  int32_t code1 = handleQueryExecRsp(pRequest);
2,632,015✔
1251
  if (pRequest->code == TSDB_CODE_SUCCESS && pRequest->code != code1) {
2,632,057!
1252
    pRequest->code = code1;
×
1253
  }
1254

1255
  if (pRequest->code == TSDB_CODE_SUCCESS && NULL != pRequest->pQuery &&
5,263,045!
1256
      incompletaFileParsing(pRequest->pQuery->pRoot)) {
2,630,986✔
1257
    continueInsertFromCsv(pWrapper, pRequest);
×
1258
    return;
22✔
1259
  }
1260

1261
  if (pRequest->relation.nextRefId) {
2,632,074✔
1262
    handlePostSubQuery(pWrapper);
436✔
1263
  } else {
1264
    destorySqlCallbackWrapper(pWrapper);
2,631,638✔
1265
    pRequest->pWrapper = NULL;
2,631,639✔
1266

1267
    // return to client
1268
    doRequestCallback(pRequest, code);
2,631,639✔
1269
  }
1270
}
1271

1272
void launchQueryImpl(SRequestObj* pRequest, SQuery* pQuery, bool keepQuery, void** res) {
65,162✔
1273
  int32_t code = 0;
65,162✔
1274
  int32_t subplanNum = 0;
65,162✔
1275

1276
  if (pQuery->pRoot) {
65,162✔
1277
    pRequest->stmtType = pQuery->pRoot->type;
64,539✔
1278
  }
1279

1280
  if (pQuery->pRoot && !pRequest->inRetry) {
65,162!
1281
    STscObj*            pTscObj = pRequest->pTscObj;
64,548✔
1282
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
64,548✔
1283
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type) {
64,548✔
1284
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
64,537✔
1285
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
11✔
1286
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
9✔
1287
    }
1288
  }
1289

1290
  pRequest->body.execMode = pQuery->execMode;
65,230✔
1291
  switch (pQuery->execMode) {
65,230!
1292
    case QUERY_EXEC_MODE_LOCAL:
×
1293
      if (!pRequest->validateOnly) {
×
1294
        if (NULL == pQuery->pRoot) {
×
1295
          terrno = TSDB_CODE_INVALID_PARA;
×
1296
          code = terrno;
×
1297
        } else {
1298
          code = execLocalCmd(pRequest, pQuery);
×
1299
        }
1300
      }
1301
      break;
×
1302
    case QUERY_EXEC_MODE_RPC:
652✔
1303
      if (!pRequest->validateOnly) {
652!
1304
        code = execDdlQuery(pRequest, pQuery);
653✔
1305
      }
1306
      break;
654✔
1307
    case QUERY_EXEC_MODE_SCHEDULE: {
64,578✔
1308
      SArray* pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
64,578✔
1309
      if (NULL == pMnodeList) {
64,540!
1310
        code = terrno;
×
1311
        break;
×
1312
      }
1313
      SQueryPlan* pDag = NULL;
64,540✔
1314
      code = getPlan(pRequest, pQuery, &pDag, pMnodeList);
64,540✔
1315
      if (TSDB_CODE_SUCCESS == code) {
64,514!
1316
        pRequest->body.subplanNum = pDag->numOfSubplans;
64,534✔
1317
        if (!pRequest->validateOnly) {
64,534✔
1318
          SArray* pNodeList = NULL;
64,508✔
1319
          code = buildSyncExecNodeList(pRequest, &pNodeList, pMnodeList);
64,508✔
1320
          if (TSDB_CODE_SUCCESS == code) {
64,554!
1321
            code = scheduleQuery(pRequest, pDag, pNodeList);
64,561✔
1322
          }
1323
          taosArrayDestroy(pNodeList);
64,532✔
1324
        }
1325
      }
1326
      taosArrayDestroy(pMnodeList);
64,586✔
1327
      break;
64,584✔
1328
    }
1329
    case QUERY_EXEC_MODE_EMPTY_RESULT:
×
1330
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
1331
      break;
×
1332
    default:
×
1333
      break;
×
1334
  }
1335

1336
  if (!keepQuery) {
65,238!
1337
    qDestroyQuery(pQuery);
×
1338
  }
1339

1340
  if (NEED_CLIENT_RM_TBLMETA_REQ(pRequest->type) && NULL == pRequest->body.resInfo.execRes.res) {
65,238!
1341
    int ret = removeMeta(pRequest->pTscObj, pRequest->targetTableList, IS_VIEW_REQUEST(pRequest->type));
204!
1342
    if (TSDB_CODE_SUCCESS != ret) {
204!
1343
      tscError("req:0x%" PRIx64 ", remove meta failed,code:%d, QID:0x%" PRIx64, pRequest->self, ret,
×
1344
               pRequest->requestId);
1345
    }
1346
  }
1347

1348
  if (TSDB_CODE_SUCCESS == code) {
65,238✔
1349
    code = handleQueryExecRsp(pRequest);
65,228✔
1350
  }
1351

1352
  if (TSDB_CODE_SUCCESS != code) {
65,237✔
1353
    pRequest->code = code;
138✔
1354
  }
1355

1356
  if (res) {
65,237!
1357
    *res = pRequest->body.resInfo.execRes.res;
×
1358
    pRequest->body.resInfo.execRes.res = NULL;
×
1359
  }
1360
}
65,237✔
1361

1362
static int32_t asyncExecSchQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta,
2,633,090✔
1363
                                 SSqlCallbackWrapper* pWrapper) {
1364
  int32_t code = TSDB_CODE_SUCCESS;
2,633,090✔
1365
  pRequest->type = pQuery->msgType;
2,633,090✔
1366
  SArray*     pMnodeList = NULL;
2,633,090✔
1367
  SQueryPlan* pDag = NULL;
2,633,090✔
1368
  int64_t     st = taosGetTimestampUs();
2,633,168✔
1369

1370
  if (!pRequest->parseOnly) {
2,633,168!
1371
    pMnodeList = taosArrayInit(4, sizeof(SQueryNodeLoad));
2,633,183✔
1372
    if (NULL == pMnodeList) {
2,633,084!
1373
      code = terrno;
×
1374
    }
1375
    SPlanContext cxt = {.queryId = pRequest->requestId,
5,266,315✔
1376
                        .acctId = pRequest->pTscObj->acctId,
2,633,084✔
1377
                        .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
2,633,084✔
1378
                        .pAstRoot = pQuery->pRoot,
2,633,231✔
1379
                        .showRewrite = pQuery->showRewrite,
2,633,231✔
1380
                        .isView = pWrapper->pParseCtx->isView,
2,633,231✔
1381
                        .isAudit = pWrapper->pParseCtx->isAudit,
2,633,231✔
1382
                        .pMsg = pRequest->msgBuf,
2,633,231✔
1383
                        .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
1384
                        .pUser = pRequest->pTscObj->user,
2,633,231✔
1385
                        .sysInfo = pRequest->pTscObj->sysInfo,
2,633,231✔
1386
                        .timezone = pRequest->pTscObj->optionInfo.timezone,
2,633,231✔
1387
                        .allocatorId = pRequest->allocatorRefId};
2,633,231✔
1388
    if (TSDB_CODE_SUCCESS == code) {
2,633,231✔
1389
      code = qCreateQueryPlan(&cxt, &pDag, pMnodeList);
2,633,215✔
1390
    }
1391
    if (code) {
2,632,863✔
1392
      tscError("req:0x%" PRIx64 ", failed to create query plan, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
674!
1393
               pRequest->requestId);
1394
    } else {
1395
      pRequest->body.subplanNum = pDag->numOfSubplans;
2,632,189✔
1396
      TSWAP(pRequest->pPostPlan, pDag->pPostPlan);
2,632,189✔
1397
    }
1398
  }
1399

1400
  pRequest->metric.execStart = taosGetTimestampUs();
2,632,917✔
1401
  pRequest->metric.planCostUs = pRequest->metric.execStart - st;
2,632,917✔
1402

1403
  if (TSDB_CODE_SUCCESS == code && !pRequest->validateOnly) {
5,265,100✔
1404
    SArray* pNodeList = NULL;
2,632,134✔
1405
    if (QUERY_NODE_VNODE_MODIFY_STMT != nodeType(pQuery->pRoot)) {
2,632,134✔
1406
      code = buildAsyncExecNodeList(pRequest, &pNodeList, pMnodeList, pResultMeta);
787,016✔
1407
    }
1408

1409
    SRequestConnInfo conn = {.pTrans = getAppInfo(pRequest)->pTransporter,
2,632,145✔
1410
                             .requestId = pRequest->requestId,
2,632,092✔
1411
                             .requestObjRefId = pRequest->self};
2,632,092✔
1412
    SSchedulerReq    req = {
5,264,146✔
1413
           .syncReq = false,
1414
           .localReq = (tsQueryPolicy == QUERY_POLICY_CLIENT),
2,632,092✔
1415
           .pConn = &conn,
1416
           .pNodeList = pNodeList,
1417
           .pDag = pDag,
1418
           .allocatorRefId = pRequest->allocatorRefId,
2,632,092✔
1419
           .sql = pRequest->sqlstr,
2,632,092✔
1420
           .startTs = pRequest->metric.start,
2,632,092✔
1421
           .execFp = schedulerExecCb,
1422
           .cbParam = pWrapper,
1423
           .chkKillFp = chkRequestKilled,
1424
           .chkKillParam = (void*)pRequest->self,
2,632,092✔
1425
           .pExecRes = NULL,
1426
           .source = pRequest->source,
2,632,092✔
1427
           .pWorkerCb = getTaskPoolWorkerCb(),
2,632,092✔
1428
    };
1429
    if (TSDB_CODE_SUCCESS == code) {
2,632,054!
1430
      code = schedulerExecJob(&req, &pRequest->body.queryJob);
2,632,080✔
1431
    }
1432

1433
    taosArrayDestroy(pNodeList);
2,632,169✔
1434
  } else {
1435
    qDestroyQueryPlan(pDag);
783✔
1436
    tscDebug("req:0x%" PRIx64 ", plan not executed, code:%s 0x%" PRIx64, pRequest->self, tstrerror(code),
903✔
1437
             pRequest->requestId);
1438
    destorySqlCallbackWrapper(pWrapper);
903✔
1439
    pRequest->pWrapper = NULL;
903✔
1440
    if (TSDB_CODE_SUCCESS != code) {
903✔
1441
      pRequest->code = terrno;
674✔
1442
    }
1443

1444
    doRequestCallback(pRequest, code);
903✔
1445
  }
1446

1447
  // todo not to be released here
1448
  taosArrayDestroy(pMnodeList);
2,633,086✔
1449

1450
  return code;
2,633,136✔
1451
}
1452

1453
void launchAsyncQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaData* pResultMeta, SSqlCallbackWrapper* pWrapper) {
2,802,881✔
1454
  int32_t code = 0;
2,802,881✔
1455

1456
  if (pRequest->parseOnly) {
2,802,881✔
1457
    doRequestCallback(pRequest, 0);
625✔
1458
    return;
625✔
1459
  }
1460

1461
  pRequest->body.execMode = pQuery->execMode;
2,802,256✔
1462
  if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
2,802,256✔
1463
    destorySqlCallbackWrapper(pWrapper);
169,334✔
1464
    pRequest->pWrapper = NULL;
169,339✔
1465
  }
1466

1467
  if (pQuery->pRoot && !pRequest->inRetry) {
2,802,261!
1468
    STscObj*            pTscObj = pRequest->pTscObj;
2,802,459✔
1469
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
2,802,459✔
1470
    if (QUERY_NODE_VNODE_MODIFY_STMT == pQuery->pRoot->type &&
2,802,459✔
1471
        (0 == ((SVnodeModifyOpStmt*)pQuery->pRoot)->sqlNodeType)) {
1,845,271✔
1472
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfInsertsReq, 1);
1,724,819✔
1473
    } else if (QUERY_NODE_SELECT_STMT == pQuery->pRoot->type) {
1,077,640✔
1474
      (void)atomic_add_fetch_64((int64_t*)&pActivity->numOfQueryReq, 1);
739,040✔
1475
    }
1476
  }
1477

1478
  switch (pQuery->execMode) {
2,802,552!
1479
    case QUERY_EXEC_MODE_LOCAL:
133,066✔
1480
      asyncExecLocalCmd(pRequest, pQuery);
133,066✔
1481
      break;
133,066✔
1482
    case QUERY_EXEC_MODE_RPC:
33,546✔
1483
      code = asyncExecDdlQuery(pRequest, pQuery);
33,546✔
1484
      break;
33,548✔
1485
    case QUERY_EXEC_MODE_SCHEDULE: {
2,633,215✔
1486
      code = asyncExecSchQuery(pRequest, pQuery, pResultMeta, pWrapper);
2,633,215✔
1487
      break;
2,633,068✔
1488
    }
1489
    case QUERY_EXEC_MODE_EMPTY_RESULT:
2,725✔
1490
      pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
2,725✔
1491
      doRequestCallback(pRequest, 0);
2,725✔
1492
      break;
2,725✔
1493
    default:
×
1494
      tscError("req:0x%" PRIx64 ", invalid execMode %d", pRequest->self, pQuery->execMode);
×
1495
      doRequestCallback(pRequest, -1);
×
1496
      break;
×
1497
  }
1498
}
1499

1500
int32_t refreshMeta(STscObj* pTscObj, SRequestObj* pRequest) {
19✔
1501
  SCatalog* pCatalog = NULL;
19✔
1502
  int32_t   code = 0;
19✔
1503
  int32_t   dbNum = taosArrayGetSize(pRequest->dbList);
19✔
1504
  int32_t   tblNum = taosArrayGetSize(pRequest->tableList);
19✔
1505

1506
  if (dbNum <= 0 && tblNum <= 0) {
19!
1507
    return TSDB_CODE_APP_ERROR;
19✔
1508
  }
1509

1510
  code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
×
1511
  if (code != TSDB_CODE_SUCCESS) {
×
1512
    return code;
×
1513
  }
1514

1515
  SRequestConnInfo conn = {.pTrans = pTscObj->pAppInfo->pTransporter,
×
1516
                           .requestId = pRequest->requestId,
×
1517
                           .requestObjRefId = pRequest->self,
×
1518
                           .mgmtEps = getEpSet_s(&pTscObj->pAppInfo->mgmtEp)};
×
1519

1520
  for (int32_t i = 0; i < dbNum; ++i) {
×
1521
    char* dbFName = taosArrayGet(pRequest->dbList, i);
×
1522

1523
    // catalogRefreshDBVgInfo will handle dbFName == null.
1524
    code = catalogRefreshDBVgInfo(pCatalog, &conn, dbFName);
×
1525
    if (code != TSDB_CODE_SUCCESS) {
×
1526
      return code;
×
1527
    }
1528
  }
1529

1530
  for (int32_t i = 0; i < tblNum; ++i) {
×
1531
    SName* tableName = taosArrayGet(pRequest->tableList, i);
×
1532

1533
    // catalogRefreshTableMeta will handle tableName == null.
1534
    code = catalogRefreshTableMeta(pCatalog, &conn, tableName, -1);
×
1535
    if (code != TSDB_CODE_SUCCESS) {
×
1536
      return code;
×
1537
    }
1538
  }
1539

1540
  return code;
×
1541
}
1542

1543
int32_t removeMeta(STscObj* pTscObj, SArray* tbList, bool isView) {
15,042✔
1544
  SCatalog* pCatalog = NULL;
15,042✔
1545
  int32_t   tbNum = taosArrayGetSize(tbList);
15,042✔
1546
  int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
15,042✔
1547
  if (code != TSDB_CODE_SUCCESS) {
15,042!
1548
    return code;
×
1549
  }
1550

1551
  if (isView) {
15,042✔
1552
    for (int32_t i = 0; i < tbNum; ++i) {
846✔
1553
      SName* pViewName = taosArrayGet(tbList, i);
423✔
1554
      char   dbFName[TSDB_DB_FNAME_LEN];
1555
      if (NULL == pViewName) {
423!
1556
        continue;
×
1557
      }
1558
      (void)tNameGetFullDbName(pViewName, dbFName);
423✔
1559
      TSC_ERR_RET(catalogRemoveViewMeta(pCatalog, dbFName, 0, pViewName->tname, 0));
423!
1560
    }
1561
  } else {
1562
    for (int32_t i = 0; i < tbNum; ++i) {
19,104✔
1563
      SName* pTbName = taosArrayGet(tbList, i);
4,485✔
1564
      TSC_ERR_RET(catalogRemoveTableMeta(pCatalog, pTbName));
4,485!
1565
    }
1566
  }
1567

1568
  return TSDB_CODE_SUCCESS;
15,042✔
1569
}
1570

1571
int32_t initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet) {
28,433✔
1572
  pEpSet->version = 0;
28,433✔
1573

1574
  // init mnode ip set
1575
  SEpSet* mgmtEpSet = &(pEpSet->epSet);
28,433✔
1576
  mgmtEpSet->numOfEps = 0;
28,433✔
1577
  mgmtEpSet->inUse = 0;
28,433✔
1578

1579
  if (firstEp && firstEp[0] != 0) {
28,433!
1580
    if (strlen(firstEp) >= TSDB_EP_LEN) {
28,435!
1581
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1582
      return -1;
×
1583
    }
1584

1585
    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
28,435✔
1586
    if (code != TSDB_CODE_SUCCESS) {
28,437!
1587
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1588
      return terrno;
×
1589
    }
1590
    // uint32_t addr = 0;
1591
    SIpAddr addr = {0};
28,437✔
1592
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
28,437✔
1593
    if (code) {
28,431✔
1594
      tscError("failed to resolve firstEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
2!
1595
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1596
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
4✔
1597
    } else {
1598
      mgmtEpSet->numOfEps++;
28,429✔
1599
    }
1600
  }
1601

1602
  if (secondEp && secondEp[0] != 0) {
28,431!
1603
    if (strlen(secondEp) >= TSDB_EP_LEN) {
21,564!
1604
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1605
      return terrno;
×
1606
    }
1607

1608
    int32_t code = taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
21,564✔
1609
    if (code != TSDB_CODE_SUCCESS) {
21,564!
1610
      return code;
×
1611
    }
1612
    SIpAddr addr = {0};
21,564✔
1613
    code = taosGetIpFromFqdn(tsEnableIpv6, mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn, &addr);
21,564✔
1614
    if (code) {
21,561!
1615
      tscError("failed to resolve secondEp fqdn: %s, code:%s", mgmtEpSet->eps[mgmtEpSet->numOfEps].fqdn,
×
1616
               tstrerror(TSDB_CODE_TSC_INVALID_FQDN));
1617
      (void)memset(&(mgmtEpSet->eps[mgmtEpSet->numOfEps]), 0, sizeof(mgmtEpSet->eps[mgmtEpSet->numOfEps]));
×
1618
    } else {
1619
      mgmtEpSet->numOfEps++;
21,561✔
1620
    }
1621
  }
1622

1623
  if (mgmtEpSet->numOfEps == 0) {
28,428✔
1624
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
4✔
1625
    return TSDB_CODE_RPC_NETWORK_UNAVAIL;
4✔
1626
  }
1627

1628
  return 0;
28,424✔
1629
}
1630

1631
int32_t taosConnectImpl(const char* user, const char* auth, const char* db, __taos_async_fn_t fp, void* param,
28,434✔
1632
                        SAppInstInfo* pAppInfo, int connType, STscObj** pTscObj) {
1633
  *pTscObj = NULL;
28,434✔
1634
  int32_t code = createTscObj(user, auth, db, connType, pAppInfo, pTscObj);
28,434✔
1635
  if (TSDB_CODE_SUCCESS != code) {
28,434!
1636
    return code;
×
1637
  }
1638

1639
  SRequestObj* pRequest = NULL;
28,434✔
1640
  code = createRequest((*pTscObj)->id, TDMT_MND_CONNECT, 0, &pRequest);
28,434✔
1641
  if (TSDB_CODE_SUCCESS != code) {
28,431!
1642
    destroyTscObj(*pTscObj);
×
1643
    return code;
×
1644
  }
1645

1646
  pRequest->sqlstr = taosStrdup("taos_connect");
28,431!
1647
  if (pRequest->sqlstr) {
28,432!
1648
    pRequest->sqlLen = strlen(pRequest->sqlstr);
28,432✔
1649
  } else {
1650
    return terrno;
×
1651
  }
1652

1653
  SMsgSendInfo* body = NULL;
28,432✔
1654
  code = buildConnectMsg(pRequest, &body);
28,432✔
1655
  if (TSDB_CODE_SUCCESS != code) {
28,422!
1656
    destroyTscObj(*pTscObj);
×
1657
    return code;
×
1658
  }
1659

1660
  // int64_t transporterId = 0;
1661
  code = asyncSendMsgToServer((*pTscObj)->pAppInfo->pTransporter, &(*pTscObj)->pAppInfo->mgmtEp.epSet, NULL, body);
28,422✔
1662
  if (TSDB_CODE_SUCCESS != code) {
28,434!
1663
    destroyTscObj(*pTscObj);
×
1664
    tscError("failed to send connect msg to server, code:%s", tstrerror(code));
×
1665
    return code;
×
1666
  }
1667
  if (TSDB_CODE_SUCCESS != tsem_wait(&pRequest->body.rspSem)) {
28,434!
1668
    destroyTscObj(*pTscObj);
×
1669
    tscError("failed to wait sem, code:%s", terrstr());
×
1670
    return terrno;
×
1671
  }
1672
  if (pRequest->code != TSDB_CODE_SUCCESS) {
28,434✔
1673
    const char* errorMsg = (code == TSDB_CODE_RPC_FQDN_ERROR) ? taos_errstr(pRequest) : tstrerror(pRequest->code);
64!
1674
    tscError("failed to connect to server, reason: %s", errorMsg);
64!
1675

1676
    terrno = pRequest->code;
64✔
1677
    destroyRequest(pRequest);
64✔
1678
    taos_close_internal(*pTscObj);
64✔
1679
    *pTscObj = NULL;
64✔
1680
    return terrno;
64✔
1681
  } else {
1682
    tscInfo("conn:0x%" PRIx64 ", connection is opening, connId:%u, dnodeConn:%p, QID:0x%" PRIx64, (*pTscObj)->id,
28,370!
1683
            (*pTscObj)->connId, (*pTscObj)->pAppInfo->pTransporter, pRequest->requestId);
1684
    destroyRequest(pRequest);
28,367✔
1685
  }
1686
  return code;
28,366✔
1687
}
1688

1689
static int32_t buildConnectMsg(SRequestObj* pRequest, SMsgSendInfo** pMsgSendInfo) {
28,428✔
1690
  *pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
28,428!
1691
  if (*pMsgSendInfo == NULL) {
28,431!
1692
    return terrno;
×
1693
  }
1694

1695
  (*pMsgSendInfo)->msgType = TDMT_MND_CONNECT;
28,431✔
1696

1697
  (*pMsgSendInfo)->requestObjRefId = pRequest->self;
28,431✔
1698
  (*pMsgSendInfo)->requestId = pRequest->requestId;
28,431✔
1699
  (*pMsgSendInfo)->fp = getMsgRspHandle((*pMsgSendInfo)->msgType);
28,431✔
1700
  (*pMsgSendInfo)->param = taosMemoryCalloc(1, sizeof(pRequest->self));
28,425!
1701
  if (NULL == (*pMsgSendInfo)->param) {
28,423!
1702
    taosMemoryFree(*pMsgSendInfo);
×
1703
    return terrno;
×
1704
  }
1705

1706
  *(int64_t*)(*pMsgSendInfo)->param = pRequest->self;
28,423✔
1707

1708
  SConnectReq connectReq = {0};
28,423✔
1709
  STscObj*    pObj = pRequest->pTscObj;
28,423✔
1710

1711
  char* db = getDbOfConnection(pObj);
28,423✔
1712
  if (db != NULL) {
28,432✔
1713
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
1,547✔
1714
  } else if (terrno) {
26,885!
1715
    taosMemoryFree(*pMsgSendInfo);
×
1716
    return terrno;
×
1717
  }
1718
  taosMemoryFreeClear(db);
28,433!
1719

1720
  connectReq.connType = pObj->connType;
28,434✔
1721
  connectReq.pid = appInfo.pid;
28,434✔
1722
  connectReq.startTime = appInfo.startTime;
28,434✔
1723

1724
  tstrncpy(connectReq.app, appInfo.appName, sizeof(connectReq.app));
28,434✔
1725
  tstrncpy(connectReq.user, pObj->user, sizeof(connectReq.user));
28,434✔
1726
  tstrncpy(connectReq.passwd, pObj->pass, sizeof(connectReq.passwd));
28,434✔
1727
  tstrncpy(connectReq.sVer, td_version, sizeof(connectReq.sVer));
28,434✔
1728

1729
  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connectReq);
28,434✔
1730
  void*   pReq = taosMemoryMalloc(contLen);
28,426!
1731
  if (NULL == pReq) {
28,428!
1732
    taosMemoryFree(*pMsgSendInfo);
×
1733
    return terrno;
×
1734
  }
1735

1736
  if (-1 == tSerializeSConnectReq(pReq, contLen, &connectReq)) {
28,428✔
1737
    taosMemoryFree(*pMsgSendInfo);
6!
1738
    taosMemoryFree(pReq);
×
1739
    return terrno;
×
1740
  }
1741

1742
  (*pMsgSendInfo)->msgInfo.len = contLen;
28,425✔
1743
  (*pMsgSendInfo)->msgInfo.pData = pReq;
28,425✔
1744
  return TSDB_CODE_SUCCESS;
28,425✔
1745
}
1746

1747
void updateTargetEpSet(SMsgSendInfo* pSendInfo, STscObj* pTscObj, SRpcMsg* pMsg, SEpSet* pEpSet) {
6,076,518✔
1748
  if (NULL == pEpSet) {
6,076,518✔
1749
    return;
4,682,404✔
1750
  }
1751

1752
  switch (pSendInfo->target.type) {
1,394,114✔
1753
    case TARGET_TYPE_MNODE:
29✔
1754
      if (NULL == pTscObj) {
29!
1755
        tscError("mnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
×
1756
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1757
        return;
×
1758
      }
1759

1760
      SEpSet* pOrig = &pTscObj->pAppInfo->mgmtEp.epSet;
29✔
1761
      SEp*    pOrigEp = &pOrig->eps[pOrig->inUse];
29✔
1762
      SEp*    pNewEp = &pEpSet->eps[pEpSet->inUse];
29✔
1763
      tscDebug("mnode epset updated from %d/%d=>%s:%d to %d/%d=>%s:%d in client", pOrig->inUse, pOrig->numOfEps,
29!
1764
               pOrigEp->fqdn, pOrigEp->port, pEpSet->inUse, pEpSet->numOfEps, pNewEp->fqdn, pNewEp->port);
1765
      updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
29✔
1766
      break;
29✔
1767
    case TARGET_TYPE_VNODE: {
782,330✔
1768
      if (NULL == pTscObj) {
782,330✔
1769
        tscError("vnode epset changed but not able to update it, msg:%s, reqObjRefId:%" PRIx64,
4!
1770
                 TMSG_INFO(pMsg->msgType), pSendInfo->requestObjRefId);
1771
        return;
4✔
1772
      }
1773

1774
      SCatalog* pCatalog = NULL;
782,326✔
1775
      int32_t   code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
782,326✔
1776
      if (code != TSDB_CODE_SUCCESS) {
782,306!
1777
        tscError("fail to get catalog handle, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1778
                 tstrerror(code));
1779
        return;
×
1780
      }
1781

1782
      code = catalogUpdateVgEpSet(pCatalog, pSendInfo->target.dbFName, pSendInfo->target.vgId, pEpSet);
782,306✔
1783
      if (code != TSDB_CODE_SUCCESS) {
782,328!
1784
        tscError("fail to update catalog vg epset, clusterId:0x%" PRIx64 ", error:%s", pTscObj->pAppInfo->clusterId,
×
1785
                 tstrerror(code));
1786
        return;
×
1787
      }
1788
      taosMemoryFreeClear(pSendInfo->target.dbFName);
782,330!
1789
      break;
782,325✔
1790
    }
1791
    default:
611,755✔
1792
      tscDebug("epset changed, not updated, msgType %s", TMSG_INFO(pMsg->msgType));
611,755!
1793
      break;
611,790✔
1794
  }
1795
}
1796

1797
int32_t doProcessMsgFromServerImpl(SRpcMsg* pMsg, SEpSet* pEpSet) {
6,076,898✔
1798
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
6,076,898✔
1799
  if (pMsg->info.ahandle == NULL) {
6,076,898✔
1800
    tscError("doProcessMsgFromServer pMsg->info.ahandle == NULL");
358!
1801
    rpcFreeCont(pMsg->pCont);
358✔
1802
    taosMemoryFree(pEpSet);
358!
1803
    return TSDB_CODE_TSC_INTERNAL_ERROR;
358✔
1804
  }
1805

1806
  STscObj* pTscObj = NULL;
6,076,540✔
1807

1808
  STraceId* trace = &pMsg->info.traceId;
6,076,540✔
1809
  char      tbuf[40] = {0};
6,076,540✔
1810
  TRACE_TO_STR(trace, tbuf);
6,076,540!
1811

1812
  tscDebug("QID:%s, process message from server, handle:%p, message:%s, size:%d, code:%s", tbuf, pMsg->info.handle,
6,076,424!
1813
           TMSG_INFO(pMsg->msgType), pMsg->contLen, tstrerror(pMsg->code));
1814

1815
  if (pSendInfo->requestObjRefId != 0) {
6,076,585✔
1816
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
4,749,819✔
1817
    if (pRequest) {
4,749,810✔
1818
      if (pRequest->self != pSendInfo->requestObjRefId) {
4,745,699!
1819
        tscError("doProcessMsgFromServer req:0x%" PRId64 " != pSendInfo->requestObjRefId:0x%" PRId64, pRequest->self,
×
1820
                 pSendInfo->requestObjRefId);
1821

1822
        if (TSDB_CODE_SUCCESS != taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId)) {
×
1823
          tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1824
        }
1825
        rpcFreeCont(pMsg->pCont);
×
1826
        taosMemoryFree(pEpSet);
×
1827
        destroySendMsgInfo(pSendInfo);
×
1828
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
1829
      }
1830
      pTscObj = pRequest->pTscObj;
4,745,699✔
1831
    }
1832
  }
1833

1834
  updateTargetEpSet(pSendInfo, pTscObj, pMsg, pEpSet);
6,076,576✔
1835

1836
  SDataBuf buf = {.msgType = pMsg->msgType,
6,076,503✔
1837
                  .len = pMsg->contLen,
6,076,503✔
1838
                  .pData = NULL,
1839
                  .handle = pMsg->info.handle,
6,076,503✔
1840
                  .handleRefId = pMsg->info.refId,
6,076,503✔
1841
                  .pEpSet = pEpSet};
1842

1843
  if (pMsg->contLen > 0) {
6,076,503✔
1844
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
6,005,860!
1845
    if (buf.pData == NULL) {
6,005,819!
1846
      pMsg->code = terrno;
×
1847
    } else {
1848
      (void)memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
6,005,819✔
1849
    }
1850
  }
1851

1852
  (void)pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
6,076,462✔
1853

1854
  if (pTscObj) {
6,076,535✔
1855
    int32_t code = taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
4,745,650✔
1856
    if (TSDB_CODE_SUCCESS != code) {
4,745,684!
1857
      tscError("doProcessMsgFromServer taosReleaseRef failed");
×
1858
      terrno = code;
×
1859
      pMsg->code = code;
×
1860
    }
1861
  }
1862

1863
  rpcFreeCont(pMsg->pCont);
6,076,569✔
1864
  destroySendMsgInfo(pSendInfo);
6,076,611✔
1865
  return TSDB_CODE_SUCCESS;
6,076,618✔
1866
}
1867

1868
int32_t doProcessMsgFromServer(void* param) {
6,076,989✔
1869
  AsyncArg* arg = (AsyncArg*)param;
6,076,989✔
1870
  int32_t   code = doProcessMsgFromServerImpl(&arg->msg, arg->pEpset);
6,076,989✔
1871
  taosMemoryFree(arg);
6,076,939!
1872
  return code;
6,076,963✔
1873
}
1874

1875
void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
6,076,112✔
1876
  int32_t code = 0;
6,076,112✔
1877
  SEpSet* tEpSet = NULL;
6,076,112✔
1878

1879
  tscDebug("msg callback, ahandle %p", pMsg->info.ahandle);
6,076,112✔
1880

1881
  if (pEpSet != NULL) {
6,076,112✔
1882
    tEpSet = taosMemoryCalloc(1, sizeof(SEpSet));
1,394,151!
1883
    if (NULL == tEpSet) {
1,394,147!
1884
      code = terrno;
×
1885
      pMsg->code = terrno;
×
1886
      goto _exit;
×
1887
    }
1888
    (void)memcpy((void*)tEpSet, (void*)pEpSet, sizeof(SEpSet));
1,394,147✔
1889
  }
1890

1891
  // pMsg is response msg
1892
  if (pMsg->msgType == TDMT_MND_CONNECT + 1) {
6,076,108✔
1893
    // restore origin code
1894
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
28,425!
1895
      pMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
×
1896
    } else if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
28,425!
1897
      pMsg->code = TSDB_CODE_RPC_BROKEN_LINK;
×
1898
    }
1899
  } else {
1900
    // uniform to one error code: TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED
1901
    if (pMsg->code == TSDB_CODE_RPC_SOMENODE_BROKEN_LINK) {
6,047,683!
1902
      pMsg->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
×
1903
    }
1904
  }
1905

1906
  AsyncArg* arg = taosMemoryCalloc(1, sizeof(AsyncArg));
6,076,108!
1907
  if (NULL == arg) {
6,076,538!
1908
    code = terrno;
×
1909
    pMsg->code = code;
×
1910
    goto _exit;
×
1911
  }
1912

1913
  arg->msg = *pMsg;
6,076,538✔
1914
  arg->pEpset = tEpSet;
6,076,538✔
1915

1916
  if ((code = taosAsyncExec(doProcessMsgFromServer, arg, NULL)) != 0) {
6,076,538✔
1917
    pMsg->code = code;
100✔
1918
    taosMemoryFree(arg);
100!
1919
    goto _exit;
×
1920
  }
1921
  return;
6,076,628✔
1922

1923
_exit:
×
1924
  tscError("failed to sched msg to tsc since %s", tstrerror(code));
×
1925
  code = doProcessMsgFromServerImpl(pMsg, tEpSet);
×
1926
  if (code != 0) {
×
1927
    tscError("failed to sched msg to tsc, tsc ready quit");
×
1928
  }
1929
}
1930

1931
TAOS* taos_connect_auth(const char* ip, const char* user, const char* auth, const char* db, uint16_t port) {
4✔
1932
  tscInfo("try to connect to %s:%u by auth, user:%s db:%s", ip, port, user, db);
4!
1933
  if (user == NULL) {
4!
1934
    user = TSDB_DEFAULT_USER;
×
1935
  }
1936

1937
  if (auth == NULL) {
4!
1938
    tscError("No auth info is given, failed to connect to server");
×
1939
    return NULL;
×
1940
  }
1941

1942
  STscObj* pObj = NULL;
4✔
1943
  int32_t  code = taos_connect_internal(ip, user, NULL, auth, db, port, CONN_TYPE__QUERY, &pObj);
4✔
1944
  if (TSDB_CODE_SUCCESS == code) {
4✔
1945
    int64_t* rid = taosMemoryCalloc(1, sizeof(int64_t));
1!
1946
    if (NULL == rid) {
1!
1947
      tscError("out of memory when taos connect to %s:%u, user:%s db:%s", ip, port, user, db);
×
1948
    }
1949
    *rid = pObj->id;
1✔
1950
    return (TAOS*)rid;
1✔
1951
  }
1952

1953
  return NULL;
3✔
1954
}
1955

1956
// TAOS* taos_connect_l(const char* ip, int ipLen, const char* user, int userLen, const char* pass, int passLen,
1957
//                      const char* db, int dbLen, uint16_t port) {
1958
//   char ipStr[TSDB_EP_LEN] = {0};
1959
//   char dbStr[TSDB_DB_NAME_LEN] = {0};
1960
//   char userStr[TSDB_USER_LEN] = {0};
1961
//   char passStr[TSDB_PASSWORD_LEN] = {0};
1962
//
1963
//   tstrncpy(ipStr, ip, TMIN(TSDB_EP_LEN - 1, ipLen));
1964
//   tstrncpy(userStr, user, TMIN(TSDB_USER_LEN - 1, userLen));
1965
//   tstrncpy(passStr, pass, TMIN(TSDB_PASSWORD_LEN - 1, passLen));
1966
//   tstrncpy(dbStr, db, TMIN(TSDB_DB_NAME_LEN - 1, dbLen));
1967
//   return taos_connect(ipStr, userStr, passStr, dbStr, port);
1968
// }
1969

1970
void doSetOneRowPtr(SReqResultInfo* pResultInfo) {
35,626,319✔
1971
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
177,544,311✔
1972
    SResultColumn* pCol = &pResultInfo->pCol[i];
141,911,493✔
1973

1974
    int32_t type = pResultInfo->fields[i].type;
141,911,493✔
1975
    int32_t schemaBytes = calcSchemaBytesFromTypeBytes(type, pResultInfo->userFields[i].bytes, false);
141,911,493✔
1976

1977
    if (IS_VAR_DATA_TYPE(type)) {
141,917,992✔
1978
      if (!IS_VAR_NULL_TYPE(type, schemaBytes) && pCol->offset[pResultInfo->current] != -1) {
27,619,355!
1979
        char* pStart = pResultInfo->pCol[i].offset[pResultInfo->current] + pResultInfo->pCol[i].pData;
26,162,124✔
1980

1981
        pResultInfo->length[i] = varDataLen(pStart);
26,162,124✔
1982
        pResultInfo->row[i] = varDataVal(pStart);
26,162,124✔
1983
      } else {
1984
        pResultInfo->row[i] = NULL;
1,457,231✔
1985
        pResultInfo->length[i] = 0;
1,457,231✔
1986
      }
1987
    } else {
1988
      if (!colDataIsNull_f(pCol->nullbitmap, pResultInfo->current)) {
114,298,637✔
1989
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + schemaBytes * pResultInfo->current;
108,787,015✔
1990
        pResultInfo->length[i] = schemaBytes;
108,787,015✔
1991
      } else {
1992
        pResultInfo->row[i] = NULL;
5,511,622✔
1993
        pResultInfo->length[i] = 0;
5,511,622✔
1994
      }
1995
    }
1996
  }
1997
}
35,632,818✔
1998

1999
void* doFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
×
2000
  if (pRequest == NULL) {
×
2001
    return NULL;
×
2002
  }
2003

2004
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
×
2005
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
×
2006
    // All data has returned to App already, no need to try again
2007
    if (pResultInfo->completed) {
×
2008
      pResultInfo->numOfRows = 0;
×
2009
      return NULL;
×
2010
    }
2011

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

2015
    pRequest->code = schedulerFetchRows(pRequest->body.queryJob, &req);
×
2016
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2017
      pResultInfo->numOfRows = 0;
×
2018
      return NULL;
×
2019
    }
2020

2021
    pRequest->code = setQueryResultFromRsp(&pRequest->body.resInfo, (const SRetrieveTableRsp*)pResInfo->pData,
×
2022
                                           convertUcs4, pRequest->isStmtBind);
×
2023
    if (pRequest->code != TSDB_CODE_SUCCESS) {
×
2024
      pResultInfo->numOfRows = 0;
×
2025
      return NULL;
×
2026
    }
2027

2028
    tscDebug("req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64
×
2029
             ", complete:%d, QID:0x%" PRIx64,
2030
             pRequest->self, pResInfo->numOfRows, pResInfo->totalRows, pResInfo->completed, pRequest->requestId);
2031

2032
    STscObj*            pTscObj = pRequest->pTscObj;
×
2033
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
×
2034
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
×
2035

2036
    if (pResultInfo->numOfRows == 0) {
×
2037
      return NULL;
×
2038
    }
2039
  }
2040

2041
  if (setupOneRowPtr) {
×
2042
    doSetOneRowPtr(pResultInfo);
×
2043
    pResultInfo->current += 1;
×
2044
  }
2045

2046
  return pResultInfo->row;
×
2047
}
2048

2049
static void syncFetchFn(void* param, TAOS_RES* res, int32_t numOfRows) {
801,003✔
2050
  tsem_t* sem = param;
801,003✔
2051
  if (TSDB_CODE_SUCCESS != tsem_post(sem)) {
801,003!
2052
    tscError("failed to post sem, code:%s", terrstr());
×
2053
  }
2054
}
801,005✔
2055

2056
void* doAsyncFetchRows(SRequestObj* pRequest, bool setupOneRowPtr, bool convertUcs4) {
20,490,437✔
2057
  if (pRequest == NULL) {
20,490,437!
2058
    return NULL;
×
2059
  }
2060

2061
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
20,490,437✔
2062
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
20,490,437✔
2063
    // All data has returned to App already, no need to try again
2064
    if (pResultInfo->completed) {
1,498,411✔
2065
      pResultInfo->numOfRows = 0;
697,407✔
2066
      return NULL;
697,407✔
2067
    }
2068

2069
    // convert ucs4 to native multi-bytes string
2070
    pResultInfo->convertUcs4 = convertUcs4;
801,004✔
2071
    tsem_t sem;
2072
    if (TSDB_CODE_SUCCESS != tsem_init(&sem, 0, 0)) {
801,004!
2073
      tscError("failed to init sem, code:%s", terrstr());
×
2074
    }
2075
    taos_fetch_rows_a(pRequest, syncFetchFn, &sem);
801,003✔
2076
    if (TSDB_CODE_SUCCESS != tsem_wait(&sem)) {
801,006!
2077
      tscError("failed to wait sem, code:%s", terrstr());
×
2078
    }
2079
    if (TSDB_CODE_SUCCESS != tsem_destroy(&sem)) {
801,002!
2080
      tscError("failed to destroy sem, code:%s", terrstr());
×
2081
    }
2082
    pRequest->inCallback = false;
800,999✔
2083
  }
2084

2085
  if (pResultInfo->numOfRows == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
19,793,025!
2086
    return NULL;
62,149✔
2087
  } else {
2088
    if (setupOneRowPtr) {
19,730,876✔
2089
      doSetOneRowPtr(pResultInfo);
18,922,014✔
2090
      pResultInfo->current += 1;
18,918,073✔
2091
    }
2092

2093
    return pResultInfo->row;
19,726,935✔
2094
  }
2095
}
2096

2097
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
1,287,151✔
2098
  if (pResInfo->row == NULL) {
1,287,151✔
2099
    pResInfo->row = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
1,121,066!
2100
    pResInfo->pCol = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
1,121,078!
2101
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
1,121,080!
2102
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
1,121,084!
2103

2104
    if (pResInfo->row == NULL || pResInfo->pCol == NULL || pResInfo->length == NULL || pResInfo->convertBuf == NULL) {
1,121,089!
2105
      taosMemoryFree(pResInfo->row);
×
2106
      taosMemoryFree(pResInfo->pCol);
×
2107
      taosMemoryFree(pResInfo->length);
×
2108
      taosMemoryFree(pResInfo->convertBuf);
×
2109
      return terrno;
×
2110
    }
2111
  }
2112

2113
  return TSDB_CODE_SUCCESS;
1,287,174✔
2114
}
2115

2116
static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength, bool isStmt) {
1,286,882✔
2117
  int32_t idx = -1;
1,286,882✔
2118
  iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt);
1,286,882✔
2119
  if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR;
1,286,947!
2120

2121
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
5,766,660✔
2122
    int32_t type = pResultInfo->fields[i].type;
4,479,696✔
2123
    int32_t schemaBytes =
2124
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
4,479,696✔
2125

2126
    if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) {
4,479,673✔
2127
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
202,055!
2128
      if (p == NULL) {
202,055!
2129
        taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
×
2130
        return terrno;
×
2131
      }
2132

2133
      pResultInfo->convertBuf[i] = p;
202,055✔
2134

2135
      SResultColumn* pCol = &pResultInfo->pCol[i];
202,055✔
2136
      for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
33,413,483✔
2137
        if (pCol->offset[j] != -1) {
33,211,388✔
2138
          char* pStart = pCol->offset[j] + pCol->pData;
30,245,889✔
2139

2140
          int32_t len = taosUcs4ToMbsEx((TdUcs4*)varDataVal(pStart), varDataLen(pStart), varDataVal(p), conv);
30,245,889✔
2141
          if (len < 0 || len > schemaBytes || (p + len) >= (pResultInfo->convertBuf[i] + colLength[i])) {
30,245,937!
2142
            tscError(
8!
2143
                "doConvertUCS4 error, invalid data. len:%d, bytes:%d, (p + len):%p, (pResultInfo->convertBuf[i] + "
2144
                "colLength[i]):%p",
2145
                len, schemaBytes, (p + len), (pResultInfo->convertBuf[i] + colLength[i]));
2146
            taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
8✔
2147
            return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2148
          }
2149

2150
          varDataSetLen(p, len);
30,245,929✔
2151
          pCol->offset[j] = (p - pResultInfo->convertBuf[i]);
30,245,929✔
2152
          p += (len + VARSTR_HEADER_SIZE);
30,245,929✔
2153
        }
2154
      }
2155

2156
      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
202,095✔
2157
      pResultInfo->row[i] = pResultInfo->pCol[i].pData;
202,095✔
2158
    }
2159
  }
2160
  taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt);
1,286,964✔
2161
  return TSDB_CODE_SUCCESS;
1,286,944✔
2162
}
2163

2164
static int32_t convertDecimalType(SReqResultInfo* pResultInfo) {
1,286,942✔
2165
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
5,767,104✔
2166
    TAOS_FIELD_E* pFieldE = pResultInfo->fields + i;
4,480,162✔
2167
    TAOS_FIELD*   pField = pResultInfo->userFields + i;
4,480,162✔
2168
    int32_t       type = pFieldE->type;
4,480,162✔
2169
    int32_t       bufLen = 0;
4,480,162✔
2170
    char*         p = NULL;
4,480,162✔
2171
    if (!IS_DECIMAL_TYPE(type) || !pResultInfo->pCol[i].pData) {
4,480,162✔
2172
      continue;
4,472,104✔
2173
    } else {
2174
      bufLen = 64;
8,058✔
2175
      p = taosMemoryRealloc(pResultInfo->convertBuf[i], bufLen * pResultInfo->numOfRows);
8,058!
2176
      pFieldE->bytes = bufLen;
8,058✔
2177
      pField->bytes = bufLen;
8,058✔
2178
    }
2179
    if (!p) return terrno;
8,058!
2180
    pResultInfo->convertBuf[i] = p;
8,058✔
2181

2182
    for (int32_t j = 0; j < pResultInfo->numOfRows; ++j) {
6,478,630✔
2183
      int32_t code = decimalToStr((DecimalWord*)(pResultInfo->pCol[i].pData + j * tDataTypes[type].bytes), type,
6,470,572✔
2184
                                  pFieldE->precision, pFieldE->scale, p, bufLen);
6,470,572✔
2185
      p += bufLen;
6,470,572✔
2186
      if (TSDB_CODE_SUCCESS != code) {
6,470,572!
2187
        return code;
×
2188
      }
2189
    }
2190
    pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
8,058✔
2191
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
8,058✔
2192
  }
2193
  return 0;
1,286,942✔
2194
}
2195

2196
int32_t getVersion1BlockMetaSize(const char* p, int32_t numOfCols) {
888✔
2197
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) * 3 + sizeof(uint64_t) +
888✔
2198
         numOfCols * (sizeof(int8_t) + sizeof(int32_t));
2199
}
2200

2201
static int32_t estimateJsonLen(SReqResultInfo* pResultInfo) {
444✔
2202
  char*   p = (char*)pResultInfo->pData;
444✔
2203
  int32_t blockVersion = *(int32_t*)p;
444✔
2204

2205
  int32_t numOfRows = pResultInfo->numOfRows;
444✔
2206
  int32_t numOfCols = pResultInfo->numOfCols;
444✔
2207

2208
  // | version | total length | total rows | total columns | flag seg| block group id | column schema | each column
2209
  // length |
2210
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
444✔
2211
  if (numOfCols != cols) {
444!
2212
    tscError("estimateJsonLen error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2213
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2214
  }
2215

2216
  int32_t  len = getVersion1BlockMetaSize(p, numOfCols);
444✔
2217
  int32_t* colLength = (int32_t*)(p + len);
444✔
2218
  len += sizeof(int32_t) * numOfCols;
444✔
2219

2220
  char* pStart = p + len;
444✔
2221
  for (int32_t i = 0; i < numOfCols; ++i) {
2,131✔
2222
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
1,687!
2223

2224
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
1,687✔
2225
      int32_t* offset = (int32_t*)pStart;
521✔
2226
      int32_t  lenTmp = numOfRows * sizeof(int32_t);
521✔
2227
      len += lenTmp;
521✔
2228
      pStart += lenTmp;
521✔
2229

2230
      int32_t estimateColLen = 0;
521✔
2231
      for (int32_t j = 0; j < numOfRows; ++j) {
3,228✔
2232
        if (offset[j] == -1) {
2,707✔
2233
          continue;
208✔
2234
        }
2235
        char* data = offset[j] + pStart;
2,499✔
2236

2237
        int32_t jsonInnerType = *data;
2,499✔
2238
        char*   jsonInnerData = data + CHAR_BYTES;
2,499✔
2239
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
2,499✔
2240
          estimateColLen += (VARSTR_HEADER_SIZE + strlen(TSDB_DATA_NULL_STR_L));
72✔
2241
        } else if (tTagIsJson(data)) {
2,427✔
2242
          estimateColLen += (VARSTR_HEADER_SIZE + ((const STag*)(data))->len);
665✔
2243
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
1,762✔
2244
          estimateColLen += varDataTLen(jsonInnerData) + CHAR_BYTES * 2;
1,466✔
2245
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
296✔
2246
          estimateColLen += (VARSTR_HEADER_SIZE + 32);
216✔
2247
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
80!
2248
          estimateColLen += (VARSTR_HEADER_SIZE + 5);
80✔
2249
        } else {
2250
          tscError("estimateJsonLen error: invalid type:%d", jsonInnerType);
×
2251
          return -1;
×
2252
        }
2253
      }
2254
      len += TMAX(colLen, estimateColLen);
521✔
2255
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
1,166!
2256
      int32_t lenTmp = numOfRows * sizeof(int32_t);
396✔
2257
      len += (lenTmp + colLen);
396✔
2258
      pStart += lenTmp;
396✔
2259
    } else {
2260
      int32_t lenTmp = BitmapLen(pResultInfo->numOfRows);
770✔
2261
      len += (lenTmp + colLen);
770✔
2262
      pStart += lenTmp;
770✔
2263
    }
2264
    pStart += colLen;
1,687✔
2265
  }
2266

2267
  // Ensure the complete structure of the block, including the blankfill field,
2268
  // even though it is not used on the client side.
2269
  len += sizeof(bool);
444✔
2270
  return len;
444✔
2271
}
2272

2273
static int32_t doConvertJson(SReqResultInfo* pResultInfo) {
1,287,171✔
2274
  int32_t numOfRows = pResultInfo->numOfRows;
1,287,171✔
2275
  int32_t numOfCols = pResultInfo->numOfCols;
1,287,171✔
2276
  bool    needConvert = false;
1,287,171✔
2277
  for (int32_t i = 0; i < numOfCols; ++i) {
5,767,821✔
2278
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
4,481,094✔
2279
      needConvert = true;
444✔
2280
      break;
444✔
2281
    }
2282
  }
2283

2284
  if (!needConvert) {
1,287,171✔
2285
    return TSDB_CODE_SUCCESS;
1,286,727✔
2286
  }
2287

2288
  tscDebug("start to convert form json format string");
444✔
2289

2290
  char*   p = (char*)pResultInfo->pData;
444✔
2291
  int32_t blockVersion = *(int32_t*)p;
444✔
2292
  int32_t dataLen = estimateJsonLen(pResultInfo);
444✔
2293
  if (dataLen <= 0) {
444!
2294
    tscError("doConvertJson error: estimateJsonLen failed");
×
2295
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2296
  }
2297

2298
  taosMemoryFreeClear(pResultInfo->convertJson);
444!
2299
  pResultInfo->convertJson = taosMemoryCalloc(1, dataLen);
444!
2300
  if (pResultInfo->convertJson == NULL) return terrno;
444!
2301
  char* p1 = pResultInfo->convertJson;
444✔
2302

2303
  int32_t totalLen = 0;
444✔
2304
  int32_t cols = *(int32_t*)(p + sizeof(int32_t) * 3);
444✔
2305
  if (numOfCols != cols) {
444!
2306
    tscError("doConvertJson error: numOfCols:%d != cols:%d", numOfCols, cols);
×
2307
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2308
  }
2309

2310
  int32_t len = getVersion1BlockMetaSize(p, numOfCols);
444✔
2311
  (void)memcpy(p1, p, len);
444✔
2312

2313
  p += len;
444✔
2314
  p1 += len;
444✔
2315
  totalLen += len;
444✔
2316

2317
  len = sizeof(int32_t) * numOfCols;
444✔
2318
  int32_t* colLength = (int32_t*)p;
444✔
2319
  int32_t* colLength1 = (int32_t*)p1;
444✔
2320
  (void)memcpy(p1, p, len);
444✔
2321
  p += len;
444✔
2322
  p1 += len;
444✔
2323
  totalLen += len;
444✔
2324

2325
  char* pStart = p;
444✔
2326
  char* pStart1 = p1;
444✔
2327
  for (int32_t i = 0; i < numOfCols; ++i) {
2,131✔
2328
    int32_t colLen = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength[i]) : colLength[i];
1,687!
2329
    int32_t colLen1 = (blockVersion == BLOCK_VERSION_1) ? htonl(colLength1[i]) : colLength1[i];
1,687!
2330
    if (colLen >= dataLen) {
1,687!
2331
      tscError("doConvertJson error: colLen:%d >= dataLen:%d", colLen, dataLen);
×
2332
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2333
    }
2334
    if (pResultInfo->fields[i].type == TSDB_DATA_TYPE_JSON) {
1,687✔
2335
      int32_t* offset = (int32_t*)pStart;
521✔
2336
      int32_t* offset1 = (int32_t*)pStart1;
521✔
2337
      len = numOfRows * sizeof(int32_t);
521✔
2338
      (void)memcpy(pStart1, pStart, len);
521✔
2339
      pStart += len;
521✔
2340
      pStart1 += len;
521✔
2341
      totalLen += len;
521✔
2342

2343
      len = 0;
521✔
2344
      for (int32_t j = 0; j < numOfRows; ++j) {
3,228✔
2345
        if (offset[j] == -1) {
2,707✔
2346
          continue;
208✔
2347
        }
2348
        char* data = offset[j] + pStart;
2,499✔
2349

2350
        int32_t jsonInnerType = *data;
2,499✔
2351
        char*   jsonInnerData = data + CHAR_BYTES;
2,499✔
2352
        char    dst[TSDB_MAX_JSON_TAG_LEN] = {0};
2,499✔
2353
        if (jsonInnerType == TSDB_DATA_TYPE_NULL) {
2,499✔
2354
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s", TSDB_DATA_NULL_STR_L);
72✔
2355
          varDataSetLen(dst, strlen(varDataVal(dst)));
72✔
2356
        } else if (tTagIsJson(data)) {
2,427✔
2357
          char* jsonString = NULL;
665✔
2358
          parseTagDatatoJson(data, &jsonString, pResultInfo->charsetCxt);
665✔
2359
          if (jsonString == NULL) {
665!
2360
            tscError("doConvertJson error: parseTagDatatoJson failed");
×
2361
            return terrno;
×
2362
          }
2363
          STR_TO_VARSTR(dst, jsonString);
665✔
2364
          taosMemoryFree(jsonString);
665!
2365
        } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) {  // value -> "value"
1,762✔
2366
          *(char*)varDataVal(dst) = '\"';
1,466✔
2367
          int32_t length = taosUcs4ToMbs((TdUcs4*)varDataVal(jsonInnerData), varDataLen(jsonInnerData),
1,466✔
2368
                                         varDataVal(dst) + CHAR_BYTES, pResultInfo->charsetCxt);
2369
          if (length <= 0) {
1,466✔
2370
            tscError("charset:%s to %s. convert failed.", DEFAULT_UNICODE_ENCODEC,
4!
2371
                     pResultInfo->charsetCxt != NULL ? ((SConvInfo*)(pResultInfo->charsetCxt))->charset : tsCharset);
2372
            length = 0;
4✔
2373
          }
2374
          varDataSetLen(dst, length + CHAR_BYTES * 2);
1,466✔
2375
          *(char*)POINTER_SHIFT(varDataVal(dst), length + CHAR_BYTES) = '\"';
1,466✔
2376
        } else if (jsonInnerType == TSDB_DATA_TYPE_DOUBLE) {
296✔
2377
          double jsonVd = *(double*)(jsonInnerData);
216✔
2378
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%.9lf", jsonVd);
216✔
2379
          varDataSetLen(dst, strlen(varDataVal(dst)));
216✔
2380
        } else if (jsonInnerType == TSDB_DATA_TYPE_BOOL) {
80!
2381
          (void)snprintf(varDataVal(dst), TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE, "%s",
80✔
2382
                         (*((char*)jsonInnerData) == 1) ? "true" : "false");
80✔
2383
          varDataSetLen(dst, strlen(varDataVal(dst)));
80✔
2384
        } else {
2385
          tscError("doConvertJson error: invalid type:%d", jsonInnerType);
×
2386
          return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2387
        }
2388

2389
        offset1[j] = len;
2,499✔
2390
        (void)memcpy(pStart1 + len, dst, varDataTLen(dst));
2,499✔
2391
        len += varDataTLen(dst);
2,499✔
2392
      }
2393
      colLen1 = len;
521✔
2394
      totalLen += colLen1;
521✔
2395
      colLength1[i] = (blockVersion == BLOCK_VERSION_1) ? htonl(len) : len;
521!
2396
    } else if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
1,166!
2397
      len = numOfRows * sizeof(int32_t);
396✔
2398
      (void)memcpy(pStart1, pStart, len);
396✔
2399
      pStart += len;
396✔
2400
      pStart1 += len;
396✔
2401
      totalLen += len;
396✔
2402
      totalLen += colLen;
396✔
2403
      (void)memcpy(pStart1, pStart, colLen);
396✔
2404
    } else {
2405
      len = BitmapLen(pResultInfo->numOfRows);
770✔
2406
      (void)memcpy(pStart1, pStart, len);
770✔
2407
      pStart += len;
770✔
2408
      pStart1 += len;
770✔
2409
      totalLen += len;
770✔
2410
      totalLen += colLen;
770✔
2411
      (void)memcpy(pStart1, pStart, colLen);
770✔
2412
    }
2413
    pStart += colLen;
1,687✔
2414
    pStart1 += colLen1;
1,687✔
2415
  }
2416

2417
  // Ensure the complete structure of the block, including the blankfill field,
2418
  // even though it is not used on the client side.
2419
  // (void)memcpy(pStart1, pStart, sizeof(bool));
2420
  totalLen += sizeof(bool);
444✔
2421

2422
  *(int32_t*)(pResultInfo->convertJson + 4) = totalLen;
444✔
2423
  pResultInfo->pData = pResultInfo->convertJson;
444✔
2424
  return TSDB_CODE_SUCCESS;
444✔
2425
}
2426

2427
int32_t setResultDataPtr(SReqResultInfo* pResultInfo, bool convertUcs4, bool isStmt) {
1,355,806✔
2428
  bool convertForDecimal = convertUcs4;
1,355,806✔
2429
  if (pResultInfo == NULL || pResultInfo->numOfCols <= 0 || pResultInfo->fields == NULL) {
1,355,806!
2430
    tscError("setResultDataPtr paras error");
×
2431
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2432
  }
2433

2434
  if (pResultInfo->numOfRows == 0) {
1,355,813✔
2435
    return TSDB_CODE_SUCCESS;
68,657✔
2436
  }
2437

2438
  if (pResultInfo->pData == NULL) {
1,287,156!
2439
    tscError("setResultDataPtr error: pData is NULL");
×
2440
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2441
  }
2442

2443
  int32_t code = doPrepareResPtr(pResultInfo);
1,287,156✔
2444
  if (code != TSDB_CODE_SUCCESS) {
1,287,173!
2445
    return code;
×
2446
  }
2447
  code = doConvertJson(pResultInfo);
1,287,173✔
2448
  if (code != TSDB_CODE_SUCCESS) {
1,287,165!
2449
    return code;
×
2450
  }
2451

2452
  char* p = (char*)pResultInfo->pData;
1,287,165✔
2453

2454
  // version:
2455
  int32_t blockVersion = *(int32_t*)p;
1,287,165✔
2456
  p += sizeof(int32_t);
1,287,165✔
2457

2458
  int32_t dataLen = *(int32_t*)p;
1,287,165✔
2459
  p += sizeof(int32_t);
1,287,165✔
2460

2461
  int32_t rows = *(int32_t*)p;
1,287,165✔
2462
  p += sizeof(int32_t);
1,287,165✔
2463

2464
  int32_t cols = *(int32_t*)p;
1,287,165✔
2465
  p += sizeof(int32_t);
1,287,165✔
2466

2467
  if (rows != pResultInfo->numOfRows || cols != pResultInfo->numOfCols) {
1,287,165!
2468
    tscError("setResultDataPtr paras error:rows;%d numOfRows:%" PRId64 " cols:%d numOfCols:%d", rows,
×
2469
             pResultInfo->numOfRows, cols, pResultInfo->numOfCols);
2470
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2471
  }
2472

2473
  int32_t hasColumnSeg = *(int32_t*)p;
1,287,167✔
2474
  p += sizeof(int32_t);
1,287,167✔
2475

2476
  uint64_t groupId = taosGetUInt64Aligned((uint64_t*)p);
1,287,167✔
2477
  p += sizeof(uint64_t);
1,287,167✔
2478

2479
  // check fields
2480
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
5,768,051✔
2481
    int8_t type = *(int8_t*)p;
4,480,894✔
2482
    p += sizeof(int8_t);
4,480,894✔
2483

2484
    int32_t bytes = *(int32_t*)p;
4,480,894✔
2485
    p += sizeof(int32_t);
4,480,894✔
2486

2487
    if (IS_DECIMAL_TYPE(type) && pResultInfo->fields[i].precision == 0) {
4,480,894!
2488
      extractDecimalTypeInfoFromBytes(&bytes, &pResultInfo->fields[i].precision, &pResultInfo->fields[i].scale);
×
2489
    }
2490
  }
2491

2492
  int32_t* colLength = (int32_t*)p;
1,287,157✔
2493
  p += sizeof(int32_t) * pResultInfo->numOfCols;
1,287,157✔
2494

2495
  char* pStart = p;
1,287,157✔
2496
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
5,767,748✔
2497
    if ((pStart - pResultInfo->pData) >= dataLen) {
4,480,611!
2498
      tscError("setResultDataPtr invalid offset over dataLen %d", dataLen);
×
2499
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2500
    }
2501
    if (blockVersion == BLOCK_VERSION_1) {
4,480,611✔
2502
      colLength[i] = htonl(colLength[i]);
2,644,423✔
2503
    }
2504
    if (colLength[i] >= dataLen) {
4,480,611!
2505
      tscError("invalid colLength %d, dataLen %d", colLength[i], dataLen);
×
2506
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2507
    }
2508
    if (IS_INVALID_TYPE(pResultInfo->fields[i].type)) {
4,480,611!
2509
      tscError("invalid type %d", pResultInfo->fields[i].type);
×
2510
      return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2511
    }
2512
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
4,480,611✔
2513
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
1,213,610✔
2514
      pStart += pResultInfo->numOfRows * sizeof(int32_t);
1,213,610✔
2515
    } else {
2516
      pResultInfo->pCol[i].nullbitmap = pStart;
3,267,001✔
2517
      pStart += BitmapLen(pResultInfo->numOfRows);
3,267,001✔
2518
    }
2519

2520
    pResultInfo->pCol[i].pData = pStart;
4,480,611✔
2521
    pResultInfo->length[i] =
8,961,202✔
2522
        calcSchemaBytesFromTypeBytes(pResultInfo->fields[i].type, pResultInfo->fields[i].bytes, isStmt);
4,480,611✔
2523
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;
4,480,591✔
2524

2525
    pStart += colLength[i];
4,480,591✔
2526
  }
2527

2528
  p = pStart;
1,287,137✔
2529
  // bool blankFill = *(bool*)p;
2530
  p += sizeof(bool);
1,287,137✔
2531
  int32_t offset = p - pResultInfo->pData;
1,287,137✔
2532
  if (offset > dataLen) {
1,287,137!
2533
    tscError("invalid offset %d, dataLen %d", offset, dataLen);
×
2534
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2535
  }
2536

2537
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
2538
  if (convertUcs4) {
1,287,137✔
2539
    code = doConvertUCS4(pResultInfo, colLength, isStmt);
1,286,877✔
2540
  }
2541
#endif
2542
  if (TSDB_CODE_SUCCESS == code && convertForDecimal) {
1,287,205✔
2543
    code = convertDecimalType(pResultInfo);
1,286,945✔
2544
  }
2545
  return code;
1,287,147✔
2546
}
2547

2548
char* getDbOfConnection(STscObj* pObj) {
3,013,082✔
2549
  terrno = TSDB_CODE_SUCCESS;
3,013,082✔
2550
  char* p = NULL;
3,013,140✔
2551
  (void)taosThreadMutexLock(&pObj->mutex);
3,013,140✔
2552
  size_t len = strlen(pObj->db);
3,013,248✔
2553
  if (len > 0) {
3,013,248✔
2554
    p = taosStrndup(pObj->db, tListLen(pObj->db));
2,557,320!
2555
    if (p == NULL) {
2,557,284!
2556
      tscError("failed to taosStrndup db name");
×
2557
    }
2558
  }
2559

2560
  (void)taosThreadMutexUnlock(&pObj->mutex);
3,013,212✔
2561
  return p;
3,013,209✔
2562
}
2563

2564
void setConnectionDB(STscObj* pTscObj, const char* db) {
7,071✔
2565
  if (db == NULL || pTscObj == NULL) {
7,071!
2566
    tscError("setConnectionDB para is NULL");
×
2567
    return;
×
2568
  }
2569

2570
  (void)taosThreadMutexLock(&pTscObj->mutex);
7,073✔
2571
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
7,075✔
2572
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
7,075✔
2573
}
2574

2575
void resetConnectDB(STscObj* pTscObj) {
×
2576
  if (pTscObj == NULL) {
×
2577
    return;
×
2578
  }
2579

2580
  (void)taosThreadMutexLock(&pTscObj->mutex);
×
2581
  pTscObj->db[0] = 0;
×
2582
  (void)taosThreadMutexUnlock(&pTscObj->mutex);
×
2583
}
2584

2585
int32_t setQueryResultFromRsp(SReqResultInfo* pResultInfo, const SRetrieveTableRsp* pRsp, bool convertUcs4,
1,019,311✔
2586
                              bool isStmt) {
2587
  if (pResultInfo == NULL || pRsp == NULL) {
1,019,311!
2588
    tscError("setQueryResultFromRsp paras is null");
×
2589
    return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2590
  }
2591

2592
  taosMemoryFreeClear(pResultInfo->pRspMsg);
1,019,317!
2593
  pResultInfo->pRspMsg = (const char*)pRsp;
1,019,317✔
2594
  pResultInfo->numOfRows = htobe64(pRsp->numOfRows);
1,019,317✔
2595
  pResultInfo->current = 0;
1,019,311✔
2596
  pResultInfo->completed = (pRsp->completed == 1);
1,019,311✔
2597
  pResultInfo->precision = pRsp->precision;
1,019,311✔
2598

2599
  // decompress data if needed
2600
  int32_t payloadLen = htonl(pRsp->payloadLen);
1,019,311✔
2601

2602
  if (pRsp->compressed) {
1,019,311✔
2603
    if (pResultInfo->decompBuf == NULL) {
646✔
2604
      pResultInfo->decompBuf = taosMemoryMalloc(payloadLen);
15!
2605
      if (pResultInfo->decompBuf == NULL) {
15!
2606
        tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2607
        return terrno;
×
2608
      }
2609
      pResultInfo->decompBufSize = payloadLen;
15✔
2610
    } else {
2611
      if (pResultInfo->decompBufSize < payloadLen) {
631✔
2612
        char* p = taosMemoryRealloc(pResultInfo->decompBuf, payloadLen);
14!
2613
        if (p == NULL) {
14!
2614
          tscError("failed to prepare the decompress buffer, size:%d", payloadLen);
×
2615
          return terrno;
×
2616
        }
2617

2618
        pResultInfo->decompBuf = p;
14✔
2619
        pResultInfo->decompBufSize = payloadLen;
14✔
2620
      }
2621
    }
2622
  }
2623

2624
  if (payloadLen > 0) {
1,019,311✔
2625
    int32_t compLen = *(int32_t*)pRsp->data;
950,655✔
2626
    int32_t rawLen = *(int32_t*)(pRsp->data + sizeof(int32_t));
950,655✔
2627

2628
    char* pStart = (char*)pRsp->data + sizeof(int32_t) * 2;
950,655✔
2629

2630
    if (pRsp->compressed && compLen < rawLen) {
950,655!
2631
      int32_t len = tsDecompressString(pStart, compLen, 1, pResultInfo->decompBuf, rawLen, ONE_STAGE_COMP, NULL, 0);
646✔
2632
      if (len < 0) {
646!
2633
        tscError("tsDecompressString failed");
×
2634
        return terrno ? terrno : TSDB_CODE_FAILED;
×
2635
      }
2636
      if (len != rawLen) {
646!
2637
        tscError("tsDecompressString failed, len:%d != rawLen:%d", len, rawLen);
×
2638
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2639
      }
2640
      pResultInfo->pData = pResultInfo->decompBuf;
646✔
2641
      pResultInfo->payloadLen = rawLen;
646✔
2642
    } else {
2643
      pResultInfo->pData = pStart;
950,009✔
2644
      pResultInfo->payloadLen = htonl(pRsp->compLen);
950,009✔
2645
      if (pRsp->compLen != pRsp->payloadLen) {
950,009!
2646
        tscError("pRsp->compLen:%d != pRsp->payloadLen:%d", pRsp->compLen, pRsp->payloadLen);
×
2647
        return TSDB_CODE_TSC_INTERNAL_ERROR;
×
2648
      }
2649
    }
2650
  }
2651

2652
  // TODO handle the compressed case
2653
  pResultInfo->totalRows += pResultInfo->numOfRows;
1,019,311✔
2654

2655
  int32_t code = setResultDataPtr(pResultInfo, convertUcs4, isStmt);
1,019,311✔
2656
  return code;
1,019,316✔
2657
}
2658

2659
TSDB_SERVER_STATUS taos_check_server_status(const char* fqdn, int port, char* details, int maxlen) {
5✔
2660
  TSDB_SERVER_STATUS code = TSDB_SRV_STATUS_UNAVAILABLE;
5✔
2661
  void*              clientRpc = NULL;
5✔
2662
  SServerStatusRsp   statusRsp = {0};
5✔
2663
  SEpSet             epSet = {.inUse = 0, .numOfEps = 1};
5✔
2664
  SRpcMsg  rpcMsg = {.info.ahandle = (void*)0x9527, .info.notFreeAhandle = 1, .msgType = TDMT_DND_SERVER_STATUS};
5✔
2665
  SRpcMsg  rpcRsp = {0};
5✔
2666
  SRpcInit rpcInit = {0};
5✔
2667
  char     pass[TSDB_PASSWORD_LEN + 1] = {0};
5✔
2668

2669
  rpcInit.label = "CHK";
5✔
2670
  rpcInit.numOfThreads = 1;
5✔
2671
  rpcInit.cfp = NULL;
5✔
2672
  rpcInit.sessions = 16;
5✔
2673
  rpcInit.connType = TAOS_CONN_CLIENT;
5✔
2674
  rpcInit.idleTime = tsShellActivityTimer * 1000;
5✔
2675
  rpcInit.compressSize = tsCompressMsgSize;
5✔
2676
  rpcInit.user = "_dnd";
5✔
2677

2678
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
5✔
2679
  connLimitNum = TMAX(connLimitNum, 10);
5✔
2680
  connLimitNum = TMIN(connLimitNum, 500);
5✔
2681
  rpcInit.connLimitNum = connLimitNum;
5✔
2682
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
5✔
2683
  rpcInit.readTimeout = tsReadTimeout;
5✔
2684
  rpcInit.ipv6 = tsEnableIpv6;
5✔
2685
  if (TSDB_CODE_SUCCESS != taosVersionStrToInt(td_version, &rpcInit.compatibilityVer)) {
5!
2686
    tscError("faild to convert taos version from str to int, errcode:%s", terrstr());
×
2687
    goto _OVER;
×
2688
  }
2689

2690
  clientRpc = rpcOpen(&rpcInit);
5✔
2691
  if (clientRpc == NULL) {
5!
2692
    code = terrno;
×
2693
    tscError("failed to init server status client since %s", tstrerror(code));
×
2694
    goto _OVER;
×
2695
  }
2696

2697
  if (fqdn == NULL) {
5!
2698
    fqdn = tsLocalFqdn;
5✔
2699
  }
2700

2701
  if (port == 0) {
5!
2702
    port = tsServerPort;
5✔
2703
  }
2704

2705
  tstrncpy(epSet.eps[0].fqdn, fqdn, TSDB_FQDN_LEN);
5✔
2706
  epSet.eps[0].port = (uint16_t)port;
5✔
2707
  int32_t ret = rpcSendRecv(clientRpc, &epSet, &rpcMsg, &rpcRsp);
5✔
2708
  if (TSDB_CODE_SUCCESS != ret) {
5!
2709
    tscError("failed to send recv since %s", tstrerror(ret));
×
2710
    goto _OVER;
×
2711
  }
2712

2713
  if (rpcRsp.code != 0 || rpcRsp.contLen <= 0 || rpcRsp.pCont == NULL) {
5!
2714
    tscError("failed to send server status req since %s", terrstr());
1!
2715
    goto _OVER;
1✔
2716
  }
2717

2718
  if (tDeserializeSServerStatusRsp(rpcRsp.pCont, rpcRsp.contLen, &statusRsp) != 0) {
4!
2719
    tscError("failed to parse server status rsp since %s", terrstr());
×
2720
    goto _OVER;
×
2721
  }
2722

2723
  code = statusRsp.statusCode;
4✔
2724
  if (details != NULL) {
4!
2725
    tstrncpy(details, statusRsp.details, maxlen);
4✔
2726
  }
2727

2728
_OVER:
×
2729
  if (clientRpc != NULL) {
5!
2730
    rpcClose(clientRpc);
5✔
2731
  }
2732
  if (rpcRsp.pCont != NULL) {
5✔
2733
    rpcFreeCont(rpcRsp.pCont);
4✔
2734
  }
2735
  return code;
5✔
2736
}
2737

2738
int32_t appendTbToReq(SHashObj* pHash, int32_t pos1, int32_t len1, int32_t pos2, int32_t len2, const char* str,
4✔
2739
                      int32_t acctId, char* db) {
2740
  SName name = {0};
4✔
2741

2742
  if (len1 <= 0) {
4!
2743
    return -1;
×
2744
  }
2745

2746
  const char* dbName = db;
4✔
2747
  const char* tbName = NULL;
4✔
2748
  int32_t     dbLen = 0;
4✔
2749
  int32_t     tbLen = 0;
4✔
2750
  if (len2 > 0) {
4!
2751
    dbName = str + pos1;
×
2752
    dbLen = len1;
×
2753
    tbName = str + pos2;
×
2754
    tbLen = len2;
×
2755
  } else {
2756
    dbLen = strlen(db);
4✔
2757
    tbName = str + pos1;
4✔
2758
    tbLen = len1;
4✔
2759
  }
2760

2761
  if (dbLen <= 0 || tbLen <= 0) {
4!
2762
    return -1;
×
2763
  }
2764

2765
  if (tNameSetDbName(&name, acctId, dbName, dbLen)) {
4!
2766
    return -1;
×
2767
  }
2768

2769
  if (tNameAddTbName(&name, tbName, tbLen)) {
4!
2770
    return -1;
×
2771
  }
2772

2773
  char dbFName[TSDB_DB_FNAME_LEN] = {0};
4✔
2774
  (void)snprintf(dbFName, TSDB_DB_FNAME_LEN, "%d.%.*s", acctId, dbLen, dbName);
4✔
2775

2776
  STablesReq* pDb = taosHashGet(pHash, dbFName, strlen(dbFName));
4✔
2777
  if (pDb) {
4!
2778
    if (NULL == taosArrayPush(pDb->pTables, &name)) {
×
2779
      return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
2780
    }
2781
  } else {
2782
    STablesReq db;
2783
    db.pTables = taosArrayInit(20, sizeof(SName));
4✔
2784
    if (NULL == db.pTables) {
4!
2785
      return terrno;
×
2786
    }
2787
    tstrncpy(db.dbFName, dbFName, TSDB_DB_FNAME_LEN);
4✔
2788
    if (NULL == taosArrayPush(db.pTables, &name)) {
8!
2789
      return terrno;
×
2790
    }
2791
    TSC_ERR_RET(taosHashPut(pHash, dbFName, strlen(dbFName), &db, sizeof(db)));
4!
2792
  }
2793

2794
  return TSDB_CODE_SUCCESS;
4✔
2795
}
2796

2797
int32_t transferTableNameList(const char* tbList, int32_t acctId, char* dbName, SArray** pReq) {
4✔
2798
  SHashObj* pHash = taosHashInit(3, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
4✔
2799
  if (NULL == pHash) {
4!
2800
    return terrno;
×
2801
  }
2802

2803
  bool    inEscape = false;
4✔
2804
  int32_t code = 0;
4✔
2805
  void*   pIter = NULL;
4✔
2806

2807
  int32_t vIdx = 0;
4✔
2808
  int32_t vPos[2];
2809
  int32_t vLen[2];
2810

2811
  (void)memset(vPos, -1, sizeof(vPos));
4✔
2812
  (void)memset(vLen, 0, sizeof(vLen));
4✔
2813

2814
  for (int32_t i = 0;; ++i) {
18✔
2815
    if (0 == *(tbList + i)) {
18✔
2816
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
4!
2817
        vLen[vIdx] = i - vPos[vIdx];
4✔
2818
      }
2819

2820
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
4✔
2821
      if (code) {
4!
2822
        goto _return;
×
2823
      }
2824

2825
      break;
4✔
2826
    }
2827

2828
    if ('`' == *(tbList + i)) {
14!
2829
      inEscape = !inEscape;
×
2830
      if (!inEscape) {
×
2831
        if (vPos[vIdx] >= 0) {
×
2832
          vLen[vIdx] = i - vPos[vIdx];
×
2833
        } else {
2834
          goto _return;
×
2835
        }
2836
      }
2837

2838
      continue;
×
2839
    }
2840

2841
    if (inEscape) {
14!
2842
      if (vPos[vIdx] < 0) {
×
2843
        vPos[vIdx] = i;
×
2844
      }
2845
      continue;
×
2846
    }
2847

2848
    if ('.' == *(tbList + i)) {
14!
2849
      if (vPos[vIdx] < 0) {
×
2850
        goto _return;
×
2851
      }
2852
      if (vLen[vIdx] <= 0) {
×
2853
        vLen[vIdx] = i - vPos[vIdx];
×
2854
      }
2855
      vIdx++;
×
2856
      if (vIdx >= 2) {
×
2857
        goto _return;
×
2858
      }
2859
      continue;
×
2860
    }
2861

2862
    if (',' == *(tbList + i)) {
14!
2863
      if (vPos[vIdx] < 0) {
×
2864
        goto _return;
×
2865
      }
2866
      if (vLen[vIdx] <= 0) {
×
2867
        vLen[vIdx] = i - vPos[vIdx];
×
2868
      }
2869

2870
      code = appendTbToReq(pHash, vPos[0], vLen[0], vPos[1], vLen[1], tbList, acctId, dbName);
×
2871
      if (code) {
×
2872
        goto _return;
×
2873
      }
2874

2875
      (void)memset(vPos, -1, sizeof(vPos));
×
2876
      (void)memset(vLen, 0, sizeof(vLen));
×
2877
      vIdx = 0;
×
2878
      continue;
×
2879
    }
2880

2881
    if (' ' == *(tbList + i) || '\r' == *(tbList + i) || '\t' == *(tbList + i) || '\n' == *(tbList + i)) {
14!
2882
      if (vPos[vIdx] >= 0 && vLen[vIdx] <= 0) {
×
2883
        vLen[vIdx] = i - vPos[vIdx];
×
2884
      }
2885
      continue;
×
2886
    }
2887

2888
    if (('a' <= *(tbList + i) && 'z' >= *(tbList + i)) || ('A' <= *(tbList + i) && 'Z' >= *(tbList + i)) ||
14!
2889
        ('0' <= *(tbList + i) && '9' >= *(tbList + i)) || ('_' == *(tbList + i))) {
1!
2890
      if (vLen[vIdx] > 0) {
14!
2891
        goto _return;
×
2892
      }
2893
      if (vPos[vIdx] < 0) {
14✔
2894
        vPos[vIdx] = i;
4✔
2895
      }
2896
      continue;
14✔
2897
    }
2898

2899
    goto _return;
×
2900
  }
2901

2902
  int32_t dbNum = taosHashGetSize(pHash);
4✔
2903
  *pReq = taosArrayInit(dbNum, sizeof(STablesReq));
4✔
2904
  if (NULL == pReq) {
4!
2905
    TSC_ERR_JRET(terrno);
×
2906
  }
2907
  pIter = taosHashIterate(pHash, NULL);
4✔
2908
  while (pIter) {
8✔
2909
    STablesReq* pDb = (STablesReq*)pIter;
4✔
2910
    if (NULL == taosArrayPush(*pReq, pDb)) {
8!
2911
      TSC_ERR_JRET(terrno);
×
2912
    }
2913
    pIter = taosHashIterate(pHash, pIter);
4✔
2914
  }
2915

2916
  taosHashCleanup(pHash);
4✔
2917

2918
  return TSDB_CODE_SUCCESS;
4✔
2919

2920
_return:
×
2921

2922
  terrno = TSDB_CODE_TSC_INVALID_OPERATION;
×
2923

2924
  pIter = taosHashIterate(pHash, NULL);
×
2925
  while (pIter) {
×
2926
    STablesReq* pDb = (STablesReq*)pIter;
×
2927
    taosArrayDestroy(pDb->pTables);
×
2928
    pIter = taosHashIterate(pHash, pIter);
×
2929
  }
2930

2931
  taosHashCleanup(pHash);
×
2932

2933
  return terrno;
×
2934
}
2935

2936
void syncCatalogFn(SMetaData* pResult, void* param, int32_t code) {
4✔
2937
  SSyncQueryParam* pParam = param;
4✔
2938
  pParam->pRequest->code = code;
4✔
2939

2940
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
4!
2941
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
2942
  }
2943
}
4✔
2944

2945
void syncQueryFn(void* param, void* res, int32_t code) {
2,911,781✔
2946
  SSyncQueryParam* pParam = param;
2,911,781✔
2947
  pParam->pRequest = res;
2,911,781✔
2948

2949
  if (pParam->pRequest) {
2,911,781!
2950
    pParam->pRequest->code = code;
2,911,804✔
2951
    clientOperateReport(pParam->pRequest);
2,911,804✔
2952
  }
2953

2954
  if (TSDB_CODE_SUCCESS != tsem_post(&pParam->sem)) {
2,911,803!
2955
    tscError("failed to post semaphore since %s", tstrerror(terrno));
×
2956
  }
2957
}
2,911,837✔
2958

2959
void taosAsyncQueryImpl(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
2,911,309✔
2960
                        int8_t source) {
2961
  if (sql == NULL || NULL == fp) {
2,911,309!
2962
    terrno = TSDB_CODE_INVALID_PARA;
×
2963
    if (fp) {
×
2964
      fp(param, NULL, terrno);
×
2965
    }
2966

2967
    return;
×
2968
  }
2969

2970
  size_t sqlLen = strlen(sql);
2,911,392✔
2971
  if (sqlLen > (size_t)TSDB_MAX_ALLOWED_SQL_LEN) {
2,911,392!
2972
    tscError("conn:0x%" PRIx64 ", sql string exceeds max length:%d", connId, TSDB_MAX_ALLOWED_SQL_LEN);
×
2973
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
2974
    fp(param, NULL, terrno);
×
2975
    return;
×
2976
  }
2977

2978
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, sql:%s", connId, sql);
2,911,392✔
2979

2980
  SRequestObj* pRequest = NULL;
2,911,392✔
2981
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, 0);
2,911,392✔
2982
  if (code != TSDB_CODE_SUCCESS) {
2,911,358!
2983
    terrno = code;
×
2984
    fp(param, NULL, terrno);
×
2985
    return;
×
2986
  }
2987

2988
  pRequest->source = source;
2,911,358✔
2989
  pRequest->body.queryFp = fp;
2,911,358✔
2990
  doAsyncQuery(pRequest, false);
2,911,358✔
2991
}
2992

2993
void taosAsyncQueryImplWithReqid(uint64_t connId, const char* sql, __taos_async_fn_t fp, void* param, bool validateOnly,
×
2994
                                 int64_t reqid) {
2995
  if (sql == NULL || NULL == fp) {
×
2996
    terrno = TSDB_CODE_INVALID_PARA;
×
2997
    if (fp) {
×
2998
      fp(param, NULL, terrno);
×
2999
    }
3000

3001
    return;
×
3002
  }
3003

3004
  size_t sqlLen = strlen(sql);
×
3005
  if (sqlLen > (size_t)TSDB_MAX_ALLOWED_SQL_LEN) {
×
3006
    tscError("conn:0x%" PRIx64 ", QID:0x%" PRIx64 ", sql string exceeds max length:%d", connId, reqid,
×
3007
             TSDB_MAX_ALLOWED_SQL_LEN);
3008
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
×
3009
    fp(param, NULL, terrno);
×
3010
    return;
×
3011
  }
3012

3013
  tscDebug("conn:0x%" PRIx64 ", taos_query execute, QID:0x%" PRIx64 ", sql:%s", connId, reqid, sql);
×
3014

3015
  SRequestObj* pRequest = NULL;
×
3016
  int32_t      code = buildRequest(connId, sql, sqlLen, param, validateOnly, &pRequest, reqid);
×
3017
  if (code != TSDB_CODE_SUCCESS) {
×
3018
    terrno = code;
×
3019
    fp(param, NULL, terrno);
×
3020
    return;
×
3021
  }
3022

3023
  pRequest->body.queryFp = fp;
×
3024
  doAsyncQuery(pRequest, false);
×
3025
}
3026

3027
TAOS_RES* taosQueryImpl(TAOS* taos, const char* sql, bool validateOnly, int8_t source) {
2,910,790✔
3028
  if (NULL == taos) {
2,910,790!
3029
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3030
    return NULL;
×
3031
  }
3032

3033
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
2,910,790!
3034
  if (NULL == param) {
2,910,878!
3035
    return NULL;
×
3036
  }
3037
  int32_t code = tsem_init(&param->sem, 0, 0);
2,910,878✔
3038
  if (TSDB_CODE_SUCCESS != code) {
2,910,838!
3039
    taosMemoryFree(param);
×
3040
    return NULL;
×
3041
  }
3042

3043
  taosAsyncQueryImpl(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, source);
2,910,838✔
3044
  code = tsem_wait(&param->sem);
2,910,594✔
3045
  if (TSDB_CODE_SUCCESS != code) {
2,910,847!
3046
    taosMemoryFree(param);
×
3047
    return NULL;
×
3048
  }
3049
  code = tsem_destroy(&param->sem);
2,910,847✔
3050
  if (TSDB_CODE_SUCCESS != code) {
2,910,841!
3051
    tscError("failed to destroy semaphore since %s", tstrerror(code));
×
3052
  }
3053

3054
  SRequestObj* pRequest = NULL;
2,910,861✔
3055
  if (param->pRequest != NULL) {
2,910,861!
3056
    param->pRequest->syncQuery = true;
2,910,861✔
3057
    pRequest = param->pRequest;
2,910,861✔
3058
    param->pRequest->inCallback = false;
2,910,861✔
3059
  }
3060
  taosMemoryFree(param);
2,910,861!
3061

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

3065
  return pRequest;
2,910,890✔
3066
}
3067

3068
TAOS_RES* taosQueryImplWithReqid(TAOS* taos, const char* sql, bool validateOnly, int64_t reqid) {
×
3069
  if (NULL == taos) {
×
3070
    terrno = TSDB_CODE_TSC_DISCONNECTED;
×
3071
    return NULL;
×
3072
  }
3073

3074
  SSyncQueryParam* param = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
×
3075
  if (param == NULL) {
×
3076
    return NULL;
×
3077
  }
3078
  int32_t code = tsem_init(&param->sem, 0, 0);
×
3079
  if (TSDB_CODE_SUCCESS != code) {
×
3080
    taosMemoryFree(param);
×
3081
    return NULL;
×
3082
  }
3083

3084
  taosAsyncQueryImplWithReqid(*(int64_t*)taos, sql, syncQueryFn, param, validateOnly, reqid);
×
3085
  code = tsem_wait(&param->sem);
×
3086
  if (TSDB_CODE_SUCCESS != code) {
×
3087
    taosMemoryFree(param);
×
3088
    return NULL;
×
3089
  }
3090
  SRequestObj* pRequest = NULL;
×
3091
  if (param->pRequest != NULL) {
×
3092
    param->pRequest->syncQuery = true;
×
3093
    pRequest = param->pRequest;
×
3094
  }
3095
  taosMemoryFree(param);
×
3096

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

3100
  return pRequest;
×
3101
}
3102

3103
static void fetchCallback(void* pResult, void* param, int32_t code) {
896,170✔
3104
  SRequestObj* pRequest = (SRequestObj*)param;
896,170✔
3105

3106
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
896,170✔
3107

3108
  tscDebug("req:0x%" PRIx64 ", enter scheduler fetch cb, code:%d - %s, QID:0x%" PRIx64, pRequest->self, code,
896,170✔
3109
           tstrerror(code), pRequest->requestId);
3110

3111
  pResultInfo->pData = pResult;
896,166✔
3112
  pResultInfo->numOfRows = 0;
896,166✔
3113

3114
  if (code != TSDB_CODE_SUCCESS) {
896,166!
3115
    pRequest->code = code;
×
3116
    taosMemoryFreeClear(pResultInfo->pData);
×
3117
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
×
3118
    return;
×
3119
  }
3120

3121
  if (pRequest->code != TSDB_CODE_SUCCESS) {
896,166!
3122
    taosMemoryFreeClear(pResultInfo->pData);
×
3123
    pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pRequest->code);
×
3124
    return;
×
3125
  }
3126

3127
  pRequest->code = setQueryResultFromRsp(pResultInfo, (const SRetrieveTableRsp*)pResultInfo->pData,
1,792,338✔
3128
                                         pResultInfo->convertUcs4, pRequest->isStmtBind);
896,166✔
3129
  if (pRequest->code != TSDB_CODE_SUCCESS) {
896,172!
3130
    pResultInfo->numOfRows = 0;
×
3131
    tscError("req:0x%" PRIx64 ", fetch results failed, code:%s, QID:0x%" PRIx64, pRequest->self,
×
3132
             tstrerror(pRequest->code), pRequest->requestId);
3133
  } else {
3134
    tscDebug(
896,172✔
3135
        "req:0x%" PRIx64 ", fetch results, numOfRows:%" PRId64 " total Rows:%" PRId64 ", complete:%d, QID:0x%" PRIx64,
3136
        pRequest->self, pResultInfo->numOfRows, pResultInfo->totalRows, pResultInfo->completed, pRequest->requestId);
3137

3138
    STscObj*            pTscObj = pRequest->pTscObj;
896,173✔
3139
    SAppClusterSummary* pActivity = &pTscObj->pAppInfo->summary;
896,173✔
3140
    (void)atomic_add_fetch_64((int64_t*)&pActivity->fetchBytes, pRequest->body.resInfo.payloadLen);
896,173✔
3141
  }
3142

3143
  pRequest->body.fetchFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, pResultInfo->numOfRows);
896,178✔
3144
}
3145

3146
void taosAsyncFetchImpl(SRequestObj* pRequest, __taos_async_fn_t fp, void* param) {
979,188✔
3147
  pRequest->body.fetchFp = fp;
979,188✔
3148
  ((SSyncQueryParam*)pRequest->body.interParam)->userParam = param;
979,188✔
3149

3150
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
979,188✔
3151

3152
  // this query has no results or error exists, return directly
3153
  if (taos_num_fields(pRequest) == 0 || pRequest->code != TSDB_CODE_SUCCESS) {
979,188!
3154
    pResultInfo->numOfRows = 0;
1✔
3155
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
1✔
3156
    return;
83,009✔
3157
  }
3158

3159
  // all data has returned to App already, no need to try again
3160
  if (pResultInfo->completed) {
979,187✔
3161
    // it is a local executed query, no need to do async fetch
3162
    if (QUERY_EXEC_MODE_SCHEDULE != pRequest->body.execMode) {
83,008✔
3163
      if (pResultInfo->localResultFetched) {
600✔
3164
        pResultInfo->numOfRows = 0;
300✔
3165
        pResultInfo->current = 0;
300✔
3166
      } else {
3167
        pResultInfo->localResultFetched = true;
300✔
3168
      }
3169
    } else {
3170
      pResultInfo->numOfRows = 0;
82,408✔
3171
    }
3172

3173
    pRequest->body.fetchFp(param, pRequest, pResultInfo->numOfRows);
83,008✔
3174
    return;
83,008✔
3175
  }
3176

3177
  SSchedulerReq req = {
896,179✔
3178
      .syncReq = false,
3179
      .fetchFp = fetchCallback,
3180
      .cbParam = pRequest,
3181
  };
3182

3183
  int32_t code = schedulerFetchRows(pRequest->body.queryJob, &req);
896,179✔
3184
  if (TSDB_CODE_SUCCESS != code) {
896,180!
3185
    tscError("0x%" PRIx64 " failed to schedule fetch rows", pRequest->requestId);
×
3186
    // pRequest->body.fetchFp(param, pRequest, code);
3187
  }
3188
}
3189

3190
void doRequestCallback(SRequestObj* pRequest, int32_t code) {
2,911,267✔
3191
  pRequest->inCallback = true;
2,911,267✔
3192
  int64_t this = pRequest->self;
2,911,267✔
3193
  if (tsQueryTbNotExistAsEmpty && TD_RES_QUERY(&pRequest->resType) && pRequest->isQuery &&
2,911,267!
3194
      (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_TDB_TABLE_NOT_EXIST)) {
316!
3195
    code = TSDB_CODE_SUCCESS;
×
3196
    pRequest->type = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
×
3197
  }
3198

3199
  tscDebug("QID:0x%" PRIx64 ", taos_query end, req:0x%" PRIx64 ", res:%p", pRequest->requestId, pRequest->self,
2,911,267✔
3200
           pRequest);
3201

3202
  if (pRequest->body.queryFp != NULL) {
2,911,268!
3203
    pRequest->body.queryFp(((SSyncQueryParam*)pRequest->body.interParam)->userParam, pRequest, code);
2,911,302✔
3204
  }
3205

3206
  SRequestObj* pReq = acquireRequest(this);
2,911,293✔
3207
  if (pReq != NULL) {
2,911,350✔
3208
    pReq->inCallback = false;
2,911,295✔
3209
    (void)releaseRequest(this);
2,911,295✔
3210
  }
3211
}
2,911,344✔
3212

3213
int32_t clientParseSql(void* param, const char* dbName, const char* sql, bool parseOnly, const char* effectiveUser,
941✔
3214
                       SParseSqlRes* pRes) {
3215
#ifndef TD_ENTERPRISE
3216
  return TSDB_CODE_SUCCESS;
3217
#else
3218
  return clientParseSqlImpl(param, dbName, sql, parseOnly, effectiveUser, pRes);
941✔
3219
#endif
3220
}
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