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

16 17
#include "tscUtil.h"
#include "hash.h"
S
slguan 已提交
18
#include "os.h"
H
hzcheng 已提交
19 20 21 22
#include "taosmsg.h"
#include "tcache.h"
#include "tkey.h"
#include "tmd5.h"
S
slguan 已提交
23
#include "tscJoinProcess.h"
H
hzcheng 已提交
24 25 26 27 28 29 30 31 32
#include "tscProfile.h"
#include "tscSecondaryMerge.h"
#include "tschemautil.h"
#include "tsclient.h"
#include "tsqldef.h"
#include "ttimer.h"

/*
 * the detailed information regarding metric meta key is:
S
slguan 已提交
33 34
 * fullmetername + '.' + tagQueryCond + '.' + tableNameCond + '.' + joinCond +
 * '.' + relation + '.' + [tagId1, tagId2,...] + '.' + group_orderType
S
slguan 已提交
35
 *
S
slguan 已提交
36 37 38
 * if querycond/tablenameCond/joinCond is null, its format is:
 * fullmetername + '.' + '(nil)' + '.' + '(nil)' + relation + '.' + [tagId1,
 * tagId2,...] + '.' + group_orderType
H
hzcheng 已提交
39
 */
H
hjxilinx 已提交
40
void tscGetMetricMetaCacheKey(SQueryInfo* pQueryInfo, char* str, uint64_t uid) {
41
  int32_t         index = -1;
H
hjxilinx 已提交
42
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoByUid(pQueryInfo, uid, &index);
H
hzcheng 已提交
43

S
slguan 已提交
44
  int32_t len = 0;
H
hzcheng 已提交
45
  char    tagIdBuf[128] = {0};
S
slguan 已提交
46 47
  for (int32_t i = 0; i < pMeterMetaInfo->numOfTags; ++i) {
    len += sprintf(&tagIdBuf[len], "%d,", pMeterMetaInfo->tagColumnIndex[i]);
H
hzcheng 已提交
48 49
  }

50
  STagCond* pTagCond = &pQueryInfo->tagCond;
S
slguan 已提交
51
  assert(len < tListLen(tagIdBuf));
H
hzcheng 已提交
52

S
slguan 已提交
53 54 55 56 57 58 59 60 61
  const int32_t maxKeySize = TSDB_MAX_TAGS_LEN;  // allowed max key size

  SCond* cond = tsGetMetricQueryCondPos(pTagCond, uid);

  char join[512] = {0};
  if (pTagCond->joinInfo.hasJoin) {
    sprintf(join, "%s,%s", pTagCond->joinInfo.left.meterId, pTagCond->joinInfo.right.meterId);
  }

H
hjxilinx 已提交
62
  // estimate the buffer size
H
hjxilinx 已提交
63
  size_t tbnameCondLen = pTagCond->tbnameCond.cond != NULL ? strlen(pTagCond->tbnameCond.cond) : 0;
H
hjxilinx 已提交
64
  size_t redundantLen = 20;
H
hjxilinx 已提交
65

H
hjxilinx 已提交
66 67 68 69
  size_t bufSize = strlen(pMeterMetaInfo->name) + tbnameCondLen + strlen(join) + strlen(tagIdBuf);
  if (cond != NULL) {
    bufSize += strlen(cond->cond);
  }
H
hjxilinx 已提交
70 71

  bufSize = (size_t)((bufSize + redundantLen) * 1.5);
H
hjxilinx 已提交
72 73 74
  char* tmp = calloc(1, bufSize);

  int32_t keyLen = snprintf(tmp, bufSize, "%s,%s,%s,%d,%s,[%s],%d", pMeterMetaInfo->name,
H
hjxilinx 已提交
75
                            (cond != NULL ? cond->cond : NULL), (tbnameCondLen > 0 ? pTagCond->tbnameCond.cond : NULL),
76
                            pTagCond->relType, join, tagIdBuf, pQueryInfo->groupbyExpr.orderType);
S
slguan 已提交
77

H
hjxilinx 已提交
78
  assert(keyLen <= bufSize);
S
slguan 已提交
79 80 81 82

  if (keyLen < maxKeySize) {
    strcpy(str, tmp);
  } else {  // using md5 to hash
H
hzcheng 已提交
83 84 85
    MD5_CTX ctx;
    MD5Init(&ctx);

H
hjxilinx 已提交
86
    MD5Update(&ctx, (uint8_t*)tmp, keyLen);
S
slguan 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
    char* pStr = base64_encode(ctx.digest, tListLen(ctx.digest));
    strcpy(str, pStr);
  }

  free(tmp);
}

SCond* tsGetMetricQueryCondPos(STagCond* pTagCond, uint64_t uid) {
  for (int32_t i = 0; i < TSDB_MAX_JOIN_TABLE_NUM; ++i) {
    if (uid == pTagCond->cond[i].uid) {
      return &pTagCond->cond[i];
    }
  }

  return NULL;
}

void tsSetMetricQueryCond(STagCond* pTagCond, uint64_t uid, const char* str) {
  size_t len = strlen(str);
  if (len == 0) {
    return;
H
hzcheng 已提交
108 109
  }

S
slguan 已提交
110 111
  SCond* pDest = &pTagCond->cond[pTagCond->numOfTagCond];
  pDest->uid = uid;
H
hjxilinx 已提交
112
  pDest->cond = strdup(str);
S
slguan 已提交
113 114 115 116 117

  pTagCond->numOfTagCond += 1;
}

bool tscQueryOnMetric(SSqlCmd* pCmd) {
118 119 120
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

  return ((pQueryInfo->type & TSDB_QUERY_TYPE_STABLE_QUERY) == TSDB_QUERY_TYPE_STABLE_QUERY) &&
S
slguan 已提交
121 122 123
         (pCmd->msgType == TSDB_MSG_TYPE_QUERY);
}

124 125 126
bool tscQueryMetricTags(SQueryInfo* pQueryInfo) {
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    if (tscSqlExprGet(pQueryInfo, i)->functionId != TSDB_FUNC_TAGPRJ) {
S
slguan 已提交
127 128 129
      return false;
    }
  }
H
hzcheng 已提交
130

S
slguan 已提交
131
  return true;
H
hzcheng 已提交
132 133
}

S
slguan 已提交
134 135 136 137
bool tscIsSelectivityWithTagQuery(SSqlCmd* pCmd) {
  bool    hasTags = false;
  int32_t numOfSelectivity = 0;

138 139 140 141
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    int32_t functId = tscSqlExprGet(pQueryInfo, i)->functionId;
S
slguan 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    if (functId == TSDB_FUNC_TAG_DUMMY) {
      hasTags = true;
      continue;
    }

    if ((aAggs[functId].nStatus & TSDB_FUNCSTATE_SELECTIVITY) != 0) {
      numOfSelectivity++;
    }
  }

  if (numOfSelectivity > 0 && hasTags) {
    return true;
  }

  return false;
}
H
hzcheng 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207

void tscGetDBInfoFromMeterId(char* meterId, char* db) {
  char* st = strstr(meterId, TS_PATH_DELIMITER);
  if (st != NULL) {
    char* end = strstr(st + 1, TS_PATH_DELIMITER);
    if (end != NULL) {
      memcpy(db, meterId, (end - meterId));
      db[end - meterId] = 0;
      return;
    }
  }

  db[0] = 0;
}

SVnodeSidList* tscGetVnodeSidList(SMetricMeta* pMetricmeta, int32_t vnodeIdx) {
  if (pMetricmeta == NULL) {
    tscError("illegal metricmeta");
    return 0;
  }

  if (pMetricmeta->numOfVnodes == 0 || pMetricmeta->numOfMeters == 0) {
    return 0;
  }

  if (vnodeIdx < 0 || vnodeIdx >= pMetricmeta->numOfVnodes) {
    int32_t vnodeRange = (pMetricmeta->numOfVnodes > 0) ? (pMetricmeta->numOfVnodes - 1) : 0;
    tscError("illegal vnodeIdx:%d, reset to 0, vnodeIdx range:%d-%d", vnodeIdx, 0, vnodeRange);

    vnodeIdx = 0;
  }

  return (SVnodeSidList*)(pMetricmeta->list[vnodeIdx] + (char*)pMetricmeta);
}

SMeterSidExtInfo* tscGetMeterSidInfo(SVnodeSidList* pSidList, int32_t idx) {
  if (pSidList == NULL) {
    tscError("illegal sidlist");
    return 0;
  }

  if (idx < 0 || idx >= pSidList->numOfSids) {
    int32_t sidRange = (pSidList->numOfSids > 0) ? (pSidList->numOfSids - 1) : 0;

    tscError("illegal sidIdx:%d, reset to 0, sidIdx range:%d-%d", idx, 0, sidRange);
    idx = 0;
  }
  return (SMeterSidExtInfo*)(pSidList->pSidExtInfoList[idx] + (char*)pSidList);
}

208
bool tscIsTwoStageMergeMetricQuery(SQueryInfo* pQueryInfo, int32_t tableIndex) {
209 210 211
  if (pQueryInfo == NULL) {
    return false;
  }
212

213
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, tableIndex);
S
slguan 已提交
214 215 216 217 218
  if (pMeterMetaInfo == NULL || pMeterMetaInfo->pMetricMeta == NULL) {
    return false;
  }

  // for projection query, iterate all qualified vnodes sequentially
219
  if (tscProjectionQueryOnSTable(pQueryInfo, tableIndex)) {
H
hzcheng 已提交
220 221 222
    return false;
  }

223
  if (((pQueryInfo->type & TSDB_QUERY_TYPE_STABLE_SUBQUERY) != TSDB_QUERY_TYPE_STABLE_SUBQUERY) &&
224
      pQueryInfo->command == TSDB_SQL_SELECT) {
225
    return UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo);
H
hzcheng 已提交
226 227 228 229 230
  }

  return false;
}

231
bool tscProjectionQueryOnSTable(SQueryInfo* pQueryInfo, int32_t tableIndex) {
232
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, tableIndex);
H
hzcheng 已提交
233 234 235

  /*
   * In following cases, return false for project query on metric
S
slguan 已提交
236
   * 1. failed to get metermeta from server; 2. not a metric; 3. limit 0; 4. show query, instead of a select query
H
hzcheng 已提交
237
   */
238
  if (pMeterMetaInfo == NULL || !UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo) ||
239
      pQueryInfo->command == TSDB_SQL_RETRIEVE_EMPTY_RESULT || pQueryInfo->exprsInfo.numOfExprs == 0) {
H
hzcheng 已提交
240 241 242
    return false;
  }

S
slguan 已提交
243
  // only query on tag, not a projection query
244
  if (tscQueryMetricTags(pQueryInfo)) {
S
slguan 已提交
245 246 247
    return false;
  }

H
hjxilinx 已提交
248
  // for project query, only the following two function is allowed
249 250
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    int32_t functionId = tscSqlExprGet(pQueryInfo, i)->functionId;
H
hjxilinx 已提交
251 252
    if (functionId != TSDB_FUNC_PRJ && functionId != TSDB_FUNC_TAGPRJ && functionId != TSDB_FUNC_TAG &&
        functionId != TSDB_FUNC_TS && functionId != TSDB_FUNC_ARITHM) {
S
slguan 已提交
253
      return false;
H
hzcheng 已提交
254 255 256
    }
  }

S
slguan 已提交
257
  return true;
H
hzcheng 已提交
258 259
}

260 261 262
bool tscProjectionQueryOnTable(SQueryInfo* pQueryInfo) {
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    int32_t functionId = tscSqlExprGet(pQueryInfo, i)->functionId;
H
hjxilinx 已提交
263 264 265 266
    if (functionId != TSDB_FUNC_PRJ && functionId != TSDB_FUNC_TS) {
      return false;
    }
  }
H
hjxilinx 已提交
267

H
hjxilinx 已提交
268 269 270
  return true;
}

271 272 273
bool tscIsPointInterpQuery(SQueryInfo* pQueryInfo) {
  for (int32_t i = 0; i < pQueryInfo->exprsInfo.numOfExprs; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
H
hzcheng 已提交
274 275 276 277
    if (pExpr == NULL) {
      return false;
    }

S
slguan 已提交
278
    int32_t functionId = pExpr->functionId;
H
hzcheng 已提交
279 280 281 282 283 284 285 286 287 288 289
    if (functionId == TSDB_FUNC_TAG) {
      continue;
    }

    if (functionId != TSDB_FUNC_INTERP) {
      return false;
    }
  }
  return true;
}

290 291 292
bool tscIsTWAQuery(SQueryInfo* pQueryInfo) {
  for (int32_t i = 0; i < pQueryInfo->exprsInfo.numOfExprs; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
293 294 295 296 297 298 299 300 301 302 303
    if (pExpr == NULL) {
      continue;
    }

    int32_t functionId = pExpr->functionId;
    if (functionId == TSDB_FUNC_TWA) {
      return true;
    }
  }

  return false;
H
hzcheng 已提交
304 305
}

306 307
void tscClearInterpInfo(SQueryInfo* pQueryInfo) {
  if (!tscIsPointInterpQuery(pQueryInfo)) {
H
hzcheng 已提交
308 309 310
    return;
  }

311
  pQueryInfo->interpoType = TSDB_INTERPO_NONE;
312
  tfree(pQueryInfo->defaultVal);
H
hzcheng 已提交
313 314 315 316
}

void tscClearSqlMetaInfoForce(SSqlCmd* pCmd) {
  /* remove the metermeta/metricmeta in cache */
317 318
  //    taosRemoveDataFromCache(tscCacheHandle, (void**)&(pCmd->pMeterMeta), true);
  //    taosRemoveDataFromCache(tscCacheHandle, (void**)&(pCmd->pMetricMeta), true);
H
hzcheng 已提交
319 320
}

321
int32_t tscCreateResPointerInfo(SQueryInfo* pQueryInfo, SSqlRes* pRes) {
H
hzcheng 已提交
322 323
  if (pRes->tsrow == NULL) {
    pRes->numOfnchar = 0;
324
    int32_t numOfOutputCols = pQueryInfo->fieldsInfo.numOfOutputCols;
H
hzcheng 已提交
325 326

    for (int32_t i = 0; i < numOfOutputCols; ++i) {
327
      TAOS_FIELD* pField = tscFieldInfoGetField(pQueryInfo, i);
H
hzcheng 已提交
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
      if (pField->type == TSDB_DATA_TYPE_NCHAR) {
        pRes->numOfnchar++;
      }
    }

    pRes->tsrow = calloc(1, (POINTER_BYTES + sizeof(short)) * numOfOutputCols + POINTER_BYTES * pRes->numOfnchar);
    if (pRes->tsrow == NULL) {
      pRes->code = TSDB_CODE_CLI_OUT_OF_MEMORY;
      return pRes->code;
    }

    pRes->bytes = (short*)((char*)pRes->tsrow + POINTER_BYTES * numOfOutputCols);
    if (pRes->numOfnchar > 0) {
      pRes->buffer = (char**)((char*)pRes->bytes + sizeof(short) * numOfOutputCols);
    }
  }

  return TSDB_CODE_SUCCESS;
}

void tscDestroyResPointerInfo(SSqlRes* pRes) {
  // free all buffers containing the multibyte string
  for (int i = 0; i < pRes->numOfnchar; i++) {
    if (pRes->buffer[i] != NULL) {
      tfree(pRes->buffer[i]);
    }
  }

  tfree(pRes->tsrow);

  pRes->numOfnchar = 0;
  pRes->buffer = NULL;
  pRes->bytes = NULL;
}

S
slguan 已提交
363
void tscFreeSqlCmdData(SSqlCmd* pCmd) {
S
slguan 已提交
364
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
365
  tscFreeSubqueryInfo(pCmd);
H
hzcheng 已提交
366 367 368
}

void tscFreeSqlObjPartial(SSqlObj* pSql) {
S
slguan 已提交
369 370 371
  if (pSql == NULL || pSql->signature != pSql) {
    return;
  }
H
hzcheng 已提交
372 373 374 375 376 377 378

  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;

  STscObj* pObj = pSql->pTscObj;

  int32_t cmd = pCmd->command;
S
slguan 已提交
379 380
  if (cmd < TSDB_SQL_INSERT || cmd == TSDB_SQL_RETRIEVE_METRIC || cmd == TSDB_SQL_RETRIEVE_EMPTY_RESULT ||
      cmd == TSDB_SQL_METRIC_JOIN_RETRIEVE) {
H
hzcheng 已提交
381 382 383
    tscRemoveFromSqlList(pSql);
  }

384
  pCmd->command = 0;
S
slguan 已提交
385

H
hzcheng 已提交
386 387 388 389 390
  // pSql->sqlstr will be used by tscBuildQueryStreamDesc
  pthread_mutex_lock(&pObj->mutex);
  tfree(pSql->sqlstr);
  pthread_mutex_unlock(&pObj->mutex);

391 392 393 394
  tfree(pRes->pRsp);
  pRes->row = 0;
  pRes->numOfRows = 0;
  pRes->numOfTotal = 0;
H
hjxilinx 已提交
395
  pRes->numOfTotalInCurrentClause = 0;
396

397 398
  pRes->numOfGroups = 0;
  tfree(pRes->pGroupRec);
H
hzcheng 已提交
399 400 401 402 403 404

  tscDestroyLocalReducer(pSql);

  tfree(pSql->pSubs);
  pSql->numOfSubs = 0;
  tscDestroyResPointerInfo(pRes);
405
  tfree(pRes->pColumnIndex);
H
hzcheng 已提交
406

S
slguan 已提交
407
  tscFreeSqlCmdData(pCmd);
H
hzcheng 已提交
408 409 410 411 412 413 414 415 416 417 418 419
}

void tscFreeSqlObj(SSqlObj* pSql) {
  if (pSql == NULL || pSql->signature != pSql) return;

  tscTrace("%p start to free sql object", pSql);
  tscFreeSqlObjPartial(pSql);

  pSql->signature = NULL;
  pSql->fp = NULL;
  SSqlCmd* pCmd = &pSql->cmd;

S
slguan 已提交
420
  memset(pCmd->payload, 0, (size_t)pCmd->allocSize);
H
hzcheng 已提交
421 422 423 424 425
  tfree(pCmd->payload);

  pCmd->allocSize = 0;

  if (pSql->res.buffer != NULL) {
426 427 428
    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

    for (int i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; i++) {
H
hzcheng 已提交
429 430 431 432 433 434 435 436 437
      if (pSql->res.buffer[i] != NULL) {
        tfree(pSql->res.buffer[i]);
      }
    }

    tfree(pSql->res.buffer);
  }

  if (pSql->fp == NULL) {
S
slguan 已提交
438 439
    tsem_destroy(&pSql->rspSem);
    tsem_destroy(&pSql->emptyRspSem);
H
hzcheng 已提交
440 441 442 443
  }
  free(pSql);
}

S
slguan 已提交
444 445
void tscDestroyDataBlock(STableDataBlocks* pDataBlock) {
  if (pDataBlock == NULL) {
H
hzcheng 已提交
446 447 448
    return;
  }

S
slguan 已提交
449
  tfree(pDataBlock->pData);
S
slguan 已提交
450
  tfree(pDataBlock->params);
H
hjxilinx 已提交
451

H
hjxilinx 已提交
452
  // free the refcount for metermeta
H
hjxilinx 已提交
453
  taosRemoveDataFromCache(tscCacheHandle, (void**)&(pDataBlock->pMeterMeta), false);
S
slguan 已提交
454
  tfree(pDataBlock);
H
hzcheng 已提交
455 456
}

457 458
SParamInfo* tscAddParamToDataBlock(STableDataBlocks* pDataBlock, char type, uint8_t timePrec, short bytes,
                                   uint32_t offset) {
S
slguan 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
  uint32_t needed = pDataBlock->numOfParams + 1;
  if (needed > pDataBlock->numOfAllocedParams) {
    needed *= 2;
    void* tmp = realloc(pDataBlock->params, needed * sizeof(SParamInfo));
    if (tmp == NULL) {
      return NULL;
    }
    pDataBlock->params = (SParamInfo*)tmp;
    pDataBlock->numOfAllocedParams = needed;
  }

  SParamInfo* param = pDataBlock->params + pDataBlock->numOfParams;
  param->idx = -1;
  param->type = type;
  param->timePrec = timePrec;
  param->bytes = bytes;
  param->offset = offset;

  ++pDataBlock->numOfParams;
  return param;
}

H
hzcheng 已提交
481 482 483 484
SDataBlockList* tscCreateBlockArrayList() {
  const int32_t DEFAULT_INITIAL_NUM_OF_BLOCK = 16;

  SDataBlockList* pDataBlockArrayList = calloc(1, sizeof(SDataBlockList));
S
slguan 已提交
485 486 487
  if (pDataBlockArrayList == NULL) {
    return NULL;
  }
H
hzcheng 已提交
488 489
  pDataBlockArrayList->nAlloc = DEFAULT_INITIAL_NUM_OF_BLOCK;
  pDataBlockArrayList->pData = calloc(1, POINTER_BYTES * pDataBlockArrayList->nAlloc);
S
slguan 已提交
490 491 492 493
  if (pDataBlockArrayList->pData == NULL) {
    free(pDataBlockArrayList);
    return NULL;
  }
H
hzcheng 已提交
494 495 496 497

  return pDataBlockArrayList;
}

498
void tscAppendDataBlock(SDataBlockList* pList, STableDataBlocks* pBlocks) {
S
slguan 已提交
499
  if (pList->nSize >= pList->nAlloc) {
H
hjxilinx 已提交
500 501
    pList->nAlloc = (pList->nAlloc) << 1U;
    pList->pData = realloc(pList->pData, POINTER_BYTES * (size_t)pList->nAlloc);
S
slguan 已提交
502 503

    // reset allocated memory
H
hjxilinx 已提交
504
    memset(pList->pData + pList->nSize, 0, POINTER_BYTES * (pList->nAlloc - pList->nSize));
S
slguan 已提交
505 506 507 508 509
  }

  pList->pData[pList->nSize++] = pBlocks;
}

S
slguan 已提交
510 511 512
void* tscDestroyBlockArrayList(SDataBlockList* pList) {
  if (pList == NULL) {
    return NULL;
H
hzcheng 已提交
513 514
  }

S
slguan 已提交
515 516
  for (int32_t i = 0; i < pList->nSize; i++) {
    tscDestroyDataBlock(pList->pData[i]);
H
hzcheng 已提交
517 518
  }

S
slguan 已提交
519 520 521 522
  tfree(pList->pData);
  tfree(pList);

  return NULL;
H
hzcheng 已提交
523 524
}

S
slguan 已提交
525
int32_t tscCopyDataBlockToPayload(SSqlObj* pSql, STableDataBlocks* pDataBlock) {
H
hjxilinx 已提交
526
  SSqlCmd* pCmd = &pSql->cmd;
H
hjxilinx 已提交
527
  assert(pDataBlock->pMeterMeta != NULL);
H
hjxilinx 已提交
528

529
  pCmd->numOfTablesInSubmit = pDataBlock->numOfMeters;
530

531 532
  assert(pCmd->numOfClause == 1);
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfo(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
533 534

  // set the correct metermeta object, the metermeta has been locked in pDataBlocks, so it must be in the cache
H
hjxilinx 已提交
535 536
  if (pMeterMetaInfo->pMeterMeta != pDataBlock->pMeterMeta) {
    strcpy(pMeterMetaInfo->name, pDataBlock->meterId);
H
hjxilinx 已提交
537
    taosRemoveDataFromCache(tscCacheHandle, (void**)&(pMeterMetaInfo->pMeterMeta), false);
538 539

    pMeterMetaInfo->pMeterMeta = taosTransferDataInCache(tscCacheHandle, (void**)&pDataBlock->pMeterMeta);
H
hjxilinx 已提交
540 541 542
  } else {
    assert(strncmp(pMeterMetaInfo->name, pDataBlock->meterId, tListLen(pDataBlock->meterId)) == 0);
  }
H
hjxilinx 已提交
543

544 545 546 547 548
  /*
   * the submit message consists of : [RPC header|message body|digest]
   * the dataBlock only includes the RPC Header buffer and actual submit messsage body, space for digest needs
   * additional space.
   */
S
slguan 已提交
549
  int ret = tscAllocPayload(pCmd, pDataBlock->nAllocSize + sizeof(STaosDigest));
H
hjxilinx 已提交
550 551 552
  if (TSDB_CODE_SUCCESS != ret) {
    return ret;
  }
H
hjxilinx 已提交
553

H
hzcheng 已提交
554
  memcpy(pCmd->payload, pDataBlock->pData, pDataBlock->nAllocSize);
H
hjxilinx 已提交
555

556 557 558 559 560
  /*
   * the payloadLen should be actual message body size
   * the old value of payloadLen is the allocated payload size
   */
  pCmd->payloadLen = pDataBlock->nAllocSize - tsRpcHeadSize;
H
hjxilinx 已提交
561

562
  assert(pCmd->allocSize >= pCmd->payloadLen + tsRpcHeadSize + sizeof(STaosDigest));
H
hjxilinx 已提交
563
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
564 565 566 567 568
}

void tscFreeUnusedDataBlocks(SDataBlockList* pList) {
  /* release additional memory consumption */
  for (int32_t i = 0; i < pList->nSize; ++i) {
S
slguan 已提交
569 570 571
    STableDataBlocks* pDataBlock = pList->pData[i];
    pDataBlock->pData = realloc(pDataBlock->pData, pDataBlock->size);
    pDataBlock->nAllocSize = (uint32_t)pDataBlock->size;
H
hzcheng 已提交
572 573 574
  }
}

H
hjxilinx 已提交
575 576 577 578 579 580
/**
 * create the in-memory buffer for each table to keep the submitted data block
 * @param initialSize
 * @param rowSize
 * @param startOffset
 * @param name
H
hjxilinx 已提交
581
 * @param dataBlocks
H
hjxilinx 已提交
582 583
 * @return
 */
H
hjxilinx 已提交
584
int32_t tscCreateDataBlock(size_t initialSize, int32_t rowSize, int32_t startOffset, const char* name,
585
                           SMeterMeta* pMeterMeta, STableDataBlocks** dataBlocks) {
H
hjxilinx 已提交
586
  STableDataBlocks* dataBuf = (STableDataBlocks*)calloc(1, sizeof(STableDataBlocks));
H
hjxilinx 已提交
587 588 589 590 591 592
  if (dataBuf == NULL) {
    tscError("failed to allocated memory, reason:%s", strerror(errno));
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }

  dataBuf->nAllocSize = (uint32_t)initialSize;
H
hjxilinx 已提交
593 594 595
  dataBuf->pData = calloc(1, dataBuf->nAllocSize);
  dataBuf->ordered = true;
  dataBuf->prevTS = INT64_MIN;
S
slguan 已提交
596 597 598

  dataBuf->rowSize = rowSize;
  dataBuf->size = startOffset;
S
slguan 已提交
599 600
  dataBuf->tsSource = -1;

S
slguan 已提交
601
  strncpy(dataBuf->meterId, name, TSDB_METER_ID_LEN);
H
hjxilinx 已提交
602 603 604

  /*
   * The metermeta may be released since the metermeta cache are completed clean by other thread
605 606
   * due to operation such as drop database. So here we add the reference count directly instead of invoke
   * taosGetDataFromCache, which may return NULL value.
H
hjxilinx 已提交
607
   */
608 609
  dataBuf->pMeterMeta = taosGetDataFromExists(tscCacheHandle, pMeterMeta);
  assert(initialSize > 0 && pMeterMeta != NULL && dataBuf->pMeterMeta != NULL);
610

611 612
  *dataBlocks = dataBuf;
  return TSDB_CODE_SUCCESS;
S
slguan 已提交
613 614
}

H
hjxilinx 已提交
615
int32_t tscGetDataBlockFromList(void* pHashList, SDataBlockList* pDataBlockList, int64_t id, int32_t size,
616
                                int32_t startOffset, int32_t rowSize, const char* tableId, SMeterMeta* pMeterMeta,
H
hjxilinx 已提交
617 618
                                STableDataBlocks** dataBlocks) {
  *dataBlocks = NULL;
S
slguan 已提交
619

620
  STableDataBlocks** t1 = (STableDataBlocks**)taosGetDataFromHash(pHashList, (const char*)&id, sizeof(id));
S
slguan 已提交
621
  if (t1 != NULL) {
H
hjxilinx 已提交
622
    *dataBlocks = *t1;
S
slguan 已提交
623 624
  }

H
hjxilinx 已提交
625
  if (*dataBlocks == NULL) {
626
    int32_t ret = tscCreateDataBlock((size_t)size, rowSize, startOffset, tableId, pMeterMeta, dataBlocks);
H
hjxilinx 已提交
627 628 629 630
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }

631
    taosAddToHashTable(pHashList, (const char*)&id, sizeof(int64_t), (char*)dataBlocks, POINTER_BYTES);
H
hjxilinx 已提交
632
    tscAppendDataBlock(pDataBlockList, *dataBlocks);
S
slguan 已提交
633 634
  }

H
hjxilinx 已提交
635
  return TSDB_CODE_SUCCESS;
S
slguan 已提交
636 637
}

S
slguan 已提交
638 639 640
int32_t tscMergeTableDataBlocks(SSqlObj* pSql, SDataBlockList* pTableDataBlockList) {
  SSqlCmd* pCmd = &pSql->cmd;

641
  void* pVnodeDataBlockHashList = taosInitHashTable(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false);
S
slguan 已提交
642 643 644 645
  SDataBlockList* pVnodeDataBlockList = tscCreateBlockArrayList();

  for (int32_t i = 0; i < pTableDataBlockList->nSize; ++i) {
    STableDataBlocks* pOneTableBlock = pTableDataBlockList->pData[i];
S
slguan 已提交
646

H
hjxilinx 已提交
647
    STableDataBlocks* dataBuf = NULL;
648 649 650
    int32_t           ret =
        tscGetDataBlockFromList(pVnodeDataBlockHashList, pVnodeDataBlockList, pOneTableBlock->vgid, TSDB_PAYLOAD_SIZE,
                                tsInsertHeadSize, 0, pOneTableBlock->meterId, pOneTableBlock->pMeterMeta, &dataBuf);
H
hjxilinx 已提交
651
    if (ret != TSDB_CODE_SUCCESS) {
652 653 654
      tscError("%p failed to prepare the data block buffer for merging table data, code:%d", pSql, ret);
      taosCleanUpHashTable(pVnodeDataBlockHashList);
      tscDestroyBlockArrayList(pVnodeDataBlockList);
H
hjxilinx 已提交
655 656
      return ret;
    }
S
slguan 已提交
657 658 659 660 661 662 663 664 665 666 667

    int64_t destSize = dataBuf->size + pOneTableBlock->size;
    if (dataBuf->nAllocSize < destSize) {
      while (dataBuf->nAllocSize < destSize) {
        dataBuf->nAllocSize = dataBuf->nAllocSize * 1.5;
      }

      char* tmp = realloc(dataBuf->pData, dataBuf->nAllocSize);
      if (tmp != NULL) {
        dataBuf->pData = tmp;
        memset(dataBuf->pData + dataBuf->size, 0, dataBuf->nAllocSize - dataBuf->size);
668
      } else {  // failed to allocate memory, free already allocated memory and return error code
S
slguan 已提交
669 670
        tscError("%p failed to allocate memory for merging submit block, size:%d", pSql, dataBuf->nAllocSize);

671
        taosCleanUpHashTable(pVnodeDataBlockHashList);
S
slguan 已提交
672 673 674 675
        tfree(dataBuf->pData);
        tscDestroyBlockArrayList(pVnodeDataBlockList);

        return TSDB_CODE_CLI_OUT_OF_MEMORY;
S
slguan 已提交
676 677 678 679
      }
    }

    SShellSubmitBlock* pBlocks = (SShellSubmitBlock*)pOneTableBlock->pData;
S
slguan 已提交
680
    sortRemoveDuplicates(pOneTableBlock);
S
slguan 已提交
681

S
slguan 已提交
682 683
    tscTrace("%p meterId:%s, sid:%d, rows:%d, sversion:%d", pSql, pOneTableBlock->meterId, pBlocks->sid,
             pBlocks->numOfRows, pBlocks->sversion);
S
slguan 已提交
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701

    pBlocks->sid = htonl(pBlocks->sid);
    pBlocks->uid = htobe64(pBlocks->uid);
    pBlocks->sversion = htonl(pBlocks->sversion);
    pBlocks->numOfRows = htons(pBlocks->numOfRows);

    memcpy(dataBuf->pData + dataBuf->size, pOneTableBlock->pData, pOneTableBlock->size);

    dataBuf->size += pOneTableBlock->size;
    dataBuf->numOfMeters += 1;
  }

  tscDestroyBlockArrayList(pTableDataBlockList);

  // free the table data blocks;
  pCmd->pDataBlocks = pVnodeDataBlockList;

  tscFreeUnusedDataBlocks(pCmd->pDataBlocks);
702
  taosCleanUpHashTable(pVnodeDataBlockHashList);
S
slguan 已提交
703 704

  return TSDB_CODE_SUCCESS;
S
slguan 已提交
705 706
}

H
hzcheng 已提交
707 708 709 710 711 712 713 714 715 716 717 718 719 720
void tscCloseTscObj(STscObj* pObj) {
  pObj->signature = NULL;
  SSqlObj* pSql = pObj->pSql;
  globalCode = pSql->res.code;

  taosTmrStopA(&(pObj->pTimer));
  tscFreeSqlObj(pSql);

  pthread_mutex_destroy(&pObj->mutex);
  tscTrace("%p DB connection is closed", pObj);
  tfree(pObj);
}

bool tscIsInsertOrImportData(char* sqlstr) {
721 722 723 724 725 726 727 728
  int32_t index = 0;

  do {
    SSQLToken t0 = tStrGetToken(sqlstr, &index, false, 0, NULL);
    if (t0.type != TK_LP) {
      return t0.type == TK_INSERT || t0.type == TK_IMPORT;
    }
  } while (1);
H
hzcheng 已提交
729 730
}

S
slguan 已提交
731
int tscAllocPayload(SSqlCmd* pCmd, int size) {
H
hzcheng 已提交
732 733 734 735 736
  assert(size > 0);

  if (pCmd->payload == NULL) {
    assert(pCmd->allocSize == 0);

S
slguan 已提交
737
    pCmd->payload = (char*)malloc(size);
H
hzcheng 已提交
738 739 740 741
    if (pCmd->payload == NULL) return TSDB_CODE_CLI_OUT_OF_MEMORY;
    pCmd->allocSize = size;
  } else {
    if (pCmd->allocSize < size) {
742
      char* b = realloc(pCmd->payload, size);
S
slguan 已提交
743 744
      if (b == NULL) return TSDB_CODE_CLI_OUT_OF_MEMORY;
      pCmd->payload = b;
H
hzcheng 已提交
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
      pCmd->allocSize = size;
    }
  }

  memset(pCmd->payload, 0, pCmd->allocSize);
  assert(pCmd->allocSize >= size);

  return TSDB_CODE_SUCCESS;
}

static void ensureSpace(SFieldInfo* pFieldInfo, int32_t size) {
  if (size > pFieldInfo->numOfAlloc) {
    int32_t oldSize = pFieldInfo->numOfAlloc;

    int32_t newSize = (oldSize <= 0) ? 8 : (oldSize << 1);
    while (newSize < size) {
      newSize = (newSize << 1);
    }

    if (newSize > TSDB_MAX_COLUMNS) {
      newSize = TSDB_MAX_COLUMNS;
    }

    int32_t inc = newSize - oldSize;

    pFieldInfo->pFields = realloc(pFieldInfo->pFields, newSize * sizeof(TAOS_FIELD));
    memset(&pFieldInfo->pFields[oldSize], 0, inc * sizeof(TAOS_FIELD));

    pFieldInfo->pOffset = realloc(pFieldInfo->pOffset, newSize * sizeof(int16_t));
    memset(&pFieldInfo->pOffset[oldSize], 0, inc * sizeof(int16_t));

S
slguan 已提交
776 777
    pFieldInfo->pVisibleCols = realloc(pFieldInfo->pVisibleCols, newSize * sizeof(bool));

H
hzcheng 已提交
778 779 780 781 782 783 784 785 786 787 788
    pFieldInfo->numOfAlloc = newSize;
  }
}

static void evic(SFieldInfo* pFieldInfo, int32_t index) {
  if (index < pFieldInfo->numOfOutputCols) {
    memmove(&pFieldInfo->pFields[index + 1], &pFieldInfo->pFields[index],
            sizeof(pFieldInfo->pFields[0]) * (pFieldInfo->numOfOutputCols - index));
  }
}

H
hjxilinx 已提交
789
static void setValueImpl(TAOS_FIELD* pField, int8_t type, const char* name, int16_t bytes) {
H
hzcheng 已提交
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
  pField->type = type;
  strncpy(pField->name, name, TSDB_COL_NAME_LEN);
  pField->bytes = bytes;
}

void tscFieldInfoSetValFromSchema(SFieldInfo* pFieldInfo, int32_t index, SSchema* pSchema) {
  ensureSpace(pFieldInfo, pFieldInfo->numOfOutputCols + 1);
  evic(pFieldInfo, index);

  TAOS_FIELD* pField = &pFieldInfo->pFields[index];
  setValueImpl(pField, pSchema->type, pSchema->name, pSchema->bytes);
  pFieldInfo->numOfOutputCols++;
}

void tscFieldInfoSetValFromField(SFieldInfo* pFieldInfo, int32_t index, TAOS_FIELD* pField) {
  ensureSpace(pFieldInfo, pFieldInfo->numOfOutputCols + 1);
  evic(pFieldInfo, index);

  memcpy(&pFieldInfo->pFields[index], pField, sizeof(TAOS_FIELD));
S
slguan 已提交
809 810
  pFieldInfo->pVisibleCols[index] = true;

H
hzcheng 已提交
811 812 813
  pFieldInfo->numOfOutputCols++;
}

S
slguan 已提交
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
void tscFieldInfoUpdateVisible(SFieldInfo* pFieldInfo, int32_t index, bool visible) {
  if (index < 0 || index > pFieldInfo->numOfOutputCols) {
    return;
  }

  bool oldVisible = pFieldInfo->pVisibleCols[index];
  pFieldInfo->pVisibleCols[index] = visible;

  if (oldVisible != visible) {
    if (!visible) {
      pFieldInfo->numOfHiddenCols += 1;
    } else {
      if (pFieldInfo->numOfHiddenCols > 0) {
        pFieldInfo->numOfHiddenCols -= 1;
      }
    }
  }
}

H
hjxilinx 已提交
833
void tscFieldInfoSetValue(SFieldInfo* pFieldInfo, int32_t index, int8_t type, const char* name, int16_t bytes) {
H
hzcheng 已提交
834 835 836 837 838
  ensureSpace(pFieldInfo, pFieldInfo->numOfOutputCols + 1);
  evic(pFieldInfo, index);

  TAOS_FIELD* pField = &pFieldInfo->pFields[index];
  setValueImpl(pField, type, name, bytes);
S
slguan 已提交
839 840

  pFieldInfo->pVisibleCols[index] = true;
H
hzcheng 已提交
841 842 843
  pFieldInfo->numOfOutputCols++;
}

844 845
void tscFieldInfoCalOffset(SQueryInfo* pQueryInfo) {
  SFieldInfo* pFieldInfo = &pQueryInfo->fieldsInfo;
H
hzcheng 已提交
846 847 848 849 850 851 852
  pFieldInfo->pOffset[0] = 0;

  for (int32_t i = 1; i < pFieldInfo->numOfOutputCols; ++i) {
    pFieldInfo->pOffset[i] = pFieldInfo->pOffset[i - 1] + pFieldInfo->pFields[i - 1].bytes;
  }
}

853
void tscFieldInfoUpdateOffsetForInterResult(SQueryInfo* pQueryInfo) {
854
  SFieldInfo* pFieldInfo = &pQueryInfo->fieldsInfo;
H
hzcheng 已提交
855 856 857 858 859 860 861 862 863 864 865
  if (pFieldInfo->numOfOutputCols == 0) {
    return;
  }

  pFieldInfo->pOffset[0] = 0;

  /*
   * the retTypeLen is used to store the intermediate result length
   * for potential secondary merge exists
   */
  for (int32_t i = 1; i < pFieldInfo->numOfOutputCols; ++i) {
866
    pFieldInfo->pOffset[i] = pFieldInfo->pOffset[i - 1] + tscSqlExprGet(pQueryInfo, i - 1)->resBytes;
H
hzcheng 已提交
867 868 869
  }
}

S
slguan 已提交
870
void tscFieldInfoCopy(SFieldInfo* src, SFieldInfo* dst, const int32_t* indexList, int32_t size) {
H
hzcheng 已提交
871 872 873 874
  if (src == NULL) {
    return;
  }

S
slguan 已提交
875 876
  if (size <= 0) {
    *dst = *src;
877
    tscFieldInfoCopyAll(dst, src);
S
slguan 已提交
878 879 880 881 882 883 884 885
  } else {  // only copy the required column
    for (int32_t i = 0; i < size; ++i) {
      assert(indexList[i] >= 0 && indexList[i] <= src->numOfOutputCols);
      tscFieldInfoSetValFromField(dst, i, &src->pFields[indexList[i]]);
    }
  }
}

886
void tscFieldInfoCopyAll(SFieldInfo* dst, SFieldInfo* src) {
H
hzcheng 已提交
887 888 889 890
  *dst = *src;

  dst->pFields = malloc(sizeof(TAOS_FIELD) * dst->numOfAlloc);
  dst->pOffset = malloc(sizeof(short) * dst->numOfAlloc);
S
slguan 已提交
891
  dst->pVisibleCols = malloc(sizeof(bool) * dst->numOfAlloc);
H
hzcheng 已提交
892 893 894

  memcpy(dst->pFields, src->pFields, sizeof(TAOS_FIELD) * dst->numOfOutputCols);
  memcpy(dst->pOffset, src->pOffset, sizeof(short) * dst->numOfOutputCols);
S
slguan 已提交
895
  memcpy(dst->pVisibleCols, src->pVisibleCols, sizeof(bool) * dst->numOfOutputCols);
H
hzcheng 已提交
896 897
}

898 899
TAOS_FIELD* tscFieldInfoGetField(SQueryInfo* pQueryInfo, int32_t index) {
  if (index >= pQueryInfo->fieldsInfo.numOfOutputCols) {
H
hzcheng 已提交
900 901 902
    return NULL;
  }

903
  return &pQueryInfo->fieldsInfo.pFields[index];
904 905
}

906
int32_t tscNumOfFields(SQueryInfo* pQueryInfo) { return pQueryInfo->fieldsInfo.numOfOutputCols; }
H
hzcheng 已提交
907

908 909
int16_t tscFieldInfoGetOffset(SQueryInfo* pQueryInfo, int32_t index) {
  if (index >= pQueryInfo->fieldsInfo.numOfOutputCols) {
H
hzcheng 已提交
910 911 912
    return 0;
  }

913
  return pQueryInfo->fieldsInfo.pOffset[index];
H
hzcheng 已提交
914 915
}

916 917
int32_t tscFieldInfoCompare(SFieldInfo* pFieldInfo1, SFieldInfo* pFieldInfo2) {
  assert(pFieldInfo1 != NULL && pFieldInfo2 != NULL);
918

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
  if (pFieldInfo1->numOfOutputCols != pFieldInfo2->numOfOutputCols) {
    return pFieldInfo1->numOfOutputCols - pFieldInfo2->numOfOutputCols;
  }

  for (int32_t i = 0; i < pFieldInfo1->numOfOutputCols; ++i) {
    TAOS_FIELD* pField1 = &pFieldInfo1->pFields[i];
    TAOS_FIELD* pField2 = &pFieldInfo2->pFields[i];

    if (pField1->type != pField2->type || pField1->bytes != pField2->bytes ||
        strcasecmp(pField1->name, pField2->name) != 0) {
      return 1;
    }
  }

  return 0;
}

936 937
int32_t tscGetResRowLength(SQueryInfo* pQueryInfo) {
  SFieldInfo* pFieldInfo = &pQueryInfo->fieldsInfo;
H
hzcheng 已提交
938 939 940 941 942 943 944 945
  if (pFieldInfo->numOfOutputCols <= 0) {
    return 0;
  }

  return pFieldInfo->pOffset[pFieldInfo->numOfOutputCols - 1] +
         pFieldInfo->pFields[pFieldInfo->numOfOutputCols - 1].bytes;
}

S
slguan 已提交
946 947
void tscClearFieldInfo(SFieldInfo* pFieldInfo) {
  if (pFieldInfo == NULL) {
H
hzcheng 已提交
948 949 950
    return;
  }

S
slguan 已提交
951 952 953 954 955
  tfree(pFieldInfo->pOffset);
  tfree(pFieldInfo->pFields);
  tfree(pFieldInfo->pVisibleCols);

  memset(pFieldInfo, 0, sizeof(SFieldInfo));
H
hzcheng 已提交
956 957 958 959
}

static void _exprCheckSpace(SSqlExprInfo* pExprInfo, int32_t size) {
  if (size > pExprInfo->numOfAlloc) {
960
    uint32_t oldSize = pExprInfo->numOfAlloc;
H
hzcheng 已提交
961

962
    uint32_t newSize = (oldSize <= 0) ? 8 : (oldSize << 1U);
H
hzcheng 已提交
963
    while (newSize < size) {
964
      newSize = (newSize << 1U);
H
hzcheng 已提交
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
    }

    if (newSize > TSDB_MAX_COLUMNS) {
      newSize = TSDB_MAX_COLUMNS;
    }

    int32_t inc = newSize - oldSize;

    pExprInfo->pExprs = realloc(pExprInfo->pExprs, newSize * sizeof(SSqlExpr));
    memset(&pExprInfo->pExprs[oldSize], 0, inc * sizeof(SSqlExpr));

    pExprInfo->numOfAlloc = newSize;
  }
}

static void _exprEvic(SSqlExprInfo* pExprInfo, int32_t index) {
  if (index < pExprInfo->numOfExprs) {
    memmove(&pExprInfo->pExprs[index + 1], &pExprInfo->pExprs[index],
            sizeof(pExprInfo->pExprs[0]) * (pExprInfo->numOfExprs - index));
  }
}

987 988
SSqlExpr* tscSqlExprInsertEmpty(SQueryInfo* pQueryInfo, int32_t index, int16_t functionId) {
  SSqlExprInfo* pExprInfo = &pQueryInfo->exprsInfo;
H
hjxilinx 已提交
989

H
hjxilinx 已提交
990 991
  _exprCheckSpace(pExprInfo, pExprInfo->numOfExprs + 1);
  _exprEvic(pExprInfo, index);
H
hjxilinx 已提交
992

H
hjxilinx 已提交
993 994
  SSqlExpr* pExpr = &pExprInfo->pExprs[index];
  pExpr->functionId = functionId;
H
hjxilinx 已提交
995

H
hjxilinx 已提交
996 997 998 999
  pExprInfo->numOfExprs++;
  return pExpr;
}

1000 1001 1002
SSqlExpr* tscSqlExprInsert(SQueryInfo* pQueryInfo, int32_t index, int16_t functionId, SColumnIndex* pColIndex,
                           int16_t type, int16_t size, int16_t interSize) {
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, pColIndex->tableIndex);
S
slguan 已提交
1003

1004
  SSqlExprInfo* pExprInfo = &pQueryInfo->exprsInfo;
H
hzcheng 已提交
1005 1006 1007 1008 1009 1010

  _exprCheckSpace(pExprInfo, pExprInfo->numOfExprs + 1);
  _exprEvic(pExprInfo, index);

  SSqlExpr* pExpr = &pExprInfo->pExprs[index];

S
slguan 已提交
1011 1012
  pExpr->functionId = functionId;
  int16_t numOfCols = pMeterMetaInfo->pMeterMeta->numOfColumns;
H
hzcheng 已提交
1013

S
slguan 已提交
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
  // set the correct column index
  if (pColIndex->columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
    pExpr->colInfo.colId = TSDB_TBNAME_COLUMN_INDEX;
  } else {
    SSchema* pSchema = tsGetColumnSchema(pMeterMetaInfo->pMeterMeta, pColIndex->columnIndex);
    pExpr->colInfo.colId = pSchema->colId;
  }

  // tag columns require the column index revised.
  if (pColIndex->columnIndex >= numOfCols) {
    pColIndex->columnIndex -= numOfCols;
    pExpr->colInfo.flag = TSDB_COL_TAG;
H
hzcheng 已提交
1026
  } else {
S
slguan 已提交
1027 1028 1029 1030 1031
    if (pColIndex->columnIndex != TSDB_TBNAME_COLUMN_INDEX) {
      pExpr->colInfo.flag = TSDB_COL_NORMAL;
    } else {
      pExpr->colInfo.flag = TSDB_COL_TAG;
    }
H
hzcheng 已提交
1032 1033
  }

S
slguan 已提交
1034
  pExpr->colInfo.colIdx = pColIndex->columnIndex;
H
hzcheng 已提交
1035 1036
  pExpr->resType = type;
  pExpr->resBytes = size;
S
slguan 已提交
1037 1038
  pExpr->interResBytes = interSize;
  pExpr->uid = pMeterMetaInfo->pMeterMeta->uid;
H
hzcheng 已提交
1039 1040 1041 1042 1043

  pExprInfo->numOfExprs++;
  return pExpr;
}

1044 1045 1046 1047
SSqlExpr* tscSqlExprUpdate(SQueryInfo* pQueryInfo, int32_t index, int16_t functionId, int16_t srcColumnIndex,
                           int16_t type, int16_t size) {
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
  SSqlExprInfo*   pExprInfo = &pQueryInfo->exprsInfo;
H
hzcheng 已提交
1048 1049 1050 1051 1052 1053
  if (index > pExprInfo->numOfExprs) {
    return NULL;
  }

  SSqlExpr* pExpr = &pExprInfo->pExprs[index];

S
slguan 已提交
1054
  pExpr->functionId = functionId;
H
hzcheng 已提交
1055 1056

  pExpr->colInfo.colIdx = srcColumnIndex;
S
slguan 已提交
1057
  pExpr->colInfo.colId = tsGetColumnSchema(pMeterMetaInfo->pMeterMeta, srcColumnIndex)->colId;
H
hzcheng 已提交
1058 1059 1060 1061 1062 1063 1064

  pExpr->resType = type;
  pExpr->resBytes = size;

  return pExpr;
}

S
slguan 已提交
1065
void addExprParams(SSqlExpr* pExpr, char* argument, int32_t type, int32_t bytes, int16_t tableIndex) {
H
hzcheng 已提交
1066 1067 1068 1069 1070 1071
  if (pExpr == NULL || argument == NULL || bytes == 0) {
    return;
  }

  // set parameter value
  // transfer to tVariant from byte data/no ascii data
S
slguan 已提交
1072
  tVariantCreateFromBinary(&pExpr->param[pExpr->numOfParams], argument, bytes, type);
H
hzcheng 已提交
1073 1074 1075 1076 1077

  pExpr->numOfParams += 1;
  assert(pExpr->numOfParams <= 3);
}

1078 1079
SSqlExpr* tscSqlExprGet(SQueryInfo* pQueryInfo, int32_t index) {
  if (pQueryInfo->exprsInfo.numOfExprs <= index) {
H
hzcheng 已提交
1080 1081 1082
    return NULL;
  }

1083
  return &pQueryInfo->exprsInfo.pExprs[index];
H
hzcheng 已提交
1084 1085
}

S
slguan 已提交
1086
void tscSqlExprCopy(SSqlExprInfo* dst, const SSqlExprInfo* src, uint64_t tableuid) {
H
hzcheng 已提交
1087 1088 1089 1090 1091 1092 1093
  if (src == NULL) {
    return;
  }

  *dst = *src;

  dst->pExprs = malloc(sizeof(SSqlExpr) * dst->numOfAlloc);
S
slguan 已提交
1094 1095 1096 1097 1098 1099
  int16_t num = 0;
  for (int32_t i = 0; i < src->numOfExprs; ++i) {
    if (src->pExprs[i].uid == tableuid) {
      dst->pExprs[num++] = src->pExprs[i];
    }
  }
H
hzcheng 已提交
1100

S
slguan 已提交
1101
  dst->numOfExprs = num;
H
hzcheng 已提交
1102 1103 1104 1105 1106 1107 1108
  for (int32_t i = 0; i < dst->numOfExprs; ++i) {
    for (int32_t j = 0; j < src->pExprs[i].numOfParams; ++j) {
      tVariantAssign(&dst->pExprs[i].param[j], &src->pExprs[i].param[j]);
    }
  }
}

S
slguan 已提交
1109 1110 1111 1112 1113 1114 1115 1116
static void clearVal(SColumnBase* pBase) {
  memset(pBase, 0, sizeof(SColumnBase));

  pBase->colIndex.tableIndex = -2;
  pBase->colIndex.columnIndex = -2;
}

static void _cf_ensureSpace(SColumnBaseInfo* pcolList, int32_t size) {
H
hzcheng 已提交
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
  if (pcolList->numOfAlloc < size) {
    int32_t oldSize = pcolList->numOfAlloc;

    int32_t newSize = (oldSize <= 0) ? 8 : (oldSize << 1);
    while (newSize < size) {
      newSize = (newSize << 1);
    }

    if (newSize > TSDB_MAX_COLUMNS) {
      newSize = TSDB_MAX_COLUMNS;
    }

    int32_t inc = newSize - oldSize;

    pcolList->pColList = realloc(pcolList->pColList, newSize * sizeof(SColumnBase));
    memset(&pcolList->pColList[oldSize], 0, inc * sizeof(SColumnBase));

    pcolList->numOfAlloc = newSize;
  }
}

S
slguan 已提交
1138
static void _cf_evic(SColumnBaseInfo* pcolList, int32_t index) {
H
hzcheng 已提交
1139 1140 1141 1142
  if (index < pcolList->numOfCols) {
    memmove(&pcolList->pColList[index + 1], &pcolList->pColList[index],
            sizeof(SColumnBase) * (pcolList->numOfCols - index));

S
slguan 已提交
1143
    clearVal(&pcolList->pColList[index]);
H
hzcheng 已提交
1144 1145 1146
  }
}

S
slguan 已提交
1147 1148
SColumnBase* tscColumnBaseInfoGet(SColumnBaseInfo* pColumnBaseInfo, int32_t index) {
  if (pColumnBaseInfo == NULL || pColumnBaseInfo->numOfCols < index) {
H
hzcheng 已提交
1149 1150 1151
    return NULL;
  }

S
slguan 已提交
1152 1153 1154 1155 1156 1157 1158
  return &pColumnBaseInfo->pColList[index];
}

void tscColumnBaseInfoUpdateTableIndex(SColumnBaseInfo* pColList, int16_t tableIndex) {
  for (int32_t i = 0; i < pColList->numOfCols; ++i) {
    pColList->pColList[i].colIndex.tableIndex = tableIndex;
  }
H
hzcheng 已提交
1159 1160
}

S
slguan 已提交
1161
// todo refactor
1162 1163
SColumnBase* tscColumnBaseInfoInsert(SQueryInfo* pQueryInfo, SColumnIndex* pColIndex) {
  SColumnBaseInfo* pcolList = &pQueryInfo->colList;
H
hzcheng 已提交
1164

S
slguan 已提交
1165 1166
  // ignore the tbname column to be inserted into source list
  if (pColIndex->columnIndex < 0) {
H
hzcheng 已提交
1167 1168 1169
    return NULL;
  }

S
slguan 已提交
1170 1171
  int16_t col = pColIndex->columnIndex;

H
hzcheng 已提交
1172
  int32_t i = 0;
S
slguan 已提交
1173 1174 1175 1176 1177 1178 1179 1180
  while (i < pcolList->numOfCols) {
    if (pcolList->pColList[i].colIndex.columnIndex < col) {
      i++;
    } else if (pcolList->pColList[i].colIndex.tableIndex < pColIndex->tableIndex) {
      i++;
    } else {
      break;
    }
H
hzcheng 已提交
1181 1182
  }

S
slguan 已提交
1183 1184 1185
  SColumnIndex* pIndex = &pcolList->pColList[i].colIndex;
  if ((i < pcolList->numOfCols && (pIndex->columnIndex > col || pIndex->tableIndex != pColIndex->tableIndex)) ||
      (i >= pcolList->numOfCols)) {
H
hzcheng 已提交
1186 1187 1188
    _cf_ensureSpace(pcolList, pcolList->numOfCols + 1);
    _cf_evic(pcolList, i);

S
slguan 已提交
1189
    pcolList->pColList[i].colIndex = *pColIndex;
H
hzcheng 已提交
1190 1191 1192 1193 1194 1195
    pcolList->numOfCols++;
  }

  return &pcolList->pColList[i];
}

S
slguan 已提交
1196
void tscColumnFilterInfoCopy(SColumnFilterInfo* dst, const SColumnFilterInfo* src) {
H
hjxilinx 已提交
1197
  assert(src != NULL && dst != NULL);
S
slguan 已提交
1198 1199 1200 1201 1202 1203 1204 1205

  assert(src->filterOnBinary == 0 || src->filterOnBinary == 1);
  if (src->lowerRelOptr == TSDB_RELATION_INVALID && src->upperRelOptr == TSDB_RELATION_INVALID) {
    assert(0);
  }

  *dst = *src;
  if (dst->filterOnBinary) {
H
hjxilinx 已提交
1206 1207 1208 1209
    size_t len = (size_t)dst->len + 1;
    char*  pTmp = calloc(1, len);
    dst->pz = (int64_t)pTmp;
    memcpy((char*)dst->pz, (char*)src->pz, (size_t)len);
S
slguan 已提交
1210 1211 1212 1213
  }
}

void tscColumnBaseCopy(SColumnBase* dst, const SColumnBase* src) {
H
hjxilinx 已提交
1214
  assert(src != NULL && dst != NULL);
S
slguan 已提交
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229

  *dst = *src;

  if (src->numOfFilters > 0) {
    dst->filterInfo = calloc(1, src->numOfFilters * sizeof(SColumnFilterInfo));

    for (int32_t j = 0; j < src->numOfFilters; ++j) {
      tscColumnFilterInfoCopy(&dst->filterInfo[j], &src->filterInfo[j]);
    }
  } else {
    assert(src->filterInfo == NULL);
  }
}

void tscColumnBaseInfoCopy(SColumnBaseInfo* dst, const SColumnBaseInfo* src, int16_t tableIndex) {
H
hzcheng 已提交
1230 1231 1232 1233 1234
  if (src == NULL) {
    return;
  }

  *dst = *src;
S
slguan 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
  dst->pColList = calloc(1, sizeof(SColumnBase) * dst->numOfAlloc);

  int16_t num = 0;
  for (int32_t i = 0; i < src->numOfCols; ++i) {
    if (src->pColList[i].colIndex.tableIndex == tableIndex || tableIndex < 0) {
      dst->pColList[num] = src->pColList[i];

      if (dst->pColList[num].numOfFilters > 0) {
        dst->pColList[num].filterInfo = calloc(1, dst->pColList[num].numOfFilters * sizeof(SColumnFilterInfo));

        for (int32_t j = 0; j < dst->pColList[num].numOfFilters; ++j) {
          tscColumnFilterInfoCopy(&dst->pColList[num].filterInfo[j], &src->pColList[i].filterInfo[j]);
        }
      }

      num += 1;
    }
  }
H
hzcheng 已提交
1253

S
slguan 已提交
1254
  dst->numOfCols = num;
H
hzcheng 已提交
1255 1256
}

S
slguan 已提交
1257 1258 1259 1260 1261 1262 1263 1264
void tscColumnBaseInfoDestroy(SColumnBaseInfo* pColumnBaseInfo) {
  if (pColumnBaseInfo == NULL) {
    return;
  }

  assert(pColumnBaseInfo->numOfCols <= TSDB_MAX_COLUMNS);

  for (int32_t i = 0; i < pColumnBaseInfo->numOfCols; ++i) {
1265
    SColumnBase* pColBase = &(pColumnBaseInfo->pColList[i]);
S
slguan 已提交
1266 1267 1268 1269 1270 1271

    if (pColBase->numOfFilters > 0) {
      for (int32_t j = 0; j < pColBase->numOfFilters; ++j) {
        assert(pColBase->filterInfo[j].filterOnBinary == 0 || pColBase->filterInfo[j].filterOnBinary == 1);

        if (pColBase->filterInfo[j].filterOnBinary) {
H
hjxilinx 已提交
1272
          free((char*)pColBase->filterInfo[j].pz);
H
hjxilinx 已提交
1273
          pColBase->filterInfo[j].pz = 0;
S
slguan 已提交
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
        }
      }
    }

    tfree(pColBase->filterInfo);
  }

  tfree(pColumnBaseInfo->pColList);
}

1284 1285 1286
void tscColumnBaseInfoReserve(SColumnBaseInfo* pColumnBaseInfo, int32_t size) {
  _cf_ensureSpace(pColumnBaseInfo, size);
}
H
hzcheng 已提交
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302

/*
 * 1. normal name, not a keyword or number
 * 2. name with quote
 * 3. string with only one delimiter '.'.
 *
 * only_one_part
 * 'only_one_part'
 * first_part.second_part
 * first_part.'second_part'
 * 'first_part'.second_part
 * 'first_part'.'second_part'
 * 'first_part.second_part'
 *
 */
static int32_t validateQuoteToken(SSQLToken* pToken) {
H
huili 已提交
1303
  pToken->n = strdequote(pToken->z);
H
hzcheng 已提交
1304 1305 1306 1307
  strtrim(pToken->z);
  pToken->n = (uint32_t)strlen(pToken->z);

  int32_t k = tSQLGetToken(pToken->z, &pToken->type);
1308

H
huili 已提交
1309 1310
  if (pToken->type == TK_STRING) {
    return tscValidateName(pToken);
S
slguan 已提交
1311
  }
H
hzcheng 已提交
1312

H
huili 已提交
1313 1314 1315
  if (k != pToken->n || pToken->type != TK_ID) {
    return TSDB_CODE_INVALID_SQL;
  }
H
hzcheng 已提交
1316 1317 1318 1319 1320 1321 1322 1323
  return TSDB_CODE_SUCCESS;
}

int32_t tscValidateName(SSQLToken* pToken) {
  if (pToken->type != TK_STRING && pToken->type != TK_ID) {
    return TSDB_CODE_INVALID_SQL;
  }

S
slguan 已提交
1324
  char* sep = strnchr(pToken->z, TS_PATH_DELIMITER[0], pToken->n, true);
H
hzcheng 已提交
1325 1326
  if (sep == NULL) {  // single part
    if (pToken->type == TK_STRING) {
H
huili 已提交
1327 1328 1329
      pToken->n = strdequote(pToken->z);
      strtrim(pToken->z);
      pToken->n = (uint32_t)strlen(pToken->z);
S
slguan 已提交
1330 1331 1332 1333

      int len = tSQLGetToken(pToken->z, &pToken->type);

      // single token, validate it
1334
      if (len == pToken->n) {
H
huili 已提交
1335
        return validateQuoteToken(pToken);
S
slguan 已提交
1336
      } else {
1337 1338 1339 1340
        sep = strnchr(pToken->z, TS_PATH_DELIMITER[0], pToken->n, true);
        if (sep == NULL) {
          return TSDB_CODE_INVALID_SQL;
        }
S
slguan 已提交
1341

H
huili 已提交
1342
        return tscValidateName(pToken);
1343
      }
H
hzcheng 已提交
1344 1345 1346 1347 1348 1349 1350 1351 1352
    } else {
      if (isNumber(pToken)) {
        return TSDB_CODE_INVALID_SQL;
      }
    }
  } else {  // two part
    int32_t oldLen = pToken->n;
    char*   pStr = pToken->z;

H
huili 已提交
1353 1354
    if (pToken->type == TK_SPACE) {
      strtrim(pToken->z);
S
slguan 已提交
1355
      pToken->n = (uint32_t)strlen(pToken->z);
H
huili 已提交
1356 1357
    }

H
hzcheng 已提交
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
    pToken->n = tSQLGetToken(pToken->z, &pToken->type);
    if (pToken->z[pToken->n] != TS_PATH_DELIMITER[0]) {
      return TSDB_CODE_INVALID_SQL;
    }

    if (pToken->type != TK_STRING && pToken->type != TK_ID) {
      return TSDB_CODE_INVALID_SQL;
    }

    if (pToken->type == TK_STRING && validateQuoteToken(pToken) != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_INVALID_SQL;
    }

    int32_t firstPartLen = pToken->n;

    pToken->z = sep + 1;
    pToken->n = oldLen - (sep - pStr) - 1;
    int32_t len = tSQLGetToken(pToken->z, &pToken->type);
    if (len != pToken->n || (pToken->type != TK_STRING && pToken->type != TK_ID)) {
      return TSDB_CODE_INVALID_SQL;
    }

    if (pToken->type == TK_STRING && validateQuoteToken(pToken) != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_INVALID_SQL;
    }

    // re-build the whole name string
    if (pStr[firstPartLen] == TS_PATH_DELIMITER[0]) {
H
hjxilinx 已提交
1386
      // first part do not have quote do nothing
H
hzcheng 已提交
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
    } else {
      pStr[firstPartLen] = TS_PATH_DELIMITER[0];
      memmove(&pStr[firstPartLen + 1], pToken->z, pToken->n);
      pStr[firstPartLen + sizeof(TS_PATH_DELIMITER[0]) + pToken->n] = 0;
    }
    pToken->n += (firstPartLen + sizeof(TS_PATH_DELIMITER[0]));
    pToken->z = pStr;
  }

  return TSDB_CODE_SUCCESS;
}

void tscIncStreamExecutionCount(void* pStream) {
  if (pStream == NULL) {
    return;
  }

  SSqlStream* ps = (SSqlStream*)pStream;
  ps->num += 1;
}

1408
bool tscValidateColumnId(SMeterMetaInfo* pMeterMetaInfo, int32_t colId) {
S
slguan 已提交
1409
  if (pMeterMetaInfo->pMeterMeta == NULL) {
H
hzcheng 已提交
1410 1411 1412
    return false;
  }

1413
  if (colId == -1 && UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {
H
hzcheng 已提交
1414 1415 1416
    return true;
  }

S
slguan 已提交
1417 1418
  SSchema* pSchema = tsGetSchema(pMeterMetaInfo->pMeterMeta);
  int32_t  numOfTotal = pMeterMetaInfo->pMeterMeta->numOfTags + pMeterMetaInfo->pMeterMeta->numOfColumns;
H
hzcheng 已提交
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428

  for (int32_t i = 0; i < numOfTotal; ++i) {
    if (pSchema[i].colId == colId) {
      return true;
    }
  }

  return false;
}

S
slguan 已提交
1429 1430
void tscTagCondCopy(STagCond* dest, const STagCond* src) {
  memset(dest, 0, sizeof(STagCond));
H
hjxilinx 已提交
1431

H
hjxilinx 已提交
1432 1433 1434
  if (src->tbnameCond.cond != NULL) {
    dest->tbnameCond.cond = strdup(src->tbnameCond.cond);
  }
S
slguan 已提交
1435 1436 1437 1438 1439 1440

  dest->tbnameCond.uid = src->tbnameCond.uid;

  memcpy(&dest->joinInfo, &src->joinInfo, sizeof(SJoinInfo));

  for (int32_t i = 0; i < src->numOfTagCond; ++i) {
H
hjxilinx 已提交
1441 1442 1443
    if (src->cond[i].cond != NULL) {
      dest->cond[i].cond = strdup(src->cond[i].cond);
    }
H
hjxilinx 已提交
1444

S
slguan 已提交
1445
    dest->cond[i].uid = src->cond[i].uid;
H
hzcheng 已提交
1446 1447
  }

S
slguan 已提交
1448 1449
  dest->relType = src->relType;
  dest->numOfTagCond = src->numOfTagCond;
H
hzcheng 已提交
1450 1451 1452
}

void tscTagCondRelease(STagCond* pCond) {
H
hjxilinx 已提交
1453
  free(pCond->tbnameCond.cond);
S
slguan 已提交
1454
  for (int32_t i = 0; i < pCond->numOfTagCond; ++i) {
H
hjxilinx 已提交
1455
    free(pCond->cond[i].cond);
H
hzcheng 已提交
1456 1457 1458 1459 1460
  }

  memset(pCond, 0, sizeof(STagCond));
}

1461 1462
void tscGetSrcColumnInfo(SSrcColumnInfo* pColInfo, SQueryInfo* pQueryInfo) {
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
S
slguan 已提交
1463
  SSchema*        pSchema = tsGetSchema(pMeterMetaInfo->pMeterMeta);
H
hzcheng 已提交
1464

1465 1466
  for (int32_t i = 0; i < pQueryInfo->exprsInfo.numOfExprs; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
1467
    pColInfo[i].functionId = pExpr->functionId;
H
hzcheng 已提交
1468

S
slguan 已提交
1469 1470 1471
    if (TSDB_COL_IS_TAG(pExpr->colInfo.flag)) {
      SSchema* pTagSchema = tsGetTagSchema(pMeterMetaInfo->pMeterMeta);
      int16_t  actualTagIndex = pMeterMetaInfo->tagColumnIndex[pExpr->colInfo.colIdx];
H
hzcheng 已提交
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487

      pColInfo[i].type = (actualTagIndex != -1) ? pTagSchema[actualTagIndex].type : TSDB_DATA_TYPE_BINARY;
    } else {
      pColInfo[i].type = pSchema[pExpr->colInfo.colIdx].type;
    }
  }
}

void tscSetFreeHeatBeat(STscObj* pObj) {
  if (pObj == NULL || pObj->signature != pObj || pObj->pHb == NULL) {
    return;
  }

  SSqlObj* pHeatBeat = pObj->pHb;
  assert(pHeatBeat == pHeatBeat->signature);

S
slguan 已提交
1488
  // to denote the heart-beat timer close connection and free all allocated resources
1489 1490
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pHeatBeat->cmd, 0);
  pQueryInfo->type = TSDB_QUERY_TYPE_FREE_RESOURCE;
H
hzcheng 已提交
1491 1492 1493 1494
}

bool tscShouldFreeHeatBeat(SSqlObj* pHb) {
  assert(pHb == pHb->signature);
1495 1496 1497

  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pHb->cmd, 0);
  return pQueryInfo->type == TSDB_QUERY_TYPE_FREE_RESOURCE;
H
hzcheng 已提交
1498 1499 1500
}

void tscCleanSqlCmd(SSqlCmd* pCmd) {
1501 1502
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
  tscFreeSubqueryInfo(pCmd);
H
hzcheng 已提交
1503

S
slguan 已提交
1504 1505
  uint32_t allocSize = pCmd->allocSize;
  char*    allocPtr = pCmd->payload;
H
hzcheng 已提交
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555

  memset(pCmd, 0, sizeof(SSqlCmd));

  // restore values
  pCmd->allocSize = allocSize;
  pCmd->payload = allocPtr;
}

/*
 * the following three kinds of SqlObj should not be freed
 * 1. SqlObj for stream computing
 * 2. main SqlObj
 * 3. heartbeat SqlObj
 *
 * If res code is error and SqlObj does not belong to above types, it should be
 * automatically freed for async query, ignoring that connection should be kept.
 *
 * If connection need to be recycled, the SqlObj also should be freed.
 */
bool tscShouldFreeAsyncSqlObj(SSqlObj* pSql) {
  if (pSql == NULL || pSql->signature != pSql || pSql->fp == NULL) {
    return false;
  }

  STscObj* pTscObj = pSql->pTscObj;
  if (pSql->pStream != NULL || pTscObj->pHb == pSql) {
    return false;
  }

  int32_t command = pSql->cmd.command;
  if (pTscObj->pSql == pSql) {
    /*
     * in case of taos_connect_a query, the object should all be released, even it is the
     * master sql object. Otherwise, the master sql should not be released
     */
    if (command == TSDB_SQL_CONNECT && pSql->res.code != TSDB_CODE_SUCCESS) {
      return true;
    }

    return false;
  }

  if (command == TSDB_SQL_INSERT) {
    SSqlCmd* pCmd = &pSql->cmd;

    /*
     * in case of multi-vnode insertion, the object should not be released until all
     * data blocks have been submit to vnode.
     */
    SDataBlockList* pDataBlocks = pCmd->pDataBlocks;
1556
    SQueryInfo*     pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
H
hjxilinx 已提交
1557

1558
    SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
1559
    assert(pQueryInfo->numOfTables == 1 || pQueryInfo->numOfTables == 2);
H
hjxilinx 已提交
1560

H
hjxilinx 已提交
1561
    if (pDataBlocks == NULL || pMeterMetaInfo->vnodeIndex >= pDataBlocks->nSize) {
H
hzcheng 已提交
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
      tscTrace("%p object should be release since all data blocks have been submit", pSql);
      return true;
    } else {
      return false;
    }
  } else {
    return tscKeepConn[command] == 0 ||
           (pSql->res.code != TSDB_CODE_ACTION_IN_PROGRESS && pSql->res.code != TSDB_CODE_SUCCESS);
  }
}

1573 1574 1575
/**
 *
 * @param pCmd
1576
 * @param clauseIndex denote the index of the union sub clause, usually are 0, if no union query exists.
1577 1578 1579
 * @param tableIndex  denote the table index for join query, where more than one table exists
 * @return
 */
1580
SMeterMetaInfo* tscGetMeterMetaInfo(SSqlCmd* pCmd, int32_t clauseIndex, int32_t tableIndex) {
1581
  if (pCmd == NULL || pCmd->numOfClause == 0) {
S
slguan 已提交
1582 1583 1584
    return NULL;
  }

1585
  assert(clauseIndex >= 0 && clauseIndex < pCmd->numOfClause);
1586

1587
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, clauseIndex);
1588
  return tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, tableIndex);
S
slguan 已提交
1589 1590
}

1591
SMeterMetaInfo* tscGetMeterMetaInfoFromQueryInfo(SQueryInfo* pQueryInfo, int32_t tableIndex) {
H
hjxilinx 已提交
1592
  assert(pQueryInfo != NULL);
1593

1594 1595 1596 1597 1598
  if (pQueryInfo->pMeterInfo == NULL) {
    assert(pQueryInfo->numOfTables == 0);
    return NULL;
  }

H
hjxilinx 已提交
1599
  assert(tableIndex >= 0 && tableIndex <= pQueryInfo->numOfTables && pQueryInfo->pMeterInfo != NULL);
1600 1601 1602 1603 1604

  return pQueryInfo->pMeterInfo[tableIndex];
}

SQueryInfo* tscGetQueryInfoDetail(SSqlCmd* pCmd, int32_t subClauseIndex) {
1605
  assert(pCmd != NULL && subClauseIndex >= 0 && subClauseIndex < TSDB_MAX_UNION_CLAUSE);
1606

1607
  if (pCmd->pQueryInfo == NULL || subClauseIndex >= pCmd->numOfClause) {
1608 1609 1610 1611 1612 1613
    return NULL;
  }

  return pCmd->pQueryInfo[subClauseIndex];
}

1614
int32_t tscGetQueryInfoDetailSafely(SSqlCmd* pCmd, int32_t subClauseIndex, SQueryInfo** pQueryInfo) {
1615
  int32_t ret = TSDB_CODE_SUCCESS;
1616

1617
  *pQueryInfo = tscGetQueryInfoDetail(pCmd, subClauseIndex);
1618

1619 1620 1621 1622
  while ((*pQueryInfo) == NULL) {
    if ((ret = tscAddSubqueryInfo(pCmd)) != TSDB_CODE_SUCCESS) {
      return ret;
    }
1623

1624 1625
    (*pQueryInfo) = tscGetQueryInfoDetail(pCmd, subClauseIndex);
  }
1626

1627 1628 1629
  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
1630
SMeterMetaInfo* tscGetMeterMetaInfoByUid(SQueryInfo* pQueryInfo, uint64_t uid, int32_t* index) {
S
slguan 已提交
1631
  int32_t k = -1;
1632 1633 1634

  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
    if (pQueryInfo->pMeterInfo[i]->pMeterMeta->uid == uid) {
S
slguan 已提交
1635 1636 1637 1638 1639 1640 1641 1642 1643
      k = i;
      break;
    }
  }

  if (index != NULL) {
    *index = k;
  }

H
hjxilinx 已提交
1644
  assert(k != -1);
1645
  return tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, k);
S
slguan 已提交
1646 1647
}

1648
int32_t tscAddSubqueryInfo(SSqlCmd* pCmd) {
1649
  assert(pCmd != NULL);
1650 1651 1652

  size_t s = pCmd->numOfClause + 1;
  char*  tmp = realloc(pCmd->pQueryInfo, s * POINTER_BYTES);
1653 1654 1655
  if (tmp == NULL) {
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
1656 1657 1658 1659 1660 1661 1662

  pCmd->pQueryInfo = (SQueryInfo**)tmp;

  SQueryInfo* pQueryInfo = calloc(1, sizeof(SQueryInfo));
  pQueryInfo->msg = pCmd->payload;  // pointer to the parent error message buffer

  pCmd->pQueryInfo[pCmd->numOfClause++] = pQueryInfo;
1663 1664 1665
  return TSDB_CODE_SUCCESS;
}

1666
static void doClearSubqueryInfo(SQueryInfo* pQueryInfo) {
1667 1668
  tscTagCondRelease(&pQueryInfo->tagCond);
  tscClearFieldInfo(&pQueryInfo->fieldsInfo);
1669

1670 1671
  tfree(pQueryInfo->exprsInfo.pExprs);
  memset(&pQueryInfo->exprsInfo, 0, sizeof(pQueryInfo->exprsInfo));
1672

1673 1674
  tscColumnBaseInfoDestroy(&pQueryInfo->colList);
  memset(&pQueryInfo->colList, 0, sizeof(pQueryInfo->colList));
1675

1676
  pQueryInfo->tsBuf = tsBufDestory(pQueryInfo->tsBuf);
1677

1678
  tfree(pQueryInfo->defaultVal);
1679
}
1680

1681
void tscClearSubqueryInfo(SSqlCmd* pCmd) {
1682
  for (int32_t i = 0; i < pCmd->numOfClause; ++i) {
1683 1684
    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, i);
    doClearSubqueryInfo(pQueryInfo);
1685
  }
1686 1687 1688 1689 1690 1691 1692 1693
}

void tscFreeSubqueryInfo(SSqlCmd* pCmd) {
  if (pCmd == NULL || pCmd->numOfClause == 0) {
    return;
  }

  for (int32_t i = 0; i < pCmd->numOfClause; ++i) {
1694 1695 1696 1697
    char* addr = (char*)pCmd - offsetof(SSqlObj, cmd);

    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, i);

1698
    doClearSubqueryInfo(pQueryInfo);
1699
    tscRemoveAllMeterMetaInfo(pQueryInfo, (const char*)addr, false);
1700
    tfree(pQueryInfo);
1701
  }
1702

1703 1704 1705 1706
  pCmd->numOfClause = 0;
  tfree(pCmd->pQueryInfo);
}

1707
SMeterMetaInfo* tscAddMeterMetaInfo(SQueryInfo* pQueryInfo, const char* name, SMeterMeta* pMeterMeta,
1708 1709
                                    SMetricMeta* pMetricMeta, int16_t numOfTags, int16_t* tags) {
  void* pAlloc = realloc(pQueryInfo->pMeterInfo, (pQueryInfo->numOfTables + 1) * POINTER_BYTES);
S
slguan 已提交
1710 1711 1712 1713
  if (pAlloc == NULL) {
    return NULL;
  }

1714 1715
  pQueryInfo->pMeterInfo = pAlloc;
  pQueryInfo->pMeterInfo[pQueryInfo->numOfTables] = calloc(1, sizeof(SMeterMetaInfo));
S
slguan 已提交
1716

1717
  SMeterMetaInfo* pMeterMetaInfo = pQueryInfo->pMeterInfo[pQueryInfo->numOfTables];
S
slguan 已提交
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
  assert(pMeterMetaInfo != NULL);

  if (name != NULL) {
    assert(strlen(name) <= TSDB_METER_ID_LEN);
    strcpy(pMeterMetaInfo->name, name);
  }

  pMeterMetaInfo->pMeterMeta = pMeterMeta;
  pMeterMetaInfo->pMetricMeta = pMetricMeta;
  pMeterMetaInfo->numOfTags = numOfTags;

  if (tags != NULL) {
H
hjxilinx 已提交
1730
    memcpy(pMeterMetaInfo->tagColumnIndex, tags, sizeof(pMeterMetaInfo->tagColumnIndex[0]) * numOfTags);
S
slguan 已提交
1731 1732
  }

1733
  pQueryInfo->numOfTables += 1;
S
slguan 已提交
1734 1735 1736
  return pMeterMetaInfo;
}

1737 1738
SMeterMetaInfo* tscAddEmptyMeterMetaInfo(SQueryInfo* pQueryInfo) {
  return tscAddMeterMetaInfo(pQueryInfo, NULL, NULL, NULL, 0, NULL);
1739
}
S
slguan 已提交
1740

1741 1742
void doRemoveMeterMetaInfo(SQueryInfo* pQueryInfo, int32_t index, bool removeFromCache) {
  if (index < 0 || index >= pQueryInfo->numOfTables) {
S
slguan 已提交
1743 1744 1745
    return;
  }

1746
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index);
S
slguan 已提交
1747 1748 1749 1750

  tscClearMeterMetaInfo(pMeterMetaInfo, removeFromCache);
  free(pMeterMetaInfo);

1751
  int32_t after = pQueryInfo->numOfTables - index - 1;
S
slguan 已提交
1752
  if (after > 0) {
1753
    memmove(&pQueryInfo->pMeterInfo[index], &pQueryInfo->pMeterInfo[index + 1], after * POINTER_BYTES);
S
slguan 已提交
1754 1755
  }

1756
  pQueryInfo->numOfTables -= 1;
S
slguan 已提交
1757 1758
}

1759 1760
void tscRemoveAllMeterMetaInfo(SQueryInfo* pQueryInfo, const char* address, bool removeFromCache) {
  tscTrace("%p deref the metric/meter meta in cache, numOfTables:%d", address, pQueryInfo->numOfTables);
S
slguan 已提交
1761

1762 1763 1764
  int32_t index = pQueryInfo->numOfTables;
  while (index >= 0) {
    doRemoveMeterMetaInfo(pQueryInfo, --index, removeFromCache);
S
slguan 已提交
1765 1766
  }

1767
  tfree(pQueryInfo->pMeterInfo);
S
slguan 已提交
1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
}

void tscClearMeterMetaInfo(SMeterMetaInfo* pMeterMetaInfo, bool removeFromCache) {
  if (pMeterMetaInfo == NULL) {
    return;
  }

  taosRemoveDataFromCache(tscCacheHandle, (void**)&(pMeterMetaInfo->pMeterMeta), removeFromCache);
  taosRemoveDataFromCache(tscCacheHandle, (void**)&(pMeterMetaInfo->pMetricMeta), removeFromCache);
}

void tscResetForNextRetrieve(SSqlRes* pRes) {
H
hjxilinx 已提交
1780 1781 1782
  if (pRes == NULL) {
    return;
  }
1783

S
slguan 已提交
1784 1785 1786 1787
  pRes->row = 0;
  pRes->numOfRows = 0;
}

H
hjxilinx 已提交
1788
SSqlObj* createSubqueryObj(SSqlObj* pSql, int16_t tableIndex, void (*fp)(), void* param, SSqlObj* pPrevSql) {
H
hjxilinx 已提交
1789
  SSqlCmd*        pCmd = &pSql->cmd;
1790
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfo(pCmd, pCmd->clauseIndex, tableIndex);
S
slguan 已提交
1791 1792 1793

  SSqlObj* pNew = (SSqlObj*)calloc(1, sizeof(SSqlObj));
  if (pNew == NULL) {
H
hjxilinx 已提交
1794
    tscError("%p new subquery failed, tableIndex:%d, vnodeIndex:%d", pSql, tableIndex, pMeterMetaInfo->vnodeIndex);
S
slguan 已提交
1795 1796 1797 1798 1799 1800 1801 1802
    return NULL;
  }

  pNew->pTscObj = pSql->pTscObj;
  pNew->signature = pNew;

  pNew->sqlstr = strdup(pSql->sqlstr);
  if (pNew->sqlstr == NULL) {
H
hjxilinx 已提交
1803
    tscError("%p new subquery failed, tableIndex:%d, vnodeIndex:%d", pSql, tableIndex, pMeterMetaInfo->vnodeIndex);
S
slguan 已提交
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814

    free(pNew);
    return NULL;
  }

  memcpy(&pNew->cmd, pCmd, sizeof(SSqlCmd));

  pNew->cmd.command = TSDB_SQL_SELECT;
  pNew->cmd.payload = NULL;
  pNew->cmd.allocSize = 0;

1815
  pNew->cmd.pQueryInfo = NULL;
1816
  pNew->cmd.numOfClause = 0;
1817
  pNew->cmd.clauseIndex = 0;
1818 1819

  if (tscAddSubqueryInfo(&pNew->cmd) != TSDB_CODE_SUCCESS) {
1820 1821 1822
    tscFreeSqlObj(pNew);
    return NULL;
  }
1823 1824

  SQueryInfo* pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
1825
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
1826 1827 1828 1829 1830

  memcpy(pNewQueryInfo, pQueryInfo, sizeof(SQueryInfo));

  memset(&pNewQueryInfo->colList, 0, sizeof(pNewQueryInfo->colList));
  memset(&pNewQueryInfo->fieldsInfo, 0, sizeof(SFieldInfo));
1831

1832 1833
  pNewQueryInfo->pMeterInfo = NULL;
  pNewQueryInfo->defaultVal = NULL;
1834 1835 1836 1837
  pNewQueryInfo->numOfTables = 0;
  pNewQueryInfo->tsBuf = NULL;

  tscTagCondCopy(&pNewQueryInfo->tagCond, &pQueryInfo->tagCond);
1838

1839 1840 1841 1842
  if (pQueryInfo->interpoType != TSDB_INTERPO_NONE) {
    pNewQueryInfo->defaultVal = malloc(pQueryInfo->fieldsInfo.numOfOutputCols * sizeof(int64_t));
    memcpy(pNewQueryInfo->defaultVal, pQueryInfo->defaultVal, pQueryInfo->fieldsInfo.numOfOutputCols * sizeof(int64_t));
  }
1843

S
slguan 已提交
1844
  if (tscAllocPayload(&pNew->cmd, TSDB_DEFAULT_PAYLOAD_SIZE) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1845
    tscError("%p new subquery failed, tableIndex:%d, vnodeIndex:%d", pSql, tableIndex, pMeterMetaInfo->vnodeIndex);
S
slguan 已提交
1846 1847 1848 1849
    tscFreeSqlObj(pNew);
    return NULL;
  }

1850 1851
  tscColumnBaseInfoCopy(&pNewQueryInfo->colList, &pQueryInfo->colList, (int16_t)tableIndex);

S
slguan 已提交
1852 1853
  // set the correct query type
  if (pPrevSql != NULL) {
1854
    SQueryInfo* pPrevQueryInfo = tscGetQueryInfoDetail(&pPrevSql->cmd, pPrevSql->cmd.clauseIndex);
1855
    pNewQueryInfo->type = pPrevQueryInfo->type;
S
slguan 已提交
1856
  } else {
1857
    pNewQueryInfo->type |= TSDB_QUERY_TYPE_SUBQUERY;  // it must be the subquery
S
slguan 已提交
1858 1859 1860
  }

  uint64_t uid = pMeterMetaInfo->pMeterMeta->uid;
1861
  tscSqlExprCopy(&pNewQueryInfo->exprsInfo, &pQueryInfo->exprsInfo, uid);
S
slguan 已提交
1862

1863
  int32_t numOfOutputCols = pNewQueryInfo->exprsInfo.numOfExprs;
S
slguan 已提交
1864 1865 1866

  if (numOfOutputCols > 0) {
    int32_t* indexList = calloc(1, numOfOutputCols * sizeof(int32_t));
1867 1868
    for (int32_t i = 0, j = 0; i < pQueryInfo->exprsInfo.numOfExprs; ++i) {
      SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
1869 1870 1871 1872 1873
      if (pExpr->uid == uid) {
        indexList[j++] = i;
      }
    }

1874
    tscFieldInfoCopy(&pQueryInfo->fieldsInfo, &pNewQueryInfo->fieldsInfo, indexList, numOfOutputCols);
S
slguan 已提交
1875 1876
    free(indexList);

1877
    tscFieldInfoUpdateOffsetForInterResult(pNewQueryInfo);
S
slguan 已提交
1878 1879 1880 1881
  }

  pNew->fp = fp;
  pNew->param = param;
H
hjxilinx 已提交
1882

S
slguan 已提交
1883
  char key[TSDB_MAX_TAGS_LEN + 1] = {0};
H
hjxilinx 已提交
1884
  tscGetMetricMetaCacheKey(pQueryInfo, key, uid);
H
hjxilinx 已提交
1885

H
hjxilinx 已提交
1886 1887 1888
#ifdef _DEBUG_VIEW
  printf("the metricmeta key is:%s\n", key);
#endif
H
hjxilinx 已提交
1889

1890
  char*           name = pMeterMetaInfo->name;
S
slguan 已提交
1891 1892 1893 1894 1895 1896
  SMeterMetaInfo* pFinalInfo = NULL;

  if (pPrevSql == NULL) {
    SMeterMeta*  pMeterMeta = taosGetDataFromCache(tscCacheHandle, name);
    SMetricMeta* pMetricMeta = taosGetDataFromCache(tscCacheHandle, key);

1897
    pFinalInfo = tscAddMeterMetaInfo(pNewQueryInfo, name, pMeterMeta, pMetricMeta, pMeterMetaInfo->numOfTags,
1898
                                     pMeterMetaInfo->tagColumnIndex);
1899 1900 1901 1902 1903 1904
  } else {  // transfer the ownership of pMeterMeta/pMetricMeta to the newly create sql object.
    SMeterMetaInfo* pPrevInfo = tscGetMeterMetaInfo(&pPrevSql->cmd, pPrevSql->cmd.clauseIndex, 0);

    SMeterMeta*  pPrevMeterMeta = taosTransferDataInCache(tscCacheHandle, (void**)&pPrevInfo->pMeterMeta);
    SMetricMeta* pPrevMetricMeta = taosTransferDataInCache(tscCacheHandle, (void**)&pPrevInfo->pMetricMeta);

1905 1906
    pFinalInfo = tscAddMeterMetaInfo(pNewQueryInfo, name, pPrevMeterMeta, pPrevMetricMeta, pMeterMetaInfo->numOfTags,
                                     pMeterMetaInfo->tagColumnIndex);
S
slguan 已提交
1907 1908
  }

1909
  assert(pFinalInfo->pMeterMeta != NULL && pNewQueryInfo->numOfTables == 1);
1910
  if (UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {
S
slguan 已提交
1911 1912 1913
    assert(pFinalInfo->pMetricMeta != NULL);
  }

1914 1915 1916 1917 1918 1919
  tscTrace(
      "%p new subquery %p, tableIndex:%d, vnodeIdx:%d, type:%d, exprInfo:%d, colList:%d,"
      "fieldInfo:%d, name:%s",
      pSql, pNew, tableIndex, pMeterMetaInfo->vnodeIndex, pNewQueryInfo->type, pNewQueryInfo->exprsInfo.numOfExprs,
      pNewQueryInfo->colList.numOfCols, pNewQueryInfo->fieldsInfo.numOfOutputCols, pFinalInfo->name);

S
slguan 已提交
1920 1921 1922
  return pNew;
}

H
hzcheng 已提交
1923 1924
void tscDoQuery(SSqlObj* pSql) {
  SSqlCmd* pCmd = &pSql->cmd;
1925
  void*    fp = pSql->fp;
H
hzcheng 已提交
1926 1927 1928 1929 1930 1931 1932 1933

  if (pCmd->command > TSDB_SQL_LOCAL) {
    tscProcessLocalCmd(pSql);
  } else {
    if (pCmd->command == TSDB_SQL_SELECT) {
      tscAddIntoSqlList(pSql);
    }

1934 1935
    if (pCmd->dataSourceType == DATA_FROM_DATA_FILE) {
      tscProcessMultiVnodesInsertFromFile(pSql);
H
hzcheng 已提交
1936
    } else {
S
slguan 已提交
1937
      // pSql may be released in this function if it is a async insertion.
H
hzcheng 已提交
1938
      tscProcessSql(pSql);
S
slguan 已提交
1939
      if (NULL == fp) tscProcessMultiVnodesInsert(pSql);
S
slguan 已提交
1940
    }
H
hzcheng 已提交
1941 1942
  }
}
S
slguan 已提交
1943

H
hjxilinx 已提交
1944
int16_t tscGetJoinTagColIndexByUid(STagCond* pTagCond, uint64_t uid) {
S
slguan 已提交
1945 1946 1947 1948 1949 1950
  if (pTagCond->joinInfo.left.uid == uid) {
    return pTagCond->joinInfo.left.tagCol;
  } else {
    return pTagCond->joinInfo.right.tagCol;
  }
}
1951 1952 1953 1954 1955 1956 1957

bool tscIsUpdateQuery(STscObj* pObj) {
  if (pObj == NULL || pObj->signature != pObj) {
    globalCode = TSDB_CODE_DISCONNECTED;
    return TSDB_CODE_DISCONNECTED;
  }

H
hjxilinx 已提交
1958 1959
  SSqlCmd* pCmd = &pObj->pSql->cmd;
  return ((pCmd->command >= TSDB_SQL_INSERT && pCmd->command <= TSDB_SQL_DROP_DNODE) ||
H
hjxilinx 已提交
1960 1961 1962
          TSDB_SQL_USE_DB == pCmd->command)
             ? 1
             : 0;
H
hjxilinx 已提交
1963
}
1964

H
hjxilinx 已提交
1965 1966 1967 1968 1969
int32_t tscInvalidSQLErrMsg(char* msg, const char* additionalInfo, const char* sql) {
  const char* msgFormat1 = "invalid SQL: %s";
  const char* msgFormat2 = "invalid SQL: syntax error near \"%s\" (%s)";
  const char* msgFormat3 = "invalid SQL: syntax error near \"%s\"";

H
hjxilinx 已提交
1970
  const int32_t BACKWARD_CHAR_STEP = 0;
H
hjxilinx 已提交
1971

H
hjxilinx 已提交
1972 1973 1974 1975 1976
  if (sql == NULL) {
    assert(additionalInfo != NULL);
    sprintf(msg, msgFormat1, additionalInfo);
    return TSDB_CODE_INVALID_SQL;
  }
H
hjxilinx 已提交
1977 1978

  char buf[64] = {0};  // only extract part of sql string
H
hjxilinx 已提交
1979
  strncpy(buf, (sql - BACKWARD_CHAR_STEP), tListLen(buf) - 1);
H
hjxilinx 已提交
1980

H
hjxilinx 已提交
1981 1982 1983
  if (additionalInfo != NULL) {
    sprintf(msg, msgFormat2, buf, additionalInfo);
  } else {
H
hjxilinx 已提交
1984
    sprintf(msg, msgFormat3, buf);  // no additional information for invalid sql error
H
hjxilinx 已提交
1985
  }
H
hjxilinx 已提交
1986

H
hjxilinx 已提交
1987
  return TSDB_CODE_INVALID_SQL;
1988
}
H
hjxilinx 已提交
1989

H
hjxilinx 已提交
1990 1991 1992
bool tscHasReachLimitation(SQueryInfo* pQueryInfo, SSqlRes* pRes) {
  assert(pQueryInfo != NULL && pQueryInfo->clauseLimit != 0);
  return (pQueryInfo->clauseLimit > 0 && pRes->numOfTotalInCurrentClause >= pQueryInfo->clauseLimit);
H
hjxilinx 已提交
1993
}
1994 1995

char* tscGetErrorMsgPayload(SSqlCmd* pCmd) { return pCmd->payload; }
1996 1997 1998 1999 2000

/**
 *  If current vnode query does not return results anymore (pRes->numOfRows == 0), try the next vnode if exists,
 *  in case of multi-vnode super table projection query and the result does not reach the limitation.
 */
2001 2002 2003 2004 2005
bool hasMoreVnodesToTry(SSqlObj* pSql) {
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;

  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
2006
  
2007 2008 2009 2010
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
  if (!UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {
    return false;
  }
2011
  
2012 2013 2014
  int32_t totalVnode = pMeterMetaInfo->pMetricMeta->numOfVnodes;
  return pRes->numOfRows == 0 && tscProjectionQueryOnSTable(pQueryInfo, 0) &&
         (!tscHasReachLimitation(pQueryInfo, pRes)) && (pMeterMetaInfo->vnodeIndex < totalVnode - 1);
2015 2016
}

2017 2018 2019 2020 2021 2022
void tscTryQueryNextVnode(SSqlObj* pSql, __async_cb_func_t fp) {
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;

  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);

2023 2024 2025 2026 2027
  /*
   * no result returned from the current virtual node anymore, try the next vnode if exists
   * if case of: multi-vnode super table projection query
   */
  assert(pRes->numOfRows == 0 && tscProjectionQueryOnSTable(pQueryInfo, 0) && !tscHasReachLimitation(pQueryInfo, pRes));
2028 2029

  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
2030
  int32_t         totalVnode = pMeterMetaInfo->pMetricMeta->numOfVnodes;
2031

2032 2033 2034
  while (++pMeterMetaInfo->vnodeIndex < totalVnode) {
    tscTrace("%p current vnode:%d exhausted, try next:%d. total vnode:%d. current numOfRes:%d", pSql,
             pMeterMetaInfo->vnodeIndex - 1, pMeterMetaInfo->vnodeIndex, totalVnode, pRes->numOfTotalInCurrentClause);
2035

2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
    /*
     * update the limit and offset value for the query on the next vnode,
     * according to current retrieval results
     *
     * NOTE:
     * if the pRes->offset is larger than 0, the start returned position has not reached yet.
     * Therefore, the pRes->numOfRows, as well as pRes->numOfTotalInCurrentClause, must be 0.
     * The pRes->offset value will be updated by virtual node, during query execution.
     */
    if (pQueryInfo->clauseLimit >= 0) {
      pQueryInfo->limit.limit = pQueryInfo->clauseLimit - pRes->numOfTotalInCurrentClause;
    }
2048

2049
    pQueryInfo->limit.offset = pRes->offset;
2050

2051 2052 2053
    assert((pRes->offset >= 0 && pRes->numOfRows == 0) || (pRes->offset == 0 && pRes->numOfRows >= 0));
    tscTrace("%p new query to next vnode, vnode index:%d, limit:%" PRId64 ", offset:%" PRId64 ", glimit:%" PRId64, pSql,
             pMeterMetaInfo->vnodeIndex, pQueryInfo->limit.limit, pQueryInfo->limit.offset, pQueryInfo->clauseLimit);
2054

2055 2056 2057 2058 2059 2060 2061 2062
    /*
     * For project query with super table join, the numOfSub is equalled to the number of all subqueries.
     * Therefore, we need to reset the value of numOfSubs to be 0.
     *
     * For super table join with projection query, if anyone of the subquery is exhausted, the query completed.
     */
    pSql->numOfSubs = 0;
    pCmd->command = TSDB_SQL_SELECT;
2063

2064
    tscResetForNextRetrieve(pRes);
2065

2066 2067
    // in case of async query, set the callback function
    void* fp1 = pSql->fp;
2068
    pSql->fp = fp;
2069

2070
    if (fp1 != NULL) {
2071
      assert(fp != NULL);
2072
    }
2073

2074
    int32_t ret = tscProcessSql(pSql);  // todo check for failure
2075

2076
    // in case of async query, return now
2077 2078 2079
    if (fp != NULL) {
      return;
    }
2080

2081 2082 2083 2084
    if (ret != TSDB_CODE_SUCCESS) {
      pSql->res.code = ret;
      return;
    }
2085

2086 2087 2088
    // retrieve data
    assert(pCmd->command == TSDB_SQL_SELECT);
    pCmd->command = TSDB_SQL_FETCH;
2089

2090 2091 2092 2093
    if ((ret = tscProcessSql(pSql)) != TSDB_CODE_SUCCESS) {
      pSql->res.code = ret;
      return;
    }
2094

2095 2096 2097 2098 2099
    // if the result from current virtual node are empty, try next if exists. otherwise, return the results.
    if (pRes->numOfRows > 0) {
      break;
    }
  }
2100

2101 2102 2103 2104
  if (pRes->numOfRows == 0) {
    tscTrace("%p all vnodes exhausted, prj query completed. total res:%d", pSql, totalVnode, pRes->numOfTotal);
  }
}
2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136

void tscTryQueryNextClause(SSqlObj* pSql, void (*queryFp)()) {
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;

  // current subclause is completed, try the next subclause
  assert(pCmd->clauseIndex < pCmd->numOfClause - 1);

  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);

  pSql->cmd.command = pQueryInfo->command;
  pCmd->clauseIndex++;

  pRes->numOfTotal += pRes->numOfTotalInCurrentClause;
  pRes->numOfTotalInCurrentClause = 0;
  pRes->rspType = 0;

  pSql->numOfSubs = 0;
  tfree(pSql->pSubs);

  if (pSql->fp != NULL) {
    pSql->fp = queryFp;
    assert(queryFp != NULL);
  }

  tscTrace("%p try data in the next subclause:%d, total subclause:%d", pSql, pCmd->clauseIndex, pCmd->numOfClause);
  if (pCmd->command > TSDB_SQL_LOCAL) {
    tscProcessLocalCmd(pSql);
  } else {
    tscProcessSql(pSql);
  }
}