tscUtil.c 65.5 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
  if (pMeterMetaInfo == NULL || pMeterMetaInfo->pMetricMeta == NULL) {
    return false;
  }

218 219
  // for ordered projection query, iterate all qualified vnodes sequentially
  if (tscNonOrderedProjectionQueryOnSTable(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 tscNonOrderedProjectionQueryOnSTable(SQueryInfo* pQueryInfo, int32_t tableIndex) {
232
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, tableIndex);
H
hzcheng 已提交
233 234

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

S
slguan 已提交
244
  // only query on tag, not a projection query
245
  if (tscQueryMetricTags(pQueryInfo)) {
S
slguan 已提交
246 247
    return false;
  }
248 249 250 251 252
  
  // order by column exists, not a non-ordered projection query
  if (pQueryInfo->order.orderColId >= 0) {
    return false;
  }
S
slguan 已提交
253

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

S
slguan 已提交
263
  return true;
H
hzcheng 已提交
264 265
}

266 267 268
bool tscProjectionQueryOnTable(SQueryInfo* pQueryInfo) {
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    int32_t functionId = tscSqlExprGet(pQueryInfo, i)->functionId;
H
hjxilinx 已提交
269 270 271 272
    if (functionId != TSDB_FUNC_PRJ && functionId != TSDB_FUNC_TS) {
      return false;
    }
  }
H
hjxilinx 已提交
273

H
hjxilinx 已提交
274 275 276
  return true;
}

277 278 279
bool tscIsPointInterpQuery(SQueryInfo* pQueryInfo) {
  for (int32_t i = 0; i < pQueryInfo->exprsInfo.numOfExprs; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
H
hzcheng 已提交
280 281 282 283
    if (pExpr == NULL) {
      return false;
    }

S
slguan 已提交
284
    int32_t functionId = pExpr->functionId;
H
hzcheng 已提交
285 286 287 288 289 290 291 292 293 294 295
    if (functionId == TSDB_FUNC_TAG) {
      continue;
    }

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

296 297 298
bool tscIsTWAQuery(SQueryInfo* pQueryInfo) {
  for (int32_t i = 0; i < pQueryInfo->exprsInfo.numOfExprs; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
299 300 301 302 303 304 305 306 307 308 309
    if (pExpr == NULL) {
      continue;
    }

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

  return false;
H
hzcheng 已提交
310 311
}

312 313
void tscClearInterpInfo(SQueryInfo* pQueryInfo) {
  if (!tscIsPointInterpQuery(pQueryInfo)) {
H
hzcheng 已提交
314 315 316
    return;
  }

317
  pQueryInfo->interpoType = TSDB_INTERPO_NONE;
318
  tfree(pQueryInfo->defaultVal);
H
hzcheng 已提交
319 320 321 322
}

void tscClearSqlMetaInfoForce(SSqlCmd* pCmd) {
  /* remove the metermeta/metricmeta in cache */
323 324
  //    taosRemoveDataFromCache(tscCacheHandle, (void**)&(pCmd->pMeterMeta), true);
  //    taosRemoveDataFromCache(tscCacheHandle, (void**)&(pCmd->pMetricMeta), true);
H
hzcheng 已提交
325 326
}

327
int32_t tscCreateResPointerInfo(SSqlRes* pRes, SQueryInfo* pQueryInfo) {
H
hzcheng 已提交
328 329
  if (pRes->tsrow == NULL) {
    pRes->numOfnchar = 0;
330
  
331
    int32_t numOfOutputCols = pQueryInfo->fieldsInfo.numOfOutputCols;
H
hzcheng 已提交
332
    for (int32_t i = 0; i < numOfOutputCols; ++i) {
333
      TAOS_FIELD* pField = tscFieldInfoGetField(pQueryInfo, i);
H
hzcheng 已提交
334 335 336 337
      if (pField->type == TSDB_DATA_TYPE_NCHAR) {
        pRes->numOfnchar++;
      }
    }
338
  
H
hzcheng 已提交
339
    pRes->tsrow = calloc(1, (POINTER_BYTES + sizeof(short)) * numOfOutputCols + POINTER_BYTES * pRes->numOfnchar);
340 341 342 343 344 345 346 347 348 349 350 351
    pRes->bytes = calloc(numOfOutputCols, sizeof(short));
  
    if (pRes->numOfnchar > 0) {
      pRes->buffer = calloc(POINTER_BYTES, pRes->numOfnchar);
    }
  
    // not enough memory
    if (pRes->tsrow == NULL || pRes->bytes == NULL || (pRes->buffer == NULL && pRes->numOfnchar > 0)) {
      tfree(pRes->tsrow);
      tfree(pRes->bytes);
      tfree(pRes->buffer);
    
H
hzcheng 已提交
352 353 354 355 356 357 358 359 360
      pRes->code = TSDB_CODE_CLI_OUT_OF_MEMORY;
      return pRes->code;
    }
  }

  return TSDB_CODE_SUCCESS;
}

void tscDestroyResPointerInfo(SSqlRes* pRes) {
361 362 363 364
  if (pRes->buffer != NULL) {
    assert(pRes->numOfnchar > 0);
    // free all buffers containing the multibyte string
    for (int i = 0; i < pRes->numOfnchar; i++) {
H
hzcheng 已提交
365 366
      tfree(pRes->buffer[i]);
    }
367 368
    
    pRes->numOfnchar = 0;
H
hzcheng 已提交
369
  }
370 371
  
  tfree(pRes->pRsp);
H
hzcheng 已提交
372
  tfree(pRes->tsrow);
373 374 375 376 377 378 379
  
  tfree(pRes->pGroupRec);
  tfree(pRes->pColumnIndex);
  tfree(pRes->buffer);
  tfree(pRes->bytes);
  
  pRes->data = NULL;  // pRes->data points to the buffer of pRsp, no need to free
H
hzcheng 已提交
380 381
}

S
slguan 已提交
382
void tscFreeSqlCmdData(SSqlCmd* pCmd) {
S
slguan 已提交
383
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
384
  tscFreeSubqueryInfo(pCmd);
H
hzcheng 已提交
385 386
}

387 388 389
/*
 * this function must not change the pRes->code value, since it may be used later.
 */
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
void tscFreeResData(SSqlObj* pSql) {
  SSqlRes* pRes = &pSql->res;
  
  pRes->row = 0;
  
  pRes->rspType = 0;
  pRes->rspLen = 0;
  pRes->row = 0;
  
  pRes->numOfRows = 0;
  pRes->numOfTotal = 0;
  pRes->numOfTotalInCurrentClause = 0;
  
  pRes->numOfGroups = 0;
  pRes->precision = 0;
  pRes->qhandle = 0;
  
  pRes->offset = 0;
  pRes->useconds = 0;
  
  tscDestroyLocalReducer(pSql);
  
  tscDestroyResPointerInfo(pRes);
}

H
hzcheng 已提交
415
void tscFreeSqlObjPartial(SSqlObj* pSql) {
S
slguan 已提交
416 417 418
  if (pSql == NULL || pSql->signature != pSql) {
    return;
  }
H
hzcheng 已提交
419 420 421 422 423

  SSqlCmd* pCmd = &pSql->cmd;
  STscObj* pObj = pSql->pTscObj;

  int32_t cmd = pCmd->command;
S
slguan 已提交
424 425
  if (cmd < TSDB_SQL_INSERT || cmd == TSDB_SQL_RETRIEVE_METRIC || cmd == TSDB_SQL_RETRIEVE_EMPTY_RESULT ||
      cmd == TSDB_SQL_METRIC_JOIN_RETRIEVE) {
H
hzcheng 已提交
426 427 428
    tscRemoveFromSqlList(pSql);
  }

429
  pCmd->command = 0;
S
slguan 已提交
430

H
hzcheng 已提交
431 432 433 434
  // pSql->sqlstr will be used by tscBuildQueryStreamDesc
  pthread_mutex_lock(&pObj->mutex);
  tfree(pSql->sqlstr);
  pthread_mutex_unlock(&pObj->mutex);
435 436 437
  
  tscFreeResData(pSql);
  
H
hzcheng 已提交
438 439 440
  tfree(pSql->pSubs);
  pSql->numOfSubs = 0;

S
slguan 已提交
441
  tscFreeSqlCmdData(pCmd);
H
hzcheng 已提交
442 443 444 445 446 447 448 449 450 451
}

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;
452
  
H
hzcheng 已提交
453 454
  SSqlCmd* pCmd = &pSql->cmd;

S
slguan 已提交
455
  memset(pCmd->payload, 0, (size_t)pCmd->allocSize);
H
hzcheng 已提交
456 457 458 459 460
  tfree(pCmd->payload);

  pCmd->allocSize = 0;

  if (pSql->fp == NULL) {
S
slguan 已提交
461 462
    tsem_destroy(&pSql->rspSem);
    tsem_destroy(&pSql->emptyRspSem);
H
hzcheng 已提交
463 464 465 466
  }
  free(pSql);
}

S
slguan 已提交
467 468
void tscDestroyDataBlock(STableDataBlocks* pDataBlock) {
  if (pDataBlock == NULL) {
H
hzcheng 已提交
469 470 471
    return;
  }

S
slguan 已提交
472
  tfree(pDataBlock->pData);
S
slguan 已提交
473
  tfree(pDataBlock->params);
H
hjxilinx 已提交
474

H
hjxilinx 已提交
475
  // free the refcount for metermeta
H
hjxilinx 已提交
476
  taosRemoveDataFromCache(tscCacheHandle, (void**)&(pDataBlock->pMeterMeta), false);
S
slguan 已提交
477
  tfree(pDataBlock);
H
hzcheng 已提交
478 479
}

480 481
SParamInfo* tscAddParamToDataBlock(STableDataBlocks* pDataBlock, char type, uint8_t timePrec, short bytes,
                                   uint32_t offset) {
S
slguan 已提交
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
  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 已提交
504 505 506 507
SDataBlockList* tscCreateBlockArrayList() {
  const int32_t DEFAULT_INITIAL_NUM_OF_BLOCK = 16;

  SDataBlockList* pDataBlockArrayList = calloc(1, sizeof(SDataBlockList));
S
slguan 已提交
508 509 510
  if (pDataBlockArrayList == NULL) {
    return NULL;
  }
H
hzcheng 已提交
511 512
  pDataBlockArrayList->nAlloc = DEFAULT_INITIAL_NUM_OF_BLOCK;
  pDataBlockArrayList->pData = calloc(1, POINTER_BYTES * pDataBlockArrayList->nAlloc);
S
slguan 已提交
513 514 515 516
  if (pDataBlockArrayList->pData == NULL) {
    free(pDataBlockArrayList);
    return NULL;
  }
H
hzcheng 已提交
517 518 519 520

  return pDataBlockArrayList;
}

521
void tscAppendDataBlock(SDataBlockList* pList, STableDataBlocks* pBlocks) {
S
slguan 已提交
522
  if (pList->nSize >= pList->nAlloc) {
H
hjxilinx 已提交
523 524
    pList->nAlloc = (pList->nAlloc) << 1U;
    pList->pData = realloc(pList->pData, POINTER_BYTES * (size_t)pList->nAlloc);
S
slguan 已提交
525 526

    // reset allocated memory
H
hjxilinx 已提交
527
    memset(pList->pData + pList->nSize, 0, POINTER_BYTES * (pList->nAlloc - pList->nSize));
S
slguan 已提交
528 529 530 531 532
  }

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

S
slguan 已提交
533 534 535
void* tscDestroyBlockArrayList(SDataBlockList* pList) {
  if (pList == NULL) {
    return NULL;
H
hzcheng 已提交
536 537
  }

S
slguan 已提交
538 539
  for (int32_t i = 0; i < pList->nSize; i++) {
    tscDestroyDataBlock(pList->pData[i]);
H
hzcheng 已提交
540 541
  }

S
slguan 已提交
542 543 544 545
  tfree(pList->pData);
  tfree(pList);

  return NULL;
H
hzcheng 已提交
546 547
}

S
slguan 已提交
548
int32_t tscCopyDataBlockToPayload(SSqlObj* pSql, STableDataBlocks* pDataBlock) {
H
hjxilinx 已提交
549
  SSqlCmd* pCmd = &pSql->cmd;
H
hjxilinx 已提交
550
  assert(pDataBlock->pMeterMeta != NULL);
H
hjxilinx 已提交
551

552
  pCmd->numOfTablesInSubmit = pDataBlock->numOfMeters;
553

554 555
  assert(pCmd->numOfClause == 1);
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfo(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
556 557

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

    pMeterMetaInfo->pMeterMeta = taosTransferDataInCache(tscCacheHandle, (void**)&pDataBlock->pMeterMeta);
H
hjxilinx 已提交
563 564 565
  } else {
    assert(strncmp(pMeterMetaInfo->name, pDataBlock->meterId, tListLen(pDataBlock->meterId)) == 0);
  }
H
hjxilinx 已提交
566

567 568 569 570 571
  /*
   * 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 已提交
572
  int ret = tscAllocPayload(pCmd, pDataBlock->nAllocSize + sizeof(STaosDigest));
H
hjxilinx 已提交
573 574 575
  if (TSDB_CODE_SUCCESS != ret) {
    return ret;
  }
H
hjxilinx 已提交
576

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

579 580 581 582 583
  /*
   * 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 已提交
584

585
  assert(pCmd->allocSize >= pCmd->payloadLen + tsRpcHeadSize + sizeof(STaosDigest));
H
hjxilinx 已提交
586
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
587 588 589 590 591
}

void tscFreeUnusedDataBlocks(SDataBlockList* pList) {
  /* release additional memory consumption */
  for (int32_t i = 0; i < pList->nSize; ++i) {
S
slguan 已提交
592 593 594
    STableDataBlocks* pDataBlock = pList->pData[i];
    pDataBlock->pData = realloc(pDataBlock->pData, pDataBlock->size);
    pDataBlock->nAllocSize = (uint32_t)pDataBlock->size;
H
hzcheng 已提交
595 596 597
  }
}

H
hjxilinx 已提交
598 599 600 601 602 603
/**
 * create the in-memory buffer for each table to keep the submitted data block
 * @param initialSize
 * @param rowSize
 * @param startOffset
 * @param name
H
hjxilinx 已提交
604
 * @param dataBlocks
H
hjxilinx 已提交
605 606
 * @return
 */
H
hjxilinx 已提交
607
int32_t tscCreateDataBlock(size_t initialSize, int32_t rowSize, int32_t startOffset, const char* name,
608
                           SMeterMeta* pMeterMeta, STableDataBlocks** dataBlocks) {
H
hjxilinx 已提交
609
  STableDataBlocks* dataBuf = (STableDataBlocks*)calloc(1, sizeof(STableDataBlocks));
H
hjxilinx 已提交
610 611 612 613 614 615
  if (dataBuf == NULL) {
    tscError("failed to allocated memory, reason:%s", strerror(errno));
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }

  dataBuf->nAllocSize = (uint32_t)initialSize;
L
[#1102]  
lihui 已提交
616
  dataBuf->headerSize = startOffset; // the header size will always be the startOffset value, reserved for the subumit block header
H
hjxilinx 已提交
617 618 619 620
  if (dataBuf->nAllocSize <= dataBuf->headerSize) {
    dataBuf->nAllocSize = dataBuf->headerSize*2;
  }
  
H
hjxilinx 已提交
621 622 623
  dataBuf->pData = calloc(1, dataBuf->nAllocSize);
  dataBuf->ordered = true;
  dataBuf->prevTS = INT64_MIN;
S
slguan 已提交
624 625 626

  dataBuf->rowSize = rowSize;
  dataBuf->size = startOffset;
S
slguan 已提交
627 628
  dataBuf->tsSource = -1;

S
slguan 已提交
629
  strncpy(dataBuf->meterId, name, TSDB_METER_ID_LEN);
H
hjxilinx 已提交
630 631 632

  /*
   * The metermeta may be released since the metermeta cache are completed clean by other thread
633 634
   * 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 已提交
635
   */
636 637
  dataBuf->pMeterMeta = taosGetDataFromExists(tscCacheHandle, pMeterMeta);
  assert(initialSize > 0 && pMeterMeta != NULL && dataBuf->pMeterMeta != NULL);
638

639 640
  *dataBlocks = dataBuf;
  return TSDB_CODE_SUCCESS;
S
slguan 已提交
641 642
}

H
hjxilinx 已提交
643
int32_t tscGetDataBlockFromList(void* pHashList, SDataBlockList* pDataBlockList, int64_t id, int32_t size,
644
                                int32_t startOffset, int32_t rowSize, const char* tableId, SMeterMeta* pMeterMeta,
H
hjxilinx 已提交
645 646
                                STableDataBlocks** dataBlocks) {
  *dataBlocks = NULL;
S
slguan 已提交
647

648
  STableDataBlocks** t1 = (STableDataBlocks**)taosGetDataFromHash(pHashList, (const char*)&id, sizeof(id));
S
slguan 已提交
649
  if (t1 != NULL) {
H
hjxilinx 已提交
650
    *dataBlocks = *t1;
S
slguan 已提交
651 652
  }

H
hjxilinx 已提交
653
  if (*dataBlocks == NULL) {
654
    int32_t ret = tscCreateDataBlock((size_t)size, rowSize, startOffset, tableId, pMeterMeta, dataBlocks);
H
hjxilinx 已提交
655 656 657 658
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }

659
    taosAddToHashTable(pHashList, (const char*)&id, sizeof(int64_t), (char*)dataBlocks, POINTER_BYTES);
H
hjxilinx 已提交
660
    tscAppendDataBlock(pDataBlockList, *dataBlocks);
S
slguan 已提交
661 662
  }

H
hjxilinx 已提交
663
  return TSDB_CODE_SUCCESS;
S
slguan 已提交
664 665
}

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

669
  void* pVnodeDataBlockHashList = taosInitHashTable(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false);
S
slguan 已提交
670 671 672 673
  SDataBlockList* pVnodeDataBlockList = tscCreateBlockArrayList();

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

H
hjxilinx 已提交
675
    STableDataBlocks* dataBuf = NULL;
676 677 678
    int32_t           ret =
        tscGetDataBlockFromList(pVnodeDataBlockHashList, pVnodeDataBlockList, pOneTableBlock->vgid, TSDB_PAYLOAD_SIZE,
                                tsInsertHeadSize, 0, pOneTableBlock->meterId, pOneTableBlock->pMeterMeta, &dataBuf);
H
hjxilinx 已提交
679
    if (ret != TSDB_CODE_SUCCESS) {
680 681 682
      tscError("%p failed to prepare the data block buffer for merging table data, code:%d", pSql, ret);
      taosCleanUpHashTable(pVnodeDataBlockHashList);
      tscDestroyBlockArrayList(pVnodeDataBlockList);
H
hjxilinx 已提交
683 684
      return ret;
    }
S
slguan 已提交
685 686 687 688 689 690 691 692 693 694 695

    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);
696
      } else {  // failed to allocate memory, free already allocated memory and return error code
S
slguan 已提交
697 698
        tscError("%p failed to allocate memory for merging submit block, size:%d", pSql, dataBuf->nAllocSize);

699
        taosCleanUpHashTable(pVnodeDataBlockHashList);
S
slguan 已提交
700 701 702 703
        tfree(dataBuf->pData);
        tscDestroyBlockArrayList(pVnodeDataBlockList);

        return TSDB_CODE_CLI_OUT_OF_MEMORY;
S
slguan 已提交
704 705 706 707
      }
    }

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

L
lihui 已提交
710 711 712 713
    char* e = (char*)pBlocks->payLoad + pOneTableBlock->rowSize*(pBlocks->numOfRows-1);
    
    tscTrace("%p meterId:%s, sid:%d rows:%d sversion:%d skey:%" PRId64 ", ekey:%" PRId64, pSql, pOneTableBlock->meterId, pBlocks->sid,
             pBlocks->numOfRows, pBlocks->sversion, GET_INT64_VAL(pBlocks->payLoad), GET_INT64_VAL(e));
S
slguan 已提交
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731

    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);
732
  taosCleanUpHashTable(pVnodeDataBlockHashList);
S
slguan 已提交
733 734

  return TSDB_CODE_SUCCESS;
S
slguan 已提交
735 736
}

H
hzcheng 已提交
737 738 739 740 741 742 743 744 745 746 747 748 749 750
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) {
751 752 753 754 755 756 757 758
  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 已提交
759 760
}

S
slguan 已提交
761
int tscAllocPayload(SSqlCmd* pCmd, int size) {
H
hzcheng 已提交
762 763 764 765 766
  assert(size > 0);

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

S
slguan 已提交
767
    pCmd->payload = (char*)malloc(size);
H
hzcheng 已提交
768 769 770 771
    if (pCmd->payload == NULL) return TSDB_CODE_CLI_OUT_OF_MEMORY;
    pCmd->allocSize = size;
  } else {
    if (pCmd->allocSize < size) {
772
      char* b = realloc(pCmd->payload, size);
S
slguan 已提交
773 774
      if (b == NULL) return TSDB_CODE_CLI_OUT_OF_MEMORY;
      pCmd->payload = b;
H
hzcheng 已提交
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
      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 已提交
806 807
    pFieldInfo->pVisibleCols = realloc(pFieldInfo->pVisibleCols, newSize * sizeof(bool));

H
hzcheng 已提交
808 809 810 811 812 813 814 815 816 817 818
    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 已提交
819
static void setValueImpl(TAOS_FIELD* pField, int8_t type, const char* name, int16_t bytes) {
H
hzcheng 已提交
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
  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 已提交
839 840
  pFieldInfo->pVisibleCols[index] = true;

H
hzcheng 已提交
841 842 843
  pFieldInfo->numOfOutputCols++;
}

S
slguan 已提交
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
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 已提交
863
void tscFieldInfoSetValue(SFieldInfo* pFieldInfo, int32_t index, int8_t type, const char* name, int16_t bytes) {
H
hzcheng 已提交
864 865 866 867 868
  ensureSpace(pFieldInfo, pFieldInfo->numOfOutputCols + 1);
  evic(pFieldInfo, index);

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

  pFieldInfo->pVisibleCols[index] = true;
H
hzcheng 已提交
871 872 873
  pFieldInfo->numOfOutputCols++;
}

874 875
void tscFieldInfoCalOffset(SQueryInfo* pQueryInfo) {
  SFieldInfo* pFieldInfo = &pQueryInfo->fieldsInfo;
H
hzcheng 已提交
876 877 878 879 880 881 882
  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;
  }
}

883
void tscFieldInfoUpdateOffsetForInterResult(SQueryInfo* pQueryInfo) {
884
  SFieldInfo* pFieldInfo = &pQueryInfo->fieldsInfo;
H
hzcheng 已提交
885 886 887 888 889 890 891 892 893 894 895
  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) {
896
    pFieldInfo->pOffset[i] = pFieldInfo->pOffset[i - 1] + tscSqlExprGet(pQueryInfo, i - 1)->resBytes;
H
hzcheng 已提交
897 898 899
  }
}

S
slguan 已提交
900
void tscFieldInfoCopy(SFieldInfo* src, SFieldInfo* dst, const int32_t* indexList, int32_t size) {
H
hzcheng 已提交
901 902 903 904
  if (src == NULL) {
    return;
  }

S
slguan 已提交
905 906
  if (size <= 0) {
    *dst = *src;
907
    tscFieldInfoCopyAll(dst, src);
S
slguan 已提交
908 909 910 911 912 913 914 915
  } 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]]);
    }
  }
}

916
void tscFieldInfoCopyAll(SFieldInfo* dst, SFieldInfo* src) {
H
hzcheng 已提交
917 918 919 920
  *dst = *src;

  dst->pFields = malloc(sizeof(TAOS_FIELD) * dst->numOfAlloc);
  dst->pOffset = malloc(sizeof(short) * dst->numOfAlloc);
S
slguan 已提交
921
  dst->pVisibleCols = malloc(sizeof(bool) * dst->numOfAlloc);
H
hzcheng 已提交
922 923 924

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

928 929
TAOS_FIELD* tscFieldInfoGetField(SQueryInfo* pQueryInfo, int32_t index) {
  if (index >= pQueryInfo->fieldsInfo.numOfOutputCols) {
H
hzcheng 已提交
930 931 932
    return NULL;
  }

933
  return &pQueryInfo->fieldsInfo.pFields[index];
934 935
}

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

938 939
int16_t tscFieldInfoGetOffset(SQueryInfo* pQueryInfo, int32_t index) {
  if (index >= pQueryInfo->fieldsInfo.numOfOutputCols) {
H
hzcheng 已提交
940 941 942
    return 0;
  }

943
  return pQueryInfo->fieldsInfo.pOffset[index];
H
hzcheng 已提交
944 945
}

946 947
int32_t tscFieldInfoCompare(SFieldInfo* pFieldInfo1, SFieldInfo* pFieldInfo2) {
  assert(pFieldInfo1 != NULL && pFieldInfo2 != NULL);
948

949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
  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;
}

966 967
int32_t tscGetResRowLength(SQueryInfo* pQueryInfo) {
  SFieldInfo* pFieldInfo = &pQueryInfo->fieldsInfo;
H
hzcheng 已提交
968 969 970 971 972 973 974 975
  if (pFieldInfo->numOfOutputCols <= 0) {
    return 0;
  }

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

S
slguan 已提交
976 977
void tscClearFieldInfo(SFieldInfo* pFieldInfo) {
  if (pFieldInfo == NULL) {
H
hzcheng 已提交
978 979 980
    return;
  }

S
slguan 已提交
981 982 983 984 985
  tfree(pFieldInfo->pOffset);
  tfree(pFieldInfo->pFields);
  tfree(pFieldInfo->pVisibleCols);

  memset(pFieldInfo, 0, sizeof(SFieldInfo));
H
hzcheng 已提交
986 987 988 989
}

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

992
    uint32_t newSize = (oldSize <= 0) ? 8 : (oldSize << 1U);
H
hzcheng 已提交
993
    while (newSize < size) {
994
      newSize = (newSize << 1U);
H
hzcheng 已提交
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
    }

    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));
  }
}

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

H
hjxilinx 已提交
1020 1021
  _exprCheckSpace(pExprInfo, pExprInfo->numOfExprs + 1);
  _exprEvic(pExprInfo, index);
H
hjxilinx 已提交
1022

H
hjxilinx 已提交
1023 1024
  SSqlExpr* pExpr = &pExprInfo->pExprs[index];
  pExpr->functionId = functionId;
H
hjxilinx 已提交
1025

H
hjxilinx 已提交
1026 1027 1028 1029
  pExprInfo->numOfExprs++;
  return pExpr;
}

1030 1031 1032
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 已提交
1033

1034
  SSqlExprInfo* pExprInfo = &pQueryInfo->exprsInfo;
H
hzcheng 已提交
1035 1036 1037 1038 1039 1040

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

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

S
slguan 已提交
1041 1042
  pExpr->functionId = functionId;
  int16_t numOfCols = pMeterMetaInfo->pMeterMeta->numOfColumns;
H
hzcheng 已提交
1043

S
slguan 已提交
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
  // 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 已提交
1056
  } else {
S
slguan 已提交
1057 1058 1059 1060 1061
    if (pColIndex->columnIndex != TSDB_TBNAME_COLUMN_INDEX) {
      pExpr->colInfo.flag = TSDB_COL_NORMAL;
    } else {
      pExpr->colInfo.flag = TSDB_COL_TAG;
    }
H
hzcheng 已提交
1062 1063
  }

S
slguan 已提交
1064
  pExpr->colInfo.colIdx = pColIndex->columnIndex;
H
hzcheng 已提交
1065 1066
  pExpr->resType = type;
  pExpr->resBytes = size;
S
slguan 已提交
1067 1068
  pExpr->interResBytes = interSize;
  pExpr->uid = pMeterMetaInfo->pMeterMeta->uid;
H
hzcheng 已提交
1069 1070 1071 1072 1073

  pExprInfo->numOfExprs++;
  return pExpr;
}

1074 1075 1076 1077
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 已提交
1078 1079 1080 1081 1082 1083
  if (index > pExprInfo->numOfExprs) {
    return NULL;
  }

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

S
slguan 已提交
1084
  pExpr->functionId = functionId;
H
hzcheng 已提交
1085 1086

  pExpr->colInfo.colIdx = srcColumnIndex;
S
slguan 已提交
1087
  pExpr->colInfo.colId = tsGetColumnSchema(pMeterMetaInfo->pMeterMeta, srcColumnIndex)->colId;
H
hzcheng 已提交
1088 1089 1090 1091 1092 1093 1094

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

  return pExpr;
}

S
slguan 已提交
1095
void addExprParams(SSqlExpr* pExpr, char* argument, int32_t type, int32_t bytes, int16_t tableIndex) {
H
hzcheng 已提交
1096 1097 1098 1099 1100 1101
  if (pExpr == NULL || argument == NULL || bytes == 0) {
    return;
  }

  // set parameter value
  // transfer to tVariant from byte data/no ascii data
S
slguan 已提交
1102
  tVariantCreateFromBinary(&pExpr->param[pExpr->numOfParams], argument, bytes, type);
H
hzcheng 已提交
1103 1104 1105 1106 1107

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

1108 1109
SSqlExpr* tscSqlExprGet(SQueryInfo* pQueryInfo, int32_t index) {
  if (pQueryInfo->exprsInfo.numOfExprs <= index) {
H
hzcheng 已提交
1110 1111 1112
    return NULL;
  }

1113
  return &pQueryInfo->exprsInfo.pExprs[index];
H
hzcheng 已提交
1114 1115
}

H
hjxilinx 已提交
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
void* tscSqlExprDestroy(SSqlExpr* pExpr) {
  if (pExpr == NULL) {
    return NULL;
  }
  
  for(int32_t i = 0; i < tListLen(pExpr->param); ++i) {
    tVariantDestroy(&pExpr->param[i]);
  }
  
  return NULL;
H
hzcheng 已提交
1126 1127
}

H
hjxilinx 已提交
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
/*
 * NOTE: Does not release SSqlExprInfo here.
 */
void tscSqlExprInfoDestroy(SSqlExprInfo* pExprInfo) {
  if (pExprInfo->numOfAlloc == 0) {
    return;
  }
  
  for(int32_t i = 0; i < pExprInfo->numOfAlloc; ++i) {
    tscSqlExprDestroy(&pExprInfo->pExprs[i]);
  }
  
  tfree(pExprInfo->pExprs);
  
  pExprInfo->numOfAlloc = 0;
  pExprInfo->numOfExprs = 0;
}


S
slguan 已提交
1147
void tscSqlExprCopy(SSqlExprInfo* dst, const SSqlExprInfo* src, uint64_t tableuid) {
H
hzcheng 已提交
1148 1149 1150 1151 1152 1153
  if (src == NULL) {
    return;
  }

  *dst = *src;

H
hjxilinx 已提交
1154
  dst->pExprs = calloc(dst->numOfAlloc, sizeof(SSqlExpr));
S
slguan 已提交
1155 1156 1157 1158 1159 1160
  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 已提交
1161

S
slguan 已提交
1162
  dst->numOfExprs = num;
H
hzcheng 已提交
1163 1164 1165 1166 1167 1168 1169
  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 已提交
1170 1171 1172 1173 1174 1175 1176 1177
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 已提交
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
  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 已提交
1199
static void _cf_evic(SColumnBaseInfo* pcolList, int32_t index) {
H
hzcheng 已提交
1200 1201 1202 1203
  if (index < pcolList->numOfCols) {
    memmove(&pcolList->pColList[index + 1], &pcolList->pColList[index],
            sizeof(SColumnBase) * (pcolList->numOfCols - index));

S
slguan 已提交
1204
    clearVal(&pcolList->pColList[index]);
H
hzcheng 已提交
1205 1206 1207
  }
}

S
slguan 已提交
1208 1209
SColumnBase* tscColumnBaseInfoGet(SColumnBaseInfo* pColumnBaseInfo, int32_t index) {
  if (pColumnBaseInfo == NULL || pColumnBaseInfo->numOfCols < index) {
H
hzcheng 已提交
1210 1211 1212
    return NULL;
  }

S
slguan 已提交
1213 1214 1215 1216 1217 1218 1219
  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 已提交
1220 1221
}

S
slguan 已提交
1222
// todo refactor
1223 1224
SColumnBase* tscColumnBaseInfoInsert(SQueryInfo* pQueryInfo, SColumnIndex* pColIndex) {
  SColumnBaseInfo* pcolList = &pQueryInfo->colList;
H
hzcheng 已提交
1225

S
slguan 已提交
1226 1227
  // ignore the tbname column to be inserted into source list
  if (pColIndex->columnIndex < 0) {
H
hzcheng 已提交
1228 1229 1230
    return NULL;
  }

S
slguan 已提交
1231 1232
  int16_t col = pColIndex->columnIndex;

H
hzcheng 已提交
1233
  int32_t i = 0;
S
slguan 已提交
1234 1235 1236 1237 1238 1239 1240 1241
  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 已提交
1242 1243
  }

S
slguan 已提交
1244 1245 1246
  SColumnIndex* pIndex = &pcolList->pColList[i].colIndex;
  if ((i < pcolList->numOfCols && (pIndex->columnIndex > col || pIndex->tableIndex != pColIndex->tableIndex)) ||
      (i >= pcolList->numOfCols)) {
H
hzcheng 已提交
1247 1248 1249
    _cf_ensureSpace(pcolList, pcolList->numOfCols + 1);
    _cf_evic(pcolList, i);

S
slguan 已提交
1250
    pcolList->pColList[i].colIndex = *pColIndex;
H
hzcheng 已提交
1251 1252 1253 1254 1255 1256
    pcolList->numOfCols++;
  }

  return &pcolList->pColList[i];
}

S
slguan 已提交
1257
void tscColumnFilterInfoCopy(SColumnFilterInfo* dst, const SColumnFilterInfo* src) {
H
hjxilinx 已提交
1258
  assert(src != NULL && dst != NULL);
S
slguan 已提交
1259 1260 1261 1262 1263 1264 1265 1266

  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 已提交
1267 1268 1269 1270
    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 已提交
1271 1272 1273 1274
  }
}

void tscColumnBaseCopy(SColumnBase* dst, const SColumnBase* src) {
H
hjxilinx 已提交
1275
  assert(src != NULL && dst != NULL);
S
slguan 已提交
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290

  *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 已提交
1291 1292 1293 1294 1295
  if (src == NULL) {
    return;
  }

  *dst = *src;
S
slguan 已提交
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
  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 已提交
1314

S
slguan 已提交
1315
  dst->numOfCols = num;
H
hzcheng 已提交
1316 1317
}

S
slguan 已提交
1318 1319 1320 1321 1322 1323 1324 1325
void tscColumnBaseInfoDestroy(SColumnBaseInfo* pColumnBaseInfo) {
  if (pColumnBaseInfo == NULL) {
    return;
  }

  assert(pColumnBaseInfo->numOfCols <= TSDB_MAX_COLUMNS);

  for (int32_t i = 0; i < pColumnBaseInfo->numOfCols; ++i) {
1326
    SColumnBase* pColBase = &(pColumnBaseInfo->pColList[i]);
S
slguan 已提交
1327 1328 1329 1330 1331 1332

    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 已提交
1333
          free((char*)pColBase->filterInfo[j].pz);
H
hjxilinx 已提交
1334
          pColBase->filterInfo[j].pz = 0;
S
slguan 已提交
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
        }
      }
    }

    tfree(pColBase->filterInfo);
  }

  tfree(pColumnBaseInfo->pColList);
}

1345 1346 1347
void tscColumnBaseInfoReserve(SColumnBaseInfo* pColumnBaseInfo, int32_t size) {
  _cf_ensureSpace(pColumnBaseInfo, size);
}
H
hzcheng 已提交
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363

/*
 * 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 已提交
1364
  pToken->n = strdequote(pToken->z);
H
hzcheng 已提交
1365 1366 1367 1368
  strtrim(pToken->z);
  pToken->n = (uint32_t)strlen(pToken->z);

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

H
huili 已提交
1370 1371
  if (pToken->type == TK_STRING) {
    return tscValidateName(pToken);
S
slguan 已提交
1372
  }
H
hzcheng 已提交
1373

H
huili 已提交
1374 1375 1376
  if (k != pToken->n || pToken->type != TK_ID) {
    return TSDB_CODE_INVALID_SQL;
  }
H
hzcheng 已提交
1377 1378 1379 1380 1381 1382 1383 1384
  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 已提交
1385
  char* sep = strnchr(pToken->z, TS_PATH_DELIMITER[0], pToken->n, true);
H
hzcheng 已提交
1386 1387
  if (sep == NULL) {  // single part
    if (pToken->type == TK_STRING) {
H
huili 已提交
1388 1389 1390
      pToken->n = strdequote(pToken->z);
      strtrim(pToken->z);
      pToken->n = (uint32_t)strlen(pToken->z);
S
slguan 已提交
1391 1392 1393 1394

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

      // single token, validate it
1395
      if (len == pToken->n) {
H
huili 已提交
1396
        return validateQuoteToken(pToken);
S
slguan 已提交
1397
      } else {
1398 1399 1400 1401
        sep = strnchr(pToken->z, TS_PATH_DELIMITER[0], pToken->n, true);
        if (sep == NULL) {
          return TSDB_CODE_INVALID_SQL;
        }
S
slguan 已提交
1402

H
huili 已提交
1403
        return tscValidateName(pToken);
1404
      }
H
hzcheng 已提交
1405 1406 1407 1408 1409 1410 1411 1412 1413
    } else {
      if (isNumber(pToken)) {
        return TSDB_CODE_INVALID_SQL;
      }
    }
  } else {  // two part
    int32_t oldLen = pToken->n;
    char*   pStr = pToken->z;

H
huili 已提交
1414 1415
    if (pToken->type == TK_SPACE) {
      strtrim(pToken->z);
S
slguan 已提交
1416
      pToken->n = (uint32_t)strlen(pToken->z);
H
huili 已提交
1417 1418
    }

H
hzcheng 已提交
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
    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 已提交
1447
      // first part do not have quote do nothing
H
hzcheng 已提交
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
    } 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;
}

1469
bool tscValidateColumnId(SMeterMetaInfo* pMeterMetaInfo, int32_t colId) {
S
slguan 已提交
1470
  if (pMeterMetaInfo->pMeterMeta == NULL) {
H
hzcheng 已提交
1471 1472 1473
    return false;
  }

1474
  if (colId == -1 && UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {
H
hzcheng 已提交
1475 1476 1477
    return true;
  }

S
slguan 已提交
1478 1479
  SSchema* pSchema = tsGetSchema(pMeterMetaInfo->pMeterMeta);
  int32_t  numOfTotal = pMeterMetaInfo->pMeterMeta->numOfTags + pMeterMetaInfo->pMeterMeta->numOfColumns;
H
hzcheng 已提交
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489

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

  return false;
}

S
slguan 已提交
1490 1491
void tscTagCondCopy(STagCond* dest, const STagCond* src) {
  memset(dest, 0, sizeof(STagCond));
H
hjxilinx 已提交
1492

H
hjxilinx 已提交
1493 1494 1495
  if (src->tbnameCond.cond != NULL) {
    dest->tbnameCond.cond = strdup(src->tbnameCond.cond);
  }
S
slguan 已提交
1496 1497 1498 1499 1500 1501

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

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

  for (int32_t i = 0; i < src->numOfTagCond; ++i) {
H
hjxilinx 已提交
1502 1503 1504
    if (src->cond[i].cond != NULL) {
      dest->cond[i].cond = strdup(src->cond[i].cond);
    }
H
hjxilinx 已提交
1505

S
slguan 已提交
1506
    dest->cond[i].uid = src->cond[i].uid;
H
hzcheng 已提交
1507 1508
  }

S
slguan 已提交
1509 1510
  dest->relType = src->relType;
  dest->numOfTagCond = src->numOfTagCond;
H
hzcheng 已提交
1511 1512 1513
}

void tscTagCondRelease(STagCond* pCond) {
H
hjxilinx 已提交
1514
  free(pCond->tbnameCond.cond);
S
slguan 已提交
1515
  for (int32_t i = 0; i < pCond->numOfTagCond; ++i) {
H
hjxilinx 已提交
1516
    free(pCond->cond[i].cond);
H
hzcheng 已提交
1517 1518 1519 1520 1521
  }

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

1522 1523
void tscGetSrcColumnInfo(SSrcColumnInfo* pColInfo, SQueryInfo* pQueryInfo) {
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
S
slguan 已提交
1524
  SSchema*        pSchema = tsGetSchema(pMeterMetaInfo->pMeterMeta);
H
hzcheng 已提交
1525

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

S
slguan 已提交
1530 1531 1532
    if (TSDB_COL_IS_TAG(pExpr->colInfo.flag)) {
      SSchema* pTagSchema = tsGetTagSchema(pMeterMetaInfo->pMeterMeta);
      int16_t  actualTagIndex = pMeterMetaInfo->tagColumnIndex[pExpr->colInfo.colIdx];
H
hzcheng 已提交
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548

      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 已提交
1549
  // to denote the heart-beat timer close connection and free all allocated resources
1550 1551
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pHeatBeat->cmd, 0);
  pQueryInfo->type = TSDB_QUERY_TYPE_FREE_RESOURCE;
H
hzcheng 已提交
1552 1553 1554 1555
}

bool tscShouldFreeHeatBeat(SSqlObj* pHb) {
  assert(pHb == pHb->signature);
1556 1557 1558

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

void tscCleanSqlCmd(SSqlCmd* pCmd) {
1562 1563
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
  tscFreeSubqueryInfo(pCmd);
H
hzcheng 已提交
1564

S
slguan 已提交
1565 1566
  uint32_t allocSize = pCmd->allocSize;
  char*    allocPtr = pCmd->payload;
H
hzcheng 已提交
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616

  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;
1617
    SQueryInfo*     pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
H
hjxilinx 已提交
1618

1619
    SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
1620
    assert(pQueryInfo->numOfTables == 1 || pQueryInfo->numOfTables == 2);
H
hjxilinx 已提交
1621

H
hjxilinx 已提交
1622
    if (pDataBlocks == NULL || pMeterMetaInfo->vnodeIndex >= pDataBlocks->nSize) {
H
hzcheng 已提交
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
      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);
  }
}

1634 1635 1636
/**
 *
 * @param pCmd
1637
 * @param clauseIndex denote the index of the union sub clause, usually are 0, if no union query exists.
1638 1639 1640
 * @param tableIndex  denote the table index for join query, where more than one table exists
 * @return
 */
1641
SMeterMetaInfo* tscGetMeterMetaInfo(SSqlCmd* pCmd, int32_t clauseIndex, int32_t tableIndex) {
1642
  if (pCmd == NULL || pCmd->numOfClause == 0) {
S
slguan 已提交
1643 1644 1645
    return NULL;
  }

1646
  assert(clauseIndex >= 0 && clauseIndex < pCmd->numOfClause);
1647

1648
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, clauseIndex);
1649
  return tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, tableIndex);
S
slguan 已提交
1650 1651
}

1652
SMeterMetaInfo* tscGetMeterMetaInfoFromQueryInfo(SQueryInfo* pQueryInfo, int32_t tableIndex) {
H
hjxilinx 已提交
1653
  assert(pQueryInfo != NULL);
1654

1655 1656 1657 1658 1659
  if (pQueryInfo->pMeterInfo == NULL) {
    assert(pQueryInfo->numOfTables == 0);
    return NULL;
  }

H
hjxilinx 已提交
1660
  assert(tableIndex >= 0 && tableIndex <= pQueryInfo->numOfTables && pQueryInfo->pMeterInfo != NULL);
1661 1662 1663 1664 1665

  return pQueryInfo->pMeterInfo[tableIndex];
}

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

1668
  if (pCmd->pQueryInfo == NULL || subClauseIndex >= pCmd->numOfClause) {
1669 1670 1671 1672 1673 1674
    return NULL;
  }

  return pCmd->pQueryInfo[subClauseIndex];
}

1675
int32_t tscGetQueryInfoDetailSafely(SSqlCmd* pCmd, int32_t subClauseIndex, SQueryInfo** pQueryInfo) {
1676
  int32_t ret = TSDB_CODE_SUCCESS;
1677

1678
  *pQueryInfo = tscGetQueryInfoDetail(pCmd, subClauseIndex);
1679

1680 1681 1682 1683
  while ((*pQueryInfo) == NULL) {
    if ((ret = tscAddSubqueryInfo(pCmd)) != TSDB_CODE_SUCCESS) {
      return ret;
    }
1684

1685 1686
    (*pQueryInfo) = tscGetQueryInfoDetail(pCmd, subClauseIndex);
  }
1687

1688 1689 1690
  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
1691
SMeterMetaInfo* tscGetMeterMetaInfoByUid(SQueryInfo* pQueryInfo, uint64_t uid, int32_t* index) {
S
slguan 已提交
1692
  int32_t k = -1;
1693 1694 1695

  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
    if (pQueryInfo->pMeterInfo[i]->pMeterMeta->uid == uid) {
S
slguan 已提交
1696 1697 1698 1699 1700 1701 1702 1703 1704
      k = i;
      break;
    }
  }

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

H
hjxilinx 已提交
1705
  assert(k != -1);
1706
  return tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, k);
S
slguan 已提交
1707 1708
}

1709
int32_t tscAddSubqueryInfo(SSqlCmd* pCmd) {
1710
  assert(pCmd != NULL);
1711 1712 1713

  size_t s = pCmd->numOfClause + 1;
  char*  tmp = realloc(pCmd->pQueryInfo, s * POINTER_BYTES);
1714 1715 1716
  if (tmp == NULL) {
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
1717 1718 1719 1720 1721 1722 1723

  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;
1724 1725 1726
  return TSDB_CODE_SUCCESS;
}

1727
static void doClearSubqueryInfo(SQueryInfo* pQueryInfo) {
1728 1729
  tscTagCondRelease(&pQueryInfo->tagCond);
  tscClearFieldInfo(&pQueryInfo->fieldsInfo);
1730

H
hjxilinx 已提交
1731
  tscSqlExprInfoDestroy(&pQueryInfo->exprsInfo);
1732
  memset(&pQueryInfo->exprsInfo, 0, sizeof(pQueryInfo->exprsInfo));
1733

1734 1735
  tscColumnBaseInfoDestroy(&pQueryInfo->colList);
  memset(&pQueryInfo->colList, 0, sizeof(pQueryInfo->colList));
1736

1737
  pQueryInfo->tsBuf = tsBufDestory(pQueryInfo->tsBuf);
1738

1739
  tfree(pQueryInfo->defaultVal);
1740
}
1741

1742
void tscClearSubqueryInfo(SSqlCmd* pCmd) {
1743
  for (int32_t i = 0; i < pCmd->numOfClause; ++i) {
1744 1745
    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, i);
    doClearSubqueryInfo(pQueryInfo);
1746
  }
1747 1748 1749 1750 1751 1752 1753 1754
}

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

  for (int32_t i = 0; i < pCmd->numOfClause; ++i) {
1755 1756 1757 1758
    char* addr = (char*)pCmd - offsetof(SSqlObj, cmd);

    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, i);

1759
    doClearSubqueryInfo(pQueryInfo);
1760
    tscRemoveAllMeterMetaInfo(pQueryInfo, (const char*)addr, false);
1761
    tfree(pQueryInfo);
1762
  }
1763

1764 1765 1766 1767
  pCmd->numOfClause = 0;
  tfree(pCmd->pQueryInfo);
}

1768
SMeterMetaInfo* tscAddMeterMetaInfo(SQueryInfo* pQueryInfo, const char* name, SMeterMeta* pMeterMeta,
1769 1770
                                    SMetricMeta* pMetricMeta, int16_t numOfTags, int16_t* tags) {
  void* pAlloc = realloc(pQueryInfo->pMeterInfo, (pQueryInfo->numOfTables + 1) * POINTER_BYTES);
S
slguan 已提交
1771 1772 1773 1774
  if (pAlloc == NULL) {
    return NULL;
  }

1775 1776
  pQueryInfo->pMeterInfo = pAlloc;
  pQueryInfo->pMeterInfo[pQueryInfo->numOfTables] = calloc(1, sizeof(SMeterMetaInfo));
S
slguan 已提交
1777

1778
  SMeterMetaInfo* pMeterMetaInfo = pQueryInfo->pMeterInfo[pQueryInfo->numOfTables];
S
slguan 已提交
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
  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 已提交
1791
    memcpy(pMeterMetaInfo->tagColumnIndex, tags, sizeof(pMeterMetaInfo->tagColumnIndex[0]) * numOfTags);
S
slguan 已提交
1792 1793
  }

1794
  pQueryInfo->numOfTables += 1;
S
slguan 已提交
1795 1796 1797
  return pMeterMetaInfo;
}

1798 1799
SMeterMetaInfo* tscAddEmptyMeterMetaInfo(SQueryInfo* pQueryInfo) {
  return tscAddMeterMetaInfo(pQueryInfo, NULL, NULL, NULL, 0, NULL);
1800
}
S
slguan 已提交
1801

1802 1803
void doRemoveMeterMetaInfo(SQueryInfo* pQueryInfo, int32_t index, bool removeFromCache) {
  if (index < 0 || index >= pQueryInfo->numOfTables) {
S
slguan 已提交
1804 1805 1806
    return;
  }

1807
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index);
S
slguan 已提交
1808 1809 1810 1811

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

1812
  int32_t after = pQueryInfo->numOfTables - index - 1;
S
slguan 已提交
1813
  if (after > 0) {
1814
    memmove(&pQueryInfo->pMeterInfo[index], &pQueryInfo->pMeterInfo[index + 1], after * POINTER_BYTES);
S
slguan 已提交
1815 1816
  }

1817
  pQueryInfo->numOfTables -= 1;
S
slguan 已提交
1818 1819
}

1820 1821
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 已提交
1822

1823 1824 1825
  int32_t index = pQueryInfo->numOfTables;
  while (index >= 0) {
    doRemoveMeterMetaInfo(pQueryInfo, --index, removeFromCache);
S
slguan 已提交
1826 1827
  }

1828
  tfree(pQueryInfo->pMeterInfo);
S
slguan 已提交
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
}

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 已提交
1841 1842 1843
  if (pRes == NULL) {
    return;
  }
1844

S
slguan 已提交
1845 1846 1847 1848
  pRes->row = 0;
  pRes->numOfRows = 0;
}

H
hjxilinx 已提交
1849
SSqlObj* createSubqueryObj(SSqlObj* pSql, int16_t tableIndex, void (*fp)(), void* param, SSqlObj* pPrevSql) {
H
hjxilinx 已提交
1850
  SSqlCmd*        pCmd = &pSql->cmd;
1851
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfo(pCmd, pCmd->clauseIndex, tableIndex);
S
slguan 已提交
1852 1853 1854

  SSqlObj* pNew = (SSqlObj*)calloc(1, sizeof(SSqlObj));
  if (pNew == NULL) {
H
hjxilinx 已提交
1855
    tscError("%p new subquery failed, tableIndex:%d, vnodeIndex:%d", pSql, tableIndex, pMeterMetaInfo->vnodeIndex);
S
slguan 已提交
1856 1857 1858 1859 1860 1861 1862 1863
    return NULL;
  }

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

  pNew->sqlstr = strdup(pSql->sqlstr);
  if (pNew->sqlstr == NULL) {
H
hjxilinx 已提交
1864
    tscError("%p new subquery failed, tableIndex:%d, vnodeIndex:%d", pSql, tableIndex, pMeterMetaInfo->vnodeIndex);
S
slguan 已提交
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875

    free(pNew);
    return NULL;
  }

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

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

1876
  pNew->cmd.pQueryInfo = NULL;
1877
  pNew->cmd.numOfClause = 0;
1878
  pNew->cmd.clauseIndex = 0;
1879 1880

  if (tscAddSubqueryInfo(&pNew->cmd) != TSDB_CODE_SUCCESS) {
1881 1882 1883
    tscFreeSqlObj(pNew);
    return NULL;
  }
1884 1885

  SQueryInfo* pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
1886
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
1887 1888 1889 1890 1891

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

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

1893 1894
  pNewQueryInfo->pMeterInfo = NULL;
  pNewQueryInfo->defaultVal = NULL;
1895 1896 1897 1898
  pNewQueryInfo->numOfTables = 0;
  pNewQueryInfo->tsBuf = NULL;

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

1900 1901 1902 1903
  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));
  }
1904

S
slguan 已提交
1905
  if (tscAllocPayload(&pNew->cmd, TSDB_DEFAULT_PAYLOAD_SIZE) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1906
    tscError("%p new subquery failed, tableIndex:%d, vnodeIndex:%d", pSql, tableIndex, pMeterMetaInfo->vnodeIndex);
S
slguan 已提交
1907 1908 1909 1910
    tscFreeSqlObj(pNew);
    return NULL;
  }

1911 1912
  tscColumnBaseInfoCopy(&pNewQueryInfo->colList, &pQueryInfo->colList, (int16_t)tableIndex);

S
slguan 已提交
1913 1914
  // set the correct query type
  if (pPrevSql != NULL) {
1915
    SQueryInfo* pPrevQueryInfo = tscGetQueryInfoDetail(&pPrevSql->cmd, pPrevSql->cmd.clauseIndex);
1916
    pNewQueryInfo->type = pPrevQueryInfo->type;
S
slguan 已提交
1917
  } else {
1918
    pNewQueryInfo->type |= TSDB_QUERY_TYPE_SUBQUERY;  // it must be the subquery
S
slguan 已提交
1919 1920 1921
  }

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

1924
  int32_t numOfOutputCols = pNewQueryInfo->exprsInfo.numOfExprs;
S
slguan 已提交
1925 1926 1927

  if (numOfOutputCols > 0) {
    int32_t* indexList = calloc(1, numOfOutputCols * sizeof(int32_t));
1928 1929
    for (int32_t i = 0, j = 0; i < pQueryInfo->exprsInfo.numOfExprs; ++i) {
      SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
1930 1931 1932 1933 1934
      if (pExpr->uid == uid) {
        indexList[j++] = i;
      }
    }

1935
    tscFieldInfoCopy(&pQueryInfo->fieldsInfo, &pNewQueryInfo->fieldsInfo, indexList, numOfOutputCols);
S
slguan 已提交
1936 1937
    free(indexList);

1938
    tscFieldInfoUpdateOffsetForInterResult(pNewQueryInfo);
S
slguan 已提交
1939 1940 1941 1942
  }

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

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

H
hjxilinx 已提交
1947 1948 1949
#ifdef _DEBUG_VIEW
  printf("the metricmeta key is:%s\n", key);
#endif
H
hjxilinx 已提交
1950

1951
  char*           name = pMeterMetaInfo->name;
S
slguan 已提交
1952 1953 1954 1955 1956 1957
  SMeterMetaInfo* pFinalInfo = NULL;

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

1958
    pFinalInfo = tscAddMeterMetaInfo(pNewQueryInfo, name, pMeterMeta, pMetricMeta, pMeterMetaInfo->numOfTags,
1959
                                     pMeterMetaInfo->tagColumnIndex);
1960 1961 1962 1963 1964 1965
  } 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);

1966 1967
    pFinalInfo = tscAddMeterMetaInfo(pNewQueryInfo, name, pPrevMeterMeta, pPrevMetricMeta, pMeterMetaInfo->numOfTags,
                                     pMeterMetaInfo->tagColumnIndex);
S
slguan 已提交
1968 1969
  }

1970
  assert(pFinalInfo->pMeterMeta != NULL && pNewQueryInfo->numOfTables == 1);
1971
  if (UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {
S
slguan 已提交
1972 1973
    assert(pFinalInfo->pMetricMeta != NULL);
  }
H
hjxilinx 已提交
1974
  
1975
  tscTrace(
H
hjxilinx 已提交
1976 1977
      "%p new subquery: %p, tableIndex:%d, vnodeIdx:%d, type:%d, exprInfo:%d, colList:%d,"
      "fieldInfo:%d, name:%s, qrang:%" PRId64 " - %" PRId64 " order:%d, limit:%" PRId64,
1978
      pSql, pNew, tableIndex, pMeterMetaInfo->vnodeIndex, pNewQueryInfo->type, pNewQueryInfo->exprsInfo.numOfExprs,
H
hjxilinx 已提交
1979 1980 1981 1982
      pNewQueryInfo->colList.numOfCols, pNewQueryInfo->fieldsInfo.numOfOutputCols, pFinalInfo->name, pNewQueryInfo->stime,
      pNewQueryInfo->etime, pNewQueryInfo->order.order, pNewQueryInfo->limit.limit);
  
  tscPrintSelectClause(pNew, 0);
1983

S
slguan 已提交
1984 1985 1986
  return pNew;
}

H
hzcheng 已提交
1987 1988
void tscDoQuery(SSqlObj* pSql) {
  SSqlCmd* pCmd = &pSql->cmd;
1989
  void*    fp = pSql->fp;
H
hjxilinx 已提交
1990
  
1991
  pSql->res.code = TSDB_CODE_SUCCESS;
H
hjxilinx 已提交
1992
  
H
hzcheng 已提交
1993 1994 1995 1996 1997 1998 1999
  if (pCmd->command > TSDB_SQL_LOCAL) {
    tscProcessLocalCmd(pSql);
  } else {
    if (pCmd->command == TSDB_SQL_SELECT) {
      tscAddIntoSqlList(pSql);
    }

2000 2001
    if (pCmd->dataSourceType == DATA_FROM_DATA_FILE) {
      tscProcessMultiVnodesInsertFromFile(pSql);
H
hzcheng 已提交
2002
    } else {
S
slguan 已提交
2003
      // pSql may be released in this function if it is a async insertion.
H
hzcheng 已提交
2004
      tscProcessSql(pSql);
S
slguan 已提交
2005
      if (NULL == fp) tscProcessMultiVnodesInsert(pSql);
S
slguan 已提交
2006
    }
H
hzcheng 已提交
2007 2008
  }
}
S
slguan 已提交
2009

H
hjxilinx 已提交
2010
int16_t tscGetJoinTagColIndexByUid(STagCond* pTagCond, uint64_t uid) {
S
slguan 已提交
2011 2012 2013 2014 2015 2016
  if (pTagCond->joinInfo.left.uid == uid) {
    return pTagCond->joinInfo.left.tagCol;
  } else {
    return pTagCond->joinInfo.right.tagCol;
  }
}
2017 2018 2019 2020 2021 2022 2023

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

H
hjxilinx 已提交
2024 2025
  SSqlCmd* pCmd = &pObj->pSql->cmd;
  return ((pCmd->command >= TSDB_SQL_INSERT && pCmd->command <= TSDB_SQL_DROP_DNODE) ||
H
hjxilinx 已提交
2026 2027 2028
          TSDB_SQL_USE_DB == pCmd->command)
             ? 1
             : 0;
H
hjxilinx 已提交
2029
}
2030

H
hjxilinx 已提交
2031 2032 2033 2034 2035
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 已提交
2036
  const int32_t BACKWARD_CHAR_STEP = 0;
H
hjxilinx 已提交
2037

H
hjxilinx 已提交
2038 2039 2040 2041 2042
  if (sql == NULL) {
    assert(additionalInfo != NULL);
    sprintf(msg, msgFormat1, additionalInfo);
    return TSDB_CODE_INVALID_SQL;
  }
H
hjxilinx 已提交
2043 2044

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

H
hjxilinx 已提交
2047 2048 2049
  if (additionalInfo != NULL) {
    sprintf(msg, msgFormat2, buf, additionalInfo);
  } else {
H
hjxilinx 已提交
2050
    sprintf(msg, msgFormat3, buf);  // no additional information for invalid sql error
H
hjxilinx 已提交
2051
  }
H
hjxilinx 已提交
2052

H
hjxilinx 已提交
2053
  return TSDB_CODE_INVALID_SQL;
2054
}
H
hjxilinx 已提交
2055

H
hjxilinx 已提交
2056 2057 2058
bool tscHasReachLimitation(SQueryInfo* pQueryInfo, SSqlRes* pRes) {
  assert(pQueryInfo != NULL && pQueryInfo->clauseLimit != 0);
  return (pQueryInfo->clauseLimit > 0 && pRes->numOfTotalInCurrentClause >= pQueryInfo->clauseLimit);
H
hjxilinx 已提交
2059
}
2060 2061

char* tscGetErrorMsgPayload(SSqlCmd* pCmd) { return pCmd->payload; }
2062 2063 2064 2065 2066

/**
 *  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.
 */
2067 2068 2069 2070 2071
bool hasMoreVnodesToTry(SSqlObj* pSql) {
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;

  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
2072
  
2073
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
2074
  if (!UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo) || (pMeterMetaInfo->pMetricMeta == NULL)) {
2075 2076
    return false;
  }
2077
  
2078
  int32_t totalVnode = pMeterMetaInfo->pMetricMeta->numOfVnodes;
2079
  return pRes->numOfRows == 0 && tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) &&
2080
         (!tscHasReachLimitation(pQueryInfo, pRes)) && (pMeterMetaInfo->vnodeIndex < totalVnode - 1);
2081 2082
}

2083 2084 2085 2086 2087 2088
void tscTryQueryNextVnode(SSqlObj* pSql, __async_cb_func_t fp) {
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;

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

2089 2090 2091 2092
  /*
   * no result returned from the current virtual node anymore, try the next vnode if exists
   * if case of: multi-vnode super table projection query
   */
2093
  assert(pRes->numOfRows == 0 && tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) && !tscHasReachLimitation(pQueryInfo, pRes));
2094 2095

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

2098 2099 2100
  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);
2101

2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
    /*
     * 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;
    }
2114

2115
    pQueryInfo->limit.offset = pRes->offset;
2116

2117 2118 2119
    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);
2120

2121 2122 2123 2124 2125 2126 2127 2128
    /*
     * 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;
2129

2130
    tscResetForNextRetrieve(pRes);
2131

2132 2133
    // in case of async query, set the callback function
    void* fp1 = pSql->fp;
2134
    pSql->fp = fp;
2135

2136
    if (fp1 != NULL) {
2137
      assert(fp != NULL);
2138
    }
2139

2140
    int32_t ret = tscProcessSql(pSql);  // todo check for failure
2141

2142
    // in case of async query, return now
2143 2144 2145
    if (fp != NULL) {
      return;
    }
2146

2147 2148 2149 2150
    if (ret != TSDB_CODE_SUCCESS) {
      pSql->res.code = ret;
      return;
    }
2151

2152 2153 2154
    // retrieve data
    assert(pCmd->command == TSDB_SQL_SELECT);
    pCmd->command = TSDB_SQL_FETCH;
2155

2156 2157 2158 2159
    if ((ret = tscProcessSql(pSql)) != TSDB_CODE_SUCCESS) {
      pSql->res.code = ret;
      return;
    }
2160

2161 2162 2163 2164 2165
    // if the result from current virtual node are empty, try next if exists. otherwise, return the results.
    if (pRes->numOfRows > 0) {
      break;
    }
  }
2166

2167 2168 2169 2170
  if (pRes->numOfRows == 0) {
    tscTrace("%p all vnodes exhausted, prj query completed. total res:%d", pSql, totalVnode, pRes->numOfTotal);
  }
}
2171 2172 2173 2174 2175 2176 2177 2178

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);

H
hjxilinx 已提交
2179
  pCmd->clauseIndex++;
2180 2181 2182 2183
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);

  pSql->cmd.command = pQueryInfo->command;

2184 2185 2186 2187 2188 2189
  //backup the total number of result first
  int64_t num = pRes->numOfTotal + pRes->numOfTotalInCurrentClause;
  tscFreeResData(pSql);
  
  pRes->numOfTotal = num;
  
2190
  tfree(pSql->pSubs);
2191 2192
  pSql->numOfSubs = 0;
  
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
  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);
  }
}