tscUtil.c 58.4 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
 */
40 41 42 43 44 45
void tscGetMetricMetaCacheKey(SSqlCmd* pCmd, int32_t subClauseIndex, char* str, uint64_t uid) {
  int32_t index = -1;

  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoByUid(pQueryInfo, subClauseIndex, uid, &index);
H
hzcheng 已提交
46

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

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

S
slguan 已提交
56 57 58 59 60 61 62 63 64
  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 已提交
65
  // estimate the buffer size
H
hjxilinx 已提交
66
  size_t tbnameCondLen = pTagCond->tbnameCond.cond != NULL ? strlen(pTagCond->tbnameCond.cond) : 0;
H
hjxilinx 已提交
67
  size_t redundantLen = 20;
H
hjxilinx 已提交
68

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

  bufSize = (size_t)((bufSize + redundantLen) * 1.5);
H
hjxilinx 已提交
75 76 77
  char* tmp = calloc(1, bufSize);

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

H
hjxilinx 已提交
81
  assert(keyLen <= bufSize);
S
slguan 已提交
82 83 84 85

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

H
hjxilinx 已提交
89
    MD5Update(&ctx, (uint8_t*)tmp, keyLen);
S
slguan 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    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 已提交
111 112
  }

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

  pTagCond->numOfTagCond += 1;
}

bool tscQueryOnMetric(SSqlCmd* pCmd) {
121 122 123
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

  return ((pQueryInfo->type & TSDB_QUERY_TYPE_STABLE_QUERY) == TSDB_QUERY_TYPE_STABLE_QUERY) &&
S
slguan 已提交
124 125 126
         (pCmd->msgType == TSDB_MSG_TYPE_QUERY);
}

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

S
slguan 已提交
134
  return true;
H
hzcheng 已提交
135 136
}

S
slguan 已提交
137 138 139 140
bool tscIsSelectivityWithTagQuery(SSqlCmd* pCmd) {
  bool    hasTags = false;
  int32_t numOfSelectivity = 0;

141 142 143 144
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    int32_t functId = tscSqlExprGet(pQueryInfo, i)->functionId;
S
slguan 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    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 已提交
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 208 209 210

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

S
slguan 已提交
211 212
bool tscIsTwoStageMergeMetricQuery(SSqlCmd* pCmd) {
  assert(pCmd != NULL);
H
hzcheng 已提交
213

214 215 216 217 218 219 220
  int32_t     subClauseIndex = 0;
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, subClauseIndex);
  if (pQueryInfo == NULL) {
    return false;
  }

  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
S
slguan 已提交
221 222 223 224 225
  if (pMeterMetaInfo == NULL || pMeterMetaInfo->pMetricMeta == NULL) {
    return false;
  }

  // for projection query, iterate all qualified vnodes sequentially
226
  if (tscProjectionQueryOnSTable(pCmd, subClauseIndex)) {
H
hzcheng 已提交
227 228 229
    return false;
  }

230
  if (((pQueryInfo->type & TSDB_QUERY_TYPE_STABLE_SUBQUERY) != TSDB_QUERY_TYPE_STABLE_SUBQUERY) &&
S
slguan 已提交
231
      pCmd->command == TSDB_SQL_SELECT) {
232
    return UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo);
H
hzcheng 已提交
233 234 235 236 237
  }

  return false;
}

238
bool tscProjectionQueryOnSTable(SSqlCmd* pCmd, int32_t subClauseIndex) {
S
slguan 已提交
239
  assert(pCmd != NULL);
H
hzcheng 已提交
240

241 242 243
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, subClauseIndex);
  assert(pQueryInfo->numOfTables > 0);
  
244
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
H
hzcheng 已提交
245 246 247

  /*
   * In following cases, return false for project query on metric
S
slguan 已提交
248
   * 1. failed to get metermeta from server; 2. not a metric; 3. limit 0; 4. show query, instead of a select query
H
hzcheng 已提交
249
   */
250 251
  if (pMeterMetaInfo == NULL || !UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo) ||
      pCmd->command == TSDB_SQL_RETRIEVE_EMPTY_RESULT || pQueryInfo->exprsInfo.numOfExprs == 0) {
H
hzcheng 已提交
252 253 254
    return false;
  }

S
slguan 已提交
255
  // only query on tag, not a projection query
256
  if (tscQueryMetricTags(pQueryInfo)) {
S
slguan 已提交
257 258 259
    return false;
  }

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

S
slguan 已提交
269
  return true;
H
hzcheng 已提交
270 271
}

272 273 274
bool tscProjectionQueryOnTable(SQueryInfo* pQueryInfo) {
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    int32_t functionId = tscSqlExprGet(pQueryInfo, i)->functionId;
H
hjxilinx 已提交
275 276 277 278
    if (functionId != TSDB_FUNC_PRJ && functionId != TSDB_FUNC_TS) {
      return false;
    }
  }
H
hjxilinx 已提交
279

H
hjxilinx 已提交
280 281 282
  return true;
}

283 284 285
bool tscIsPointInterpQuery(SQueryInfo* pQueryInfo) {
  for (int32_t i = 0; i < pQueryInfo->exprsInfo.numOfExprs; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
H
hzcheng 已提交
286 287 288 289
    if (pExpr == NULL) {
      return false;
    }

S
slguan 已提交
290
    int32_t functionId = pExpr->functionId;
H
hzcheng 已提交
291 292 293 294 295 296 297 298 299 300 301
    if (functionId == TSDB_FUNC_TAG) {
      continue;
    }

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

302 303 304
bool tscIsTWAQuery(SQueryInfo* pQueryInfo) {
  for (int32_t i = 0; i < pQueryInfo->exprsInfo.numOfExprs; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
305 306 307 308 309 310 311 312 313 314 315
    if (pExpr == NULL) {
      continue;
    }

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

  return false;
H
hzcheng 已提交
316 317
}

318 319
void tscClearInterpInfo(SQueryInfo* pQueryInfo) {
  if (!tscIsPointInterpQuery(pQueryInfo)) {
H
hzcheng 已提交
320 321 322
    return;
  }

323
  pQueryInfo->interpoType = TSDB_INTERPO_NONE;
324
  tfree(pQueryInfo->defaultVal);
H
hzcheng 已提交
325 326 327 328
}

void tscClearSqlMetaInfoForce(SSqlCmd* pCmd) {
  /* remove the metermeta/metricmeta in cache */
329 330
  //    taosRemoveDataFromCache(tscCacheHandle, (void**)&(pCmd->pMeterMeta), true);
  //    taosRemoveDataFromCache(tscCacheHandle, (void**)&(pCmd->pMetricMeta), true);
H
hzcheng 已提交
331 332
}

333
int32_t tscCreateResPointerInfo(SQueryInfo* pQueryInfo, SSqlRes* pRes) {
H
hzcheng 已提交
334 335
  if (pRes->tsrow == NULL) {
    pRes->numOfnchar = 0;
336
    int32_t numOfOutputCols = pQueryInfo->fieldsInfo.numOfOutputCols;
H
hzcheng 已提交
337 338

    for (int32_t i = 0; i < numOfOutputCols; ++i) {
339
      TAOS_FIELD* pField = tscFieldInfoGetField(pQueryInfo, i);
H
hzcheng 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
      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 已提交
375
void tscFreeSqlCmdData(SSqlCmd* pCmd) {
S
slguan 已提交
376
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
377
  tscFreeSubqueryInfo(pCmd);
H
hzcheng 已提交
378 379 380
}

void tscFreeSqlObjPartial(SSqlObj* pSql) {
S
slguan 已提交
381 382 383
  if (pSql == NULL || pSql->signature != pSql) {
    return;
  }
H
hzcheng 已提交
384 385 386 387 388 389 390

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

  STscObj* pObj = pSql->pTscObj;

  int32_t cmd = pCmd->command;
S
slguan 已提交
391 392
  if (cmd < TSDB_SQL_INSERT || cmd == TSDB_SQL_RETRIEVE_METRIC || cmd == TSDB_SQL_RETRIEVE_EMPTY_RESULT ||
      cmd == TSDB_SQL_METRIC_JOIN_RETRIEVE) {
H
hzcheng 已提交
393 394 395
    tscRemoveFromSqlList(pSql);
  }

396
  pCmd->command = 0;
S
slguan 已提交
397

H
hzcheng 已提交
398 399 400 401 402
  // pSql->sqlstr will be used by tscBuildQueryStreamDesc
  pthread_mutex_lock(&pObj->mutex);
  tfree(pSql->sqlstr);
  pthread_mutex_unlock(&pObj->mutex);

403 404 405 406
  tfree(pRes->pRsp);
  pRes->row = 0;
  pRes->numOfRows = 0;
  pRes->numOfTotal = 0;
H
hzcheng 已提交
407

408 409
  pRes->numOfGroups = 0;
  tfree(pRes->pGroupRec);
H
hzcheng 已提交
410 411 412 413 414 415

  tscDestroyLocalReducer(pSql);

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

S
slguan 已提交
418
  tscFreeSqlCmdData(pCmd);
H
hzcheng 已提交
419 420 421 422 423 424 425 426 427 428 429 430
}

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 已提交
431
  memset(pCmd->payload, 0, (size_t)pCmd->allocSize);
H
hzcheng 已提交
432 433 434 435 436
  tfree(pCmd->payload);

  pCmd->allocSize = 0;

  if (pSql->res.buffer != NULL) {
437 438 439
    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

    for (int i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; i++) {
H
hzcheng 已提交
440 441 442 443 444 445 446 447 448
      if (pSql->res.buffer[i] != NULL) {
        tfree(pSql->res.buffer[i]);
      }
    }

    tfree(pSql->res.buffer);
  }

  if (pSql->fp == NULL) {
S
slguan 已提交
449 450
    tsem_destroy(&pSql->rspSem);
    tsem_destroy(&pSql->emptyRspSem);
H
hzcheng 已提交
451 452 453 454
  }
  free(pSql);
}

S
slguan 已提交
455 456
void tscDestroyDataBlock(STableDataBlocks* pDataBlock) {
  if (pDataBlock == NULL) {
H
hzcheng 已提交
457 458 459
    return;
  }

S
slguan 已提交
460
  tfree(pDataBlock->pData);
S
slguan 已提交
461
  tfree(pDataBlock->params);
H
hjxilinx 已提交
462

H
hjxilinx 已提交
463
  // free the refcount for metermeta
H
hjxilinx 已提交
464
  taosRemoveDataFromCache(tscCacheHandle, (void**)&(pDataBlock->pMeterMeta), false);
S
slguan 已提交
465
  tfree(pDataBlock);
H
hzcheng 已提交
466 467
}

468 469
SParamInfo* tscAddParamToDataBlock(STableDataBlocks* pDataBlock, char type, uint8_t timePrec, short bytes,
                                   uint32_t offset) {
S
slguan 已提交
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
  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 已提交
492 493 494 495
SDataBlockList* tscCreateBlockArrayList() {
  const int32_t DEFAULT_INITIAL_NUM_OF_BLOCK = 16;

  SDataBlockList* pDataBlockArrayList = calloc(1, sizeof(SDataBlockList));
S
slguan 已提交
496 497 498
  if (pDataBlockArrayList == NULL) {
    return NULL;
  }
H
hzcheng 已提交
499 500
  pDataBlockArrayList->nAlloc = DEFAULT_INITIAL_NUM_OF_BLOCK;
  pDataBlockArrayList->pData = calloc(1, POINTER_BYTES * pDataBlockArrayList->nAlloc);
S
slguan 已提交
501 502 503 504
  if (pDataBlockArrayList->pData == NULL) {
    free(pDataBlockArrayList);
    return NULL;
  }
H
hzcheng 已提交
505 506 507 508

  return pDataBlockArrayList;
}

509
void tscAppendDataBlock(SDataBlockList* pList, STableDataBlocks* pBlocks) {
S
slguan 已提交
510
  if (pList->nSize >= pList->nAlloc) {
H
hjxilinx 已提交
511 512
    pList->nAlloc = (pList->nAlloc) << 1U;
    pList->pData = realloc(pList->pData, POINTER_BYTES * (size_t)pList->nAlloc);
S
slguan 已提交
513 514

    // reset allocated memory
H
hjxilinx 已提交
515
    memset(pList->pData + pList->nSize, 0, POINTER_BYTES * (pList->nAlloc - pList->nSize));
S
slguan 已提交
516 517 518 519 520
  }

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

S
slguan 已提交
521 522 523
void* tscDestroyBlockArrayList(SDataBlockList* pList) {
  if (pList == NULL) {
    return NULL;
H
hzcheng 已提交
524 525
  }

S
slguan 已提交
526 527
  for (int32_t i = 0; i < pList->nSize; i++) {
    tscDestroyDataBlock(pList->pData[i]);
H
hzcheng 已提交
528 529
  }

S
slguan 已提交
530 531 532 533
  tfree(pList->pData);
  tfree(pList);

  return NULL;
H
hzcheng 已提交
534 535
}

S
slguan 已提交
536
int32_t tscCopyDataBlockToPayload(SSqlObj* pSql, STableDataBlocks* pDataBlock) {
H
hjxilinx 已提交
537
  SSqlCmd* pCmd = &pSql->cmd;
H
hjxilinx 已提交
538
  assert(pDataBlock->pMeterMeta != NULL);
H
hjxilinx 已提交
539

540
  pCmd->numOfTablesInSubmit = pDataBlock->numOfMeters;
541
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfo(pCmd, 0, 0);
H
hjxilinx 已提交
542 543

  // set the correct metermeta object, the metermeta has been locked in pDataBlocks, so it must be in the cache
H
hjxilinx 已提交
544 545
  if (pMeterMetaInfo->pMeterMeta != pDataBlock->pMeterMeta) {
    strcpy(pMeterMetaInfo->name, pDataBlock->meterId);
H
hjxilinx 已提交
546
    taosRemoveDataFromCache(tscCacheHandle, (void**)&(pMeterMetaInfo->pMeterMeta), false);
547 548
  
    pMeterMetaInfo->pMeterMeta = taosTransferDataInCache(tscCacheHandle, (void**) &pDataBlock->pMeterMeta);
H
hjxilinx 已提交
549 550 551
  } else {
    assert(strncmp(pMeterMetaInfo->name, pDataBlock->meterId, tListLen(pDataBlock->meterId)) == 0);
  }
H
hjxilinx 已提交
552

553 554 555 556 557
  /*
   * 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 已提交
558
  int ret = tscAllocPayload(pCmd, pDataBlock->nAllocSize + sizeof(STaosDigest));
H
hjxilinx 已提交
559 560 561
  if (TSDB_CODE_SUCCESS != ret) {
    return ret;
  }
H
hjxilinx 已提交
562

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

565 566 567 568 569
  /*
   * 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 已提交
570

571
  assert(pCmd->allocSize >= pCmd->payloadLen + tsRpcHeadSize + sizeof(STaosDigest));
H
hjxilinx 已提交
572
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
573 574 575 576 577
}

void tscFreeUnusedDataBlocks(SDataBlockList* pList) {
  /* release additional memory consumption */
  for (int32_t i = 0; i < pList->nSize; ++i) {
S
slguan 已提交
578 579 580
    STableDataBlocks* pDataBlock = pList->pData[i];
    pDataBlock->pData = realloc(pDataBlock->pData, pDataBlock->size);
    pDataBlock->nAllocSize = (uint32_t)pDataBlock->size;
H
hzcheng 已提交
581 582 583
  }
}

H
hjxilinx 已提交
584 585 586 587 588 589
/**
 * create the in-memory buffer for each table to keep the submitted data block
 * @param initialSize
 * @param rowSize
 * @param startOffset
 * @param name
H
hjxilinx 已提交
590
 * @param dataBlocks
H
hjxilinx 已提交
591 592
 * @return
 */
H
hjxilinx 已提交
593
int32_t tscCreateDataBlock(size_t initialSize, int32_t rowSize, int32_t startOffset, const char* name,
594
                           SMeterMeta* pMeterMeta, STableDataBlocks** dataBlocks) {
H
hjxilinx 已提交
595
  STableDataBlocks* dataBuf = (STableDataBlocks*)calloc(1, sizeof(STableDataBlocks));
H
hjxilinx 已提交
596 597 598 599 600 601
  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 已提交
602 603 604
  dataBuf->pData = calloc(1, dataBuf->nAllocSize);
  dataBuf->ordered = true;
  dataBuf->prevTS = INT64_MIN;
S
slguan 已提交
605 606 607

  dataBuf->rowSize = rowSize;
  dataBuf->size = startOffset;
S
slguan 已提交
608 609
  dataBuf->tsSource = -1;

S
slguan 已提交
610
  strncpy(dataBuf->meterId, name, TSDB_METER_ID_LEN);
H
hjxilinx 已提交
611 612 613

  /*
   * The metermeta may be released since the metermeta cache are completed clean by other thread
614 615
   * 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 已提交
616
   */
617 618
  dataBuf->pMeterMeta = taosGetDataFromExists(tscCacheHandle, pMeterMeta);
  assert(initialSize > 0 && pMeterMeta != NULL && dataBuf->pMeterMeta != NULL);
619

620 621
  *dataBlocks = dataBuf;
  return TSDB_CODE_SUCCESS;
S
slguan 已提交
622 623
}

H
hjxilinx 已提交
624
int32_t tscGetDataBlockFromList(void* pHashList, SDataBlockList* pDataBlockList, int64_t id, int32_t size,
625
                                int32_t startOffset, int32_t rowSize, const char* tableId, SMeterMeta* pMeterMeta,
H
hjxilinx 已提交
626 627
                                STableDataBlocks** dataBlocks) {
  *dataBlocks = NULL;
S
slguan 已提交
628

629
  STableDataBlocks** t1 = (STableDataBlocks**)taosGetDataFromHash(pHashList, (const char*)&id, sizeof(id));
S
slguan 已提交
630
  if (t1 != NULL) {
H
hjxilinx 已提交
631
    *dataBlocks = *t1;
S
slguan 已提交
632 633
  }

H
hjxilinx 已提交
634
  if (*dataBlocks == NULL) {
635
    int32_t ret = tscCreateDataBlock((size_t)size, rowSize, startOffset, tableId, pMeterMeta, dataBlocks);
H
hjxilinx 已提交
636 637 638 639
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }

640
    taosAddToHashTable(pHashList, (const char*)&id, sizeof(int64_t), (char*)dataBlocks, POINTER_BYTES);
H
hjxilinx 已提交
641
    tscAppendDataBlock(pDataBlockList, *dataBlocks);
S
slguan 已提交
642 643
  }

H
hjxilinx 已提交
644
  return TSDB_CODE_SUCCESS;
S
slguan 已提交
645 646
}

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

650
  void* pVnodeDataBlockHashList = taosInitHashTable(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false);
S
slguan 已提交
651 652 653 654
  SDataBlockList* pVnodeDataBlockList = tscCreateBlockArrayList();

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

H
hjxilinx 已提交
656
    STableDataBlocks* dataBuf = NULL;
657
    int32_t           ret = tscGetDataBlockFromList(pVnodeDataBlockHashList, pVnodeDataBlockList, pOneTableBlock->vgid,
658 659
                                          TSDB_PAYLOAD_SIZE, tsInsertHeadSize, 0, pOneTableBlock->meterId,
                                          pOneTableBlock->pMeterMeta, &dataBuf);
H
hjxilinx 已提交
660
    if (ret != TSDB_CODE_SUCCESS) {
661 662 663
      tscError("%p failed to prepare the data block buffer for merging table data, code:%d", pSql, ret);
      taosCleanUpHashTable(pVnodeDataBlockHashList);
      tscDestroyBlockArrayList(pVnodeDataBlockList);
H
hjxilinx 已提交
664 665
      return ret;
    }
S
slguan 已提交
666 667 668 669 670 671 672 673 674 675 676

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

680
        taosCleanUpHashTable(pVnodeDataBlockHashList);
S
slguan 已提交
681 682 683 684
        tfree(dataBuf->pData);
        tscDestroyBlockArrayList(pVnodeDataBlockList);

        return TSDB_CODE_CLI_OUT_OF_MEMORY;
S
slguan 已提交
685 686 687 688
      }
    }

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

S
slguan 已提交
691 692
    tscTrace("%p meterId:%s, sid:%d, rows:%d, sversion:%d", pSql, pOneTableBlock->meterId, pBlocks->sid,
             pBlocks->numOfRows, pBlocks->sversion);
S
slguan 已提交
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710

    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);
711
  taosCleanUpHashTable(pVnodeDataBlockHashList);
S
slguan 已提交
712 713

  return TSDB_CODE_SUCCESS;
S
slguan 已提交
714 715
}

H
hzcheng 已提交
716 717 718 719 720 721 722 723 724 725 726 727 728 729
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) {
730 731 732 733 734 735 736 737
  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 已提交
738 739
}

S
slguan 已提交
740
int tscAllocPayload(SSqlCmd* pCmd, int size) {
H
hzcheng 已提交
741 742 743 744 745
  assert(size > 0);

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

S
slguan 已提交
746
    pCmd->payload = (char*)malloc(size);
H
hzcheng 已提交
747 748 749 750
    if (pCmd->payload == NULL) return TSDB_CODE_CLI_OUT_OF_MEMORY;
    pCmd->allocSize = size;
  } else {
    if (pCmd->allocSize < size) {
751
      char* b = realloc(pCmd->payload, size);
S
slguan 已提交
752 753
      if (b == NULL) return TSDB_CODE_CLI_OUT_OF_MEMORY;
      pCmd->payload = b;
H
hzcheng 已提交
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
      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 已提交
785 786
    pFieldInfo->pVisibleCols = realloc(pFieldInfo->pVisibleCols, newSize * sizeof(bool));

H
hzcheng 已提交
787 788 789 790 791 792 793 794 795 796 797
    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 已提交
798
static void setValueImpl(TAOS_FIELD* pField, int8_t type, const char* name, int16_t bytes) {
H
hzcheng 已提交
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
  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 已提交
818 819
  pFieldInfo->pVisibleCols[index] = true;

H
hzcheng 已提交
820 821 822
  pFieldInfo->numOfOutputCols++;
}

S
slguan 已提交
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
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 已提交
842
void tscFieldInfoSetValue(SFieldInfo* pFieldInfo, int32_t index, int8_t type, const char* name, int16_t bytes) {
H
hzcheng 已提交
843 844 845 846 847
  ensureSpace(pFieldInfo, pFieldInfo->numOfOutputCols + 1);
  evic(pFieldInfo, index);

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

  pFieldInfo->pVisibleCols[index] = true;
H
hzcheng 已提交
850 851 852
  pFieldInfo->numOfOutputCols++;
}

853 854
void tscFieldInfoCalOffset(SQueryInfo* pQueryInfo) {
  SFieldInfo* pFieldInfo = &pQueryInfo->fieldsInfo;
H
hzcheng 已提交
855 856 857 858 859 860 861
  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;
  }
}

862 863
void tscFieldInfoUpdateOffset(SQueryInfo* pQueryInfo) {
  SFieldInfo* pFieldInfo = &pQueryInfo->fieldsInfo;
H
hzcheng 已提交
864 865 866 867 868 869 870 871 872 873 874
  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) {
875
    pFieldInfo->pOffset[i] = pFieldInfo->pOffset[i - 1] + tscSqlExprGet(pQueryInfo, i - 1)->resBytes;
H
hzcheng 已提交
876 877 878
  }
}

S
slguan 已提交
879
void tscFieldInfoCopy(SFieldInfo* src, SFieldInfo* dst, const int32_t* indexList, int32_t size) {
H
hzcheng 已提交
880 881 882 883
  if (src == NULL) {
    return;
  }

S
slguan 已提交
884 885
  if (size <= 0) {
    *dst = *src;
886
    tscFieldInfoCopyAll(dst, src);
S
slguan 已提交
887 888 889 890 891 892 893 894
  } 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]]);
    }
  }
}

895
void tscFieldInfoCopyAll(SFieldInfo* dst, SFieldInfo* src) {
H
hzcheng 已提交
896 897 898 899
  *dst = *src;

  dst->pFields = malloc(sizeof(TAOS_FIELD) * dst->numOfAlloc);
  dst->pOffset = malloc(sizeof(short) * dst->numOfAlloc);
S
slguan 已提交
900
  dst->pVisibleCols = malloc(sizeof(bool) * dst->numOfAlloc);
H
hzcheng 已提交
901 902 903

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

907 908
TAOS_FIELD* tscFieldInfoGetField(SQueryInfo* pQueryInfo, int32_t index) {
  if (index >= pQueryInfo->fieldsInfo.numOfOutputCols) {
H
hzcheng 已提交
909 910 911
    return NULL;
  }

912
  return &pQueryInfo->fieldsInfo.pFields[index];
913 914
}

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

917 918
int16_t tscFieldInfoGetOffset(SQueryInfo* pQueryInfo, int32_t index) {
  if (index >= pQueryInfo->fieldsInfo.numOfOutputCols) {
H
hzcheng 已提交
919 920 921
    return 0;
  }

922
  return pQueryInfo->fieldsInfo.pOffset[index];
H
hzcheng 已提交
923 924
}

925 926
int32_t tscGetResRowLength(SQueryInfo* pQueryInfo) {
  SFieldInfo* pFieldInfo = &pQueryInfo->fieldsInfo;
H
hzcheng 已提交
927 928 929 930 931 932 933 934
  if (pFieldInfo->numOfOutputCols <= 0) {
    return 0;
  }

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

S
slguan 已提交
935 936
void tscClearFieldInfo(SFieldInfo* pFieldInfo) {
  if (pFieldInfo == NULL) {
H
hzcheng 已提交
937 938 939
    return;
  }

S
slguan 已提交
940 941 942 943 944
  tfree(pFieldInfo->pOffset);
  tfree(pFieldInfo->pFields);
  tfree(pFieldInfo->pVisibleCols);

  memset(pFieldInfo, 0, sizeof(SFieldInfo));
H
hzcheng 已提交
945 946 947 948
}

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

951
    uint32_t newSize = (oldSize <= 0) ? 8 : (oldSize << 1U);
H
hzcheng 已提交
952
    while (newSize < size) {
953
      newSize = (newSize << 1U);
H
hzcheng 已提交
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
    }

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

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

H
hjxilinx 已提交
979 980
  _exprCheckSpace(pExprInfo, pExprInfo->numOfExprs + 1);
  _exprEvic(pExprInfo, index);
H
hjxilinx 已提交
981

H
hjxilinx 已提交
982 983
  SSqlExpr* pExpr = &pExprInfo->pExprs[index];
  pExpr->functionId = functionId;
H
hjxilinx 已提交
984

H
hjxilinx 已提交
985 986 987 988
  pExprInfo->numOfExprs++;
  return pExpr;
}

989 990 991
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 已提交
992

993
  SSqlExprInfo* pExprInfo = &pQueryInfo->exprsInfo;
H
hzcheng 已提交
994 995 996 997 998 999

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

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

S
slguan 已提交
1000 1001
  pExpr->functionId = functionId;
  int16_t numOfCols = pMeterMetaInfo->pMeterMeta->numOfColumns;
H
hzcheng 已提交
1002

S
slguan 已提交
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
  // 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 已提交
1015
  } else {
S
slguan 已提交
1016 1017 1018 1019 1020
    if (pColIndex->columnIndex != TSDB_TBNAME_COLUMN_INDEX) {
      pExpr->colInfo.flag = TSDB_COL_NORMAL;
    } else {
      pExpr->colInfo.flag = TSDB_COL_TAG;
    }
H
hzcheng 已提交
1021 1022
  }

S
slguan 已提交
1023
  pExpr->colInfo.colIdx = pColIndex->columnIndex;
H
hzcheng 已提交
1024 1025
  pExpr->resType = type;
  pExpr->resBytes = size;
S
slguan 已提交
1026 1027
  pExpr->interResBytes = interSize;
  pExpr->uid = pMeterMetaInfo->pMeterMeta->uid;
H
hzcheng 已提交
1028 1029 1030 1031 1032

  pExprInfo->numOfExprs++;
  return pExpr;
}

1033 1034 1035 1036
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 已提交
1037 1038 1039 1040 1041 1042
  if (index > pExprInfo->numOfExprs) {
    return NULL;
  }

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

S
slguan 已提交
1043
  pExpr->functionId = functionId;
H
hzcheng 已提交
1044 1045

  pExpr->colInfo.colIdx = srcColumnIndex;
S
slguan 已提交
1046
  pExpr->colInfo.colId = tsGetColumnSchema(pMeterMetaInfo->pMeterMeta, srcColumnIndex)->colId;
H
hzcheng 已提交
1047 1048 1049 1050 1051 1052 1053

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

  return pExpr;
}

S
slguan 已提交
1054
void addExprParams(SSqlExpr* pExpr, char* argument, int32_t type, int32_t bytes, int16_t tableIndex) {
H
hzcheng 已提交
1055 1056 1057 1058 1059 1060
  if (pExpr == NULL || argument == NULL || bytes == 0) {
    return;
  }

  // set parameter value
  // transfer to tVariant from byte data/no ascii data
S
slguan 已提交
1061
  tVariantCreateFromBinary(&pExpr->param[pExpr->numOfParams], argument, bytes, type);
H
hzcheng 已提交
1062 1063 1064 1065 1066

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

1067 1068
SSqlExpr* tscSqlExprGet(SQueryInfo* pQueryInfo, int32_t index) {
  if (pQueryInfo->exprsInfo.numOfExprs <= index) {
H
hzcheng 已提交
1069 1070 1071
    return NULL;
  }

1072
  return &pQueryInfo->exprsInfo.pExprs[index];
H
hzcheng 已提交
1073 1074
}

S
slguan 已提交
1075
void tscSqlExprCopy(SSqlExprInfo* dst, const SSqlExprInfo* src, uint64_t tableuid) {
H
hzcheng 已提交
1076 1077 1078 1079 1080 1081 1082
  if (src == NULL) {
    return;
  }

  *dst = *src;

  dst->pExprs = malloc(sizeof(SSqlExpr) * dst->numOfAlloc);
S
slguan 已提交
1083 1084 1085 1086 1087 1088
  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 已提交
1089

S
slguan 已提交
1090
  dst->numOfExprs = num;
H
hzcheng 已提交
1091 1092 1093 1094 1095 1096 1097
  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 已提交
1098 1099 1100 1101 1102 1103 1104 1105
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 已提交
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
  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 已提交
1127
static void _cf_evic(SColumnBaseInfo* pcolList, int32_t index) {
H
hzcheng 已提交
1128 1129 1130 1131
  if (index < pcolList->numOfCols) {
    memmove(&pcolList->pColList[index + 1], &pcolList->pColList[index],
            sizeof(SColumnBase) * (pcolList->numOfCols - index));

S
slguan 已提交
1132
    clearVal(&pcolList->pColList[index]);
H
hzcheng 已提交
1133 1134 1135
  }
}

S
slguan 已提交
1136 1137
SColumnBase* tscColumnBaseInfoGet(SColumnBaseInfo* pColumnBaseInfo, int32_t index) {
  if (pColumnBaseInfo == NULL || pColumnBaseInfo->numOfCols < index) {
H
hzcheng 已提交
1138 1139 1140
    return NULL;
  }

S
slguan 已提交
1141 1142 1143 1144 1145 1146 1147
  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 已提交
1148 1149
}

S
slguan 已提交
1150
// todo refactor
1151 1152
SColumnBase* tscColumnBaseInfoInsert(SQueryInfo* pQueryInfo, SColumnIndex* pColIndex) {
  SColumnBaseInfo* pcolList = &pQueryInfo->colList;
H
hzcheng 已提交
1153

S
slguan 已提交
1154 1155
  // ignore the tbname column to be inserted into source list
  if (pColIndex->columnIndex < 0) {
H
hzcheng 已提交
1156 1157 1158
    return NULL;
  }

S
slguan 已提交
1159 1160
  int16_t col = pColIndex->columnIndex;

H
hzcheng 已提交
1161
  int32_t i = 0;
S
slguan 已提交
1162 1163 1164 1165 1166 1167 1168 1169
  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 已提交
1170 1171
  }

S
slguan 已提交
1172 1173 1174
  SColumnIndex* pIndex = &pcolList->pColList[i].colIndex;
  if ((i < pcolList->numOfCols && (pIndex->columnIndex > col || pIndex->tableIndex != pColIndex->tableIndex)) ||
      (i >= pcolList->numOfCols)) {
H
hzcheng 已提交
1175 1176 1177
    _cf_ensureSpace(pcolList, pcolList->numOfCols + 1);
    _cf_evic(pcolList, i);

S
slguan 已提交
1178
    pcolList->pColList[i].colIndex = *pColIndex;
H
hzcheng 已提交
1179 1180 1181 1182 1183 1184
    pcolList->numOfCols++;
  }

  return &pcolList->pColList[i];
}

S
slguan 已提交
1185
void tscColumnFilterInfoCopy(SColumnFilterInfo* dst, const SColumnFilterInfo* src) {
H
hjxilinx 已提交
1186
  assert(src != NULL && dst != NULL);
S
slguan 已提交
1187 1188 1189 1190 1191 1192 1193 1194

  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 已提交
1195 1196 1197 1198
    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 已提交
1199 1200 1201 1202
  }
}

void tscColumnBaseCopy(SColumnBase* dst, const SColumnBase* src) {
H
hjxilinx 已提交
1203
  assert(src != NULL && dst != NULL);
S
slguan 已提交
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218

  *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 已提交
1219 1220 1221 1222 1223
  if (src == NULL) {
    return;
  }

  *dst = *src;
S
slguan 已提交
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
  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 已提交
1242

S
slguan 已提交
1243
  dst->numOfCols = num;
H
hzcheng 已提交
1244 1245
}

S
slguan 已提交
1246 1247 1248 1249 1250 1251 1252 1253
void tscColumnBaseInfoDestroy(SColumnBaseInfo* pColumnBaseInfo) {
  if (pColumnBaseInfo == NULL) {
    return;
  }

  assert(pColumnBaseInfo->numOfCols <= TSDB_MAX_COLUMNS);

  for (int32_t i = 0; i < pColumnBaseInfo->numOfCols; ++i) {
1254
    SColumnBase* pColBase = &(pColumnBaseInfo->pColList[i]);
S
slguan 已提交
1255 1256 1257 1258 1259 1260

    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 已提交
1261
          free((char*)pColBase->filterInfo[j].pz);
H
hjxilinx 已提交
1262
          pColBase->filterInfo[j].pz = 0;
S
slguan 已提交
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
        }
      }
    }

    tfree(pColBase->filterInfo);
  }

  tfree(pColumnBaseInfo->pColList);
}

1273 1274 1275
void tscColumnBaseInfoReserve(SColumnBaseInfo* pColumnBaseInfo, int32_t size) {
  _cf_ensureSpace(pColumnBaseInfo, size);
}
H
hzcheng 已提交
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291

/*
 * 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 已提交
1292
  pToken->n = strdequote(pToken->z);
H
hzcheng 已提交
1293 1294 1295 1296
  strtrim(pToken->z);
  pToken->n = (uint32_t)strlen(pToken->z);

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

H
huili 已提交
1298 1299
  if (pToken->type == TK_STRING) {
    return tscValidateName(pToken);
S
slguan 已提交
1300
  }
H
hzcheng 已提交
1301

H
huili 已提交
1302 1303 1304
  if (k != pToken->n || pToken->type != TK_ID) {
    return TSDB_CODE_INVALID_SQL;
  }
H
hzcheng 已提交
1305 1306 1307 1308 1309 1310 1311 1312
  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 已提交
1313
  char* sep = strnchr(pToken->z, TS_PATH_DELIMITER[0], pToken->n, true);
H
hzcheng 已提交
1314 1315
  if (sep == NULL) {  // single part
    if (pToken->type == TK_STRING) {
H
huili 已提交
1316 1317 1318
      pToken->n = strdequote(pToken->z);
      strtrim(pToken->z);
      pToken->n = (uint32_t)strlen(pToken->z);
S
slguan 已提交
1319 1320 1321 1322

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

      // single token, validate it
1323
      if (len == pToken->n) {
H
huili 已提交
1324
        return validateQuoteToken(pToken);
S
slguan 已提交
1325
      } else {
1326 1327 1328 1329
        sep = strnchr(pToken->z, TS_PATH_DELIMITER[0], pToken->n, true);
        if (sep == NULL) {
          return TSDB_CODE_INVALID_SQL;
        }
S
slguan 已提交
1330

H
huili 已提交
1331
        return tscValidateName(pToken);
1332
      }
H
hzcheng 已提交
1333 1334 1335 1336 1337 1338 1339 1340 1341
    } else {
      if (isNumber(pToken)) {
        return TSDB_CODE_INVALID_SQL;
      }
    }
  } else {  // two part
    int32_t oldLen = pToken->n;
    char*   pStr = pToken->z;

H
huili 已提交
1342 1343
    if (pToken->type == TK_SPACE) {
      strtrim(pToken->z);
S
slguan 已提交
1344
      pToken->n = (uint32_t)strlen(pToken->z);
H
huili 已提交
1345 1346
    }

H
hzcheng 已提交
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
    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 已提交
1375
      // first part do not have quote do nothing
H
hzcheng 已提交
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
    } 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;
}

bool tscValidateColumnId(SSqlCmd* pCmd, int32_t colId) {
1398
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfo(pCmd, 0, 0);
S
slguan 已提交
1399
  if (pMeterMetaInfo->pMeterMeta == NULL) {
H
hzcheng 已提交
1400 1401 1402
    return false;
  }

1403
  if (colId == -1 && UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {
H
hzcheng 已提交
1404 1405 1406
    return true;
  }

S
slguan 已提交
1407 1408
  SSchema* pSchema = tsGetSchema(pMeterMetaInfo->pMeterMeta);
  int32_t  numOfTotal = pMeterMetaInfo->pMeterMeta->numOfTags + pMeterMetaInfo->pMeterMeta->numOfColumns;
H
hzcheng 已提交
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418

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

  return false;
}

S
slguan 已提交
1419 1420
void tscTagCondCopy(STagCond* dest, const STagCond* src) {
  memset(dest, 0, sizeof(STagCond));
H
hjxilinx 已提交
1421

H
hjxilinx 已提交
1422 1423 1424
  if (src->tbnameCond.cond != NULL) {
    dest->tbnameCond.cond = strdup(src->tbnameCond.cond);
  }
S
slguan 已提交
1425 1426 1427 1428 1429 1430

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

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

  for (int32_t i = 0; i < src->numOfTagCond; ++i) {
H
hjxilinx 已提交
1431 1432 1433
    if (src->cond[i].cond != NULL) {
      dest->cond[i].cond = strdup(src->cond[i].cond);
    }
H
hjxilinx 已提交
1434

S
slguan 已提交
1435
    dest->cond[i].uid = src->cond[i].uid;
H
hzcheng 已提交
1436 1437
  }

S
slguan 已提交
1438 1439
  dest->relType = src->relType;
  dest->numOfTagCond = src->numOfTagCond;
H
hzcheng 已提交
1440 1441 1442
}

void tscTagCondRelease(STagCond* pCond) {
H
hjxilinx 已提交
1443
  free(pCond->tbnameCond.cond);
S
slguan 已提交
1444
  for (int32_t i = 0; i < pCond->numOfTagCond; ++i) {
H
hjxilinx 已提交
1445
    free(pCond->cond[i].cond);
H
hzcheng 已提交
1446 1447 1448 1449 1450
  }

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

1451 1452
void tscGetSrcColumnInfo(SSrcColumnInfo* pColInfo, SQueryInfo* pQueryInfo) {
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
S
slguan 已提交
1453
  SSchema*        pSchema = tsGetSchema(pMeterMetaInfo->pMeterMeta);
H
hzcheng 已提交
1454

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

S
slguan 已提交
1459 1460 1461
    if (TSDB_COL_IS_TAG(pExpr->colInfo.flag)) {
      SSchema* pTagSchema = tsGetTagSchema(pMeterMetaInfo->pMeterMeta);
      int16_t  actualTagIndex = pMeterMetaInfo->tagColumnIndex[pExpr->colInfo.colIdx];
H
hzcheng 已提交
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477

      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 已提交
1478
  // to denote the heart-beat timer close connection and free all allocated resources
1479 1480
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pHeatBeat->cmd, 0);
  pQueryInfo->type = TSDB_QUERY_TYPE_FREE_RESOURCE;
H
hzcheng 已提交
1481 1482 1483 1484
}

bool tscShouldFreeHeatBeat(SSqlObj* pHb) {
  assert(pHb == pHb->signature);
1485 1486 1487

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

void tscCleanSqlCmd(SSqlCmd* pCmd) {
1491 1492
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
  tscFreeSubqueryInfo(pCmd);
H
hzcheng 已提交
1493

S
slguan 已提交
1494 1495
  uint32_t allocSize = pCmd->allocSize;
  char*    allocPtr = pCmd->payload;
H
hzcheng 已提交
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 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

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

1548
    SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
1549
    assert(pQueryInfo->numOfTables == 1 || pQueryInfo->numOfTables == 2);
H
hjxilinx 已提交
1550

H
hjxilinx 已提交
1551
    if (pDataBlocks == NULL || pMeterMetaInfo->vnodeIndex >= pDataBlocks->nSize) {
H
hzcheng 已提交
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
      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);
  }
}

1563 1564 1565
/**
 *
 * @param pCmd
1566
 * @param clauseIndex denote the index of the union sub clause, usually are 0, if no union query exists.
1567 1568 1569
 * @param tableIndex  denote the table index for join query, where more than one table exists
 * @return
 */
1570
SMeterMetaInfo* tscGetMeterMetaInfo(SSqlCmd* pCmd, int32_t clauseIndex, int32_t tableIndex) {
1571
  if (pCmd == NULL || pCmd->numOfClause == 0) {
S
slguan 已提交
1572 1573 1574
    return NULL;
  }

1575
  assert(clauseIndex >= 0 && clauseIndex < pCmd->numOfClause);
1576

1577
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, clauseIndex);
1578
  return tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, tableIndex);
S
slguan 已提交
1579 1580
}

1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
SMeterMetaInfo* tscGetMeterMetaInfoFromQueryInfo(SQueryInfo* pQueryInfo, int32_t tableIndex) {
  if (pQueryInfo->pMeterInfo == NULL) {
    assert(pQueryInfo->numOfTables == 0);
    return NULL;
  }

  assert(pQueryInfo != NULL && tableIndex >= 0 && tableIndex <= pQueryInfo->numOfTables &&
         pQueryInfo->pMeterInfo != NULL);

  return pQueryInfo->pMeterInfo[tableIndex];
}

SQueryInfo* tscGetQueryInfoDetail(SSqlCmd* pCmd, int32_t subClauseIndex) {
  if (pCmd->pQueryInfo == NULL) {
    return NULL;
  }

  assert(pCmd != NULL && subClauseIndex >= 0 && subClauseIndex < pCmd->numOfClause);
  return pCmd->pQueryInfo[subClauseIndex];
}

1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
int32_t tscGetQueryInfoDetailSafely(SSqlCmd *pCmd, int32_t subClauseIndex, SQueryInfo** pQueryInfo) {
  int32_t ret = TSDB_CODE_SUCCESS;
  assert(subClauseIndex >= 0 && subClauseIndex < TSDB_MAX_UNION_CLAUSE);
  
  *pQueryInfo = tscGetQueryInfoDetail(pCmd, subClauseIndex);
  
  while ((*pQueryInfo) == NULL) {
    if ((ret = tscAddSubqueryInfo(pCmd)) != TSDB_CODE_SUCCESS) {
      return ret;
    }
    
    (*pQueryInfo) = tscGetQueryInfoDetail(pCmd, subClauseIndex);
  }
  
  return TSDB_CODE_SUCCESS;
}

1619
SMeterMetaInfo* tscGetMeterMetaInfoByUid(SQueryInfo* pQueryInfo, int32_t subClauseIndex, uint64_t uid, int32_t* index) {
S
slguan 已提交
1620
  int32_t k = -1;
1621 1622 1623

  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
    if (pQueryInfo->pMeterInfo[i]->pMeterMeta->uid == uid) {
S
slguan 已提交
1624 1625 1626 1627 1628 1629 1630 1631 1632
      k = i;
      break;
    }
  }

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

1633
  return tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, k);
S
slguan 已提交
1634 1635
}

1636
int32_t tscAddSubqueryInfo(SSqlCmd* pCmd) {
1637
  assert(pCmd != NULL);
1638 1639 1640

  size_t s = pCmd->numOfClause + 1;
  char*  tmp = realloc(pCmd->pQueryInfo, s * POINTER_BYTES);
1641 1642 1643
  if (tmp == NULL) {
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
1644 1645 1646 1647 1648 1649 1650

  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;
1651 1652 1653
  return TSDB_CODE_SUCCESS;
}

1654
static void doClearSubqueryInfo(SQueryInfo* pQueryInfo) {
1655 1656
  tscTagCondRelease(&pQueryInfo->tagCond);
  tscClearFieldInfo(&pQueryInfo->fieldsInfo);
1657
  
1658 1659
  tfree(pQueryInfo->exprsInfo.pExprs);
  memset(&pQueryInfo->exprsInfo, 0, sizeof(pQueryInfo->exprsInfo));
1660
  
1661 1662
  tscColumnBaseInfoDestroy(&pQueryInfo->colList);
  memset(&pQueryInfo->colList, 0, sizeof(pQueryInfo->colList));
1663 1664
  
  pQueryInfo->tsBuf = tsBufDestory(pQueryInfo->tsBuf);
1665 1666
  
  tfree(pQueryInfo->defaultVal);
1667
}
1668

1669 1670 1671 1672
void tscClearSubqueryInfo(SSqlCmd* pCmd) {
  for(int32_t i = 0; i < pCmd->numOfClause; ++i) {
    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, i);
    doClearSubqueryInfo(pQueryInfo);
1673
  }
1674 1675 1676 1677 1678 1679 1680 1681
}

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

  for (int32_t i = 0; i < pCmd->numOfClause; ++i) {
1682
    char *addr = (char *) pCmd - offsetof(SSqlObj, cmd);
1683
    
1684 1685 1686 1687 1688
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, i);
  
    doClearSubqueryInfo(pQueryInfo);
    tscRemoveAllMeterMetaInfo(pQueryInfo, (const char *) addr, false);
    tfree(pQueryInfo);
1689
  }
1690
  
1691 1692 1693 1694
  pCmd->numOfClause = 0;
  tfree(pCmd->pQueryInfo);
}

1695
SMeterMetaInfo* tscAddMeterMetaInfo(SQueryInfo* pQueryInfo, const char* name, SMeterMeta* pMeterMeta,
1696
                                    SMetricMeta* pMetricMeta, int16_t numOfTags, int16_t* tags) {
1697 1698 1699
//  while (pCmd->numOfClause <= subClauseIndex) {
//    tscAddSubqueryInfo(pCmd);
//  }
1700

1701
//  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
1702

1703
  void* pAlloc = realloc(pQueryInfo->pMeterInfo, (pQueryInfo->numOfTables + 1) * POINTER_BYTES);
S
slguan 已提交
1704 1705 1706 1707
  if (pAlloc == NULL) {
    return NULL;
  }

1708 1709
  pQueryInfo->pMeterInfo = pAlloc;
  pQueryInfo->pMeterInfo[pQueryInfo->numOfTables] = calloc(1, sizeof(SMeterMetaInfo));
S
slguan 已提交
1710

1711
  SMeterMetaInfo* pMeterMetaInfo = pQueryInfo->pMeterInfo[pQueryInfo->numOfTables];
S
slguan 已提交
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
  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 已提交
1724
    memcpy(pMeterMetaInfo->tagColumnIndex, tags, sizeof(pMeterMetaInfo->tagColumnIndex[0]) * numOfTags);
S
slguan 已提交
1725 1726
  }

1727
  pQueryInfo->numOfTables += 1;
S
slguan 已提交
1728 1729 1730
  return pMeterMetaInfo;
}

1731 1732
SMeterMetaInfo* tscAddEmptyMeterMetaInfo(SQueryInfo* pQueryInfo) {
  return tscAddMeterMetaInfo(pQueryInfo, NULL, NULL, NULL, 0, NULL);
1733
}
S
slguan 已提交
1734

1735 1736
void doRemoveMeterMetaInfo(SQueryInfo* pQueryInfo, int32_t index, bool removeFromCache) {
  if (index < 0 || index >= pQueryInfo->numOfTables) {
S
slguan 已提交
1737 1738 1739
    return;
  }

1740
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index);
S
slguan 已提交
1741 1742 1743 1744

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

1745
  int32_t after = pQueryInfo->numOfTables - index - 1;
S
slguan 已提交
1746
  if (after > 0) {
1747
    memmove(&pQueryInfo->pMeterInfo[index], &pQueryInfo->pMeterInfo[index + 1], after * POINTER_BYTES);
S
slguan 已提交
1748 1749
  }

1750
  pQueryInfo->numOfTables -= 1;
S
slguan 已提交
1751 1752
}

1753 1754
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 已提交
1755

1756 1757 1758
  int32_t index = pQueryInfo->numOfTables;
  while (index >= 0) {
    doRemoveMeterMetaInfo(pQueryInfo, --index, removeFromCache);
S
slguan 已提交
1759 1760
  }

1761
  tfree(pQueryInfo->pMeterInfo);
S
slguan 已提交
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
}

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) {
  pRes->row = 0;
  pRes->numOfRows = 0;
}

H
hjxilinx 已提交
1778
SSqlObj* createSubqueryObj(SSqlObj* pSql, int16_t tableIndex, void (*fp)(), void* param, SSqlObj* pPrevSql) {
H
hjxilinx 已提交
1779
  SSqlCmd*        pCmd = &pSql->cmd;
1780
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfo(pCmd, 0, tableIndex);
S
slguan 已提交
1781 1782 1783

  SSqlObj* pNew = (SSqlObj*)calloc(1, sizeof(SSqlObj));
  if (pNew == NULL) {
H
hjxilinx 已提交
1784
    tscError("%p new subquery failed, tableIndex:%d, vnodeIndex:%d", pSql, tableIndex, pMeterMetaInfo->vnodeIndex);
S
slguan 已提交
1785 1786 1787 1788 1789 1790 1791 1792
    return NULL;
  }

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

  pNew->sqlstr = strdup(pSql->sqlstr);
  if (pNew->sqlstr == NULL) {
H
hjxilinx 已提交
1793
    tscError("%p new subquery failed, tableIndex:%d, vnodeIndex:%d", pSql, tableIndex, pMeterMetaInfo->vnodeIndex);
S
slguan 已提交
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804

    free(pNew);
    return NULL;
  }

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

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

1805
  pNew->cmd.pQueryInfo = NULL;
1806 1807 1808
  pNew->cmd.numOfClause = 0;

  if (tscAddSubqueryInfo(&pNew->cmd) != TSDB_CODE_SUCCESS) {
1809 1810 1811
    tscFreeSqlObj(pNew);
    return NULL;
  }
1812 1813 1814 1815 1816 1817 1818 1819

  SQueryInfo* pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

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

  memset(&pNewQueryInfo->colList, 0, sizeof(pNewQueryInfo->colList));
  memset(&pNewQueryInfo->fieldsInfo, 0, sizeof(SFieldInfo));
1820 1821 1822
  
  pNewQueryInfo->pMeterInfo = NULL;
  pNewQueryInfo->defaultVal = NULL;
1823 1824 1825 1826
  pNewQueryInfo->numOfTables = 0;
  pNewQueryInfo->tsBuf = NULL;

  tscTagCondCopy(&pNewQueryInfo->tagCond, &pQueryInfo->tagCond);
1827 1828 1829 1830 1831 1832
  
  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));
  }
  
S
slguan 已提交
1833
  if (tscAllocPayload(&pNew->cmd, TSDB_DEFAULT_PAYLOAD_SIZE) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1834
    tscError("%p new subquery failed, tableIndex:%d, vnodeIndex:%d", pSql, tableIndex, pMeterMetaInfo->vnodeIndex);
S
slguan 已提交
1835 1836 1837 1838
    tscFreeSqlObj(pNew);
    return NULL;
  }

1839 1840
  tscColumnBaseInfoCopy(&pNewQueryInfo->colList, &pQueryInfo->colList, (int16_t)tableIndex);

S
slguan 已提交
1841 1842
  // set the correct query type
  if (pPrevSql != NULL) {
1843 1844
    SQueryInfo* pPrevQueryInfo = tscGetQueryInfoDetail(&pPrevSql->cmd, 0);
    pNewQueryInfo->type = pPrevQueryInfo->type;
S
slguan 已提交
1845
  } else {
1846
    pNewQueryInfo->type |= TSDB_QUERY_TYPE_SUBQUERY;  // it must be the subquery
S
slguan 已提交
1847 1848 1849
  }

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

1852
  int32_t numOfOutputCols = pNewQueryInfo->exprsInfo.numOfExprs;
S
slguan 已提交
1853 1854 1855

  if (numOfOutputCols > 0) {
    int32_t* indexList = calloc(1, numOfOutputCols * sizeof(int32_t));
1856 1857
    for (int32_t i = 0, j = 0; i < pQueryInfo->exprsInfo.numOfExprs; ++i) {
      SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
1858 1859 1860 1861 1862
      if (pExpr->uid == uid) {
        indexList[j++] = i;
      }
    }

1863
    tscFieldInfoCopy(&pQueryInfo->fieldsInfo, &pNewQueryInfo->fieldsInfo, indexList, numOfOutputCols);
S
slguan 已提交
1864 1865
    free(indexList);

1866
    tscFieldInfoUpdateOffset(pNewQueryInfo);
S
slguan 已提交
1867 1868 1869 1870
  }

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

S
slguan 已提交
1872
  char key[TSDB_MAX_TAGS_LEN + 1] = {0};
1873
  tscGetMetricMetaCacheKey(pCmd, 0, key, uid);
H
hjxilinx 已提交
1874

H
hjxilinx 已提交
1875 1876 1877
#ifdef _DEBUG_VIEW
  printf("the metricmeta key is:%s\n", key);
#endif
H
hjxilinx 已提交
1878

1879 1880
  char* name = pMeterMetaInfo->name;

S
slguan 已提交
1881 1882 1883 1884 1885 1886
  SMeterMetaInfo* pFinalInfo = NULL;

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

1887
    pFinalInfo = tscAddMeterMetaInfo(pNewQueryInfo, name, pMeterMeta, pMetricMeta, pMeterMetaInfo->numOfTags,
1888
                                     pMeterMetaInfo->tagColumnIndex);
1889
  } else { // transfer the ownership of pMeterMeta/pMetricMeta to the newly create sql object.
1890
    SMeterMetaInfo* pPrevInfo = tscGetMeterMetaInfo(&pPrevSql->cmd, 0, 0);
1891 1892 1893 1894 1895 1896
    
    SMeterMeta* pPrevMeterMeta = taosTransferDataInCache(tscCacheHandle, (void**) &pPrevInfo->pMeterMeta);
    SMetricMeta* pPrevMetricMeta = taosTransferDataInCache(tscCacheHandle, (void**) &pPrevInfo->pMetricMeta);
    
    pFinalInfo = tscAddMeterMetaInfo(pNewQueryInfo, name, pPrevMeterMeta, pPrevMetricMeta, pMeterMetaInfo->numOfTags,
                                     pMeterMetaInfo->tagColumnIndex);
S
slguan 已提交
1897 1898 1899
  }

  assert(pFinalInfo->pMeterMeta != NULL);
1900
  if (UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {
S
slguan 已提交
1901 1902 1903
    assert(pFinalInfo->pMetricMeta != NULL);
  }

H
hjxilinx 已提交
1904
  tscTrace("%p new subquery %p, tableIndex:%d, vnodeIdx:%d, type:%d", pSql, pNew, tableIndex,
1905
           pMeterMetaInfo->vnodeIndex, pNewQueryInfo->type);
S
slguan 已提交
1906 1907 1908
  return pNew;
}

H
hzcheng 已提交
1909 1910
void tscDoQuery(SSqlObj* pSql) {
  SSqlCmd* pCmd = &pSql->cmd;
1911
  void*    fp = pSql->fp;
H
hzcheng 已提交
1912 1913 1914 1915 1916 1917 1918 1919

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

1920 1921
    if (pCmd->dataSourceType == DATA_FROM_DATA_FILE) {
      tscProcessMultiVnodesInsertFromFile(pSql);
H
hzcheng 已提交
1922
    } else {
S
slguan 已提交
1923
      // pSql may be released in this function if it is a async insertion.
H
hzcheng 已提交
1924
      tscProcessSql(pSql);
S
slguan 已提交
1925
      if (NULL == fp) tscProcessMultiVnodesInsert(pSql);
S
slguan 已提交
1926
    }
H
hzcheng 已提交
1927 1928
  }
}
S
slguan 已提交
1929

H
hjxilinx 已提交
1930
int16_t tscGetJoinTagColIndexByUid(STagCond* pTagCond, uint64_t uid) {
S
slguan 已提交
1931 1932 1933 1934 1935 1936
  if (pTagCond->joinInfo.left.uid == uid) {
    return pTagCond->joinInfo.left.tagCol;
  } else {
    return pTagCond->joinInfo.right.tagCol;
  }
}
1937 1938 1939 1940 1941 1942 1943

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

H
hjxilinx 已提交
1944 1945
  SSqlCmd* pCmd = &pObj->pSql->cmd;
  return ((pCmd->command >= TSDB_SQL_INSERT && pCmd->command <= TSDB_SQL_DROP_DNODE) ||
H
hjxilinx 已提交
1946 1947 1948
          TSDB_SQL_USE_DB == pCmd->command)
             ? 1
             : 0;
H
hjxilinx 已提交
1949
}
1950

H
hjxilinx 已提交
1951 1952 1953 1954 1955
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 已提交
1956
  const int32_t BACKWARD_CHAR_STEP = 0;
H
hjxilinx 已提交
1957

H
hjxilinx 已提交
1958 1959 1960 1961 1962
  if (sql == NULL) {
    assert(additionalInfo != NULL);
    sprintf(msg, msgFormat1, additionalInfo);
    return TSDB_CODE_INVALID_SQL;
  }
H
hjxilinx 已提交
1963 1964

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

H
hjxilinx 已提交
1967 1968 1969
  if (additionalInfo != NULL) {
    sprintf(msg, msgFormat2, buf, additionalInfo);
  } else {
H
hjxilinx 已提交
1970
    sprintf(msg, msgFormat3, buf);  // no additional information for invalid sql error
H
hjxilinx 已提交
1971
  }
H
hjxilinx 已提交
1972

H
hjxilinx 已提交
1973
  return TSDB_CODE_INVALID_SQL;
1974
}
H
hjxilinx 已提交
1975

H
hjxilinx 已提交
1976 1977
bool tscHasReachLimitation(SSqlObj* pSql) {
  assert(pSql != NULL && pSql->cmd.globalLimit != 0);
H
hjxilinx 已提交
1978

H
hjxilinx 已提交
1979 1980
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;
H
hjxilinx 已提交
1981

H
hjxilinx 已提交
1982 1983
  return (pCmd->globalLimit > 0 && pRes->numOfTotal >= pCmd->globalLimit);
}
1984 1985

char* tscGetErrorMsgPayload(SSqlCmd* pCmd) { return pCmd->payload; }