tscUtil.c 64.6 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"
18
#include "os.h"
H
hjxilinx 已提交
19
#include "qast.h"
H
hzcheng 已提交
20 21 22 23 24 25
#include "taosmsg.h"
#include "tcache.h"
#include "tkey.h"
#include "tmd5.h"
#include "tscProfile.h"
#include "tscSecondaryMerge.h"
H
hjxilinx 已提交
26
#include "tscSubquery.h"
H
hzcheng 已提交
27 28 29
#include "tschemautil.h"
#include "tsclient.h"
#include "ttimer.h"
30
#include "ttokendef.h"
S
slguan 已提交
31
#include "tscLog.h"
H
hzcheng 已提交
32

33 34 35 36
static void freeQueryInfoImpl(SQueryInfo* pQueryInfo);
static void clearAllTableMetaInfo(SQueryInfo* pQueryInfo, const char* address, bool removeFromCache);
  
  SCond* tsGetSTableQueryCond(STagCond* pTagCond, uint64_t uid) {
37 38 39 40 41 42 43 44 45 46
  if (pTagCond->pCond == NULL) {
    return NULL;
  }
  
  size_t size = taosArrayGetSize(pTagCond->pCond);
  for (int32_t i = 0; i < size; ++i) {
    SCond* pCond = taosArrayGet(pTagCond->pCond, i);
    
    if (uid == pCond->uid) {
      return pCond;
S
slguan 已提交
47 48 49 50 51 52
    }
  }

  return NULL;
}

53 54
void tsSetSTableQueryCond(STagCond* pTagCond, uint64_t uid, SBufferWriter* bw) {
  if (tbufTell(bw) == 0) {
S
slguan 已提交
55
    return;
H
hzcheng 已提交
56
  }
57 58 59
  
  SCond cond = {
    .uid = uid,
60
    .len = tbufTell(bw),
61 62 63
    .cond = NULL,
  };
  
64
  cond.cond = tbufGetData(bw, true);
65 66 67 68 69 70
  
  if (pTagCond->pCond == NULL) {
    pTagCond->pCond = taosArrayInit(3, sizeof(SCond));
  }
  
  taosArrayPush(pTagCond->pCond, &cond);
S
slguan 已提交
71 72
}

73
bool tscQueryOnSTable(SSqlCmd* pCmd) {
74 75 76
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

  return ((pQueryInfo->type & TSDB_QUERY_TYPE_STABLE_QUERY) == TSDB_QUERY_TYPE_STABLE_QUERY) &&
S
slguan 已提交
77
         (pCmd->msgType == TSDB_MSG_TYPE_QUERY);
S
slguan 已提交
78 79
}

H
hjxilinx 已提交
80
bool tscQueryTags(SQueryInfo* pQueryInfo) {
H
hjxilinx 已提交
81
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutput; ++i) {
82 83 84
    int32_t functId = tscSqlExprGet(pQueryInfo, i)->functionId;
    
    if (functId != TSDB_FUNC_TAGPRJ && functId != TSDB_FUNC_TID_TAG) {
S
slguan 已提交
85 86 87
      return false;
    }
  }
H
hzcheng 已提交
88

S
slguan 已提交
89
  return true;
H
hzcheng 已提交
90 91
}

S
slguan 已提交
92 93 94 95
bool tscIsSelectivityWithTagQuery(SSqlCmd* pCmd) {
  bool    hasTags = false;
  int32_t numOfSelectivity = 0;

96 97
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

H
hjxilinx 已提交
98
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutput; ++i) {
99
    int32_t functId = tscSqlExprGet(pQueryInfo, i)->functionId;
S
slguan 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    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 已提交
116

S
slguan 已提交
117 118
void tscGetDBInfoFromMeterId(char* tableId, char* db) {
  char* st = strstr(tableId, TS_PATH_DELIMITER);
H
hzcheng 已提交
119 120 121
  if (st != NULL) {
    char* end = strstr(st + 1, TS_PATH_DELIMITER);
    if (end != NULL) {
S
slguan 已提交
122 123
      memcpy(db, tableId, (end - tableId));
      db[end - tableId] = 0;
H
hzcheng 已提交
124 125 126 127 128 129 130
      return;
    }
  }

  db[0] = 0;
}

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
//STableIdInfo* 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;
//  }
//
//  assert(pSidList->pSidExtInfoList[idx] >= 0);
//
//  return (STableIdInfo*)(pSidList->pSidExtInfoList[idx] + (char*)pSidList);
//}
H
hzcheng 已提交
148

H
hjxilinx 已提交
149
bool tscIsTwoStageSTableQuery(SQueryInfo* pQueryInfo, int32_t tableIndex) {
150 151 152
  if (pQueryInfo == NULL) {
    return false;
  }
153

H
hjxilinx 已提交
154
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, tableIndex);
H
hjxilinx 已提交
155
  if (pTableMetaInfo == NULL) {
156 157 158
    return false;
  }
  
H
hjxilinx 已提交
159
  // for select query super table, the super table vgroup list can not be null in any cases.
weixin_48148422's avatar
weixin_48148422 已提交
160
  if (pQueryInfo->command == TSDB_SQL_SELECT && UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
H
hjxilinx 已提交
161
    assert(pTableMetaInfo->vgroupList != NULL);
162 163
  }
  
H
hjxilinx 已提交
164 165
  if ((pQueryInfo->type & TSDB_QUERY_TYPE_FREE_RESOURCE) == TSDB_QUERY_TYPE_FREE_RESOURCE) {
    return false;
S
slguan 已提交
166 167
  }

168 169
  // for ordered projection query, iterate all qualified vnodes sequentially
  if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, tableIndex)) {
H
hzcheng 已提交
170 171 172
    return false;
  }

173
  if (((pQueryInfo->type & TSDB_QUERY_TYPE_STABLE_SUBQUERY) != TSDB_QUERY_TYPE_STABLE_SUBQUERY) &&
174
      pQueryInfo->command == TSDB_SQL_SELECT) {
weixin_48148422's avatar
weixin_48148422 已提交
175
    return UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo);
H
hzcheng 已提交
176 177 178 179 180
  }

  return false;
}

181
bool tscIsProjectionQueryOnSTable(SQueryInfo* pQueryInfo, int32_t tableIndex) {
H
hjxilinx 已提交
182
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, tableIndex);
183
  
H
hzcheng 已提交
184
  /*
185 186 187
   * 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 已提交
188
   */
H
hjxilinx 已提交
189
  size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
weixin_48148422's avatar
weixin_48148422 已提交
190
  if (pTableMetaInfo == NULL || !UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo) ||
H
hjxilinx 已提交
191
      pQueryInfo->command == TSDB_SQL_RETRIEVE_EMPTY_RESULT || numOfExprs == 0) {
H
hzcheng 已提交
192 193
    return false;
  }
194
  
H
hjxilinx 已提交
195
  // only query on tag, a project query
H
hjxilinx 已提交
196
  if (tscQueryTags(pQueryInfo)) {
H
hjxilinx 已提交
197
    return true;
S
slguan 已提交
198
  }
199
  
H
hjxilinx 已提交
200
  for (int32_t i = 0; i < numOfExprs; ++i) {
201
    int32_t functionId = tscSqlExprGet(pQueryInfo, i)->functionId;
H
hjxilinx 已提交
202 203
    if (functionId != TSDB_FUNC_PRJ && functionId != TSDB_FUNC_TAGPRJ && functionId != TSDB_FUNC_TAG &&
        functionId != TSDB_FUNC_TS && functionId != TSDB_FUNC_ARITHM) {
S
slguan 已提交
204
      return false;
H
hzcheng 已提交
205 206
    }
  }
207
  
S
slguan 已提交
208
  return true;
H
hzcheng 已提交
209 210
}

211 212 213 214 215
bool tscNonOrderedProjectionQueryOnSTable(SQueryInfo* pQueryInfo, int32_t tableIndex) {
  if (!tscIsProjectionQueryOnSTable(pQueryInfo, tableIndex)) {
    return false;
  }
  
216
  // order by columnIndex exists, not a non-ordered projection query
217 218 219 220 221 222 223 224
  return pQueryInfo->order.orderColId < 0;
}

bool tscOrderedProjectionQueryOnSTable(SQueryInfo* pQueryInfo, int32_t tableIndex) {
  if (!tscIsProjectionQueryOnSTable(pQueryInfo, tableIndex)) {
    return false;
  }
  
225
  // order by columnIndex exists, a non-ordered projection query
226 227 228
  return pQueryInfo->order.orderColId >= 0;
}

229
bool tscProjectionQueryOnTable(SQueryInfo* pQueryInfo) {
H
hjxilinx 已提交
230
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutput; ++i) {
231
    int32_t functionId = tscSqlExprGet(pQueryInfo, i)->functionId;
H
hjxilinx 已提交
232 233 234 235
    if (functionId != TSDB_FUNC_PRJ && functionId != TSDB_FUNC_TS) {
      return false;
    }
  }
H
hjxilinx 已提交
236

H
hjxilinx 已提交
237 238 239
  return true;
}

240
bool tscIsPointInterpQuery(SQueryInfo* pQueryInfo) {
H
hjxilinx 已提交
241 242 243
  size_t size = tscSqlExprNumOfExprs(pQueryInfo);
  
  for (int32_t i = 0; i < size; ++i) {
244
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
H
hzcheng 已提交
245 246 247 248
    if (pExpr == NULL) {
      return false;
    }

S
slguan 已提交
249
    int32_t functionId = pExpr->functionId;
H
hzcheng 已提交
250 251 252 253 254 255 256 257 258 259 260
    if (functionId == TSDB_FUNC_TAG) {
      continue;
    }

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

261
bool tscIsTWAQuery(SQueryInfo* pQueryInfo) {
H
hjxilinx 已提交
262 263
  size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
  for (int32_t i = 0; i < numOfExprs; ++i) {
264
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
265 266 267 268 269 270 271 272 273 274 275
    if (pExpr == NULL) {
      continue;
    }

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

  return false;
H
hzcheng 已提交
276 277
}

278 279
void tscClearInterpInfo(SQueryInfo* pQueryInfo) {
  if (!tscIsPointInterpQuery(pQueryInfo)) {
H
hzcheng 已提交
280 281 282
    return;
  }

283
  pQueryInfo->interpoType = TSDB_INTERPO_NONE;
284
  tfree(pQueryInfo->defaultVal);
H
hzcheng 已提交
285 286
}

287
int32_t tscCreateResPointerInfo(SSqlRes* pRes, SQueryInfo* pQueryInfo) {
H
hzcheng 已提交
288
  if (pRes->tsrow == NULL) {
H
hjxilinx 已提交
289 290
    int32_t numOfOutput = pQueryInfo->fieldsInfo.numOfOutput;
    pRes->numOfCols = numOfOutput;
291
  
292 293 294
    pRes->tsrow  = calloc(numOfOutput, POINTER_BYTES);
    pRes->length = calloc(numOfOutput, sizeof(int32_t));  // todo refactor
    pRes->buffer = calloc(numOfOutput, POINTER_BYTES);
295 296
  
    // not enough memory
H
hjxilinx 已提交
297
    if (pRes->tsrow == NULL || (pRes->buffer == NULL && pRes->numOfCols > 0)) {
298 299
      tfree(pRes->tsrow);
      tfree(pRes->buffer);
300
      tfree(pRes->length);
301
    
H
hzcheng 已提交
302 303 304 305 306 307 308 309 310
      pRes->code = TSDB_CODE_CLI_OUT_OF_MEMORY;
      return pRes->code;
    }
  }

  return TSDB_CODE_SUCCESS;
}

void tscDestroyResPointerInfo(SSqlRes* pRes) {
H
hjxilinx 已提交
311
  if (pRes->buffer != NULL) { // free all buffers containing the multibyte string
H
hjxilinx 已提交
312
    for (int i = 0; i < pRes->numOfCols; i++) {
H
hzcheng 已提交
313 314
      tfree(pRes->buffer[i]);
    }
315
    
H
hjxilinx 已提交
316
    pRes->numOfCols = 0;
H
hzcheng 已提交
317
  }
318 319
  
  tfree(pRes->pRsp);
H
hzcheng 已提交
320
  tfree(pRes->tsrow);
321
  tfree(pRes->length);
322 323 324 325 326
  
  tfree(pRes->pGroupRec);
  tfree(pRes->pColumnIndex);
  tfree(pRes->buffer);
  
327 328 329 330 331
  if (pRes->pArithSup != NULL) {
    tfree(pRes->pArithSup->data);
    tfree(pRes->pArithSup);
  }
  
332
  pRes->data = NULL;  // pRes->data points to the buffer of pRsp, no need to free
H
hzcheng 已提交
333 334
}

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
static void tscFreeQueryInfo(SSqlCmd* pCmd) {
  if (pCmd == NULL || pCmd->numOfClause == 0) {
    return;
  }
  
  for (int32_t i = 0; i < pCmd->numOfClause; ++i) {
    char* addr = (char*)pCmd - offsetof(SSqlObj, cmd);
    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, i);
    
    freeQueryInfoImpl(pQueryInfo);
    clearAllTableMetaInfo(pQueryInfo, (const char*)addr, false);
    tfree(pQueryInfo);
  }
  
  pCmd->numOfClause = 0;
  tfree(pCmd->pQueryInfo);
}

353 354
void tscResetSqlCmdObj(SSqlCmd* pCmd) {
  pCmd->command   = 0;
355
  pCmd->numOfCols = 0;
356 357 358 359
  pCmd->count     = 0;
  pCmd->curSql    = NULL;
  pCmd->msgType   = 0;
  pCmd->parseFinished = 0;
360
  pCmd->autoCreated = 0;
361 362
  
  taosHashCleanup(pCmd->pTableList);
363
  pCmd->pTableList = NULL;
364
  
S
slguan 已提交
365
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
366
  
367
  tscFreeQueryInfo(pCmd);
H
hzcheng 已提交
368 369
}

H
hjxilinx 已提交
370
void tscFreeSqlResult(SSqlObj* pSql) {
371 372
  tscDestroyLocalReducer(pSql);
  
H
hjxilinx 已提交
373
  SSqlRes* pRes = &pSql->res;
374
  tscDestroyResPointerInfo(pRes);
375
  
H
hjxilinx 已提交
376
  memset(&pSql->res, 0, sizeof(SSqlRes));
377 378
}

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

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

  int32_t cmd = pCmd->command;
H
hjxilinx 已提交
388
  if (cmd < TSDB_SQL_INSERT || cmd == TSDB_SQL_RETRIEVE_LOCALMERGE || cmd == TSDB_SQL_RETRIEVE_EMPTY_RESULT ||
389
      cmd == TSDB_SQL_TABLE_JOIN_RETRIEVE) {
H
hzcheng 已提交
390 391
    tscRemoveFromSqlList(pSql);
  }
392
  
H
hzcheng 已提交
393
  // pSql->sqlstr will be used by tscBuildQueryStreamDesc
L
lihui 已提交
394 395 396 397 398
  if (pObj->signature == pObj) {
    pthread_mutex_lock(&pObj->mutex);
    tfree(pSql->sqlstr);
    pthread_mutex_unlock(&pObj->mutex);
  }
399
  
weixin_48148422's avatar
weixin_48148422 已提交
400
  tscFreeSqlResult(pSql);
H
[TD-98]  
hjxilinx 已提交
401
  
402
  tfree(pSql->pSubs);
403
  pSql->freed = 0;
H
[TD-98]  
hjxilinx 已提交
404 405
  pSql->numOfSubs = 0;
  
406
  tscResetSqlCmdObj(pCmd);
407
  
408
  tscTrace("%p partially free sqlObj completed", pSql);
H
hzcheng 已提交
409 410 411 412 413 414
}

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

  tscTrace("%p start to free sql object", pSql);
H
hjxilinx 已提交
415
  tscPartiallyFreeSqlObj(pSql);
H
hzcheng 已提交
416 417 418

  pSql->signature = NULL;
  pSql->fp = NULL;
419
  
H
hzcheng 已提交
420 421
  SSqlCmd* pCmd = &pSql->cmd;

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

  pCmd->allocSize = 0;
  free(pSql);
}

S
slguan 已提交
429 430
void tscDestroyDataBlock(STableDataBlocks* pDataBlock) {
  if (pDataBlock == NULL) {
H
hzcheng 已提交
431 432 433
    return;
  }

S
slguan 已提交
434
  tfree(pDataBlock->pData);
S
slguan 已提交
435
  tfree(pDataBlock->params);
H
hjxilinx 已提交
436

H
hjxilinx 已提交
437
  // free the refcount for metermeta
H
hjxilinx 已提交
438
  taosCacheRelease(tscCacheHandle, (void**)&(pDataBlock->pTableMeta), false);
S
slguan 已提交
439
  tfree(pDataBlock);
H
hzcheng 已提交
440 441
}

442 443
SParamInfo* tscAddParamToDataBlock(STableDataBlocks* pDataBlock, char type, uint8_t timePrec, short bytes,
                                   uint32_t offset) {
S
slguan 已提交
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
  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 已提交
466 467 468 469
SDataBlockList* tscCreateBlockArrayList() {
  const int32_t DEFAULT_INITIAL_NUM_OF_BLOCK = 16;

  SDataBlockList* pDataBlockArrayList = calloc(1, sizeof(SDataBlockList));
S
slguan 已提交
470 471 472
  if (pDataBlockArrayList == NULL) {
    return NULL;
  }
H
hjxilinx 已提交
473
  
H
hzcheng 已提交
474 475
  pDataBlockArrayList->nAlloc = DEFAULT_INITIAL_NUM_OF_BLOCK;
  pDataBlockArrayList->pData = calloc(1, POINTER_BYTES * pDataBlockArrayList->nAlloc);
S
slguan 已提交
476 477 478 479
  if (pDataBlockArrayList->pData == NULL) {
    free(pDataBlockArrayList);
    return NULL;
  }
H
hzcheng 已提交
480 481 482 483

  return pDataBlockArrayList;
}

484
void tscAppendDataBlock(SDataBlockList* pList, STableDataBlocks* pBlocks) {
S
slguan 已提交
485
  if (pList->nSize >= pList->nAlloc) {
H
hjxilinx 已提交
486 487
    pList->nAlloc = (pList->nAlloc) << 1U;
    pList->pData = realloc(pList->pData, POINTER_BYTES * (size_t)pList->nAlloc);
S
slguan 已提交
488 489

    // reset allocated memory
H
hjxilinx 已提交
490
    memset(pList->pData + pList->nSize, 0, POINTER_BYTES * (pList->nAlloc - pList->nSize));
S
slguan 已提交
491 492 493 494 495
  }

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

S
slguan 已提交
496 497 498
void* tscDestroyBlockArrayList(SDataBlockList* pList) {
  if (pList == NULL) {
    return NULL;
H
hzcheng 已提交
499 500
  }

S
slguan 已提交
501 502
  for (int32_t i = 0; i < pList->nSize; i++) {
    tscDestroyDataBlock(pList->pData[i]);
H
hzcheng 已提交
503 504
  }

S
slguan 已提交
505 506 507 508
  tfree(pList->pData);
  tfree(pList);

  return NULL;
H
hzcheng 已提交
509 510
}

S
slguan 已提交
511
int32_t tscCopyDataBlockToPayload(SSqlObj* pSql, STableDataBlocks* pDataBlock) {
H
hjxilinx 已提交
512
  SSqlCmd* pCmd = &pSql->cmd;
H
hjxilinx 已提交
513
  assert(pDataBlock->pTableMeta != NULL);
H
hjxilinx 已提交
514

S
slguan 已提交
515
  pCmd->numOfTablesInSubmit = pDataBlock->numOfTables;
516

517
  assert(pCmd->numOfClause == 1);
518
  STableMetaInfo* pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
519

520
  // set the correct table meta object, the table meta has been locked in pDataBlocks, so it must be in the cache
H
hjxilinx 已提交
521 522 523
  if (pTableMetaInfo->pTableMeta != pDataBlock->pTableMeta) {
    strcpy(pTableMetaInfo->name, pDataBlock->tableId);
    taosCacheRelease(tscCacheHandle, (void**)&(pTableMetaInfo->pTableMeta), false);
524

H
hjxilinx 已提交
525
    pTableMetaInfo->pTableMeta = taosCacheTransfer(tscCacheHandle, (void**)&pDataBlock->pTableMeta);
H
hjxilinx 已提交
526
  } else {
H
hjxilinx 已提交
527
    assert(strncmp(pTableMetaInfo->name, pDataBlock->tableId, tListLen(pDataBlock->tableId)) == 0);
H
hjxilinx 已提交
528
  }
H
hjxilinx 已提交
529

530 531
  /*
   * the submit message consists of : [RPC header|message body|digest]
532
   * the dataBlock only includes the RPC Header buffer and actual submit message body, space for digest needs
533 534
   * additional space.
   */
S
slguan 已提交
535
  int ret = tscAllocPayload(pCmd, pDataBlock->nAllocSize + 100);
H
hjxilinx 已提交
536 537 538
  if (TSDB_CODE_SUCCESS != ret) {
    return ret;
  }
H
hjxilinx 已提交
539

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

542 543 544 545
  /*
   * the payloadLen should be actual message body size
   * the old value of payloadLen is the allocated payload size
   */
546
  pCmd->payloadLen = pDataBlock->nAllocSize - tsRpcHeadSize;
H
hjxilinx 已提交
547

H
hjxilinx 已提交
548
  assert(pCmd->allocSize >= pCmd->payloadLen + tsRpcHeadSize + 100 && pCmd->payloadLen > 0);
H
hjxilinx 已提交
549
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
550 551 552 553 554
}

void tscFreeUnusedDataBlocks(SDataBlockList* pList) {
  /* release additional memory consumption */
  for (int32_t i = 0; i < pList->nSize; ++i) {
S
slguan 已提交
555 556 557
    STableDataBlocks* pDataBlock = pList->pData[i];
    pDataBlock->pData = realloc(pDataBlock->pData, pDataBlock->size);
    pDataBlock->nAllocSize = (uint32_t)pDataBlock->size;
H
hzcheng 已提交
558 559 560
  }
}

H
hjxilinx 已提交
561 562 563 564 565 566
/**
 * create the in-memory buffer for each table to keep the submitted data block
 * @param initialSize
 * @param rowSize
 * @param startOffset
 * @param name
H
hjxilinx 已提交
567
 * @param dataBlocks
H
hjxilinx 已提交
568 569
 * @return
 */
H
hjxilinx 已提交
570
int32_t tscCreateDataBlock(size_t initialSize, int32_t rowSize, int32_t startOffset, const char* name,
H
hjxilinx 已提交
571
                           STableMeta* pTableMeta, STableDataBlocks** dataBlocks) {
H
hjxilinx 已提交
572
  STableDataBlocks* dataBuf = (STableDataBlocks*)calloc(1, sizeof(STableDataBlocks));
H
hjxilinx 已提交
573 574 575 576 577 578
  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 已提交
579
  dataBuf->headerSize = startOffset; // the header size will always be the startOffset value, reserved for the subumit block header
H
hjxilinx 已提交
580 581 582 583
  if (dataBuf->nAllocSize <= dataBuf->headerSize) {
    dataBuf->nAllocSize = dataBuf->headerSize*2;
  }
  
H
hjxilinx 已提交
584 585 586
  dataBuf->pData = calloc(1, dataBuf->nAllocSize);
  dataBuf->ordered = true;
  dataBuf->prevTS = INT64_MIN;
S
slguan 已提交
587 588 589

  dataBuf->rowSize = rowSize;
  dataBuf->size = startOffset;
S
slguan 已提交
590 591
  dataBuf->tsSource = -1;

S
slguan 已提交
592
  strncpy(dataBuf->tableId, name, TSDB_TABLE_ID_LEN);
H
hjxilinx 已提交
593 594

  /*
595
   * The table meta may be released since the table meta cache are completed clean by other thread
596 597
   * 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 已提交
598
   */
H
hjxilinx 已提交
599 600
  dataBuf->pTableMeta = taosCacheAcquireByData(tscCacheHandle, pTableMeta);
  assert(initialSize > 0 && pTableMeta != NULL && dataBuf->pTableMeta != NULL);
601

602 603
  *dataBlocks = dataBuf;
  return TSDB_CODE_SUCCESS;
S
slguan 已提交
604 605
}

H
hjxilinx 已提交
606
int32_t tscGetDataBlockFromList(void* pHashList, SDataBlockList* pDataBlockList, int64_t id, int32_t size,
H
hjxilinx 已提交
607
                                int32_t startOffset, int32_t rowSize, const char* tableId, STableMeta* pTableMeta,
H
hjxilinx 已提交
608 609
                                STableDataBlocks** dataBlocks) {
  *dataBlocks = NULL;
S
slguan 已提交
610

H
hjxilinx 已提交
611
  STableDataBlocks** t1 = (STableDataBlocks**)taosHashGet(pHashList, (const char*)&id, sizeof(id));
S
slguan 已提交
612
  if (t1 != NULL) {
H
hjxilinx 已提交
613
    *dataBlocks = *t1;
S
slguan 已提交
614 615
  }

H
hjxilinx 已提交
616
  if (*dataBlocks == NULL) {
H
hjxilinx 已提交
617
    int32_t ret = tscCreateDataBlock((size_t)size, rowSize, startOffset, tableId, pTableMeta, dataBlocks);
H
hjxilinx 已提交
618 619 620 621
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }

H
hjxilinx 已提交
622
    taosHashPut(pHashList, (const char*)&id, sizeof(int64_t), (char*)dataBlocks, POINTER_BYTES);
H
hjxilinx 已提交
623
    tscAppendDataBlock(pDataBlockList, *dataBlocks);
S
slguan 已提交
624 625
  }

H
hjxilinx 已提交
626
  return TSDB_CODE_SUCCESS;
S
slguan 已提交
627 628
}

H
TD-100  
hzcheng 已提交
629
static int trimDataBlock(void* pDataBlock, STableDataBlocks* pTableDataBlock) {
630
  // TODO: optimize this function, handle the case while binary is not presented
H
TD-100  
hzcheng 已提交
631
  int len = 0;
H
TD-166  
hzcheng 已提交
632 633

  STableMeta*   pTableMeta = pTableDataBlock->pTableMeta;
634
  STableComInfo tinfo = tscGetTableInfo(pTableMeta);
H
TD-166  
hzcheng 已提交
635 636 637
  SSchema*      pSchema = tscGetTableSchema(pTableMeta);

  SSubmitBlk* pBlock = pDataBlock;
638 639
  memcpy(pDataBlock, pTableDataBlock->pData, sizeof(SSubmitBlk));
  pDataBlock += sizeof(SSubmitBlk);
H
TD-166  
hzcheng 已提交
640

H
hjxilinx 已提交
641
  int32_t flen = 0;  // original total length of row
H
TD-166  
hzcheng 已提交
642 643
  for (int32_t i = 0; i < tinfo.numOfColumns; ++i) {
    flen += TYPE_BYTES[pSchema[i].type];
644
  }
H
TD-166  
hzcheng 已提交
645

646
  char* p = pTableDataBlock->pData + sizeof(SSubmitBlk);
H
TD-166  
hzcheng 已提交
647
  pBlock->len = 0;
H
hjxilinx 已提交
648 649 650
  int32_t numOfRows = htons(pBlock->numOfRows);
  
  for (int32_t i = 0; i < numOfRows; ++i) {
H
TD-166  
hzcheng 已提交
651 652 653 654 655
    SDataRow trow = (SDataRow)pDataBlock;
    dataRowSetLen(trow, TD_DATA_ROW_HEAD_SIZE + flen);

    int toffset = 0;
    for (int32_t j = 0; j < tinfo.numOfColumns; j++) {
H
TD-166  
hzcheng 已提交
656
      tdAppendColVal(trow, p, pSchema[j].type, pSchema[j].bytes, toffset);
H
TD-166  
hzcheng 已提交
657 658 659 660 661 662 663
      toffset += TYPE_BYTES[pSchema[j].type];
      p += pSchema[j].bytes;
    }

    // p += pTableDataBlock->rowSize;
    pDataBlock += dataRowLen(trow);
    pBlock->len += dataRowLen(trow);
664
  }
H
TD-166  
hzcheng 已提交
665

H
TD-100  
hzcheng 已提交
666
  len = pBlock->len;
H
TD-166  
hzcheng 已提交
667
  pBlock->len = htonl(pBlock->len);
H
TD-100  
hzcheng 已提交
668
  return len;
669 670
}

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

H
hjxilinx 已提交
674
  void* pVnodeDataBlockHashList = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false);
S
slguan 已提交
675 676 677 678
  SDataBlockList* pVnodeDataBlockList = tscCreateBlockArrayList();

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

H
hjxilinx 已提交
680
    STableDataBlocks* dataBuf = NULL;
H
hjxilinx 已提交
681 682 683
    
    int32_t ret =
        tscGetDataBlockFromList(pVnodeDataBlockHashList, pVnodeDataBlockList, pOneTableBlock->vgId, TSDB_PAYLOAD_SIZE,
H
hjxilinx 已提交
684
                                tsInsertHeadSize, 0, pOneTableBlock->tableId, pOneTableBlock->pTableMeta, &dataBuf);
H
hjxilinx 已提交
685
    if (ret != TSDB_CODE_SUCCESS) {
686
      tscError("%p failed to prepare the data block buffer for merging table data, code:%d", pSql, ret);
H
hjxilinx 已提交
687
      taosHashCleanup(pVnodeDataBlockHashList);
688
      tscDestroyBlockArrayList(pVnodeDataBlockList);
H
hjxilinx 已提交
689 690
      return ret;
    }
S
slguan 已提交
691

692
    int64_t destSize = dataBuf->size + pOneTableBlock->size + pOneTableBlock->size*sizeof(int32_t)*2;
S
slguan 已提交
693 694 695 696 697 698 699 700 701
    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);
702
      } else {  // failed to allocate memory, free already allocated memory and return error code
S
slguan 已提交
703 704
        tscError("%p failed to allocate memory for merging submit block, size:%d", pSql, dataBuf->nAllocSize);

H
hjxilinx 已提交
705
        taosHashCleanup(pVnodeDataBlockHashList);
S
slguan 已提交
706
        tscDestroyBlockArrayList(pVnodeDataBlockList);
707
        tfree(dataBuf->pData);
S
slguan 已提交
708 709

        return TSDB_CODE_CLI_OUT_OF_MEMORY;
S
slguan 已提交
710 711 712
      }
    }

713
    SSubmitBlk* pBlocks = (SSubmitBlk*) pOneTableBlock->pData;
H
hjxilinx 已提交
714
    tscSortRemoveDataBlockDupRows(pOneTableBlock);
S
slguan 已提交
715

716
    char* e = (char*)pBlocks->data + pOneTableBlock->rowSize*(pBlocks->numOfRows-1);
L
lihui 已提交
717
    
718 719
    tscTrace("%p tableId:%s, sid:%d rows:%d sversion:%d skey:%" PRId64 ", ekey:%" PRId64, pSql, pOneTableBlock->tableId,
        pBlocks->tid, pBlocks->numOfRows, pBlocks->sversion, GET_INT64_VAL(pBlocks->data), GET_INT64_VAL(e));
S
slguan 已提交
720

721 722 723
    int32_t len = pBlocks->numOfRows * (pOneTableBlock->rowSize + sizeof(int32_t) * 2);
    
    pBlocks->tid = htonl(pBlocks->tid);
S
slguan 已提交
724 725 726
    pBlocks->uid = htobe64(pBlocks->uid);
    pBlocks->sversion = htonl(pBlocks->sversion);
    pBlocks->numOfRows = htons(pBlocks->numOfRows);
727 728 729 730
    
    pBlocks->len = htonl(len);
    
    // erase the empty space reserved for binary data
H
TD-100  
hzcheng 已提交
731
    len = trimDataBlock(dataBuf->pData + dataBuf->size, pOneTableBlock);
732
    dataBuf->size += (len + sizeof(SSubmitBlk));
S
slguan 已提交
733
    dataBuf->numOfTables += 1;
S
slguan 已提交
734 735 736 737 738 739 740 741
  }

  tscDestroyBlockArrayList(pTableDataBlockList);

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

  tscFreeUnusedDataBlocks(pCmd->pDataBlocks);
H
hjxilinx 已提交
742
  taosHashCleanup(pVnodeDataBlockHashList);
S
slguan 已提交
743 744

  return TSDB_CODE_SUCCESS;
S
slguan 已提交
745 746
}

H
hzcheng 已提交
747
void tscCloseTscObj(STscObj* pObj) {
H
hjxilinx 已提交
748 749
  assert(pObj != NULL);
  
H
hzcheng 已提交
750 751
  pObj->signature = NULL;
  SSqlObj* pSql = pObj->pSql;
H
hjxilinx 已提交
752
  
753
  if (pSql) {
H
hjxilinx 已提交
754
    terrno = pSql->res.code;
H
hjxilinx 已提交
755
    sem_destroy(&pSql->rspSem);
756 757
  }
  
H
hzcheng 已提交
758 759 760
  taosTmrStopA(&(pObj->pTimer));
  tscFreeSqlObj(pSql);

761 762 763
  if (pSql) {
    sem_destroy(&pSql->rspSem);
  }
764
  
H
hzcheng 已提交
765
  pthread_mutex_destroy(&pObj->mutex);
766
  
767 768 769 770
  if (pObj->pDnodeConn != NULL) {
    rpcClose(pObj->pDnodeConn);
  }
  
771
  tscTrace("%p DB connection is closed, dnodeConn:%p", pObj, pObj->pDnodeConn);
H
hzcheng 已提交
772 773 774
  tfree(pObj);
}

H
hjxilinx 已提交
775
bool tscIsInsertData(char* sqlstr) {
776 777 778 779 780 781 782 783
  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 已提交
784 785
}

S
slguan 已提交
786
int tscAllocPayload(SSqlCmd* pCmd, int size) {
H
hzcheng 已提交
787 788 789 790 791
  assert(size > 0);

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

792
    pCmd->payload = (char*)calloc(1, size);
H
hzcheng 已提交
793 794 795 796
    if (pCmd->payload == NULL) return TSDB_CODE_CLI_OUT_OF_MEMORY;
    pCmd->allocSize = size;
  } else {
    if (pCmd->allocSize < size) {
797
      char* b = realloc(pCmd->payload, size);
S
slguan 已提交
798 799
      if (b == NULL) return TSDB_CODE_CLI_OUT_OF_MEMORY;
      pCmd->payload = b;
H
hzcheng 已提交
800 801
      pCmd->allocSize = size;
    }
802
    
H
hjxilinx 已提交
803
    memset(pCmd->payload, 0, pCmd->allocSize);
H
hzcheng 已提交
804 805 806 807 808 809
  }

  assert(pCmd->allocSize >= size);
  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
810 811 812 813
TAOS_FIELD tscCreateField(int8_t type, const char* name, int16_t bytes) {
  TAOS_FIELD f = { .type = type, .bytes = bytes, };
  strncpy(f.name, name, TSDB_COL_NAME_LEN);
  return f;
H
hzcheng 已提交
814 815
}

H
hjxilinx 已提交
816 817 818 819
SFieldSupInfo* tscFieldInfoAppend(SFieldInfo* pFieldInfo, TAOS_FIELD* pField) {
  assert(pFieldInfo != NULL);
  taosArrayPush(pFieldInfo->pFields, pField);
  pFieldInfo->numOfOutput++;
H
hjxilinx 已提交
820
  
H
hjxilinx 已提交
821 822 823 824 825 826 827
  struct SFieldSupInfo info = {
    .pSqlExpr = NULL,
    .pArithExprInfo = NULL,
    .visible = true,
  };
  
  return taosArrayPush(pFieldInfo->pSupportInfo, &info);
H
hzcheng 已提交
828 829
}

H
hjxilinx 已提交
830 831
SFieldSupInfo* tscFieldInfoGetSupp(SFieldInfo* pFieldInfo, int32_t index) {
  return taosArrayGet(pFieldInfo->pSupportInfo, index);
H
hjxilinx 已提交
832 833
}

H
hjxilinx 已提交
834 835 836 837 838 839 840 841 842 843 844
SFieldSupInfo* tscFieldInfoInsert(SFieldInfo* pFieldInfo, int32_t index, TAOS_FIELD* field) {
  taosArrayInsert(pFieldInfo->pFields, index, field);
  pFieldInfo->numOfOutput++;
  
  struct SFieldSupInfo info = {
      .pSqlExpr = NULL,
      .pArithExprInfo = NULL,
      .visible = true,
  };
  
  return taosArrayInsert(pFieldInfo->pSupportInfo, index, &info);
H
hjxilinx 已提交
845
}
H
hzcheng 已提交
846

H
hjxilinx 已提交
847
void tscFieldInfoUpdateOffset(SQueryInfo* pQueryInfo) {
H
hjxilinx 已提交
848 849
  size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
  
H
hjxilinx 已提交
850
  SSqlExpr* pExpr = taosArrayGetP(pQueryInfo->exprList, 0);
H
hjxilinx 已提交
851
  pExpr->offset = 0;
H
hjxilinx 已提交
852
  
H
hjxilinx 已提交
853
  for (int32_t i = 1; i < numOfExprs; ++i) {
H
hjxilinx 已提交
854 855
    SSqlExpr* prev = taosArrayGetP(pQueryInfo->exprList, i - 1);
    SSqlExpr* p = taosArrayGetP(pQueryInfo->exprList, i);
H
hjxilinx 已提交
856 857
  
    p->offset = prev->offset + prev->resBytes;
H
hzcheng 已提交
858 859 860
  }
}

861
void tscFieldInfoUpdateOffsetForInterResult(SQueryInfo* pQueryInfo) {
H
hjxilinx 已提交
862
  if (tscSqlExprNumOfExprs(pQueryInfo) == 0) {
H
hzcheng 已提交
863 864
    return;
  }
H
hjxilinx 已提交
865
  
H
hjxilinx 已提交
866
  SSqlExpr* pExpr = taosArrayGetP(pQueryInfo->exprList, 0);
H
hjxilinx 已提交
867
  pExpr->offset = 0;
H
hjxilinx 已提交
868
  
H
hjxilinx 已提交
869 870
  size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
  for (int32_t i = 1; i < numOfExprs; ++i) {
H
hjxilinx 已提交
871 872
    SSqlExpr* prev = taosArrayGetP(pQueryInfo->exprList, i - 1);
    SSqlExpr* p = taosArrayGetP(pQueryInfo->exprList, i);
H
hjxilinx 已提交
873 874
    
    p->offset = prev->offset + prev->resBytes;
H
hzcheng 已提交
875 876 877
  }
}

H
hjxilinx 已提交
878
void tscFieldInfoCopy(SFieldInfo* dst, const SFieldInfo* src) {
H
hjxilinx 已提交
879
  dst->numOfOutput = src->numOfOutput;
H
hzcheng 已提交
880

H
hjxilinx 已提交
881 882 883 884 885 886 887 888 889 890 891
  if (dst->pFields == NULL) {
    dst->pFields = taosArrayClone(src->pFields);
  } else {
    taosArrayCopy(dst->pFields, src->pFields);
  }
  
  if (dst->pSupportInfo == NULL) {
    dst->pSupportInfo = taosArrayClone(src->pSupportInfo);
  } else {
    taosArrayCopy(dst->pSupportInfo, src->pSupportInfo);
  }
H
hzcheng 已提交
892 893
}

H
hjxilinx 已提交
894 895
TAOS_FIELD* tscFieldInfoGetField(SFieldInfo* pFieldInfo, int32_t index) {
  return taosArrayGet(pFieldInfo->pFields, index);
896 897
}

H
hjxilinx 已提交
898
int32_t tscNumOfFields(SQueryInfo* pQueryInfo) { return pQueryInfo->fieldsInfo.numOfOutput; }
H
hzcheng 已提交
899

900
int16_t tscFieldInfoGetOffset(SQueryInfo* pQueryInfo, int32_t index) {
H
hjxilinx 已提交
901 902
  SFieldSupInfo* pInfo = tscFieldInfoGetSupp(&pQueryInfo->fieldsInfo, index);
  assert(pInfo != NULL);
H
hzcheng 已提交
903

H
hjxilinx 已提交
904
  return pInfo->pSqlExpr->offset;
H
hzcheng 已提交
905 906
}

H
hjxilinx 已提交
907
int32_t tscFieldInfoCompare(const SFieldInfo* pFieldInfo1, const SFieldInfo* pFieldInfo2) {
908
  assert(pFieldInfo1 != NULL && pFieldInfo2 != NULL);
909

H
hjxilinx 已提交
910 911
  if (pFieldInfo1->numOfOutput != pFieldInfo2->numOfOutput) {
    return pFieldInfo1->numOfOutput - pFieldInfo2->numOfOutput;
912 913
  }

H
hjxilinx 已提交
914 915 916
  for (int32_t i = 0; i < pFieldInfo1->numOfOutput; ++i) {
    TAOS_FIELD* pField1 = tscFieldInfoGetField((SFieldInfo*) pFieldInfo1, i);
    TAOS_FIELD* pField2 = tscFieldInfoGetField((SFieldInfo*) pFieldInfo2, i);
917

H
hjxilinx 已提交
918 919
    if (pField1->type != pField2->type ||
        pField1->bytes != pField2->bytes ||
920 921 922 923 924 925 926 927
        strcasecmp(pField1->name, pField2->name) != 0) {
      return 1;
    }
  }

  return 0;
}

H
hjxilinx 已提交
928 929 930
int32_t tscGetResRowLength(SArray* pExprList) {
  size_t num = taosArrayGetSize(pExprList);
  if (num == 0) {
H
hzcheng 已提交
931 932
    return 0;
  }
H
hjxilinx 已提交
933 934
  
  int32_t size = 0;
H
hjxilinx 已提交
935 936 937
  for(int32_t i = 0; i < num; ++i) {
    SSqlExpr* pExpr = taosArrayGetP(pExprList, i);
    size += pExpr->resBytes;
H
hjxilinx 已提交
938 939 940
  }
  
  return size;
H
hzcheng 已提交
941 942
}

H
hjxilinx 已提交
943
void tscFieldInfoClear(SFieldInfo* pFieldInfo) {
S
slguan 已提交
944
  if (pFieldInfo == NULL) {
H
hzcheng 已提交
945 946 947
    return;
  }

H
hjxilinx 已提交
948
  taosArrayDestroy(pFieldInfo->pFields);
H
hjxilinx 已提交
949
  
H
hjxilinx 已提交
950 951 952 953
  for(int32_t i = 0; i < pFieldInfo->numOfOutput; ++i) {
    SFieldSupInfo* pInfo = taosArrayGet(pFieldInfo->pSupportInfo, i);
    
    if (pInfo->pArithExprInfo != NULL) {
954
      tExprTreeDestroy(&pInfo->pArithExprInfo->pExpr, NULL);
955
      tfree(pInfo->pArithExprInfo);
H
hjxilinx 已提交
956 957 958
    }
  }
  
H
hjxilinx 已提交
959
  taosArrayDestroy(pFieldInfo->pSupportInfo);
S
slguan 已提交
960
  memset(pFieldInfo, 0, sizeof(SFieldInfo));
H
hzcheng 已提交
961 962
}

H
hjxilinx 已提交
963
static SSqlExpr* doBuildSqlExpr(SQueryInfo* pQueryInfo, int16_t functionId, SColumnIndex* pColIndex, int16_t type,
964
    int16_t size, int16_t interSize, bool isTagCol) {
H
hjxilinx 已提交
965
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, pColIndex->tableIndex);
H
hjxilinx 已提交
966
  
H
hjxilinx 已提交
967
  SSqlExpr* pExpr = calloc(1, sizeof(SSqlExpr));
S
slguan 已提交
968
  pExpr->functionId = functionId;
969
  
970
  // set the correct columnIndex index
S
slguan 已提交
971 972 973
  if (pColIndex->columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
    pExpr->colInfo.colId = TSDB_TBNAME_COLUMN_INDEX;
  } else {
974 975 976 977
    if (isTagCol) {
      SSchema* pSchema = tscGetTableTagSchema(pTableMetaInfo->pTableMeta);
      pExpr->colInfo.colId = pSchema[pColIndex->columnIndex].colId;
      strncpy(pExpr->colInfo.name, pSchema[pColIndex->columnIndex].name, TSDB_COL_NAME_LEN);
S
slguan 已提交
978
    } else {
979 980 981
      SSchema* pSchema = tscGetTableColumnSchema(pTableMetaInfo->pTableMeta, pColIndex->columnIndex);
      pExpr->colInfo.colId = pSchema->colId;
      strncpy(pExpr->colInfo.name, pSchema->name, TSDB_COL_NAME_LEN);
S
slguan 已提交
982
    }
H
hzcheng 已提交
983
  }
H
hjxilinx 已提交
984
  
985 986
  pExpr->colInfo.flag = isTagCol? TSDB_COL_TAG:TSDB_COL_NORMAL;
  
987
  pExpr->colInfo.colIndex = pColIndex->columnIndex;
H
hjxilinx 已提交
988 989
  pExpr->resType       = type;
  pExpr->resBytes      = size;
990
  pExpr->interBytes = interSize;
H
hjxilinx 已提交
991
  pExpr->uid           = pTableMetaInfo->pTableMeta->uid;
H
hjxilinx 已提交
992
  
H
hjxilinx 已提交
993 994 995 996
  return pExpr;
}

SSqlExpr* tscSqlExprInsert(SQueryInfo* pQueryInfo, int32_t index, int16_t functionId, SColumnIndex* pColIndex, int16_t type,
997
                           int16_t size, int16_t interSize, bool isTagCol) {
H
hjxilinx 已提交
998
  int32_t num = taosArrayGetSize(pQueryInfo->exprList);
H
hjxilinx 已提交
999
  if (index == num) {
1000
    return tscSqlExprAppend(pQueryInfo, functionId, pColIndex, type, size, interSize, isTagCol);
H
hjxilinx 已提交
1001 1002
  }
  
1003
  SSqlExpr* pExpr = doBuildSqlExpr(pQueryInfo, functionId, pColIndex, type, size, interSize, isTagCol);
H
hjxilinx 已提交
1004
  taosArrayInsert(pQueryInfo->exprList, index, &pExpr);
H
hjxilinx 已提交
1005 1006 1007 1008
  return pExpr;
}

SSqlExpr* tscSqlExprAppend(SQueryInfo* pQueryInfo, int16_t functionId, SColumnIndex* pColIndex, int16_t type,
1009 1010
    int16_t size, int16_t interSize, bool isTagCol) {
  SSqlExpr* pExpr = doBuildSqlExpr(pQueryInfo, functionId, pColIndex, type, size, interSize, isTagCol);
H
hjxilinx 已提交
1011
  taosArrayPush(pQueryInfo->exprList, &pExpr);
H
hzcheng 已提交
1012 1013 1014
  return pExpr;
}

1015 1016
SSqlExpr* tscSqlExprUpdate(SQueryInfo* pQueryInfo, int32_t index, int16_t functionId, int16_t srcColumnIndex,
                           int16_t type, int16_t size) {
H
hjxilinx 已提交
1017
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hjxilinx 已提交
1018 1019
  SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, index);
  if (pExpr == NULL) {
H
hzcheng 已提交
1020 1021 1022
    return NULL;
  }

S
slguan 已提交
1023
  pExpr->functionId = functionId;
H
hzcheng 已提交
1024

1025
  pExpr->colInfo.colIndex = srcColumnIndex;
H
hjxilinx 已提交
1026
  pExpr->colInfo.colId = tscGetTableColumnSchema(pTableMetaInfo->pTableMeta, srcColumnIndex)->colId;
H
hzcheng 已提交
1027 1028 1029 1030 1031 1032 1033

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

  return pExpr;
}

H
hjxilinx 已提交
1034
int32_t  tscSqlExprNumOfExprs(SQueryInfo* pQueryInfo) {
H
hjxilinx 已提交
1035
  return taosArrayGetSize(pQueryInfo->exprList);
H
hjxilinx 已提交
1036 1037
}

S
slguan 已提交
1038
void addExprParams(SSqlExpr* pExpr, char* argument, int32_t type, int32_t bytes, int16_t tableIndex) {
H
hzcheng 已提交
1039 1040 1041 1042 1043 1044
  if (pExpr == NULL || argument == NULL || bytes == 0) {
    return;
  }

  // set parameter value
  // transfer to tVariant from byte data/no ascii data
S
slguan 已提交
1045
  tVariantCreateFromBinary(&pExpr->param[pExpr->numOfParams], argument, bytes, type);
H
hzcheng 已提交
1046 1047 1048 1049 1050

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

1051
SSqlExpr* tscSqlExprGet(SQueryInfo* pQueryInfo, int32_t index) {
H
hjxilinx 已提交
1052
  return taosArrayGetP(pQueryInfo->exprList, index);
H
hzcheng 已提交
1053 1054
}

H
hjxilinx 已提交
1055
void* sqlExprDestroy(SSqlExpr* pExpr) {
H
hjxilinx 已提交
1056 1057 1058 1059 1060 1061 1062 1063
  if (pExpr == NULL) {
    return NULL;
  }
  
  for(int32_t i = 0; i < tListLen(pExpr->param); ++i) {
    tVariantDestroy(&pExpr->param[i]);
  }
  
H
hjxilinx 已提交
1064 1065
  tfree(pExpr);
  
H
hjxilinx 已提交
1066
  return NULL;
H
hzcheng 已提交
1067 1068
}

H
hjxilinx 已提交
1069 1070 1071
/*
 * NOTE: Does not release SSqlExprInfo here.
 */
H
hjxilinx 已提交
1072 1073
void tscSqlExprInfoDestroy(SArray* pExprInfo) {
  size_t size = taosArrayGetSize(pExprInfo);
H
hjxilinx 已提交
1074
  
H
hjxilinx 已提交
1075 1076 1077
  for(int32_t i = 0; i < size; ++i) {
    SSqlExpr* pExpr = taosArrayGetP(pExprInfo, i);
    sqlExprDestroy(pExpr);
H
hjxilinx 已提交
1078 1079
  }
  
H
hjxilinx 已提交
1080
  taosArrayDestroy(pExprInfo);
H
hjxilinx 已提交
1081 1082
}

H
hjxilinx 已提交
1083 1084
void tscSqlExprCopy(SArray* dst, const SArray* src, uint64_t uid, bool deepcopy) {
  assert(src != NULL && dst != NULL);
H
hjxilinx 已提交
1085
  
H
hjxilinx 已提交
1086 1087 1088 1089 1090
  size_t size = taosArrayGetSize(src);
  for (int32_t i = 0; i < size; ++i) {
    SSqlExpr* pExpr = taosArrayGetP(src, i);
    
    if (pExpr->uid == uid) {
H
hjxilinx 已提交
1091 1092
      
      if (deepcopy) {
H
hjxilinx 已提交
1093 1094 1095 1096 1097 1098 1099 1100
        SSqlExpr* p1 = calloc(1, sizeof(SSqlExpr));
        *p1 = *pExpr;
  
        for (int32_t j = 0; j < pExpr->numOfParams; ++j) {
          tVariantAssign(&p1->param[j], &pExpr->param[j]);
        }
        
        taosArrayPush(dst, &p1);
H
hjxilinx 已提交
1101
      } else {
H
hjxilinx 已提交
1102
        taosArrayPush(dst, &pExpr);
H
hjxilinx 已提交
1103
      }
S
slguan 已提交
1104 1105
    }
  }
H
hzcheng 已提交
1106 1107
}

1108
SColumn* tscColumnListInsert(SArray* pColumnList, SColumnIndex* pColIndex) {
1109
  // ignore the tbname columnIndex to be inserted into source list
S
slguan 已提交
1110
  if (pColIndex->columnIndex < 0) {
H
hzcheng 已提交
1111 1112
    return NULL;
  }
1113 1114
  
  size_t numOfCols = taosArrayGetSize(pColumnList);
S
slguan 已提交
1115 1116
  int16_t col = pColIndex->columnIndex;

H
hzcheng 已提交
1117
  int32_t i = 0;
1118 1119 1120
  while (i < numOfCols) {
    SColumn* pCol = taosArrayGetP(pColumnList, i);
    if (pCol->colIndex.columnIndex < col) {
S
slguan 已提交
1121
      i++;
1122
    } else if (pCol->colIndex.tableIndex < pColIndex->tableIndex) {
S
slguan 已提交
1123 1124 1125 1126
      i++;
    } else {
      break;
    }
H
hzcheng 已提交
1127 1128
  }

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
  if (i >= numOfCols || numOfCols == 0) {
    SColumn* b = calloc(1, sizeof(SColumn));
    b->colIndex = *pColIndex;
    
    taosArrayInsert(pColumnList, i, &b);
  } else {
    SColumn* pCol = taosArrayGetP(pColumnList, i);
  
    if (i < numOfCols && (pCol->colIndex.columnIndex > col || pCol->colIndex.tableIndex != pColIndex->tableIndex)) {
      SColumn* b = calloc(1, sizeof(SColumn));
      b->colIndex = *pColIndex;
      
      taosArrayInsert(pColumnList, i, &b);
    }
H
hzcheng 已提交
1143 1144
  }

1145
  return taosArrayGetP(pColumnList, i);
H
hzcheng 已提交
1146 1147
}

1148
SColumnFilterInfo* tscFilterInfoClone(const SColumnFilterInfo* src, int32_t numOfFilters) {
1149
  if (numOfFilters == 0) {
1150 1151
    assert(src == NULL);
    return NULL;
S
slguan 已提交
1152
  }
1153
  
1154 1155
  SColumnFilterInfo* pFilter = calloc(1, numOfFilters * sizeof(SColumnFilterInfo));
  
1156 1157
  memcpy(pFilter, src, sizeof(SColumnFilterInfo) * numOfFilters);
  for (int32_t j = 0; j < numOfFilters; ++j) {
1158
    
1159 1160
    if (pFilter[j].filterstr) {
      size_t len = (size_t) pFilter[j].len + 1;
1161
      pFilter[j].pz = (int64_t) calloc(1, len);
1162
      
1163
      memcpy((char*)pFilter[j].pz, (char*)src[j].pz, (size_t)len);
1164
    }
S
slguan 已提交
1165
  }
1166 1167 1168 1169 1170
  
  assert(src->filterstr == 0 || src->filterstr == 1);
  assert(!(src->lowerRelOptr == TSDB_RELATION_INVALID && src->upperRelOptr == TSDB_RELATION_INVALID));
  
  return pFilter;
S
slguan 已提交
1171 1172
}

1173 1174 1175 1176
static void destroyFilterInfo(SColumnFilterInfo* pFilterInfo, int32_t numOfFilters) {
  for(int32_t i = 0; i < numOfFilters; ++i) {
    if (pFilterInfo[i].filterstr) {
      tfree(pFilterInfo[i].pz);
S
slguan 已提交
1177 1178
    }
  }
1179 1180
  
  tfree(pFilterInfo);
S
slguan 已提交
1181 1182
}

1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
SColumn* tscColumnClone(const SColumn* src) {
  assert(src != NULL);
  
  SColumn* dst = calloc(1, sizeof(SColumn));
  
  dst->colIndex     = src->colIndex;
  dst->numOfFilters = src->numOfFilters;
  dst->filterInfo   = tscFilterInfoClone(src->filterInfo, src->numOfFilters);
  
  return dst;
}

static void tscColumnDestroy(SColumn* pCol) {
  destroyFilterInfo(pCol->filterInfo, pCol->numOfFilters);
  free(pCol);
}

H
hjxilinx 已提交
1200
void tscColumnListCopy(SArray* dst, const SArray* src, int16_t tableIndex) {
H
hjxilinx 已提交
1201
  assert(src != NULL && dst != NULL);
1202 1203 1204 1205
  
  size_t num = taosArrayGetSize(src);
  for (int32_t i = 0; i < num; ++i) {
    SColumn* pCol = taosArrayGetP(src, i);
H
hzcheng 已提交
1206

1207 1208 1209
    if (pCol->colIndex.tableIndex == tableIndex || tableIndex < 0) {
      SColumn* p = tscColumnClone(pCol);
      taosArrayPush(dst, &p);
S
slguan 已提交
1210 1211
    }
  }
H
hzcheng 已提交
1212 1213
}

1214 1215
void tscColumnListDestroy(SArray* pColumnList) {
  if (pColumnList == NULL) {
S
slguan 已提交
1216 1217 1218
    return;
  }

1219
  size_t num = taosArrayGetSize(pColumnList);
1220
  for (int32_t i = 0; i < num; ++i) {
1221
    SColumn* pCol = taosArrayGetP(pColumnList, i);
1222
    tscColumnDestroy(pCol);
S
slguan 已提交
1223 1224
  }

1225
  taosArrayDestroy(pColumnList);
1226
}
H
hzcheng 已提交
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242

/*
 * 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 已提交
1243
  pToken->n = strdequote(pToken->z);
H
hzcheng 已提交
1244 1245 1246 1247
  strtrim(pToken->z);
  pToken->n = (uint32_t)strlen(pToken->z);

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

H
huili 已提交
1249 1250
  if (pToken->type == TK_STRING) {
    return tscValidateName(pToken);
S
slguan 已提交
1251
  }
H
hzcheng 已提交
1252

H
huili 已提交
1253 1254 1255
  if (k != pToken->n || pToken->type != TK_ID) {
    return TSDB_CODE_INVALID_SQL;
  }
H
hzcheng 已提交
1256 1257 1258 1259 1260 1261 1262 1263
  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 已提交
1264
  char* sep = strnchr(pToken->z, TS_PATH_DELIMITER[0], pToken->n, true);
H
hzcheng 已提交
1265 1266
  if (sep == NULL) {  // single part
    if (pToken->type == TK_STRING) {
H
huili 已提交
1267 1268 1269
      pToken->n = strdequote(pToken->z);
      strtrim(pToken->z);
      pToken->n = (uint32_t)strlen(pToken->z);
S
slguan 已提交
1270 1271 1272 1273

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

      // single token, validate it
1274
      if (len == pToken->n) {
H
huili 已提交
1275
        return validateQuoteToken(pToken);
S
slguan 已提交
1276
      } else {
1277 1278 1279 1280
        sep = strnchr(pToken->z, TS_PATH_DELIMITER[0], pToken->n, true);
        if (sep == NULL) {
          return TSDB_CODE_INVALID_SQL;
        }
S
slguan 已提交
1281

H
huili 已提交
1282
        return tscValidateName(pToken);
1283
      }
H
hzcheng 已提交
1284 1285 1286 1287 1288 1289 1290 1291 1292
    } else {
      if (isNumber(pToken)) {
        return TSDB_CODE_INVALID_SQL;
      }
    }
  } else {  // two part
    int32_t oldLen = pToken->n;
    char*   pStr = pToken->z;

H
huili 已提交
1293 1294
    if (pToken->type == TK_SPACE) {
      strtrim(pToken->z);
S
slguan 已提交
1295
      pToken->n = (uint32_t)strlen(pToken->z);
H
huili 已提交
1296 1297
    }

H
hzcheng 已提交
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
    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 已提交
1326
      // first part do not have quote do nothing
H
hzcheng 已提交
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
    } 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;
}

H
hjxilinx 已提交
1348 1349
bool tscValidateColumnId(STableMetaInfo* pTableMetaInfo, int32_t colId) {
  if (pTableMetaInfo->pTableMeta == NULL) {
H
hzcheng 已提交
1350 1351 1352
    return false;
  }

weixin_48148422's avatar
weixin_48148422 已提交
1353
  if (colId == -1 && UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
H
hzcheng 已提交
1354 1355 1356
    return true;
  }

H
hjxilinx 已提交
1357
  SSchema* pSchema = tscGetTableSchema(pTableMetaInfo->pTableMeta);
H
hjxilinx 已提交
1358
  STableComInfo tinfo = tscGetTableInfo(pTableMetaInfo->pTableMeta);
H
hjxilinx 已提交
1359 1360
  
  int32_t  numOfTotal = tinfo.numOfTags + tinfo.numOfColumns;
H
hzcheng 已提交
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370

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

  return false;
}

S
slguan 已提交
1371 1372
void tscTagCondCopy(STagCond* dest, const STagCond* src) {
  memset(dest, 0, sizeof(STagCond));
H
hjxilinx 已提交
1373

H
hjxilinx 已提交
1374 1375 1376
  if (src->tbnameCond.cond != NULL) {
    dest->tbnameCond.cond = strdup(src->tbnameCond.cond);
  }
S
slguan 已提交
1377 1378 1379 1380

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

  memcpy(&dest->joinInfo, &src->joinInfo, sizeof(SJoinInfo));
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
  dest->relType = src->relType;
  
  if (src->pCond == NULL) {
    return;
  }
  
  size_t s = taosArrayGetSize(src->pCond);
  dest->pCond = taosArrayInit(s, sizeof(SCond));
  
  for (int32_t i = 0; i < s; ++i) {
    SCond* pCond = taosArrayGet(src->pCond, i);
    
    SCond c = {0};
    c.len = pCond->len;
    c.uid = pCond->uid;
    
    if (pCond->len > 0) {
      assert(pCond->cond != NULL);
      c.cond = malloc(c.len);
      memcpy(c.cond, pCond->cond, c.len);
H
hjxilinx 已提交
1401
    }
1402 1403
    
    taosArrayPush(dest->pCond, &c);
H
hzcheng 已提交
1404 1405 1406
  }
}

1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
void tscTagCondRelease(STagCond* pTagCond) {
  free(pTagCond->tbnameCond.cond);
  
  if (pTagCond->pCond != NULL) {
    size_t s = taosArrayGetSize(pTagCond->pCond);
    for (int32_t i = 0; i < s; ++i) {
      SCond* p = taosArrayGet(pTagCond->pCond, i);
      tfree(p->cond);
    }
  
    taosArrayDestroy(pTagCond->pCond);
H
hzcheng 已提交
1418 1419
  }

1420
  memset(pTagCond, 0, sizeof(STagCond));
H
hzcheng 已提交
1421 1422
}

1423
void tscGetSrcColumnInfo(SSrcColumnInfo* pColInfo, SQueryInfo* pQueryInfo) {
H
hjxilinx 已提交
1424
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hjxilinx 已提交
1425
  SSchema*        pSchema = tscGetTableSchema(pTableMetaInfo->pTableMeta);
H
hjxilinx 已提交
1426 1427 1428
  
  size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
  for (int32_t i = 0; i < numOfExprs; ++i) {
1429
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
1430
    pColInfo[i].functionId = pExpr->functionId;
H
hzcheng 已提交
1431

S
slguan 已提交
1432
    if (TSDB_COL_IS_TAG(pExpr->colInfo.flag)) {
H
hjxilinx 已提交
1433
      SSchema* pTagSchema = tscGetTableTagSchema(pTableMetaInfo->pTableMeta);
1434 1435 1436
      
      int16_t index = pExpr->colInfo.colIndex;
      pColInfo[i].type = (index != -1) ? pTagSchema[index].type : TSDB_DATA_TYPE_BINARY;
H
hzcheng 已提交
1437
    } else {
1438
      pColInfo[i].type = pSchema[pExpr->colInfo.colIndex].type;
H
hzcheng 已提交
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
    }
  }
}

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

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

S
slguan 已提交
1451
  // to denote the heart-beat timer close connection and free all allocated resources
1452 1453
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pHeatBeat->cmd, 0);
  pQueryInfo->type = TSDB_QUERY_TYPE_FREE_RESOURCE;
H
hzcheng 已提交
1454 1455 1456 1457
}

bool tscShouldFreeHeatBeat(SSqlObj* pHb) {
  assert(pHb == pHb->signature);
1458 1459 1460

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

/*
weixin_48148422's avatar
weixin_48148422 已提交
1464
 * the following four kinds of SqlObj should not be freed
H
hzcheng 已提交
1465 1466 1467
 * 1. SqlObj for stream computing
 * 2. main SqlObj
 * 3. heartbeat SqlObj
weixin_48148422's avatar
weixin_48148422 已提交
1468
 * 4. SqlObj for subscription
H
hzcheng 已提交
1469 1470 1471 1472 1473 1474
 *
 * 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.
 */
H
hjxilinx 已提交
1475
bool tscShouldBeFreed(SSqlObj* pSql) {
H
hzcheng 已提交
1476 1477 1478 1479 1480
  if (pSql == NULL || pSql->signature != pSql || pSql->fp == NULL) {
    return false;
  }

  STscObj* pTscObj = pSql->pTscObj;
weixin_48148422's avatar
weixin_48148422 已提交
1481
  if (pSql->pStream != NULL || pTscObj->pHb == pSql || pTscObj->pSql == pSql || pSql->pSubscription != NULL) {
H
hzcheng 已提交
1482 1483 1484 1485
    return false;
  }

  int32_t command = pSql->cmd.command;
1486
  if (command == TSDB_SQL_CONNECT || command == TSDB_SQL_INSERT) {
1487
    return true;
H
hzcheng 已提交
1488 1489 1490 1491 1492 1493
  } else {
    return tscKeepConn[command] == 0 ||
           (pSql->res.code != TSDB_CODE_ACTION_IN_PROGRESS && pSql->res.code != TSDB_CODE_SUCCESS);
  }
}

1494 1495 1496
/**
 *
 * @param pCmd
1497
 * @param clauseIndex denote the index of the union sub clause, usually are 0, if no union query exists.
1498 1499 1500
 * @param tableIndex  denote the table index for join query, where more than one table exists
 * @return
 */
1501
STableMetaInfo* tscGetTableMetaInfoFromCmd(SSqlCmd* pCmd, int32_t clauseIndex, int32_t tableIndex) {
1502
  if (pCmd == NULL || pCmd->numOfClause == 0) {
S
slguan 已提交
1503 1504 1505
    return NULL;
  }

1506
  assert(clauseIndex >= 0 && clauseIndex < pCmd->numOfClause);
1507

1508
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, clauseIndex);
H
hjxilinx 已提交
1509
  return tscGetMetaInfo(pQueryInfo, tableIndex);
S
slguan 已提交
1510 1511
}

H
hjxilinx 已提交
1512
STableMetaInfo* tscGetMetaInfo(SQueryInfo* pQueryInfo, int32_t tableIndex) {
H
hjxilinx 已提交
1513
  assert(pQueryInfo != NULL);
1514

H
hjxilinx 已提交
1515
  if (pQueryInfo->pTableMetaInfo == NULL) {
1516 1517 1518 1519
    assert(pQueryInfo->numOfTables == 0);
    return NULL;
  }

H
hjxilinx 已提交
1520
  assert(tableIndex >= 0 && tableIndex <= pQueryInfo->numOfTables && pQueryInfo->pTableMetaInfo != NULL);
1521

H
hjxilinx 已提交
1522
  return pQueryInfo->pTableMetaInfo[tableIndex];
1523 1524 1525
}

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

1528
  if (pCmd->pQueryInfo == NULL || subClauseIndex >= pCmd->numOfClause) {
1529 1530 1531 1532 1533 1534
    return NULL;
  }

  return pCmd->pQueryInfo[subClauseIndex];
}

1535
int32_t tscGetQueryInfoDetailSafely(SSqlCmd* pCmd, int32_t subClauseIndex, SQueryInfo** pQueryInfo) {
1536
  int32_t ret = TSDB_CODE_SUCCESS;
1537

1538
  *pQueryInfo = tscGetQueryInfoDetail(pCmd, subClauseIndex);
1539

1540 1541 1542 1543
  while ((*pQueryInfo) == NULL) {
    if ((ret = tscAddSubqueryInfo(pCmd)) != TSDB_CODE_SUCCESS) {
      return ret;
    }
1544

1545 1546
    (*pQueryInfo) = tscGetQueryInfoDetail(pCmd, subClauseIndex);
  }
1547

1548 1549 1550
  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
1551
STableMetaInfo* tscGetTableMetaInfoByUid(SQueryInfo* pQueryInfo, uint64_t uid, int32_t* index) {
S
slguan 已提交
1552
  int32_t k = -1;
1553 1554

  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
H
hjxilinx 已提交
1555
    if (pQueryInfo->pTableMetaInfo[i]->pTableMeta->uid == uid) {
S
slguan 已提交
1556 1557 1558 1559 1560 1561 1562 1563 1564
      k = i;
      break;
    }
  }

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

H
hjxilinx 已提交
1565
  assert(k != -1);
H
hjxilinx 已提交
1566
  return tscGetMetaInfo(pQueryInfo, k);
S
slguan 已提交
1567 1568
}

H
hjxilinx 已提交
1569 1570 1571 1572 1573 1574 1575 1576 1577
void tscInitQueryInfo(SQueryInfo* pQueryInfo) {
  assert(pQueryInfo->fieldsInfo.pFields == NULL);
  pQueryInfo->fieldsInfo.pFields = taosArrayInit(4, sizeof(TAOS_FIELD));
  
  assert(pQueryInfo->fieldsInfo.pSupportInfo == NULL);
  pQueryInfo->fieldsInfo.pSupportInfo = taosArrayInit(4, sizeof(SFieldSupInfo));
  
  assert(pQueryInfo->exprList == NULL);
  pQueryInfo->exprList = taosArrayInit(4, POINTER_BYTES);
1578
  pQueryInfo->colList  = taosArrayInit(4, POINTER_BYTES);
H
hjxilinx 已提交
1579 1580
}

1581
int32_t tscAddSubqueryInfo(SSqlCmd* pCmd) {
1582
  assert(pCmd != NULL);
1583

H
hjxilinx 已提交
1584
  // todo refactor: remove this structure
1585 1586
  size_t s = pCmd->numOfClause + 1;
  char*  tmp = realloc(pCmd->pQueryInfo, s * POINTER_BYTES);
1587 1588 1589
  if (tmp == NULL) {
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
1590 1591 1592 1593

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

  SQueryInfo* pQueryInfo = calloc(1, sizeof(SQueryInfo));
H
hjxilinx 已提交
1594
  tscInitQueryInfo(pQueryInfo);
H
hjxilinx 已提交
1595
  
1596 1597 1598
  pQueryInfo->msg = pCmd->payload;  // pointer to the parent error message buffer

  pCmd->pQueryInfo[pCmd->numOfClause++] = pQueryInfo;
1599 1600 1601
  return TSDB_CODE_SUCCESS;
}

1602
static void freeQueryInfoImpl(SQueryInfo* pQueryInfo) {
1603
  tscTagCondRelease(&pQueryInfo->tagCond);
H
hjxilinx 已提交
1604
  tscFieldInfoClear(&pQueryInfo->fieldsInfo);
1605

H
hjxilinx 已提交
1606 1607
  tscSqlExprInfoDestroy(pQueryInfo->exprList);
  pQueryInfo->exprList = NULL;
1608

1609
  tscColumnListDestroy(pQueryInfo->colList);
H
hjxilinx 已提交
1610
  pQueryInfo->colList = NULL;
1611

1612 1613 1614 1615 1616
  if (pQueryInfo->groupbyExpr.columnInfo != NULL) {
    taosArrayDestroy(pQueryInfo->groupbyExpr.columnInfo);
    pQueryInfo->groupbyExpr.columnInfo = NULL;
  }
  
1617
  pQueryInfo->tsBuf = tsBufDestory(pQueryInfo->tsBuf);
1618

1619
  tfree(pQueryInfo->defaultVal);
1620
}
1621

1622
void tscClearSubqueryInfo(SSqlCmd* pCmd) {
1623
  for (int32_t i = 0; i < pCmd->numOfClause; ++i) {
1624
    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, i);
1625
    freeQueryInfoImpl(pQueryInfo);
1626
  }
1627 1628
}

1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
void doRemoveTableMetaInfo(SQueryInfo* pQueryInfo, int32_t index, bool removeFromCache) {
  if (index < 0 || index >= pQueryInfo->numOfTables) {
    return;
  }
  
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, index);
  
  tscClearTableMetaInfo(pTableMetaInfo, removeFromCache);
  free(pTableMetaInfo);
  
  int32_t after = pQueryInfo->numOfTables - index - 1;
  if (after > 0) {
    memmove(&pQueryInfo->pTableMetaInfo[index], &pQueryInfo->pTableMetaInfo[index + 1], after * POINTER_BYTES);
  }
  
  pQueryInfo->numOfTables -= 1;
}

void clearAllTableMetaInfo(SQueryInfo* pQueryInfo, const char* address, bool removeFromCache) {
  tscTrace("%p deref the table meta in cache, numOfTables:%d", address, pQueryInfo->numOfTables);
  
1650 1651 1652 1653 1654
  for(int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
    STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, i);
  
    tscClearTableMetaInfo(pTableMetaInfo, removeFromCache);
    free(pTableMetaInfo);
1655 1656 1657 1658 1659
  }
  
  tfree(pQueryInfo->pTableMetaInfo);
}

1660
STableMetaInfo* tscAddTableMetaInfo(SQueryInfo* pQueryInfo, const char* name, STableMeta* pTableMeta,
1661
                                    SVgroupsInfo* vgroupList, SArray* pTagCols) {
H
hjxilinx 已提交
1662
  void* pAlloc = realloc(pQueryInfo->pTableMetaInfo, (pQueryInfo->numOfTables + 1) * POINTER_BYTES);
S
slguan 已提交
1663 1664 1665 1666
  if (pAlloc == NULL) {
    return NULL;
  }

H
hjxilinx 已提交
1667 1668
  pQueryInfo->pTableMetaInfo = pAlloc;
  pQueryInfo->pTableMetaInfo[pQueryInfo->numOfTables] = calloc(1, sizeof(STableMetaInfo));
S
slguan 已提交
1669

H
hjxilinx 已提交
1670
  STableMetaInfo* pTableMetaInfo = pQueryInfo->pTableMetaInfo[pQueryInfo->numOfTables];
H
hjxilinx 已提交
1671
  assert(pTableMetaInfo != NULL);
S
slguan 已提交
1672 1673

  if (name != NULL) {
1674
    strncpy(pTableMetaInfo->name, name, TSDB_TABLE_ID_LEN);
S
slguan 已提交
1675 1676
  }

H
hjxilinx 已提交
1677
  pTableMetaInfo->pTableMeta = pTableMeta;
1678 1679
  
  if (vgroupList != NULL) {
H
hjxilinx 已提交
1680
    size_t size = sizeof(SVgroupsInfo) + sizeof(SCMVgroupInfo) * vgroupList->numOfVgroups;
1681 1682
    pTableMetaInfo->vgroupList = malloc(size);
    memcpy(pTableMetaInfo->vgroupList, vgroupList, size);
1683
  }
S
slguan 已提交
1684

1685 1686 1687
  pTableMetaInfo->tagColList = taosArrayInit(4, POINTER_BYTES);
  if (pTagCols != NULL) {
    tscColumnListCopy(pTableMetaInfo->tagColList, pTagCols, -1);
S
slguan 已提交
1688
  }
1689
  
1690
  pQueryInfo->numOfTables += 1;
H
hjxilinx 已提交
1691
  return pTableMetaInfo;
S
slguan 已提交
1692 1693
}

H
hjxilinx 已提交
1694
STableMetaInfo* tscAddEmptyMetaInfo(SQueryInfo* pQueryInfo) {
1695
  return tscAddTableMetaInfo(pQueryInfo, NULL, NULL, NULL, NULL);
1696
}
S
slguan 已提交
1697

1698
void tscClearTableMetaInfo(STableMetaInfo* pTableMetaInfo, bool removeFromCache) {
H
hjxilinx 已提交
1699
  if (pTableMetaInfo == NULL) {
S
slguan 已提交
1700 1701 1702
    return;
  }

H
hjxilinx 已提交
1703
  taosCacheRelease(tscCacheHandle, (void**)&(pTableMetaInfo->pTableMeta), removeFromCache);
1704
  tfree(pTableMetaInfo->vgroupList);
1705
  
1706 1707
  tscColumnListDestroy(pTableMetaInfo->tagColList);
  pTableMetaInfo->tagColList = NULL;
S
slguan 已提交
1708 1709 1710
}

void tscResetForNextRetrieve(SSqlRes* pRes) {
H
hjxilinx 已提交
1711 1712 1713
  if (pRes == NULL) {
    return;
  }
1714

S
slguan 已提交
1715 1716 1717 1718
  pRes->row = 0;
  pRes->numOfRows = 0;
}

1719
SSqlObj* createSubqueryObj(SSqlObj* pSql, int16_t tableIndex, void (*fp)(), void* param, int32_t cmd, SSqlObj* pPrevSql) {
1720
  SSqlCmd* pCmd = &pSql->cmd;
S
slguan 已提交
1721 1722
  SSqlObj* pNew = (SSqlObj*)calloc(1, sizeof(SSqlObj));
  if (pNew == NULL) {
1723
    tscError("%p new subquery failed, tableIndex:%d", pSql, tableIndex);
S
slguan 已提交
1724 1725
    return NULL;
  }
1726 1727
  
  STableMetaInfo* pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, tableIndex);
S
slguan 已提交
1728 1729 1730 1731 1732 1733

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

  pNew->sqlstr = strdup(pSql->sqlstr);
  if (pNew->sqlstr == NULL) {
H
hjxilinx 已提交
1734
    tscError("%p new subquery failed, tableIndex:%d, vgroupIndex:%d", pSql, tableIndex, pTableMetaInfo->vgroupIndex);
S
slguan 已提交
1735 1736 1737 1738 1739

    free(pNew);
    return NULL;
  }

1740 1741 1742 1743 1744 1745
  SSqlCmd* pnCmd = &pNew->cmd;
  memcpy(pnCmd, pCmd, sizeof(SSqlCmd));
  
  pnCmd->command = cmd;
  pnCmd->payload = NULL;
  pnCmd->allocSize = 0;
S
slguan 已提交
1746

1747 1748 1749 1750
  pnCmd->pQueryInfo = NULL;
  pnCmd->numOfClause = 0;
  pnCmd->clauseIndex = 0;
  pnCmd->pDataBlocks = NULL;
1751

1752
  if (tscAddSubqueryInfo(pnCmd) != TSDB_CODE_SUCCESS) {
1753 1754 1755
    tscFreeSqlObj(pNew);
    return NULL;
  }
1756

1757
  SQueryInfo* pNewQueryInfo = tscGetQueryInfoDetail(pnCmd, 0);
1758
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
1759

H
hjxilinx 已提交
1760 1761 1762
  pNewQueryInfo->command = pQueryInfo->command;
  pNewQueryInfo->slidingTimeUnit = pQueryInfo->slidingTimeUnit;
  pNewQueryInfo->intervalTime = pQueryInfo->intervalTime;
H
hjxilinx 已提交
1763 1764 1765 1766
  pNewQueryInfo->slidingTime  = pQueryInfo->slidingTime;
  pNewQueryInfo->type   = pQueryInfo->type;
  pNewQueryInfo->window = pQueryInfo->window;
  pNewQueryInfo->limit  = pQueryInfo->limit;
H
hjxilinx 已提交
1767
  pNewQueryInfo->slimit = pQueryInfo->slimit;
H
hjxilinx 已提交
1768
  pNewQueryInfo->order  = pQueryInfo->order;
H
hjxilinx 已提交
1769
  pNewQueryInfo->clauseLimit = pQueryInfo->clauseLimit;
H
hjxilinx 已提交
1770
  pNewQueryInfo->pTableMetaInfo = NULL;
H
hjxilinx 已提交
1771
  pNewQueryInfo->defaultVal  = NULL;
1772 1773
  pNewQueryInfo->numOfTables = 0;
  pNewQueryInfo->tsBuf = NULL;
H
hjxilinx 已提交
1774
  
H
hjxilinx 已提交
1775 1776 1777 1778 1779
  pNewQueryInfo->groupbyExpr = pQueryInfo->groupbyExpr;
  if (pQueryInfo->groupbyExpr.columnInfo != NULL) {
    pNewQueryInfo->groupbyExpr.columnInfo = taosArrayClone(pQueryInfo->groupbyExpr.columnInfo);
  }
  
1780
  tscTagCondCopy(&pNewQueryInfo->tagCond, &pQueryInfo->tagCond);
1781

1782
  if (pQueryInfo->interpoType != TSDB_INTERPO_NONE) {
H
hjxilinx 已提交
1783 1784
    pNewQueryInfo->defaultVal = malloc(pQueryInfo->fieldsInfo.numOfOutput * sizeof(int64_t));
    memcpy(pNewQueryInfo->defaultVal, pQueryInfo->defaultVal, pQueryInfo->fieldsInfo.numOfOutput * sizeof(int64_t));
1785
  }
1786

1787
  if (tscAllocPayload(pnCmd, TSDB_DEFAULT_PAYLOAD_SIZE) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1788
    tscError("%p new subquery failed, tableIndex:%d, vgroupIndex:%d", pSql, tableIndex, pTableMetaInfo->vgroupIndex);
S
slguan 已提交
1789 1790 1791
    tscFreeSqlObj(pNew);
    return NULL;
  }
1792
  
H
hjxilinx 已提交
1793
  tscColumnListCopy(pNewQueryInfo->colList, pQueryInfo->colList, (int16_t)tableIndex);
1794

S
slguan 已提交
1795 1796
  // set the correct query type
  if (pPrevSql != NULL) {
1797
    SQueryInfo* pPrevQueryInfo = tscGetQueryInfoDetail(&pPrevSql->cmd, pPrevSql->cmd.clauseIndex);
1798
    pNewQueryInfo->type = pPrevQueryInfo->type;
S
slguan 已提交
1799
  } else {
1800
    pNewQueryInfo->type |= TSDB_QUERY_TYPE_SUBQUERY;  // it must be the subquery
S
slguan 已提交
1801 1802
  }

H
hjxilinx 已提交
1803
  uint64_t uid = pTableMetaInfo->pTableMeta->uid;
H
hjxilinx 已提交
1804
  tscSqlExprCopy(pNewQueryInfo->exprList, pQueryInfo->exprList, uid, true);
S
slguan 已提交
1805

H
hjxilinx 已提交
1806
  int32_t numOfOutput = tscSqlExprNumOfExprs(pNewQueryInfo);
S
slguan 已提交
1807

H
hjxilinx 已提交
1808
  if (numOfOutput > 0) {  // todo refactor to extract method
H
hjxilinx 已提交
1809
    size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
H
hjxilinx 已提交
1810 1811 1812
    SFieldInfo* pFieldInfo = &pQueryInfo->fieldsInfo;
    
    for (int32_t i = 0; i < numOfExprs; ++i) {
1813
      SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
H
hjxilinx 已提交
1814
      
S
slguan 已提交
1815
      if (pExpr->uid == uid) {
H
hjxilinx 已提交
1816 1817 1818 1819 1820
        TAOS_FIELD* p = tscFieldInfoGetField(pFieldInfo, i);
        SFieldSupInfo* pInfo = tscFieldInfoGetSupp(pFieldInfo, i);
  
        SFieldSupInfo* pInfo1 = tscFieldInfoAppend(&pNewQueryInfo->fieldsInfo, p);
        *pInfo1 = *pInfo;
S
slguan 已提交
1821 1822 1823
      }
    }

H
hjxilinx 已提交
1824
    // make sure the the sqlExpr for each fields is correct
H
hjxilinx 已提交
1825
// todo handle the agg arithmetic expression
H
hjxilinx 已提交
1826 1827
    for(int32_t f = 0; f < pNewQueryInfo->fieldsInfo.numOfOutput; ++f) {
      TAOS_FIELD* field = tscFieldInfoGetField(&pNewQueryInfo->fieldsInfo, f);
H
hjxilinx 已提交
1828 1829
      numOfExprs = tscSqlExprNumOfExprs(pNewQueryInfo);
      
H
hjxilinx 已提交
1830
      for(int32_t k1 = 0; k1 < numOfExprs; ++k1) {
H
hjxilinx 已提交
1831
        SSqlExpr* pExpr1 = tscSqlExprGet(pNewQueryInfo, k1);
H
hjxilinx 已提交
1832 1833
        
        if (strcmp(field->name, pExpr1->aliasName) == 0) {  // eatablish link according to the result field name
H
hjxilinx 已提交
1834 1835
          SFieldSupInfo* pInfo = tscFieldInfoGetSupp(&pNewQueryInfo->fieldsInfo, f);
          pInfo->pSqlExpr = pExpr1;
H
hjxilinx 已提交
1836 1837 1838
        }
      }
    }
H
hjxilinx 已提交
1839 1840
  
    tscFieldInfoUpdateOffset(pNewQueryInfo);
S
slguan 已提交
1841 1842 1843 1844
  }

  pNew->fp = fp;
  pNew->param = param;
1845
  pNew->maxRetry = TSDB_MAX_REPLICA_NUM;
H
hjxilinx 已提交
1846

1847
  char* name = pTableMetaInfo->name;
H
hjxilinx 已提交
1848
  STableMetaInfo* pFinalInfo = NULL;
S
slguan 已提交
1849 1850

  if (pPrevSql == NULL) {
1851
    STableMeta* pTableMeta = taosCacheAcquireByName(tscCacheHandle, name);
1852 1853
    // todo handle error
    assert(pTableMeta != NULL);
1854
    pFinalInfo = tscAddTableMetaInfo(pNewQueryInfo, name, pTableMeta, pTableMetaInfo->vgroupList, pTableMetaInfo->tagColList);
1855 1856
  } else {  // transfer the ownership of pTableMeta to the newly create sql object.
    STableMetaInfo* pPrevInfo = tscGetTableMetaInfoFromCmd(&pPrevSql->cmd, pPrevSql->cmd.clauseIndex, 0);
1857

1858
    STableMeta*  pPrevTableMeta = taosCacheTransfer(tscCacheHandle, (void**)&pPrevInfo->pTableMeta);
1859
    
1860 1861
    SVgroupsInfo* pVgroupsInfo = pPrevInfo->vgroupList;
    pPrevInfo->vgroupList = NULL;
1862
    pFinalInfo = tscAddTableMetaInfo(pNewQueryInfo, name, pPrevTableMeta, pVgroupsInfo, pTableMetaInfo->tagColList);
S
slguan 已提交
1863 1864
  }

L
lihui 已提交
1865 1866 1867 1868 1869 1870 1871 1872
  if (pFinalInfo->pTableMeta == NULL) {
    tscError("%p new subquery failed for get pMeterMeta is NULL from cache", pSql);
    tscFreeSqlObj(pNew);
    return NULL;
  }
  
  assert(pNewQueryInfo->numOfTables == 1);
  
weixin_48148422's avatar
weixin_48148422 已提交
1873
  if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
1874
    assert(pFinalInfo->vgroupList != NULL);
S
slguan 已提交
1875
  }
H
hjxilinx 已提交
1876
  
1877
  if (cmd == TSDB_SQL_SELECT) {
1878 1879
    size_t size = taosArrayGetSize(pNewQueryInfo->colList);
    
1880
    tscTrace(
H
hjxilinx 已提交
1881
        "%p new subquery:%p, tableIndex:%d, vgroupIndex:%d, type:%d, exprInfo:%d, colList:%d,"
1882
        "fieldInfo:%d, name:%s, qrang:%" PRId64 " - %" PRId64 " order:%d, limit:%" PRId64,
H
hjxilinx 已提交
1883
        pSql, pNew, tableIndex, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, tscSqlExprNumOfExprs(pNewQueryInfo),
H
hjxilinx 已提交
1884 1885
        size, pNewQueryInfo->fieldsInfo.numOfOutput, pFinalInfo->name, pNewQueryInfo->window.skey,
        pNewQueryInfo->window.ekey, pNewQueryInfo->order.order, pNewQueryInfo->limit.limit);
1886 1887 1888
    
    tscPrintSelectClause(pNew, 0);
  } else {
H
hjxilinx 已提交
1889
    tscTrace("%p new sub insertion: %p, vnodeIdx:%d", pSql, pNew, pTableMetaInfo->vgroupIndex);
1890
  }
1891

S
slguan 已提交
1892 1893 1894
  return pNew;
}

H
hjxilinx 已提交
1895 1896 1897 1898 1899
/**
 * To decide if current is a two-stage super table query, join query, or insert. And invoke different
 * procedure accordingly
 * @param pSql
 */
H
hzcheng 已提交
1900 1901
void tscDoQuery(SSqlObj* pSql) {
  SSqlCmd* pCmd = &pSql->cmd;
H
hjxilinx 已提交
1902
  SSqlRes* pRes = &pSql->res;
H
hjxilinx 已提交
1903
  
H
hjxilinx 已提交
1904
  pRes->code = TSDB_CODE_SUCCESS;
H
hjxilinx 已提交
1905
  
H
hzcheng 已提交
1906 1907
  if (pCmd->command > TSDB_SQL_LOCAL) {
    tscProcessLocalCmd(pSql);
H
hjxilinx 已提交
1908 1909 1910 1911 1912 1913 1914 1915 1916
    return;
  }
  
  if (pCmd->command == TSDB_SQL_SELECT) {
    tscAddIntoSqlList(pSql);
  }

  if (pCmd->dataSourceType == DATA_FROM_DATA_FILE) {
    tscProcessMultiVnodesInsertFromFile(pSql);
H
hzcheng 已提交
1917
  } else {
H
hjxilinx 已提交
1918 1919 1920 1921 1922 1923
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
    uint16_t type = pQueryInfo->type;
  
    if (pSql->fp == (void(*)())tscHandleMultivnodeInsert) {  // multi-vnodes insertion
      tscHandleMultivnodeInsert(pSql);
      return;
H
hzcheng 已提交
1924
    }
H
hjxilinx 已提交
1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
  
    if (QUERY_IS_JOIN_QUERY(type)) {
      if ((pQueryInfo->type & TSDB_QUERY_TYPE_SUBQUERY) == 0) {
        tscHandleMasterJoinQuery(pSql);
        return;
      } else {
        // for first stage sub query, iterate all vnodes to get all timestamp
        if ((pQueryInfo->type & TSDB_QUERY_TYPE_JOIN_SEC_STAGE) != TSDB_QUERY_TYPE_JOIN_SEC_STAGE) {
//          doProcessSql(pSql);
          assert(0);
        }
      }
    } else if (tscIsTwoStageSTableQuery(pQueryInfo, 0)) {  // super table query
      tscHandleMasterSTableQuery(pSql);
      return;
S
slguan 已提交
1940
    }
H
hjxilinx 已提交
1941 1942
    
    tscProcessSql(pSql);
H
hzcheng 已提交
1943 1944
  }
}
S
slguan 已提交
1945

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

bool tscIsUpdateQuery(STscObj* pObj) {
  if (pObj == NULL || pObj->signature != pObj) {
H
hjxilinx 已提交
1956
    terrno = TSDB_CODE_DISCONNECTED;
1957 1958 1959
    return TSDB_CODE_DISCONNECTED;
  }

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

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

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

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

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

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

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

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

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

/**
 *  If current vnode query does not return results anymore (pRes->numOfRows == 0), try the next vnode if exists,
1999
 *  while multi-vnode super table projection query and the result does not reach the limitation.
2000
 */
2001
bool hasMoreVnodesToTry(SSqlObj* pSql) {
2002 2003 2004 2005 2006
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;
  if (pCmd->command != TSDB_SQL_FETCH) {
    return false;
  }
2007

2008
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
2009
  
2010 2011 2012 2013
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
  assert(pRes->completed);
  
  // for normal table, do not try any more if result are exhausted
H
hjLiao 已提交
2014
  if (!UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo) || (pTableMetaInfo->vgroupList == NULL)) {
2015
    return false;
2016
  }
2017
  
2018 2019 2020
  int32_t numOfVgroups = pTableMetaInfo->vgroupList->numOfVgroups;
  return tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) &&
         (!tscHasReachLimitation(pQueryInfo, pRes)) && (pTableMetaInfo->vgroupIndex < numOfVgroups - 1);
2021 2022
}

2023 2024 2025 2026 2027 2028
void tscTryQueryNextVnode(SSqlObj* pSql, __async_cb_func_t fp) {
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;

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

2029 2030 2031 2032
  /*
   * no result returned from the current virtual node anymore, try the next vnode if exists
   * if case of: multi-vnode super table projection query
   */
2033
  assert(pRes->numOfRows == 0 && tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) && !tscHasReachLimitation(pQueryInfo, pRes));
2034

H
hjxilinx 已提交
2035
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
2036 2037 2038
  
  int32_t totalVgroups = pTableMetaInfo->vgroupList->numOfVgroups;
  while (++pTableMetaInfo->vgroupIndex < totalVgroups) {
2039
    tscTrace("%p current vnode:%d exhausted, try next:%d. total vnode:%d. current numOfRes:%d", pSql,
2040
             pTableMetaInfo->vgroupIndex - 1, pTableMetaInfo->vgroupIndex, totalVgroups, pRes->numOfTotalInCurrentClause);
2041

2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
    /*
     * 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;
    }
2054

2055 2056
    pQueryInfo->limit.offset = pRes->offset;
    assert((pRes->offset >= 0 && pRes->numOfRows == 0) || (pRes->offset == 0 && pRes->numOfRows >= 0));
2057 2058 2059
    
    tscTrace("%p new query to next vgroup, index:%d, limit:%" PRId64 ", offset:%" PRId64 ", glimit:%" PRId64,
        pSql, pTableMetaInfo->vgroupIndex, pQueryInfo->limit.limit, pQueryInfo->limit.offset, pQueryInfo->clauseLimit);
2060

2061 2062 2063 2064 2065 2066 2067 2068
    /*
     * 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;
2069

2070
    tscResetForNextRetrieve(pRes);
2071

2072
    // set the callback function
2073
    pSql->fp = fp;
2074 2075
    int32_t ret = tscProcessSql(pSql);
    if (ret == TSDB_CODE_SUCCESS) {
2076
      return;
2077
    } else {// todo check for failure
2078 2079 2080
    }
  }
}
2081 2082 2083 2084 2085 2086 2087 2088

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 已提交
2089
  pCmd->clauseIndex++;
2090 2091 2092 2093
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);

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

2094 2095
  //backup the total number of result first
  int64_t num = pRes->numOfTotal + pRes->numOfTotalInCurrentClause;
H
hjxilinx 已提交
2096
  tscFreeSqlResult(pSql);
2097 2098 2099
  
  pRes->numOfTotal = num;
  
2100
  tfree(pSql->pSubs);
2101 2102
  pSql->numOfSubs = 0;
  
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114
  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);
  }
}
H
hjxilinx 已提交
2115

2116 2117 2118 2119
void tscGetResultColumnChr(SSqlRes* pRes, SFieldInfo* pFieldInfo, int32_t columnIndex) {
  SFieldSupInfo* pInfo = tscFieldInfoGetSupp(pFieldInfo, columnIndex);
  assert(pInfo->pSqlExpr != NULL);

H
hjxilinx 已提交
2120
  int32_t type = pInfo->pSqlExpr->resType;
2121 2122
  int32_t bytes = pInfo->pSqlExpr->resBytes;
  
H
hjxilinx 已提交
2123
  char* pData = ((char*) pRes->data) + pInfo->pSqlExpr->offset * pRes->numOfRows + bytes * pRes->row;
H
hjxilinx 已提交
2124
  
H
hjxilinx 已提交
2125
  if (type == TSDB_DATA_TYPE_NCHAR || type == TSDB_DATA_TYPE_BINARY) {
2126
    int32_t realLen = varDataLen(pData);
H
hjxilinx 已提交
2127 2128
    assert(realLen <= bytes - VARSTR_HEADER_SIZE);
    
2129
    if (realLen < pInfo->pSqlExpr->resBytes - VARSTR_HEADER_SIZE) { // todo refactor
H
hjxilinx 已提交
2130
      *(char*) (pData + realLen + VARSTR_HEADER_SIZE) = 0;
H
hjxilinx 已提交
2131 2132
    }
    
2133 2134
    pRes->tsrow[columnIndex] = pData + VARSTR_HEADER_SIZE;
    pRes->length[columnIndex] = realLen;
H
hjxilinx 已提交
2135
  } else {
2136 2137 2138 2139
    assert(bytes == tDataTypeDesc[type].nSize);
    
    pRes->tsrow[columnIndex] = pData;
    pRes->length[columnIndex] = bytes;
H
hjxilinx 已提交
2140
  }
H
hjxilinx 已提交
2141 2142
}

weixin_48148422's avatar
weixin_48148422 已提交
2143 2144 2145 2146 2147 2148 2149 2150 2151
void* malloc_throw(size_t size) {
  void* p = malloc(size);
  if (p == NULL) {
    THROW(TSDB_CODE_CLI_OUT_OF_MEMORY);
  }
  return p;
}

void* calloc_throw(size_t nmemb, size_t size) {
weixin_48148422's avatar
weixin_48148422 已提交
2152
  void* p = calloc(nmemb, size);
weixin_48148422's avatar
weixin_48148422 已提交
2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
  if (p == NULL) {
    THROW(TSDB_CODE_CLI_OUT_OF_MEMORY);
  }
  return p;
}

char* strdup_throw(const char* str) {
  char* p = strdup(str);
  if (p == NULL) {
    THROW(TSDB_CODE_CLI_OUT_OF_MEMORY);
  }
  return p;
}
2166 2167 2168 2169 2170 2171

int tscSetMgmtIpListFromCfg(const char *first, const char *second) {
  tscMgmtIpSet.numOfIps = 0;
  tscMgmtIpSet.inUse = 0;

  if (first && first[0] != 0) {
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
2172 2173 2174 2175
    if (strlen(first) >= TSDB_FQDN_LEN) {
      terrno = TSDB_CODE_INVALID_FQDN;
      return -1;
    }
2176 2177 2178 2179 2180
    taosGetFqdnPortFromEp(first, tscMgmtIpSet.fqdn[tscMgmtIpSet.numOfIps], &tscMgmtIpSet.port[tscMgmtIpSet.numOfIps]);
    tscMgmtIpSet.numOfIps++;
  }

  if (second && second[0] != 0) {
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
2181 2182 2183 2184
    if (strlen(second) >= TSDB_FQDN_LEN) {
      terrno = TSDB_CODE_INVALID_FQDN;
      return -1;
    }
2185 2186 2187 2188
    taosGetFqdnPortFromEp(second, tscMgmtIpSet.fqdn[tscMgmtIpSet.numOfIps], &tscMgmtIpSet.port[tscMgmtIpSet.numOfIps]);
    tscMgmtIpSet.numOfIps++;
  }

陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
2189 2190 2191 2192
  if ( tscMgmtIpSet.numOfIps == 0) {
    terrno = TSDB_CODE_INVALID_FQDN;
    return -1;
  }
2193 2194 2195

  return 0;
}