tscUtil.c 70.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/>.
 */

H
Haojun Liao 已提交
16
#include "tscUtil.h"
H
Haojun Liao 已提交
17 18 19
#include "hash.h"
#include "os.h"
#include "qAst.h"
H
hzcheng 已提交
20 21 22 23
#include "taosmsg.h"
#include "tcache.h"
#include "tkey.h"
#include "tmd5.h"
24
#include "tscLocalMerge.h"
H
Haojun Liao 已提交
25 26
#include "tscLog.h"
#include "tscProfile.h"
H
hjxilinx 已提交
27
#include "tscSubquery.h"
H
hzcheng 已提交
28 29 30
#include "tschemautil.h"
#include "tsclient.h"
#include "ttimer.h"
31
#include "ttokendef.h"
H
hzcheng 已提交
32

33 34
static void freeQueryInfoImpl(SQueryInfo* pQueryInfo);
static void clearAllTableMetaInfo(SQueryInfo* pQueryInfo, const char* address, bool removeFromCache);
35

B
Bomin Zhang 已提交
36
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,
S
Shengliang Guan 已提交
60
    .len = (int32_t)(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
}

H
hjxilinx 已提交
73
bool tscQueryTags(SQueryInfo* pQueryInfo) {
H
hjxilinx 已提交
74
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutput; ++i) {
H
Haojun Liao 已提交
75 76 77 78 79 80 81 82
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
    int32_t functId = pExpr->functionId;

    // "select count(tbname)" query
    if (functId == TSDB_FUNC_COUNT && pExpr->colInfo.colId == TSDB_TBNAME_COLUMN_INDEX) {
      continue;
    }

83
    if (functId != TSDB_FUNC_TAGPRJ && functId != TSDB_FUNC_TID_TAG) {
S
slguan 已提交
84 85 86
      return false;
    }
  }
H
hzcheng 已提交
87

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

H
Haojun Liao 已提交
91 92
// todo refactor, extract methods and move the common module
void tscGetDBInfoFromTableFullName(char* tableId, char* db) {
S
slguan 已提交
93
  char* st = strstr(tableId, TS_PATH_DELIMITER);
H
hzcheng 已提交
94 95 96
  if (st != NULL) {
    char* end = strstr(st + 1, TS_PATH_DELIMITER);
    if (end != NULL) {
S
slguan 已提交
97 98
      memcpy(db, tableId, (end - tableId));
      db[end - tableId] = 0;
H
hzcheng 已提交
99 100 101 102 103 104 105
      return;
    }
  }

  db[0] = 0;
}

H
hjxilinx 已提交
106
bool tscIsTwoStageSTableQuery(SQueryInfo* pQueryInfo, int32_t tableIndex) {
107 108 109
  if (pQueryInfo == NULL) {
    return false;
  }
110

H
hjxilinx 已提交
111
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, tableIndex);
H
hjxilinx 已提交
112
  if (pTableMetaInfo == NULL) {
113 114 115
    return false;
  }
  
H
hjxilinx 已提交
116
  // for select query super table, the super table vgroup list can not be null in any cases.
weixin_48148422's avatar
weixin_48148422 已提交
117
  if (pQueryInfo->command == TSDB_SQL_SELECT && UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
H
hjxilinx 已提交
118
    assert(pTableMetaInfo->vgroupList != NULL);
119 120
  }
  
H
hjxilinx 已提交
121 122
  if ((pQueryInfo->type & TSDB_QUERY_TYPE_FREE_RESOURCE) == TSDB_QUERY_TYPE_FREE_RESOURCE) {
    return false;
S
slguan 已提交
123 124
  }

125 126
  // for ordered projection query, iterate all qualified vnodes sequentially
  if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, tableIndex)) {
H
hzcheng 已提交
127 128 129
    return false;
  }

130
  if (!TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_STABLE_SUBQUERY) && pQueryInfo->command == TSDB_SQL_SELECT) {
weixin_48148422's avatar
weixin_48148422 已提交
131
    return UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo);
H
hzcheng 已提交
132 133 134 135 136
  }

  return false;
}

137
bool tscIsProjectionQueryOnSTable(SQueryInfo* pQueryInfo, int32_t tableIndex) {
H
hjxilinx 已提交
138
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, tableIndex);
139
  
H
hzcheng 已提交
140
  /*
141
   * In following cases, return false for non ordered project query on super table
H
Haojun Liao 已提交
142
   * 1. failed to get tableMeta from server; 2. not a super table; 3. limitation is 0;
143
   * 4. show queries, instead of a select query
H
hzcheng 已提交
144
   */
H
hjxilinx 已提交
145
  size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
weixin_48148422's avatar
weixin_48148422 已提交
146
  if (pTableMetaInfo == NULL || !UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo) ||
H
hjxilinx 已提交
147
      pQueryInfo->command == TSDB_SQL_RETRIEVE_EMPTY_RESULT || numOfExprs == 0) {
H
hzcheng 已提交
148 149
    return false;
  }
150
  
H
hjxilinx 已提交
151
  for (int32_t i = 0; i < numOfExprs; ++i) {
152
    int32_t functionId = tscSqlExprGet(pQueryInfo, i)->functionId;
H
Haojun Liao 已提交
153 154 155 156 157 158 159 160

    if (functionId != TSDB_FUNC_PRJ &&
        functionId != TSDB_FUNC_TAGPRJ &&
        functionId != TSDB_FUNC_TAG &&
        functionId != TSDB_FUNC_TS &&
        functionId != TSDB_FUNC_ARITHM &&
        functionId != TSDB_FUNC_TS_COMP &&
        functionId != TSDB_FUNC_TID_TAG) {
S
slguan 已提交
161
      return false;
H
hzcheng 已提交
162 163
    }
  }
164
  
S
slguan 已提交
165
  return true;
H
hzcheng 已提交
166 167
}

H
Haojun Liao 已提交
168
// not order by timestamp projection query on super table
169 170 171 172 173
bool tscNonOrderedProjectionQueryOnSTable(SQueryInfo* pQueryInfo, int32_t tableIndex) {
  if (!tscIsProjectionQueryOnSTable(pQueryInfo, tableIndex)) {
    return false;
  }
  
174
  // order by columnIndex exists, not a non-ordered projection query
175 176 177 178 179 180 181 182
  return pQueryInfo->order.orderColId < 0;
}

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

H
Haojun Liao 已提交
187 188 189 190
bool tscIsProjectionQuery(SQueryInfo* pQueryInfo) {
  size_t size = tscSqlExprNumOfExprs(pQueryInfo);

  for (int32_t i = 0; i < size; ++i) {
191
    int32_t functionId = tscSqlExprGet(pQueryInfo, i)->functionId;
H
Haojun Liao 已提交
192 193 194

    if (functionId != TSDB_FUNC_PRJ && functionId != TSDB_FUNC_TAGPRJ && functionId != TSDB_FUNC_TAG &&
        functionId != TSDB_FUNC_TS && functionId != TSDB_FUNC_ARITHM) {
H
hjxilinx 已提交
195 196 197
      return false;
    }
  }
H
hjxilinx 已提交
198

H
hjxilinx 已提交
199 200 201
  return true;
}

202
bool tscIsPointInterpQuery(SQueryInfo* pQueryInfo) {
H
hjxilinx 已提交
203 204 205
  size_t size = tscSqlExprNumOfExprs(pQueryInfo);
  
  for (int32_t i = 0; i < size; ++i) {
206
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
H
Haojun Liao 已提交
207 208 209 210
    assert(pExpr != NULL);
//    if (pExpr == NULL) {
//      return false;
//    }
H
hzcheng 已提交
211

S
slguan 已提交
212
    int32_t functionId = pExpr->functionId;
H
hzcheng 已提交
213 214 215 216 217 218 219 220
    if (functionId == TSDB_FUNC_TAG) {
      continue;
    }

    if (functionId != TSDB_FUNC_INTERP) {
      return false;
    }
  }
H
Haojun Liao 已提交
221

H
hzcheng 已提交
222 223 224
  return true;
}

225
bool tscIsTWAQuery(SQueryInfo* pQueryInfo) {
H
hjxilinx 已提交
226 227
  size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
  for (int32_t i = 0; i < numOfExprs; ++i) {
228
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
229 230 231 232 233 234 235 236 237 238 239
    if (pExpr == NULL) {
      continue;
    }

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

  return false;
H
hzcheng 已提交
240 241
}

242 243
void tscClearInterpInfo(SQueryInfo* pQueryInfo) {
  if (!tscIsPointInterpQuery(pQueryInfo)) {
H
hzcheng 已提交
244 245 246
    return;
  }

247
  pQueryInfo->fillType = TSDB_FILL_NONE;
S
Shengliang Guan 已提交
248
  taosTFree(pQueryInfo->fillVal);
H
hzcheng 已提交
249 250
}

251
int32_t tscCreateResPointerInfo(SSqlRes* pRes, SQueryInfo* pQueryInfo) {
H
hzcheng 已提交
252
  if (pRes->tsrow == NULL) {
H
hjxilinx 已提交
253 254
    int32_t numOfOutput = pQueryInfo->fieldsInfo.numOfOutput;
    pRes->numOfCols = numOfOutput;
H
Haojun Liao 已提交
255

256
    pRes->tsrow  = calloc(numOfOutput, POINTER_BYTES);
H
Haojun Liao 已提交
257
    pRes->length = calloc(numOfOutput, sizeof(int32_t));
258
    pRes->buffer = calloc(numOfOutput, POINTER_BYTES);
H
Haojun Liao 已提交
259

260
    // not enough memory
H
hjxilinx 已提交
261
    if (pRes->tsrow == NULL || (pRes->buffer == NULL && pRes->numOfCols > 0)) {
S
Shengliang Guan 已提交
262
      taosTFree(pRes->tsrow);
263
      pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hzcheng 已提交
264 265 266 267 268 269 270
      return pRes->code;
    }
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
271
static void tscDestroyResPointerInfo(SSqlRes* pRes) {
H
hjxilinx 已提交
272
  if (pRes->buffer != NULL) { // free all buffers containing the multibyte string
H
hjxilinx 已提交
273
    for (int i = 0; i < pRes->numOfCols; i++) {
S
Shengliang Guan 已提交
274
      taosTFree(pRes->buffer[i]);
H
hzcheng 已提交
275
    }
276
    
H
hjxilinx 已提交
277
    pRes->numOfCols = 0;
H
hzcheng 已提交
278
  }
279
  
S
Shengliang Guan 已提交
280
  taosTFree(pRes->pRsp);
H
Haojun Liao 已提交
281

S
Shengliang Guan 已提交
282 283
  taosTFree(pRes->tsrow);
  taosTFree(pRes->length);
H
Haojun Liao 已提交
284 285
  taosTFree(pRes->buffer);

S
Shengliang Guan 已提交
286 287
  taosTFree(pRes->pGroupRec);
  taosTFree(pRes->pColumnIndex);
H
Haojun Liao 已提交
288

289
  if (pRes->pArithSup != NULL) {
S
Shengliang Guan 已提交
290 291
    taosTFree(pRes->pArithSup->data);
    taosTFree(pRes->pArithSup);
292 293
  }
  
294
  pRes->data = NULL;  // pRes->data points to the buffer of pRsp, no need to free
H
hzcheng 已提交
295 296
}

B
Bomin Zhang 已提交
297
static void tscFreeQueryInfo(SSqlCmd* pCmd, bool removeFromCache) {
298 299 300 301 302 303 304 305 306
  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);
B
Bomin Zhang 已提交
307
    clearAllTableMetaInfo(pQueryInfo, (const char*)addr, removeFromCache);
S
Shengliang Guan 已提交
308
    taosTFree(pQueryInfo);
309 310 311
  }
  
  pCmd->numOfClause = 0;
S
Shengliang Guan 已提交
312
  taosTFree(pCmd->pQueryInfo);
313 314
}

B
Bomin Zhang 已提交
315
void tscResetSqlCmdObj(SSqlCmd* pCmd, bool removeFromCache) {
316
  pCmd->command   = 0;
317
  pCmd->numOfCols = 0;
318 319 320 321
  pCmd->count     = 0;
  pCmd->curSql    = NULL;
  pCmd->msgType   = 0;
  pCmd->parseFinished = 0;
322
  pCmd->autoCreated = 0;
323 324
  
  taosHashCleanup(pCmd->pTableList);
325
  pCmd->pTableList = NULL;
326
  
S
slguan 已提交
327
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
328
  
B
Bomin Zhang 已提交
329
  tscFreeQueryInfo(pCmd, removeFromCache);
H
hzcheng 已提交
330 331
}

H
hjxilinx 已提交
332
void tscFreeSqlResult(SSqlObj* pSql) {
333 334
  tscDestroyLocalReducer(pSql);
  
H
hjxilinx 已提交
335
  SSqlRes* pRes = &pSql->res;
336
  tscDestroyResPointerInfo(pRes);
337
  
H
hjxilinx 已提交
338
  memset(&pSql->res, 0, sizeof(SSqlRes));
339 340
}

H
hjxilinx 已提交
341
void tscPartiallyFreeSqlObj(SSqlObj* pSql) {
S
slguan 已提交
342 343 344
  if (pSql == NULL || pSql->signature != pSql) {
    return;
  }
H
hzcheng 已提交
345 346 347

  SSqlCmd* pCmd = &pSql->cmd;
  int32_t cmd = pCmd->command;
H
hjxilinx 已提交
348
  if (cmd < TSDB_SQL_INSERT || cmd == TSDB_SQL_RETRIEVE_LOCALMERGE || cmd == TSDB_SQL_RETRIEVE_EMPTY_RESULT ||
349
      cmd == TSDB_SQL_TABLE_JOIN_RETRIEVE) {
H
Haojun Liao 已提交
350
    tscRemoveFromSqlList(pSql);
H
hzcheng 已提交
351
  }
352
  
H
hzcheng 已提交
353
  // pSql->sqlstr will be used by tscBuildQueryStreamDesc
H
Haojun Liao 已提交
354
//  if (pObj->signature == pObj) {
L
Liu Tao 已提交
355
    //pthread_mutex_lock(&pObj->mutex);
S
Shengliang Guan 已提交
356
    taosTFree(pSql->sqlstr);
L
Liu Tao 已提交
357
    //pthread_mutex_unlock(&pObj->mutex);
H
Haojun Liao 已提交
358
//  }
359
  
weixin_48148422's avatar
weixin_48148422 已提交
360
  tscFreeSqlResult(pSql);
H
[TD-98]  
hjxilinx 已提交
361
  
S
Shengliang Guan 已提交
362
  taosTFree(pSql->pSubs);
H
[TD-98]  
hjxilinx 已提交
363
  pSql->numOfSubs = 0;
H
Haojun Liao 已提交
364
  pSql->self = 0;
H
[TD-98]  
hjxilinx 已提交
365
  
B
Bomin Zhang 已提交
366
  tscResetSqlCmdObj(pCmd, false);
H
hzcheng 已提交
367 368
}

H
Haojun Liao 已提交
369
static UNUSED_FUNC void tscFreeSubobj(SSqlObj* pSql) {
H
Haojun Liao 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
  if (pSql->numOfSubs == 0) {
    return;
  }

  tscDebug("%p start to free sub SqlObj, numOfSub:%d", pSql, pSql->numOfSubs);

  for(int32_t i = 0; i < pSql->numOfSubs; ++i) {
    tscDebug("%p free sub SqlObj:%p, index:%d", pSql, pSql->pSubs[i], i);
    taos_free_result(pSql->pSubs[i]);
    pSql->pSubs[i] = NULL;
  }

  pSql->numOfSubs = 0;
}

H
Haojun Liao 已提交
385 386 387 388 389 390 391
/**
 * The free operation will cause the pSql to be removed from hash table and free it in
 * the function of processmsgfromserver is impossible in this case, since it will fail
 * to retrieve pSqlObj in hashtable.
 *
 * @param pSql
 */
H
Haojun Liao 已提交
392 393
void tscFreeSqlObjInCache(void *pSql) {
  assert(pSql != NULL);
H
Haojun Liao 已提交
394

H
Haojun Liao 已提交
395
  SSqlObj** p = (SSqlObj**)pSql;
H
Haojun Liao 已提交
396
  STscObj* pTscObj = (*p)->pTscObj;
H
Haojun Liao 已提交
397

H
Haojun Liao 已提交
398
  assert((*p)->self != 0 && (*p)->self == (p));
H
Haojun Liao 已提交
399
  tscFreeSqlObj(*p);
H
Haojun Liao 已提交
400 401 402 403 404 405 406 407 408

  int32_t ref = T_REF_DEC(pTscObj);
  assert(ref >= 0);

  tscDebug("%p free sqlObj completed, tscObj:%p ref:%d", *p, pTscObj, ref);
  if (ref == 0) {
    tscDebug("%p all sqlObj freed, free tscObj:%p", *p, pTscObj);
    tscCloseTscObj(pTscObj);
  }
H
Haojun Liao 已提交
409 410
}

H
hzcheng 已提交
411
void tscFreeSqlObj(SSqlObj* pSql) {
H
Haojun Liao 已提交
412 413 414
  if (pSql == NULL || pSql->signature != pSql) {
    return;
  }
415

H
Haojun Liao 已提交
416 417
  tscDebug("%p start to free sqlObj", pSql);

H
Haojun Liao 已提交
418
  tscFreeSubobj(pSql);
H
hjxilinx 已提交
419
  tscPartiallyFreeSqlObj(pSql);
H
hzcheng 已提交
420 421 422

  pSql->signature = NULL;
  pSql->fp = NULL;
423
  
H
hzcheng 已提交
424 425
  SSqlCmd* pCmd = &pSql->cmd;

S
slguan 已提交
426
  memset(pCmd->payload, 0, (size_t)pCmd->allocSize);
S
Shengliang Guan 已提交
427
  taosTFree(pCmd->payload);
H
hzcheng 已提交
428
  pCmd->allocSize = 0;
429
  
S
Shengliang Guan 已提交
430
  taosTFree(pSql->sqlstr);
S
TD-1057  
Shengliang Guan 已提交
431
  tsem_destroy(&pSql->rspSem);
H
Haojun Liao 已提交
432

H
hzcheng 已提交
433 434 435
  free(pSql);
}

S
slguan 已提交
436 437
void tscDestroyDataBlock(STableDataBlocks* pDataBlock) {
  if (pDataBlock == NULL) {
H
hzcheng 已提交
438 439 440
    return;
  }

S
Shengliang Guan 已提交
441 442
  taosTFree(pDataBlock->pData);
  taosTFree(pDataBlock->params);
H
hjxilinx 已提交
443

H
hjxilinx 已提交
444
  // free the refcount for metermeta
H
Haojun Liao 已提交
445
  if (pDataBlock->pTableMeta != NULL) {
H
Haojun Liao 已提交
446
    taosCacheRelease(tscMetaCache, (void**)&(pDataBlock->pTableMeta), false);
H
Haojun Liao 已提交
447 448
  }

S
Shengliang Guan 已提交
449
  taosTFree(pDataBlock);
H
hzcheng 已提交
450 451
}

452
SParamInfo* tscAddParamToDataBlock(STableDataBlocks* pDataBlock, char type, uint8_t timePrec, int16_t bytes,
453
                                   uint32_t offset) {
S
slguan 已提交
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
  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;
}

476 477
void*  tscDestroyBlockArrayList(SArray* pDataBlockList) {
  if (pDataBlockList == NULL) {
S
slguan 已提交
478 479 480
    return NULL;
  }

481 482 483 484
  size_t size = taosArrayGetSize(pDataBlockList);
  for (int32_t i = 0; i < size; i++) {
    void* d = taosArrayGetP(pDataBlockList, i);
    tscDestroyDataBlock(d);
S
slguan 已提交
485 486
  }

487
  taosArrayDestroy(pDataBlockList);
S
slguan 已提交
488
  return NULL;
H
hzcheng 已提交
489 490
}

S
slguan 已提交
491
int32_t tscCopyDataBlockToPayload(SSqlObj* pSql, STableDataBlocks* pDataBlock) {
H
hjxilinx 已提交
492
  SSqlCmd* pCmd = &pSql->cmd;
H
hjxilinx 已提交
493
  assert(pDataBlock->pTableMeta != NULL);
H
hjxilinx 已提交
494

S
slguan 已提交
495
  pCmd->numOfTablesInSubmit = pDataBlock->numOfTables;
496

497
  assert(pCmd->numOfClause == 1);
498
  STableMetaInfo* pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
499

500
  // set the correct table meta object, the table meta has been locked in pDataBlocks, so it must be in the cache
H
hjxilinx 已提交
501
  if (pTableMetaInfo->pTableMeta != pDataBlock->pTableMeta) {
502
    tstrncpy(pTableMetaInfo->name, pDataBlock->tableId, sizeof(pTableMetaInfo->name));
H
Haojun Liao 已提交
503 504

    if (pTableMetaInfo->pTableMeta != NULL) {
H
Haojun Liao 已提交
505
      taosCacheRelease(tscMetaCache, (void**)&(pTableMetaInfo->pTableMeta), false);
H
Haojun Liao 已提交
506
    }
507

H
Haojun Liao 已提交
508
    pTableMetaInfo->pTableMeta = taosCacheTransfer(tscMetaCache, (void**)&pDataBlock->pTableMeta);
H
hjxilinx 已提交
509
  } else {
H
hjxilinx 已提交
510
    assert(strncmp(pTableMetaInfo->name, pDataBlock->tableId, tListLen(pDataBlock->tableId)) == 0);
H
hjxilinx 已提交
511
  }
H
hjxilinx 已提交
512

513 514
  /*
   * the submit message consists of : [RPC header|message body|digest]
515
   * the dataBlock only includes the RPC Header buffer and actual submit message body, space for digest needs
516 517
   * additional space.
   */
518
  int ret = tscAllocPayload(pCmd, pDataBlock->size + 100);
H
hjxilinx 已提交
519 520 521
  if (TSDB_CODE_SUCCESS != ret) {
    return ret;
  }
H
hjxilinx 已提交
522

523 524
  assert(pDataBlock->size <= pDataBlock->nAllocSize);
  memcpy(pCmd->payload, pDataBlock->pData, pDataBlock->size);
H
hjxilinx 已提交
525

526 527 528 529
  /*
   * the payloadLen should be actual message body size
   * the old value of payloadLen is the allocated payload size
   */
530
  pCmd->payloadLen = pDataBlock->size;
H
hjxilinx 已提交
531

S
Shengliang Guan 已提交
532
  assert(pCmd->allocSize >= (uint32_t)(pCmd->payloadLen + 100) && pCmd->payloadLen > 0);
H
hjxilinx 已提交
533
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
534 535
}

H
hjxilinx 已提交
536 537 538 539 540 541
/**
 * create the in-memory buffer for each table to keep the submitted data block
 * @param initialSize
 * @param rowSize
 * @param startOffset
 * @param name
H
hjxilinx 已提交
542
 * @param dataBlocks
H
hjxilinx 已提交
543 544
 * @return
 */
H
hjxilinx 已提交
545
int32_t tscCreateDataBlock(size_t initialSize, int32_t rowSize, int32_t startOffset, const char* name,
H
hjxilinx 已提交
546
                           STableMeta* pTableMeta, STableDataBlocks** dataBlocks) {
H
hjxilinx 已提交
547
  STableDataBlocks* dataBuf = (STableDataBlocks*)calloc(1, sizeof(STableDataBlocks));
H
hjxilinx 已提交
548 549
  if (dataBuf == NULL) {
    tscError("failed to allocated memory, reason:%s", strerror(errno));
550
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
551 552 553
  }

  dataBuf->nAllocSize = (uint32_t)initialSize;
L
[#1102]  
lihui 已提交
554
  dataBuf->headerSize = startOffset; // the header size will always be the startOffset value, reserved for the subumit block header
H
hjxilinx 已提交
555 556 557 558
  if (dataBuf->nAllocSize <= dataBuf->headerSize) {
    dataBuf->nAllocSize = dataBuf->headerSize*2;
  }
  
H
hjxilinx 已提交
559
  dataBuf->pData = calloc(1, dataBuf->nAllocSize);
560 561 562 563 564
  if (dataBuf->pData == NULL) {
    tscError("failed to allocated memory, reason:%s", strerror(errno));
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }

H
hjxilinx 已提交
565 566
  dataBuf->ordered = true;
  dataBuf->prevTS = INT64_MIN;
S
slguan 已提交
567 568 569

  dataBuf->rowSize = rowSize;
  dataBuf->size = startOffset;
S
slguan 已提交
570 571
  dataBuf->tsSource = -1;

B
Bomin Zhang 已提交
572
  tstrncpy(dataBuf->tableId, name, sizeof(dataBuf->tableId));
H
hjxilinx 已提交
573 574

  /*
575
   * The table meta may be released since the table meta cache are completed clean by other thread
576 577
   * 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 已提交
578
   */
H
Haojun Liao 已提交
579
  dataBuf->pTableMeta = taosCacheAcquireByData(tscMetaCache, pTableMeta);
H
hjxilinx 已提交
580
  assert(initialSize > 0 && pTableMeta != NULL && dataBuf->pTableMeta != NULL);
581

582 583
  *dataBlocks = dataBuf;
  return TSDB_CODE_SUCCESS;
S
slguan 已提交
584 585
}

586
int32_t tscGetDataBlockFromList(void* pHashList, SArray* pDataBlockList, int64_t id, int32_t size,
H
hjxilinx 已提交
587
                                int32_t startOffset, int32_t rowSize, const char* tableId, STableMeta* pTableMeta,
H
hjxilinx 已提交
588 589
                                STableDataBlocks** dataBlocks) {
  *dataBlocks = NULL;
S
slguan 已提交
590

H
hjxilinx 已提交
591
  STableDataBlocks** t1 = (STableDataBlocks**)taosHashGet(pHashList, (const char*)&id, sizeof(id));
S
slguan 已提交
592
  if (t1 != NULL) {
H
hjxilinx 已提交
593
    *dataBlocks = *t1;
S
slguan 已提交
594 595
  }

H
hjxilinx 已提交
596
  if (*dataBlocks == NULL) {
H
hjxilinx 已提交
597
    int32_t ret = tscCreateDataBlock((size_t)size, rowSize, startOffset, tableId, pTableMeta, dataBlocks);
H
hjxilinx 已提交
598 599 600 601
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }

H
hjxilinx 已提交
602
    taosHashPut(pHashList, (const char*)&id, sizeof(int64_t), (char*)dataBlocks, POINTER_BYTES);
603
    taosArrayPush(pDataBlockList, dataBlocks);
S
slguan 已提交
604 605
  }

H
hjxilinx 已提交
606
  return TSDB_CODE_SUCCESS;
S
slguan 已提交
607 608
}

609
static int trimDataBlock(void* pDataBlock, STableDataBlocks* pTableDataBlock, bool includeSchema) {
610
  // TODO: optimize this function, handle the case while binary is not presented
H
TD-166  
hzcheng 已提交
611
  STableMeta*   pTableMeta = pTableDataBlock->pTableMeta;
612
  STableComInfo tinfo = tscGetTableInfo(pTableMeta);
H
TD-166  
hzcheng 已提交
613 614 615
  SSchema*      pSchema = tscGetTableSchema(pTableMeta);

  SSubmitBlk* pBlock = pDataBlock;
616
  memcpy(pDataBlock, pTableDataBlock->pData, sizeof(SSubmitBlk));
S
Shengliang Guan 已提交
617
  pDataBlock = (char*)pDataBlock + sizeof(SSubmitBlk);
H
TD-166  
hzcheng 已提交
618

H
hjxilinx 已提交
619
  int32_t flen = 0;  // original total length of row
620 621 622 623 624 625

  // schema needs to be included into the submit data block
  if (includeSchema) {
    int32_t numOfCols = tscGetNumOfColumns(pTableDataBlock->pTableMeta);
    for(int32_t j = 0; j < numOfCols; ++j) {
      STColumn* pCol = (STColumn*) pDataBlock;
H
Hongze Cheng 已提交
626
      pCol->colId = htons(pSchema[j].colId);
627
      pCol->type  = pSchema[j].type;
H
Hongze Cheng 已提交
628
      pCol->bytes = htons(pSchema[j].bytes);
629 630
      pCol->offset = 0;

S
Shengliang Guan 已提交
631
      pDataBlock = (char*)pDataBlock + sizeof(STColumn);
632 633 634 635 636 637 638 639 640 641 642
      flen += TYPE_BYTES[pSchema[j].type];
    }

    int32_t schemaSize = sizeof(STColumn) * numOfCols;
    pBlock->schemaLen = schemaSize;
  } else {
    for (int32_t j = 0; j < tinfo.numOfColumns; ++j) {
      flen += TYPE_BYTES[pSchema[j].type];
    }

    pBlock->schemaLen = 0;
643
  }
H
TD-166  
hzcheng 已提交
644

645
  char* p = pTableDataBlock->pData + sizeof(SSubmitBlk);
646
  pBlock->dataLen = 0;
H
hjxilinx 已提交
647 648 649
  int32_t numOfRows = htons(pBlock->numOfRows);
  
  for (int32_t i = 0; i < numOfRows; ++i) {
650
    SDataRow trow = (SDataRow) pDataBlock;
S
Shengliang Guan 已提交
651
    dataRowSetLen(trow, (uint16_t)(TD_DATA_ROW_HEAD_SIZE + flen));
H
TD-90  
Hongze Cheng 已提交
652
    dataRowSetVersion(trow, pTableMeta->sversion);
H
TD-166  
hzcheng 已提交
653 654 655

    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
      toffset += TYPE_BYTES[pSchema[j].type];
      p += pSchema[j].bytes;
    }

S
Shengliang Guan 已提交
661
    pDataBlock = (char*)pDataBlock + dataRowLen(trow);
662
    pBlock->dataLen += dataRowLen(trow);
663
  }
H
TD-166  
hzcheng 已提交
664

665 666 667 668
  int32_t len = pBlock->dataLen + pBlock->schemaLen;
  pBlock->dataLen = htonl(pBlock->dataLen);
  pBlock->schemaLen = htonl(pBlock->schemaLen);

H
TD-100  
hzcheng 已提交
669
  return len;
670 671
}

672 673 674 675 676 677 678 679 680 681 682 683
static int32_t getRowExpandSize(STableMeta* pTableMeta) {
  int32_t result = TD_DATA_ROW_HEAD_SIZE;
  int32_t columns = tscGetNumOfColumns(pTableMeta);
  SSchema* pSchema = tscGetTableSchema(pTableMeta);
  for(int32_t i = 0; i < columns; i++) {
    if (IS_VAR_DATA_TYPE((pSchema + i)->type)) {
      result += TYPE_BYTES[TSDB_DATA_TYPE_BINARY];
    }
  }
  return result;
}

684
int32_t tscMergeTableDataBlocks(SSqlObj* pSql, SArray* pTableDataBlockList) {
S
slguan 已提交
685 686
  SSqlCmd* pCmd = &pSql->cmd;

687
  // the maximum expanded size in byte when a row-wise data is converted to SDataRow format
688 689
  STableDataBlocks* pOneTableBlock = taosArrayGetP(pTableDataBlockList, 0);
  int32_t expandSize = getRowExpandSize(pOneTableBlock->pTableMeta);
H
Haojun Liao 已提交
690

H
Haojun Liao 已提交
691
  void* pVnodeDataBlockHashList = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, false);
692
  SArray* pVnodeDataBlockList = taosArrayInit(8, POINTER_BYTES);
S
slguan 已提交
693

694 695
  size_t total = taosArrayGetSize(pTableDataBlockList);
  for (int32_t i = 0; i < total; ++i) {
696
    pOneTableBlock = taosArrayGetP(pTableDataBlockList, i);
H
hjxilinx 已提交
697
    STableDataBlocks* dataBuf = NULL;
H
hjxilinx 已提交
698 699 700
    
    int32_t ret =
        tscGetDataBlockFromList(pVnodeDataBlockHashList, pVnodeDataBlockList, pOneTableBlock->vgId, TSDB_PAYLOAD_SIZE,
H
hjxilinx 已提交
701
                                tsInsertHeadSize, 0, pOneTableBlock->tableId, pOneTableBlock->pTableMeta, &dataBuf);
H
hjxilinx 已提交
702
    if (ret != TSDB_CODE_SUCCESS) {
703
      tscError("%p failed to prepare the data block buffer for merging table data, code:%d", pSql, ret);
H
hjxilinx 已提交
704
      taosHashCleanup(pVnodeDataBlockHashList);
705
      tscDestroyBlockArrayList(pVnodeDataBlockList);
H
hjxilinx 已提交
706 707
      return ret;
    }
S
slguan 已提交
708

H
Haojun Liao 已提交
709
    SSubmitBlk* pBlocks = (SSubmitBlk*) pOneTableBlock->pData;
H
Hongze Cheng 已提交
710
    int64_t destSize = dataBuf->size + pOneTableBlock->size + pBlocks->numOfRows * expandSize + sizeof(STColumn) * tscGetNumOfColumns(pOneTableBlock->pTableMeta);
H
Haojun Liao 已提交
711

S
slguan 已提交
712 713
    if (dataBuf->nAllocSize < destSize) {
      while (dataBuf->nAllocSize < destSize) {
S
Shengliang Guan 已提交
714
        dataBuf->nAllocSize = (uint32_t)(dataBuf->nAllocSize * 1.5);
S
slguan 已提交
715 716 717 718 719 720
      }

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

H
hjxilinx 已提交
724
        taosHashCleanup(pVnodeDataBlockHashList);
S
slguan 已提交
725
        tscDestroyBlockArrayList(pVnodeDataBlockList);
S
Shengliang Guan 已提交
726
        taosTFree(dataBuf->pData);
S
slguan 已提交
727

728
        return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
729 730 731
      }
    }

H
hjxilinx 已提交
732
    tscSortRemoveDataBlockDupRows(pOneTableBlock);
733
    char* ekey = (char*)pBlocks->data + pOneTableBlock->rowSize*(pBlocks->numOfRows-1);
L
lihui 已提交
734
    
735
    tscDebug("%p tableId:%s, sid:%d rows:%d sversion:%d skey:%" PRId64 ", ekey:%" PRId64, pSql, pOneTableBlock->tableId,
736
        pBlocks->tid, pBlocks->numOfRows, pBlocks->sversion, GET_INT64_VAL(pBlocks->data), GET_INT64_VAL(ekey));
S
slguan 已提交
737

H
Hongze Cheng 已提交
738
    int32_t len = pBlocks->numOfRows * (pOneTableBlock->rowSize + expandSize) + sizeof(STColumn) * tscGetNumOfColumns(pOneTableBlock->pTableMeta);
H
Haojun Liao 已提交
739

740
    pBlocks->tid = htonl(pBlocks->tid);
S
slguan 已提交
741 742 743
    pBlocks->uid = htobe64(pBlocks->uid);
    pBlocks->sversion = htonl(pBlocks->sversion);
    pBlocks->numOfRows = htons(pBlocks->numOfRows);
744
    pBlocks->schemaLen = 0;
H
Haojun Liao 已提交
745

746
    // erase the empty space reserved for binary data
747
    int32_t finalLen = trimDataBlock(dataBuf->pData + dataBuf->size, pOneTableBlock, pCmd->submitSchema);
H
Haojun Liao 已提交
748 749 750 751 752 753
    assert(finalLen <= len);

    dataBuf->size += (finalLen + sizeof(SSubmitBlk));
    assert(dataBuf->size <= dataBuf->nAllocSize);

    // the length does not include the SSubmitBlk structure
754
    pBlocks->dataLen = htonl(finalLen);
H
Haojun Liao 已提交
755

S
slguan 已提交
756
    dataBuf->numOfTables += 1;
S
slguan 已提交
757 758 759 760 761 762 763
  }

  tscDestroyBlockArrayList(pTableDataBlockList);

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

764
//  tscFreeUnusedDataBlocks(pCmd->pDataBlocks);
H
hjxilinx 已提交
765
  taosHashCleanup(pVnodeDataBlockHashList);
S
slguan 已提交
766 767

  return TSDB_CODE_SUCCESS;
S
slguan 已提交
768 769
}

H
Haojun Liao 已提交
770
// TODO: all subqueries should be freed correctly before close this connection.
H
hzcheng 已提交
771
void tscCloseTscObj(STscObj* pObj) {
H
hjxilinx 已提交
772
  assert(pObj != NULL);
H
Haojun Liao 已提交
773

H
hzcheng 已提交
774 775
  pObj->signature = NULL;
  taosTmrStopA(&(pObj->pTimer));
H
Haojun Liao 已提交
776

H
Haojun Liao 已提交
777
  void* p = pObj->pDnodeConn;
778 779
  if (pObj->pDnodeConn != NULL) {
    rpcClose(pObj->pDnodeConn);
H
Haojun Liao 已提交
780
    pObj->pDnodeConn = NULL;
781
  }
H
Haojun Liao 已提交
782 783 784

  pthread_mutex_destroy(&pObj->mutex);

H
Haojun Liao 已提交
785
  tscDebug("%p DB connection is closed, dnodeConn:%p", pObj, p);
S
Shengliang Guan 已提交
786
  taosTFree(pObj);
H
hzcheng 已提交
787 788
}

H
hjxilinx 已提交
789
bool tscIsInsertData(char* sqlstr) {
790 791 792
  int32_t index = 0;

  do {
H
Haojun Liao 已提交
793
    SStrToken t0 = tStrGetToken(sqlstr, &index, false, 0, NULL);
794 795 796 797
    if (t0.type != TK_LP) {
      return t0.type == TK_INSERT || t0.type == TK_IMPORT;
    }
  } while (1);
H
hzcheng 已提交
798 799
}

S
slguan 已提交
800
int tscAllocPayload(SSqlCmd* pCmd, int size) {
H
hzcheng 已提交
801 802 803 804 805
  assert(size > 0);

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

806
    pCmd->payload = (char*)calloc(1, size);
807
    if (pCmd->payload == NULL) return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hzcheng 已提交
808 809
    pCmd->allocSize = size;
  } else {
S
Shengliang Guan 已提交
810
    if (pCmd->allocSize < (uint32_t)size) {
811
      char* b = realloc(pCmd->payload, size);
812
      if (b == NULL) return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
813
      pCmd->payload = b;
H
hzcheng 已提交
814 815
      pCmd->allocSize = size;
    }
816
    
H
hjxilinx 已提交
817
    memset(pCmd->payload, 0, pCmd->allocSize);
H
hzcheng 已提交
818 819
  }

S
Shengliang Guan 已提交
820
  assert(pCmd->allocSize >= (uint32_t)size);
H
hzcheng 已提交
821 822 823
  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
824 825
TAOS_FIELD tscCreateField(int8_t type, const char* name, int16_t bytes) {
  TAOS_FIELD f = { .type = type, .bytes = bytes, };
B
Bomin Zhang 已提交
826
  tstrncpy(f.name, name, sizeof(f.name));
H
hjxilinx 已提交
827
  return f;
H
hzcheng 已提交
828 829
}

H
hjxilinx 已提交
830 831 832 833
SFieldSupInfo* tscFieldInfoAppend(SFieldInfo* pFieldInfo, TAOS_FIELD* pField) {
  assert(pFieldInfo != NULL);
  taosArrayPush(pFieldInfo->pFields, pField);
  pFieldInfo->numOfOutput++;
H
hjxilinx 已提交
834
  
H
hjxilinx 已提交
835 836 837 838 839 840 841
  struct SFieldSupInfo info = {
    .pSqlExpr = NULL,
    .pArithExprInfo = NULL,
    .visible = true,
  };
  
  return taosArrayPush(pFieldInfo->pSupportInfo, &info);
H
hzcheng 已提交
842 843
}

H
hjxilinx 已提交
844
SFieldSupInfo* tscFieldInfoGetSupp(SFieldInfo* pFieldInfo, int32_t index) {
H
Haojun Liao 已提交
845
  return TARRAY_GET_ELEM(pFieldInfo->pSupportInfo, index);
H
hjxilinx 已提交
846 847
}

H
hjxilinx 已提交
848 849 850 851 852 853 854 855 856 857 858
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 已提交
859
}
H
hzcheng 已提交
860

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

875
void tscFieldInfoUpdateOffsetForInterResult(SQueryInfo* pQueryInfo) {
H
hjxilinx 已提交
876
  if (tscSqlExprNumOfExprs(pQueryInfo) == 0) {
H
hzcheng 已提交
877 878
    return;
  }
H
hjxilinx 已提交
879
  
H
hjxilinx 已提交
880
  SSqlExpr* pExpr = taosArrayGetP(pQueryInfo->exprList, 0);
H
hjxilinx 已提交
881
  pExpr->offset = 0;
H
hjxilinx 已提交
882
  
H
hjxilinx 已提交
883 884
  size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
  for (int32_t i = 1; i < numOfExprs; ++i) {
H
hjxilinx 已提交
885 886
    SSqlExpr* prev = taosArrayGetP(pQueryInfo->exprList, i - 1);
    SSqlExpr* p = taosArrayGetP(pQueryInfo->exprList, i);
H
hjxilinx 已提交
887 888
    
    p->offset = prev->offset + prev->resBytes;
H
hzcheng 已提交
889 890 891
  }
}

H
hjxilinx 已提交
892
void tscFieldInfoCopy(SFieldInfo* dst, const SFieldInfo* src) {
H
hjxilinx 已提交
893
  dst->numOfOutput = src->numOfOutput;
H
hzcheng 已提交
894

H
hjxilinx 已提交
895 896 897 898 899 900 901 902 903 904 905
  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 已提交
906 907
}

H
hjxilinx 已提交
908
TAOS_FIELD* tscFieldInfoGetField(SFieldInfo* pFieldInfo, int32_t index) {
909
  assert(index < pFieldInfo->numOfOutput);
H
Haojun Liao 已提交
910
  return TARRAY_GET_ELEM(pFieldInfo->pFields, index);
911 912
}

913
int16_t tscFieldInfoGetOffset(SQueryInfo* pQueryInfo, int32_t index) {
H
hjxilinx 已提交
914
  SFieldSupInfo* pInfo = tscFieldInfoGetSupp(&pQueryInfo->fieldsInfo, index);
915
  assert(pInfo != NULL && pInfo->pSqlExpr != NULL);
H
hzcheng 已提交
916

H
hjxilinx 已提交
917
  return pInfo->pSqlExpr->offset;
H
hzcheng 已提交
918 919
}

H
hjxilinx 已提交
920
int32_t tscFieldInfoCompare(const SFieldInfo* pFieldInfo1, const SFieldInfo* pFieldInfo2) {
921
  assert(pFieldInfo1 != NULL && pFieldInfo2 != NULL);
922

H
hjxilinx 已提交
923 924
  if (pFieldInfo1->numOfOutput != pFieldInfo2->numOfOutput) {
    return pFieldInfo1->numOfOutput - pFieldInfo2->numOfOutput;
925 926
  }

H
hjxilinx 已提交
927 928 929
  for (int32_t i = 0; i < pFieldInfo1->numOfOutput; ++i) {
    TAOS_FIELD* pField1 = tscFieldInfoGetField((SFieldInfo*) pFieldInfo1, i);
    TAOS_FIELD* pField2 = tscFieldInfoGetField((SFieldInfo*) pFieldInfo2, i);
930

H
hjxilinx 已提交
931 932
    if (pField1->type != pField2->type ||
        pField1->bytes != pField2->bytes ||
933 934 935 936 937 938 939 940
        strcasecmp(pField1->name, pField2->name) != 0) {
      return 1;
    }
  }

  return 0;
}

H
hjxilinx 已提交
941 942 943
int32_t tscGetResRowLength(SArray* pExprList) {
  size_t num = taosArrayGetSize(pExprList);
  if (num == 0) {
H
hzcheng 已提交
944 945
    return 0;
  }
H
hjxilinx 已提交
946 947
  
  int32_t size = 0;
H
hjxilinx 已提交
948 949 950
  for(int32_t i = 0; i < num; ++i) {
    SSqlExpr* pExpr = taosArrayGetP(pExprList, i);
    size += pExpr->resBytes;
H
hjxilinx 已提交
951 952 953
  }
  
  return size;
H
hzcheng 已提交
954 955
}

H
hjxilinx 已提交
956
void tscFieldInfoClear(SFieldInfo* pFieldInfo) {
S
slguan 已提交
957
  if (pFieldInfo == NULL) {
H
hzcheng 已提交
958 959 960
    return;
  }

H
hjxilinx 已提交
961
  taosArrayDestroy(pFieldInfo->pFields);
H
hjxilinx 已提交
962
  
H
hjxilinx 已提交
963 964 965 966
  for(int32_t i = 0; i < pFieldInfo->numOfOutput; ++i) {
    SFieldSupInfo* pInfo = taosArrayGet(pFieldInfo->pSupportInfo, i);
    
    if (pInfo->pArithExprInfo != NULL) {
967
      tExprTreeDestroy(&pInfo->pArithExprInfo->pExpr, NULL);
S
Shengliang Guan 已提交
968
      taosTFree(pInfo->pArithExprInfo);
H
hjxilinx 已提交
969 970 971
    }
  }
  
H
hjxilinx 已提交
972
  taosArrayDestroy(pFieldInfo->pSupportInfo);
S
slguan 已提交
973
  memset(pFieldInfo, 0, sizeof(SFieldInfo));
H
hzcheng 已提交
974 975
}

H
hjxilinx 已提交
976
static SSqlExpr* doBuildSqlExpr(SQueryInfo* pQueryInfo, int16_t functionId, SColumnIndex* pColIndex, int16_t type,
H
Haojun Liao 已提交
977
    int16_t size, int16_t interSize, int32_t colType) {
H
hjxilinx 已提交
978
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, pColIndex->tableIndex);
H
hjxilinx 已提交
979
  
H
hjxilinx 已提交
980
  SSqlExpr* pExpr = calloc(1, sizeof(SSqlExpr));
981 982 983 984
  if (pExpr == NULL) {
    return NULL;
  }

S
slguan 已提交
985
  pExpr->functionId = functionId;
986

987
  // set the correct columnIndex index
S
slguan 已提交
988 989
  if (pColIndex->columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
    pExpr->colInfo.colId = TSDB_TBNAME_COLUMN_INDEX;
990 991
  } else if (pColIndex->columnIndex <= TSDB_UD_COLUMN_INDEX) {
    pExpr->colInfo.colId = pColIndex->columnIndex;
S
slguan 已提交
992
  } else {
H
Haojun Liao 已提交
993
    if (TSDB_COL_IS_TAG(colType)) {
994 995
      SSchema* pSchema = tscGetTableTagSchema(pTableMetaInfo->pTableMeta);
      pExpr->colInfo.colId = pSchema[pColIndex->columnIndex].colId;
B
Bomin Zhang 已提交
996
      tstrncpy(pExpr->colInfo.name, pSchema[pColIndex->columnIndex].name, sizeof(pExpr->colInfo.name));
H
Haojun Liao 已提交
997 998
    } else if (pTableMetaInfo->pTableMeta != NULL) {
      // in handling select database/version/server_status(), the pTableMeta is NULL
999 1000
      SSchema* pSchema = tscGetTableColumnSchema(pTableMetaInfo->pTableMeta, pColIndex->columnIndex);
      pExpr->colInfo.colId = pSchema->colId;
B
Bomin Zhang 已提交
1001
      tstrncpy(pExpr->colInfo.name, pSchema->name, sizeof(pExpr->colInfo.name));
S
slguan 已提交
1002
    }
H
hzcheng 已提交
1003
  }
H
hjxilinx 已提交
1004
  
H
Haojun Liao 已提交
1005
  pExpr->colInfo.flag     = colType;
1006
  pExpr->colInfo.colIndex = pColIndex->columnIndex;
H
Haojun Liao 已提交
1007

H
hjxilinx 已提交
1008 1009
  pExpr->resType       = type;
  pExpr->resBytes      = size;
H
Haojun Liao 已提交
1010 1011 1012
  pExpr->interBytes    = interSize;
  
  if (pTableMetaInfo->pTableMeta) {
1013
    pExpr->uid = pTableMetaInfo->pTableMeta->id.uid;
H
Haojun Liao 已提交
1014 1015
  }
  
H
hjxilinx 已提交
1016 1017 1018 1019
  return pExpr;
}

SSqlExpr* tscSqlExprInsert(SQueryInfo* pQueryInfo, int32_t index, int16_t functionId, SColumnIndex* pColIndex, int16_t type,
1020
                           int16_t size, int16_t interSize, bool isTagCol) {
S
Shengliang Guan 已提交
1021
  int32_t num = (int32_t)taosArrayGetSize(pQueryInfo->exprList);
H
hjxilinx 已提交
1022
  if (index == num) {
1023
    return tscSqlExprAppend(pQueryInfo, functionId, pColIndex, type, size, interSize, isTagCol);
H
hjxilinx 已提交
1024 1025
  }
  
1026
  SSqlExpr* pExpr = doBuildSqlExpr(pQueryInfo, functionId, pColIndex, type, size, interSize, isTagCol);
H
hjxilinx 已提交
1027
  taosArrayInsert(pQueryInfo->exprList, index, &pExpr);
H
hjxilinx 已提交
1028 1029 1030 1031
  return pExpr;
}

SSqlExpr* tscSqlExprAppend(SQueryInfo* pQueryInfo, int16_t functionId, SColumnIndex* pColIndex, int16_t type,
1032 1033
    int16_t size, int16_t interSize, bool isTagCol) {
  SSqlExpr* pExpr = doBuildSqlExpr(pQueryInfo, functionId, pColIndex, type, size, interSize, isTagCol);
H
hjxilinx 已提交
1034
  taosArrayPush(pQueryInfo->exprList, &pExpr);
H
hzcheng 已提交
1035 1036 1037
  return pExpr;
}

1038 1039
SSqlExpr* tscSqlExprUpdate(SQueryInfo* pQueryInfo, int32_t index, int16_t functionId, int16_t srcColumnIndex,
                           int16_t type, int16_t size) {
H
hjxilinx 已提交
1040
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hjxilinx 已提交
1041 1042
  SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, index);
  if (pExpr == NULL) {
H
hzcheng 已提交
1043 1044 1045
    return NULL;
  }

S
slguan 已提交
1046
  pExpr->functionId = functionId;
H
hzcheng 已提交
1047

1048
  pExpr->colInfo.colIndex = srcColumnIndex;
H
hjxilinx 已提交
1049
  pExpr->colInfo.colId = tscGetTableColumnSchema(pTableMetaInfo->pTableMeta, srcColumnIndex)->colId;
H
hzcheng 已提交
1050 1051 1052 1053 1054 1055 1056

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

  return pExpr;
}

1057
size_t tscSqlExprNumOfExprs(SQueryInfo* pQueryInfo) {
H
hjxilinx 已提交
1058
  return taosArrayGetSize(pQueryInfo->exprList);
H
hjxilinx 已提交
1059 1060
}

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

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

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

1074
SSqlExpr* tscSqlExprGet(SQueryInfo* pQueryInfo, int32_t index) {
H
hjxilinx 已提交
1075
  return taosArrayGetP(pQueryInfo->exprList, index);
H
hzcheng 已提交
1076 1077
}

H
hjxilinx 已提交
1078
void* sqlExprDestroy(SSqlExpr* pExpr) {
H
hjxilinx 已提交
1079 1080 1081 1082 1083 1084 1085 1086
  if (pExpr == NULL) {
    return NULL;
  }
  
  for(int32_t i = 0; i < tListLen(pExpr->param); ++i) {
    tVariantDestroy(&pExpr->param[i]);
  }
  
S
Shengliang Guan 已提交
1087
  taosTFree(pExpr);
H
hjxilinx 已提交
1088
  
H
hjxilinx 已提交
1089
  return NULL;
H
hzcheng 已提交
1090 1091
}

H
hjxilinx 已提交
1092 1093 1094
/*
 * NOTE: Does not release SSqlExprInfo here.
 */
H
hjxilinx 已提交
1095 1096
void tscSqlExprInfoDestroy(SArray* pExprInfo) {
  size_t size = taosArrayGetSize(pExprInfo);
H
hjxilinx 已提交
1097
  
H
hjxilinx 已提交
1098 1099 1100
  for(int32_t i = 0; i < size; ++i) {
    SSqlExpr* pExpr = taosArrayGetP(pExprInfo, i);
    sqlExprDestroy(pExpr);
H
hjxilinx 已提交
1101 1102
  }
  
H
hjxilinx 已提交
1103
  taosArrayDestroy(pExprInfo);
H
hjxilinx 已提交
1104 1105
}

H
Haojun Liao 已提交
1106
int32_t tscSqlExprCopy(SArray* dst, const SArray* src, uint64_t uid, bool deepcopy) {
H
hjxilinx 已提交
1107
  assert(src != NULL && dst != NULL);
H
hjxilinx 已提交
1108
  
H
hjxilinx 已提交
1109 1110 1111 1112 1113
  size_t size = taosArrayGetSize(src);
  for (int32_t i = 0; i < size; ++i) {
    SSqlExpr* pExpr = taosArrayGetP(src, i);
    
    if (pExpr->uid == uid) {
H
hjxilinx 已提交
1114 1115
      
      if (deepcopy) {
H
hjxilinx 已提交
1116
        SSqlExpr* p1 = calloc(1, sizeof(SSqlExpr));
1117
        if (p1 == NULL) {
H
Haojun Liao 已提交
1118
          return -1;
1119 1120
        }

H
hjxilinx 已提交
1121 1122 1123 1124 1125 1126
        *p1 = *pExpr;
        for (int32_t j = 0; j < pExpr->numOfParams; ++j) {
          tVariantAssign(&p1->param[j], &pExpr->param[j]);
        }
        
        taosArrayPush(dst, &p1);
H
hjxilinx 已提交
1127
      } else {
H
hjxilinx 已提交
1128
        taosArrayPush(dst, &pExpr);
H
hjxilinx 已提交
1129
      }
S
slguan 已提交
1130 1131
    }
  }
H
Haojun Liao 已提交
1132 1133

  return 0;
H
hzcheng 已提交
1134 1135
}

1136
SColumn* tscColumnListInsert(SArray* pColumnList, SColumnIndex* pColIndex) {
1137
  // ignore the tbname columnIndex to be inserted into source list
S
slguan 已提交
1138
  if (pColIndex->columnIndex < 0) {
H
hzcheng 已提交
1139 1140
    return NULL;
  }
1141 1142
  
  size_t numOfCols = taosArrayGetSize(pColumnList);
S
slguan 已提交
1143 1144
  int16_t col = pColIndex->columnIndex;

H
hzcheng 已提交
1145
  int32_t i = 0;
1146 1147 1148
  while (i < numOfCols) {
    SColumn* pCol = taosArrayGetP(pColumnList, i);
    if (pCol->colIndex.columnIndex < col) {
S
slguan 已提交
1149
      i++;
1150
    } else if (pCol->colIndex.tableIndex < pColIndex->tableIndex) {
S
slguan 已提交
1151 1152 1153 1154
      i++;
    } else {
      break;
    }
H
hzcheng 已提交
1155 1156
  }

1157 1158
  if (i >= numOfCols || numOfCols == 0) {
    SColumn* b = calloc(1, sizeof(SColumn));
1159 1160 1161 1162
    if (b == NULL) {
      return NULL;
    }

1163 1164 1165 1166 1167 1168 1169
    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));
1170 1171 1172 1173
      if (b == NULL) {
        return NULL;
      }

1174 1175 1176
      b->colIndex = *pColIndex;
      taosArrayInsert(pColumnList, i, &b);
    }
H
hzcheng 已提交
1177 1178
  }

1179
  return taosArrayGetP(pColumnList, i);
H
hzcheng 已提交
1180 1181
}

1182 1183 1184
static void destroyFilterInfo(SColumnFilterInfo* pFilterInfo, int32_t numOfFilters) {
  for(int32_t i = 0; i < numOfFilters; ++i) {
    if (pFilterInfo[i].filterstr) {
S
Shengliang Guan 已提交
1185
      taosTFree(pFilterInfo[i].pz);
S
slguan 已提交
1186 1187
    }
  }
1188
  
S
Shengliang Guan 已提交
1189
  taosTFree(pFilterInfo);
S
slguan 已提交
1190 1191
}

1192 1193 1194 1195
SColumn* tscColumnClone(const SColumn* src) {
  assert(src != NULL);
  
  SColumn* dst = calloc(1, sizeof(SColumn));
1196 1197 1198 1199
  if (dst == NULL) {
    return NULL;
  }

1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
  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 已提交
1212
void tscColumnListCopy(SArray* dst, const SArray* src, int16_t tableIndex) {
H
hjxilinx 已提交
1213
  assert(src != NULL && dst != NULL);
1214 1215 1216 1217
  
  size_t num = taosArrayGetSize(src);
  for (int32_t i = 0; i < num; ++i) {
    SColumn* pCol = taosArrayGetP(src, i);
H
hzcheng 已提交
1218

1219 1220 1221
    if (pCol->colIndex.tableIndex == tableIndex || tableIndex < 0) {
      SColumn* p = tscColumnClone(pCol);
      taosArrayPush(dst, &p);
S
slguan 已提交
1222 1223
    }
  }
H
hzcheng 已提交
1224 1225
}

1226 1227
void tscColumnListDestroy(SArray* pColumnList) {
  if (pColumnList == NULL) {
S
slguan 已提交
1228 1229 1230
    return;
  }

1231
  size_t num = taosArrayGetSize(pColumnList);
1232
  for (int32_t i = 0; i < num; ++i) {
1233
    SColumn* pCol = taosArrayGetP(pColumnList, i);
1234
    tscColumnDestroy(pCol);
S
slguan 已提交
1235 1236
  }

1237
  taosArrayDestroy(pColumnList);
1238
}
H
hzcheng 已提交
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253

/*
 * 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'
 *
 */
H
Haojun Liao 已提交
1254
static int32_t validateQuoteToken(SStrToken* pToken) {
H
Haojun Liao 已提交
1255
  strdequote(pToken->z);
S
Shengliang Guan 已提交
1256
  pToken->n = (uint32_t)strtrim(pToken->z);
H
hzcheng 已提交
1257 1258

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

H
huili 已提交
1260 1261
  if (pToken->type == TK_STRING) {
    return tscValidateName(pToken);
S
slguan 已提交
1262
  }
H
hzcheng 已提交
1263

H
huili 已提交
1264
  if (k != pToken->n || pToken->type != TK_ID) {
1265
    return TSDB_CODE_TSC_INVALID_SQL;
H
huili 已提交
1266
  }
H
hzcheng 已提交
1267 1268 1269
  return TSDB_CODE_SUCCESS;
}

B
Bomin Zhang 已提交
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
void tscDequoteAndTrimToken(SStrToken* pToken) {
  assert(pToken->type == TK_STRING);

  uint32_t first = 0, last = pToken->n;

  // trim leading spaces
  while (first < last) {
    char c = pToken->z[first];
    if (c != ' ' && c != '\t') {
      break;
    }
    first++;
  }

  // trim ending spaces
  while (first < last) {
    char c = pToken->z[last - 1];
    if (c != ' ' && c != '\t') {
      break;
    }
    last--;
  }

  // there are still at least two characters
  if (first < last - 1) {
    char c = pToken->z[first];
    // dequote
    if ((c == '\'' || c == '"') && c == pToken->z[last - 1]) {
      first++;
      last--;
    }
  }

  // left shift the string and pad spaces
  for (uint32_t i = 0; i + first < last; i++) {
    pToken->z[i] = pToken->z[first + i];
  }
  for (uint32_t i = last - first; i < pToken->n; i++) {
    pToken->z[i] = ' ';
  }

  // adjust token length
  pToken->n = last - first;
}

H
Haojun Liao 已提交
1315
int32_t tscValidateName(SStrToken* pToken) {
H
hzcheng 已提交
1316
  if (pToken->type != TK_STRING && pToken->type != TK_ID) {
1317
    return TSDB_CODE_TSC_INVALID_SQL;
H
hzcheng 已提交
1318 1319
  }

S
slguan 已提交
1320
  char* sep = strnchr(pToken->z, TS_PATH_DELIMITER[0], pToken->n, true);
H
hzcheng 已提交
1321 1322
  if (sep == NULL) {  // single part
    if (pToken->type == TK_STRING) {
H
Haojun Liao 已提交
1323
      strdequote(pToken->z);
S
Shengliang Guan 已提交
1324
      pToken->n = (uint32_t)strtrim(pToken->z);
S
slguan 已提交
1325 1326 1327 1328

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

      // single token, validate it
1329
      if (len == pToken->n) {
H
huili 已提交
1330
        return validateQuoteToken(pToken);
S
slguan 已提交
1331
      } else {
1332 1333
        sep = strnchr(pToken->z, TS_PATH_DELIMITER[0], pToken->n, true);
        if (sep == NULL) {
1334
          return TSDB_CODE_TSC_INVALID_SQL;
1335
        }
S
slguan 已提交
1336

H
huili 已提交
1337
        return tscValidateName(pToken);
1338
      }
H
hzcheng 已提交
1339 1340
    } else {
      if (isNumber(pToken)) {
1341
        return TSDB_CODE_TSC_INVALID_SQL;
H
hzcheng 已提交
1342 1343 1344 1345 1346 1347
      }
    }
  } else {  // two part
    int32_t oldLen = pToken->n;
    char*   pStr = pToken->z;

H
huili 已提交
1348
    if (pToken->type == TK_SPACE) {
S
Shengliang Guan 已提交
1349
      pToken->n = (uint32_t)strtrim(pToken->z);
H
huili 已提交
1350 1351
    }

H
hzcheng 已提交
1352 1353
    pToken->n = tSQLGetToken(pToken->z, &pToken->type);
    if (pToken->z[pToken->n] != TS_PATH_DELIMITER[0]) {
1354
      return TSDB_CODE_TSC_INVALID_SQL;
H
hzcheng 已提交
1355 1356 1357
    }

    if (pToken->type != TK_STRING && pToken->type != TK_ID) {
1358
      return TSDB_CODE_TSC_INVALID_SQL;
H
hzcheng 已提交
1359 1360 1361
    }

    if (pToken->type == TK_STRING && validateQuoteToken(pToken) != TSDB_CODE_SUCCESS) {
1362
      return TSDB_CODE_TSC_INVALID_SQL;
H
hzcheng 已提交
1363 1364 1365 1366 1367
    }

    int32_t firstPartLen = pToken->n;

    pToken->z = sep + 1;
S
Shengliang Guan 已提交
1368
    pToken->n = (uint32_t)(oldLen - (sep - pStr) - 1);
H
hzcheng 已提交
1369 1370
    int32_t len = tSQLGetToken(pToken->z, &pToken->type);
    if (len != pToken->n || (pToken->type != TK_STRING && pToken->type != TK_ID)) {
1371
      return TSDB_CODE_TSC_INVALID_SQL;
H
hzcheng 已提交
1372 1373 1374
    }

    if (pToken->type == TK_STRING && validateQuoteToken(pToken) != TSDB_CODE_SUCCESS) {
1375
      return TSDB_CODE_TSC_INVALID_SQL;
H
hzcheng 已提交
1376 1377 1378 1379
    }

    // re-build the whole name string
    if (pStr[firstPartLen] == TS_PATH_DELIMITER[0]) {
H
hjxilinx 已提交
1380
      // first part do not have quote do nothing
H
hzcheng 已提交
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
    } 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;
}

1402
bool tscValidateColumnId(STableMetaInfo* pTableMetaInfo, int32_t colId, int32_t numOfParams) {
H
hjxilinx 已提交
1403
  if (pTableMetaInfo->pTableMeta == NULL) {
H
hzcheng 已提交
1404 1405 1406
    return false;
  }

1407
  if (colId == TSDB_TBNAME_COLUMN_INDEX || (colId <= TSDB_UD_COLUMN_INDEX && numOfParams == 2)) {
H
hzcheng 已提交
1408 1409 1410
    return true;
  }

H
hjxilinx 已提交
1411
  SSchema* pSchema = tscGetTableSchema(pTableMetaInfo->pTableMeta);
H
hjxilinx 已提交
1412
  STableComInfo tinfo = tscGetTableInfo(pTableMetaInfo->pTableMeta);
H
hjxilinx 已提交
1413 1414
  
  int32_t  numOfTotal = tinfo.numOfTags + tinfo.numOfColumns;
H
hzcheng 已提交
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424

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

  return false;
}

H
Haojun Liao 已提交
1425
int32_t tscTagCondCopy(STagCond* dest, const STagCond* src) {
S
slguan 已提交
1426
  memset(dest, 0, sizeof(STagCond));
H
hjxilinx 已提交
1427

H
hjxilinx 已提交
1428 1429
  if (src->tbnameCond.cond != NULL) {
    dest->tbnameCond.cond = strdup(src->tbnameCond.cond);
H
Haojun Liao 已提交
1430 1431 1432
    if (dest->tbnameCond.cond == NULL) {
      return -1;
    }
H
hjxilinx 已提交
1433
  }
S
slguan 已提交
1434 1435 1436 1437

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

  memcpy(&dest->joinInfo, &src->joinInfo, sizeof(SJoinInfo));
1438 1439 1440
  dest->relType = src->relType;
  
  if (src->pCond == NULL) {
H
Haojun Liao 已提交
1441
    return 0;
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
  }
  
  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);
1457
      if (c.cond == NULL) {
H
Haojun Liao 已提交
1458
        return -1;
1459 1460
      }

1461
      memcpy(c.cond, pCond->cond, c.len);
H
hjxilinx 已提交
1462
    }
1463 1464
    
    taosArrayPush(dest->pCond, &c);
H
hzcheng 已提交
1465
  }
H
Haojun Liao 已提交
1466 1467

  return 0;
H
hzcheng 已提交
1468 1469
}

1470 1471 1472 1473 1474 1475 1476
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);
S
Shengliang Guan 已提交
1477
      taosTFree(p->cond);
1478 1479 1480
    }
  
    taosArrayDestroy(pTagCond->pCond);
H
hzcheng 已提交
1481 1482
  }

1483
  memset(pTagCond, 0, sizeof(STagCond));
H
hzcheng 已提交
1484 1485
}

1486
void tscGetSrcColumnInfo(SSrcColumnInfo* pColInfo, SQueryInfo* pQueryInfo) {
H
hjxilinx 已提交
1487
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hjxilinx 已提交
1488
  SSchema*        pSchema = tscGetTableSchema(pTableMetaInfo->pTableMeta);
H
hjxilinx 已提交
1489 1490 1491
  
  size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
  for (int32_t i = 0; i < numOfExprs; ++i) {
1492
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
1493
    pColInfo[i].functionId = pExpr->functionId;
H
hzcheng 已提交
1494

S
slguan 已提交
1495
    if (TSDB_COL_IS_TAG(pExpr->colInfo.flag)) {
H
hjxilinx 已提交
1496
      SSchema* pTagSchema = tscGetTableTagSchema(pTableMetaInfo->pTableMeta);
1497 1498 1499
      
      int16_t index = pExpr->colInfo.colIndex;
      pColInfo[i].type = (index != -1) ? pTagSchema[index].type : TSDB_DATA_TYPE_BINARY;
H
hzcheng 已提交
1500
    } else {
1501
      pColInfo[i].type = pSchema[pExpr->colInfo.colIndex].type;
H
hzcheng 已提交
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
    }
  }
}

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

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

S
slguan 已提交
1514
  // to denote the heart-beat timer close connection and free all allocated resources
1515 1516
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pHeatBeat->cmd, 0);
  pQueryInfo->type = TSDB_QUERY_TYPE_FREE_RESOURCE;
H
hzcheng 已提交
1517 1518
}

1519
bool tscShouldFreeHeartBeat(SSqlObj* pHb) {
H
hzcheng 已提交
1520
  assert(pHb == pHb->signature);
1521 1522 1523

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

/*
weixin_48148422's avatar
weixin_48148422 已提交
1527
 * the following four kinds of SqlObj should not be freed
H
hzcheng 已提交
1528 1529 1530
 * 1. SqlObj for stream computing
 * 2. main SqlObj
 * 3. heartbeat SqlObj
weixin_48148422's avatar
weixin_48148422 已提交
1531
 * 4. SqlObj for subscription
H
hzcheng 已提交
1532 1533 1534 1535 1536 1537
 *
 * 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 已提交
1538
bool tscShouldBeFreed(SSqlObj* pSql) {
H
Haojun Liao 已提交
1539
  if (pSql == NULL || pSql->signature != pSql) {
H
hzcheng 已提交
1540 1541
    return false;
  }
H
Haojun Liao 已提交
1542
  
H
hzcheng 已提交
1543
  STscObj* pTscObj = pSql->pTscObj;
H
Haojun Liao 已提交
1544
  if (pSql->pStream != NULL || pTscObj->pHb == pSql || pSql->pSubscription != NULL) {
H
hzcheng 已提交
1545 1546 1547
    return false;
  }

H
Haojun Liao 已提交
1548
  // only the table meta and super table vgroup query will free resource automatically
H
hzcheng 已提交
1549
  int32_t command = pSql->cmd.command;
H
Haojun Liao 已提交
1550
  if (command == TSDB_SQL_META || command == TSDB_SQL_STABLEVGROUP) {
1551
    return true;
H
hzcheng 已提交
1552
  }
H
Haojun Liao 已提交
1553

H
Haojun Liao 已提交
1554
  return false;
H
hzcheng 已提交
1555 1556
}

1557 1558 1559
/**
 *
 * @param pCmd
1560
 * @param clauseIndex denote the index of the union sub clause, usually are 0, if no union query exists.
1561 1562 1563
 * @param tableIndex  denote the table index for join query, where more than one table exists
 * @return
 */
1564
STableMetaInfo* tscGetTableMetaInfoFromCmd(SSqlCmd* pCmd, int32_t clauseIndex, int32_t tableIndex) {
1565
  if (pCmd == NULL || pCmd->numOfClause == 0) {
S
slguan 已提交
1566 1567 1568
    return NULL;
  }

1569
  assert(clauseIndex >= 0 && clauseIndex < pCmd->numOfClause);
1570

1571
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, clauseIndex);
H
hjxilinx 已提交
1572
  return tscGetMetaInfo(pQueryInfo, tableIndex);
S
slguan 已提交
1573 1574
}

H
hjxilinx 已提交
1575
STableMetaInfo* tscGetMetaInfo(SQueryInfo* pQueryInfo, int32_t tableIndex) {
H
hjxilinx 已提交
1576
  assert(pQueryInfo != NULL);
1577

H
hjxilinx 已提交
1578
  if (pQueryInfo->pTableMetaInfo == NULL) {
1579 1580 1581 1582
    assert(pQueryInfo->numOfTables == 0);
    return NULL;
  }

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

H
hjxilinx 已提交
1585
  return pQueryInfo->pTableMetaInfo[tableIndex];
1586 1587
}

1588 1589
SQueryInfo* tscGetQueryInfoDetailSafely(SSqlCmd* pCmd, int32_t subClauseIndex) {
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, subClauseIndex);
1590
  int32_t ret = TSDB_CODE_SUCCESS;
1591

1592
  while ((pQueryInfo) == NULL) {
1593
    if ((ret = tscAddSubqueryInfo(pCmd)) != TSDB_CODE_SUCCESS) {
1594 1595
      terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
      return NULL;
1596
    }
1597

1598
    pQueryInfo = tscGetQueryInfoDetail(pCmd, subClauseIndex);
1599
  }
1600

1601
  return pQueryInfo;
1602 1603
}

H
hjxilinx 已提交
1604
STableMetaInfo* tscGetTableMetaInfoByUid(SQueryInfo* pQueryInfo, uint64_t uid, int32_t* index) {
S
slguan 已提交
1605
  int32_t k = -1;
1606 1607

  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
1608
    if (pQueryInfo->pTableMetaInfo[i]->pTableMeta->id.uid == uid) {
S
slguan 已提交
1609 1610 1611 1612 1613 1614 1615 1616 1617
      k = i;
      break;
    }
  }

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

H
hjxilinx 已提交
1618
  assert(k != -1);
H
hjxilinx 已提交
1619
  return tscGetMetaInfo(pQueryInfo, k);
S
slguan 已提交
1620 1621
}

H
hjxilinx 已提交
1622 1623 1624 1625 1626 1627 1628 1629
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);
H
Haojun Liao 已提交
1630 1631
  pQueryInfo->exprList   = taosArrayInit(4, POINTER_BYTES);
  pQueryInfo->colList    = taosArrayInit(4, POINTER_BYTES);
1632
  pQueryInfo->udColumnId = TSDB_UD_COLUMN_INDEX;
H
hjxilinx 已提交
1633 1634
}

1635
int32_t tscAddSubqueryInfo(SSqlCmd* pCmd) {
1636
  assert(pCmd != NULL);
1637

H
hjxilinx 已提交
1638
  // todo refactor: remove this structure
1639 1640
  size_t s = pCmd->numOfClause + 1;
  char*  tmp = realloc(pCmd->pQueryInfo, s * POINTER_BYTES);
1641
  if (tmp == NULL) {
1642
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
1643
  }
1644 1645 1646 1647

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

  SQueryInfo* pQueryInfo = calloc(1, sizeof(SQueryInfo));
H
Haojun Liao 已提交
1648 1649 1650 1651
  if (pQueryInfo == NULL) {
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }

H
hjxilinx 已提交
1652
  tscInitQueryInfo(pQueryInfo);
H
Haojun Liao 已提交
1653 1654

  pQueryInfo->window = TSWINDOW_INITIALIZER;
1655 1656 1657
  pQueryInfo->msg = pCmd->payload;  // pointer to the parent error message buffer

  pCmd->pQueryInfo[pCmd->numOfClause++] = pQueryInfo;
1658 1659 1660
  return TSDB_CODE_SUCCESS;
}

1661
static void freeQueryInfoImpl(SQueryInfo* pQueryInfo) {
1662
  tscTagCondRelease(&pQueryInfo->tagCond);
H
hjxilinx 已提交
1663
  tscFieldInfoClear(&pQueryInfo->fieldsInfo);
1664

H
hjxilinx 已提交
1665 1666
  tscSqlExprInfoDestroy(pQueryInfo->exprList);
  pQueryInfo->exprList = NULL;
1667

1668
  tscColumnListDestroy(pQueryInfo->colList);
H
hjxilinx 已提交
1669
  pQueryInfo->colList = NULL;
1670

1671 1672 1673 1674 1675
  if (pQueryInfo->groupbyExpr.columnInfo != NULL) {
    taosArrayDestroy(pQueryInfo->groupbyExpr.columnInfo);
    pQueryInfo->groupbyExpr.columnInfo = NULL;
  }
  
H
Haojun Liao 已提交
1676
  pQueryInfo->tsBuf = tsBufDestroy(pQueryInfo->tsBuf);
1677

S
Shengliang Guan 已提交
1678
  taosTFree(pQueryInfo->fillVal);
1679
}
1680

1681
void tscClearSubqueryInfo(SSqlCmd* pCmd) {
1682
  for (int32_t i = 0; i < pCmd->numOfClause; ++i) {
1683
    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, i);
1684
    freeQueryInfoImpl(pQueryInfo);
1685
  }
1686 1687
}

1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
void tscFreeVgroupTableInfo(SArray* pVgroupTables) {
  if (pVgroupTables != NULL) {
    for (size_t i = 0; i < taosArrayGetSize(pVgroupTables); i++) {
      SVgroupTableInfo* pInfo = taosArrayGet(pVgroupTables, i);
      taosArrayDestroy(pInfo->itemList);
    }
    taosArrayDestroy(pVgroupTables);
  }
}

1698
void clearAllTableMetaInfo(SQueryInfo* pQueryInfo, const char* address, bool removeFromCache) {
1699
  tscDebug("%p deref the table meta in cache, numOfTables:%d", address, pQueryInfo->numOfTables);
1700
  
1701 1702
  for(int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
    STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, i);
1703
    tscFreeVgroupTableInfo(pTableMetaInfo->pVgroupTables);
1704 1705
    tscClearTableMetaInfo(pTableMetaInfo, removeFromCache);
    free(pTableMetaInfo);
1706 1707
  }
  
S
Shengliang Guan 已提交
1708
  taosTFree(pQueryInfo->pTableMetaInfo);
1709 1710
}

1711
STableMetaInfo* tscAddTableMetaInfo(SQueryInfo* pQueryInfo, const char* name, STableMeta* pTableMeta,
1712
                                    SVgroupsInfo* vgroupList, SArray* pTagCols) {
H
hjxilinx 已提交
1713
  void* pAlloc = realloc(pQueryInfo->pTableMetaInfo, (pQueryInfo->numOfTables + 1) * POINTER_BYTES);
S
slguan 已提交
1714
  if (pAlloc == NULL) {
1715
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
1716 1717 1718
    return NULL;
  }

H
hjxilinx 已提交
1719
  pQueryInfo->pTableMetaInfo = pAlloc;
1720 1721 1722 1723 1724
  STableMetaInfo* pTableMetaInfo = calloc(1, sizeof(STableMetaInfo));
  if (pTableMetaInfo == NULL) {
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return NULL;
  }
S
slguan 已提交
1725

1726
  pQueryInfo->pTableMetaInfo[pQueryInfo->numOfTables] = pTableMetaInfo;
S
slguan 已提交
1727 1728

  if (name != NULL) {
B
Bomin Zhang 已提交
1729
    tstrncpy(pTableMetaInfo->name, name, sizeof(pTableMetaInfo->name));
S
slguan 已提交
1730 1731
  }

H
hjxilinx 已提交
1732
  pTableMetaInfo->pTableMeta = pTableMeta;
1733 1734
  
  if (vgroupList != NULL) {
H
hjxilinx 已提交
1735
    size_t size = sizeof(SVgroupsInfo) + sizeof(SCMVgroupInfo) * vgroupList->numOfVgroups;
1736
    pTableMetaInfo->vgroupList = malloc(size);
1737 1738 1739 1740
    if (pTableMetaInfo->vgroupList == NULL) {
      return NULL;
    }

1741
    memcpy(pTableMetaInfo->vgroupList, vgroupList, size);
1742
  }
S
slguan 已提交
1743

1744
  pTableMetaInfo->tagColList = taosArrayInit(4, POINTER_BYTES);
1745 1746 1747 1748
  if (pTableMetaInfo->tagColList == NULL) {
    return NULL;
  }

1749 1750
  if (pTagCols != NULL) {
    tscColumnListCopy(pTableMetaInfo->tagColList, pTagCols, -1);
S
slguan 已提交
1751
  }
1752
  
1753
  pQueryInfo->numOfTables += 1;
H
hjxilinx 已提交
1754
  return pTableMetaInfo;
S
slguan 已提交
1755 1756
}

H
hjxilinx 已提交
1757
STableMetaInfo* tscAddEmptyMetaInfo(SQueryInfo* pQueryInfo) {
1758
  return tscAddTableMetaInfo(pQueryInfo, NULL, NULL, NULL, NULL);
1759
}
S
slguan 已提交
1760

1761
void tscClearTableMetaInfo(STableMetaInfo* pTableMetaInfo, bool removeFromCache) {
H
hjxilinx 已提交
1762
  if (pTableMetaInfo == NULL) {
S
slguan 已提交
1763 1764 1765
    return;
  }

H
Haojun Liao 已提交
1766
  if (pTableMetaInfo->pTableMeta != NULL) {
H
Haojun Liao 已提交
1767
    taosCacheRelease(tscMetaCache, (void**)&(pTableMetaInfo->pTableMeta), removeFromCache);
H
Haojun Liao 已提交
1768 1769
  }

S
Shengliang Guan 已提交
1770
  taosTFree(pTableMetaInfo->vgroupList);
1771
  
1772 1773
  tscColumnListDestroy(pTableMetaInfo->tagColList);
  pTableMetaInfo->tagColList = NULL;
S
slguan 已提交
1774 1775 1776
}

void tscResetForNextRetrieve(SSqlRes* pRes) {
H
hjxilinx 已提交
1777 1778 1779
  if (pRes == NULL) {
    return;
  }
1780

S
slguan 已提交
1781 1782 1783 1784
  pRes->row = 0;
  pRes->numOfRows = 0;
}

1785
void registerSqlObj(SSqlObj* pSql) {
H
Haojun Liao 已提交
1786
  int32_t DEFAULT_LIFE_TIME = 2 * 600 * 1000;  // 1200 sec
1787 1788 1789 1790 1791 1792 1793 1794

  int32_t ref = T_REF_INC(pSql->pTscObj);
  tscDebug("%p add to tscObj:%p, ref:%d", pSql, pSql->pTscObj, ref);

  uint64_t p = (uint64_t) pSql;
  pSql->self = taosCachePut(tscObjCache, &p, sizeof(uint64_t), &p, sizeof(uint64_t), DEFAULT_LIFE_TIME);
}

H
Haojun Liao 已提交
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
SSqlObj* createSimpleSubObj(SSqlObj* pSql, void (*fp)(), void* param, int32_t cmd) {
  SSqlObj* pNew = (SSqlObj*)calloc(1, sizeof(SSqlObj));
  if (pNew == NULL) {
    tscError("%p new subquery failed, tableIndex:%d", pSql, 0);
    return NULL;
  }

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

  SSqlCmd* pCmd = &pNew->cmd;
  pCmd->command = cmd;
H
Haojun Liao 已提交
1807
  pCmd->parseFinished = 1;
B
Bomin Zhang 已提交
1808
  pCmd->autoCreated = pSql->cmd.autoCreated;
H
Haojun Liao 已提交
1809 1810 1811 1812 1813 1814 1815

  if (tscAddSubqueryInfo(pCmd) != TSDB_CODE_SUCCESS) {
    tscFreeSqlObj(pNew);
    return NULL;
  }

  pNew->fp = fp;
H
Haojun Liao 已提交
1816
  pNew->fetchFp = fp;
H
Haojun Liao 已提交
1817
  pNew->param = param;
1818
  pNew->maxRetry = TSDB_MAX_REPLICA;
H
Haojun Liao 已提交
1819

H
Haojun Liao 已提交
1820 1821 1822
  pNew->sqlstr = strdup(pSql->sqlstr);
  if (pNew->sqlstr == NULL) {
    tscError("%p new subquery failed", pSql);
H
Haojun Liao 已提交
1823
    tscFreeSqlObj(pNew);
H
Haojun Liao 已提交
1824 1825 1826
    return NULL;
  }

1827
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetailSafely(pCmd, 0);
H
Haojun Liao 已提交
1828 1829 1830 1831 1832

  assert(pSql->cmd.clauseIndex == 0);
  STableMetaInfo* pMasterTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, pSql->cmd.clauseIndex, 0);

  tscAddTableMetaInfo(pQueryInfo, pMasterTableMetaInfo->name, NULL, NULL, NULL);
H
Haojun Liao 已提交
1833

1834
  registerSqlObj(pNew);
H
Haojun Liao 已提交
1835 1836 1837
  return pNew;
}

H
Haojun Liao 已提交
1838 1839
// current sql function is not direct output result, so create a dummy output field
static void doSetNewFieldInfo(SQueryInfo* pNewQueryInfo, SSqlExpr* pExpr) {
S
Shengliang Guan 已提交
1840
  TAOS_FIELD f = {.type = (uint8_t)pExpr->resType, .bytes = pExpr->resBytes};
H
Haojun Liao 已提交
1841 1842 1843 1844 1845 1846 1847 1848 1849
  tstrncpy(f.name, pExpr->aliasName, sizeof(f.name));

  SFieldSupInfo* pInfo1 = tscFieldInfoAppend(&pNewQueryInfo->fieldsInfo, &f);

  pInfo1->pSqlExpr = pExpr;
  pInfo1->visible = false;
}

static void doSetSqlExprAndResultFieldInfo(SQueryInfo* pQueryInfo, SQueryInfo* pNewQueryInfo, int64_t uid) {
S
Shengliang Guan 已提交
1850
  int32_t numOfOutput = (int32_t)tscSqlExprNumOfExprs(pNewQueryInfo);
H
Haojun Liao 已提交
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
  if (numOfOutput == 0) {
    return;
  }

  size_t      numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
  SFieldInfo* pFieldInfo = &pQueryInfo->fieldsInfo;

  // set the field info in pNewQueryInfo object
  for (int32_t i = 0; i < numOfExprs; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);

    if (pExpr->uid == uid) {
      if (i < pFieldInfo->numOfOutput) {
        SFieldSupInfo* pInfo = tscFieldInfoGetSupp(pFieldInfo, i);

        if (pInfo->pSqlExpr != NULL) {
          TAOS_FIELD* p = tscFieldInfoGetField(pFieldInfo, i);
          assert(strcmp(p->name, pExpr->aliasName) == 0);

          SFieldSupInfo* pInfo1 = tscFieldInfoAppend(&pNewQueryInfo->fieldsInfo, p);
          *pInfo1 = *pInfo;
        } else {
          assert(pInfo->pArithExprInfo != NULL);
          doSetNewFieldInfo(pNewQueryInfo, pExpr);
        }
      } else { // it is a arithmetic column, does not have actual field for sqlExpr, so build it
        doSetNewFieldInfo(pNewQueryInfo, pExpr);
      }
    }
  }

  // make sure the the sqlExpr for each fields is correct
  numOfExprs = tscSqlExprNumOfExprs(pNewQueryInfo);

  // update the pSqlExpr pointer in SFieldSupInfo according the field name
  // make sure the pSqlExpr point to the correct SqlExpr in pNewQueryInfo, not SqlExpr in pQueryInfo
  for (int32_t f = 0; f < pNewQueryInfo->fieldsInfo.numOfOutput; ++f) {
    TAOS_FIELD* field = tscFieldInfoGetField(&pNewQueryInfo->fieldsInfo, f);

    bool matched = false;
    for (int32_t k1 = 0; k1 < numOfExprs; ++k1) {
      SSqlExpr* pExpr1 = tscSqlExprGet(pNewQueryInfo, k1);

      if (strcmp(field->name, pExpr1->aliasName) == 0) {  // establish link according to the result field name
        SFieldSupInfo* pInfo = tscFieldInfoGetSupp(&pNewQueryInfo->fieldsInfo, f);
        pInfo->pSqlExpr = pExpr1;

        matched = true;
        break;
      }
    }

    assert(matched);
1904
    (void)matched;
H
Haojun Liao 已提交
1905 1906 1907 1908 1909
  }

  tscFieldInfoUpdateOffset(pNewQueryInfo);
}

1910
SSqlObj* createSubqueryObj(SSqlObj* pSql, int16_t tableIndex, void (*fp)(), void* param, int32_t cmd, SSqlObj* pPrevSql) {
1911
  SSqlCmd* pCmd = &pSql->cmd;
1912

S
slguan 已提交
1913 1914
  SSqlObj* pNew = (SSqlObj*)calloc(1, sizeof(SSqlObj));
  if (pNew == NULL) {
1915
    tscError("%p new subquery failed, tableIndex:%d", pSql, tableIndex);
1916
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
1917 1918
    return NULL;
  }
1919 1920
  
  STableMetaInfo* pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, tableIndex);
S
slguan 已提交
1921 1922 1923 1924

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

H
Haojun Liao 已提交
1925 1926 1927
  pNew->sqlstr = strdup(pSql->sqlstr);
  if (pNew->sqlstr == NULL) {
    tscError("%p new subquery failed, tableIndex:%d, vgroupIndex:%d", pSql, tableIndex, pTableMetaInfo->vgroupIndex);
1928
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
1929
    goto _error;
H
Haojun Liao 已提交
1930 1931
  }

1932 1933 1934 1935 1936 1937
  SSqlCmd* pnCmd = &pNew->cmd;
  memcpy(pnCmd, pCmd, sizeof(SSqlCmd));
  
  pnCmd->command = cmd;
  pnCmd->payload = NULL;
  pnCmd->allocSize = 0;
S
slguan 已提交
1938

1939 1940 1941 1942
  pnCmd->pQueryInfo = NULL;
  pnCmd->numOfClause = 0;
  pnCmd->clauseIndex = 0;
  pnCmd->pDataBlocks = NULL;
H
Haojun Liao 已提交
1943
  pnCmd->parseFinished = 1;
1944

1945
  if (tscAddSubqueryInfo(pnCmd) != TSDB_CODE_SUCCESS) {
1946
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
1947
    goto _error;
1948
  }
1949

1950
  SQueryInfo* pNewQueryInfo = tscGetQueryInfoDetail(pnCmd, 0);
1951
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
1952

H
hjxilinx 已提交
1953
  pNewQueryInfo->command = pQueryInfo->command;
1954
  memcpy(&pNewQueryInfo->interval, &pQueryInfo->interval, sizeof(pNewQueryInfo->interval));
H
hjxilinx 已提交
1955 1956 1957
  pNewQueryInfo->type   = pQueryInfo->type;
  pNewQueryInfo->window = pQueryInfo->window;
  pNewQueryInfo->limit  = pQueryInfo->limit;
H
hjxilinx 已提交
1958
  pNewQueryInfo->slimit = pQueryInfo->slimit;
H
hjxilinx 已提交
1959
  pNewQueryInfo->order  = pQueryInfo->order;
H
Haojun Liao 已提交
1960 1961
  pNewQueryInfo->tsBuf  = NULL;
  pNewQueryInfo->fillType = pQueryInfo->fillType;
1962
  pNewQueryInfo->fillVal  = NULL;
H
Haojun Liao 已提交
1963
  pNewQueryInfo->clauseLimit = pQueryInfo->clauseLimit;
1964
  pNewQueryInfo->numOfTables = 0;
H
Haojun Liao 已提交
1965
  pNewQueryInfo->pTableMetaInfo = NULL;
H
hjxilinx 已提交
1966
  
H
hjxilinx 已提交
1967 1968 1969
  pNewQueryInfo->groupbyExpr = pQueryInfo->groupbyExpr;
  if (pQueryInfo->groupbyExpr.columnInfo != NULL) {
    pNewQueryInfo->groupbyExpr.columnInfo = taosArrayClone(pQueryInfo->groupbyExpr.columnInfo);
1970 1971 1972 1973
    if (pNewQueryInfo->groupbyExpr.columnInfo == NULL) {
      terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
      goto _error;
    }
H
hjxilinx 已提交
1974 1975
  }
  
H
Haojun Liao 已提交
1976 1977 1978 1979
  if (tscTagCondCopy(&pNewQueryInfo->tagCond, &pQueryInfo->tagCond) != 0) {
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
    goto _error;
  }
1980

1981
  if (pQueryInfo->fillType != TSDB_FILL_NONE) {
1982
    pNewQueryInfo->fillVal = malloc(pQueryInfo->fieldsInfo.numOfOutput * sizeof(int64_t));
1983 1984 1985 1986 1987
    if (pNewQueryInfo->fillVal == NULL) {
      terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
      goto _error;
    }

1988
    memcpy(pNewQueryInfo->fillVal, pQueryInfo->fillVal, pQueryInfo->fieldsInfo.numOfOutput * sizeof(int64_t));
1989
  }
1990

1991
  if (tscAllocPayload(pnCmd, TSDB_DEFAULT_PAYLOAD_SIZE) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1992
    tscError("%p new subquery failed, tableIndex:%d, vgroupIndex:%d", pSql, tableIndex, pTableMetaInfo->vgroupIndex);
1993
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
1994
    goto _error;
S
slguan 已提交
1995
  }
1996
  
H
hjxilinx 已提交
1997
  tscColumnListCopy(pNewQueryInfo->colList, pQueryInfo->colList, (int16_t)tableIndex);
1998

S
slguan 已提交
1999 2000
  // set the correct query type
  if (pPrevSql != NULL) {
2001
    SQueryInfo* pPrevQueryInfo = tscGetQueryInfoDetail(&pPrevSql->cmd, pPrevSql->cmd.clauseIndex);
2002
    pNewQueryInfo->type = pPrevQueryInfo->type;
S
slguan 已提交
2003
  } else {
H
Haojun Liao 已提交
2004
    TSDB_QUERY_SET_TYPE(pNewQueryInfo->type, TSDB_QUERY_TYPE_SUBQUERY);// it must be the subquery
S
slguan 已提交
2005 2006
  }

2007
  uint64_t uid = pTableMetaInfo->pTableMeta->id.uid;
H
Haojun Liao 已提交
2008 2009 2010 2011
  if (tscSqlExprCopy(pNewQueryInfo->exprList, pQueryInfo->exprList, uid, true) != 0) {
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
    goto _error;
  }
S
slguan 已提交
2012

H
Haojun Liao 已提交
2013
  doSetSqlExprAndResultFieldInfo(pQueryInfo, pNewQueryInfo, uid);
S
slguan 已提交
2014 2015

  pNew->fp = fp;
H
Haojun Liao 已提交
2016 2017
  pNew->fetchFp = fp;

S
slguan 已提交
2018
  pNew->param = param;
2019
  pNew->maxRetry = TSDB_MAX_REPLICA;
H
hjxilinx 已提交
2020

2021
  char* name = pTableMetaInfo->name;
H
hjxilinx 已提交
2022
  STableMetaInfo* pFinalInfo = NULL;
S
slguan 已提交
2023 2024

  if (pPrevSql == NULL) {
H
Haojun Liao 已提交
2025
    STableMeta* pTableMeta = taosCacheAcquireByData(tscMetaCache, pTableMetaInfo->pTableMeta);  // get by name may failed due to the cache cleanup
2026
    assert(pTableMeta != NULL);
H
Haojun Liao 已提交
2027

2028
    pFinalInfo = tscAddTableMetaInfo(pNewQueryInfo, name, pTableMeta, pTableMetaInfo->vgroupList, pTableMetaInfo->tagColList);
2029 2030
  } else {  // transfer the ownership of pTableMeta to the newly create sql object.
    STableMetaInfo* pPrevInfo = tscGetTableMetaInfoFromCmd(&pPrevSql->cmd, pPrevSql->cmd.clauseIndex, 0);
2031

H
Haojun Liao 已提交
2032
    STableMeta*  pPrevTableMeta = taosCacheTransfer(tscMetaCache, (void**)&pPrevInfo->pTableMeta);
2033
    
2034
    SVgroupsInfo* pVgroupsInfo = pPrevInfo->vgroupList;
2035
    pFinalInfo = tscAddTableMetaInfo(pNewQueryInfo, name, pPrevTableMeta, pVgroupsInfo, pTableMetaInfo->tagColList);
S
slguan 已提交
2036 2037
  }

L
lihui 已提交
2038
  if (pFinalInfo->pTableMeta == NULL) {
2039 2040
    tscError("%p new subquery failed since no tableMeta in cache, name:%s", pSql, name);

2041
    if (pPrevSql != NULL) { // pass the previous error to client
2042 2043 2044 2045 2046 2047
      assert(pPrevSql->res.code != TSDB_CODE_SUCCESS);
      terrno = pPrevSql->res.code;
    } else {
      terrno = TSDB_CODE_TSC_APP_ERROR;
    }

2048
    goto _error;
L
lihui 已提交
2049 2050 2051 2052
  }
  
  assert(pNewQueryInfo->numOfTables == 1);
  
weixin_48148422's avatar
weixin_48148422 已提交
2053
  if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
2054
    assert(pFinalInfo->vgroupList != NULL);
S
slguan 已提交
2055
  }
B
Bomin Zhang 已提交
2056

2057
  if (cmd == TSDB_SQL_SELECT) {
2058 2059
    size_t size = taosArrayGetSize(pNewQueryInfo->colList);
    
2060
    tscDebug(
S
TD-1057  
Shengliang Guan 已提交
2061
        "%p new subquery:%p, tableIndex:%d, vgroupIndex:%d, type:%d, exprInfo:%" PRIzu ", colList:%" PRIzu ","
2062
        "fieldInfo:%d, name:%s, qrang:%" PRId64 " - %" PRId64 " order:%d, limit:%" PRId64,
H
hjxilinx 已提交
2063
        pSql, pNew, tableIndex, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, tscSqlExprNumOfExprs(pNewQueryInfo),
H
hjxilinx 已提交
2064 2065
        size, pNewQueryInfo->fieldsInfo.numOfOutput, pFinalInfo->name, pNewQueryInfo->window.skey,
        pNewQueryInfo->window.ekey, pNewQueryInfo->order.order, pNewQueryInfo->limit.limit);
2066 2067 2068
    
    tscPrintSelectClause(pNew, 0);
  } else {
2069
    tscDebug("%p new sub insertion: %p, vnodeIdx:%d", pSql, pNew, pTableMetaInfo->vgroupIndex);
2070
  }
2071

2072
  registerSqlObj(pNew);
S
slguan 已提交
2073
  return pNew;
2074 2075 2076 2077

_error:
  tscFreeSqlObj(pNew);
  return NULL;
S
slguan 已提交
2078 2079
}

H
hjxilinx 已提交
2080 2081 2082 2083 2084
/**
 * To decide if current is a two-stage super table query, join query, or insert. And invoke different
 * procedure accordingly
 * @param pSql
 */
H
hzcheng 已提交
2085 2086
void tscDoQuery(SSqlObj* pSql) {
  SSqlCmd* pCmd = &pSql->cmd;
H
hjxilinx 已提交
2087
  SSqlRes* pRes = &pSql->res;
H
hjxilinx 已提交
2088
  
H
hjxilinx 已提交
2089
  pRes->code = TSDB_CODE_SUCCESS;
H
hjxilinx 已提交
2090
  
H
hzcheng 已提交
2091 2092
  if (pCmd->command > TSDB_SQL_LOCAL) {
    tscProcessLocalCmd(pSql);
H
hjxilinx 已提交
2093 2094 2095 2096
    return;
  }
  
  if (pCmd->command == TSDB_SQL_SELECT) {
H
Haojun Liao 已提交
2097
    tscAddIntoSqlList(pSql);
H
hjxilinx 已提交
2098 2099 2100
  }

  if (pCmd->dataSourceType == DATA_FROM_DATA_FILE) {
H
Haojun Liao 已提交
2101
    tscProcessMultiVnodesImportFromFile(pSql);
H
hzcheng 已提交
2102
  } else {
H
hjxilinx 已提交
2103 2104 2105 2106 2107 2108
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
    uint16_t type = pQueryInfo->type;
  
    if (pSql->fp == (void(*)())tscHandleMultivnodeInsert) {  // multi-vnodes insertion
      tscHandleMultivnodeInsert(pSql);
      return;
H
hzcheng 已提交
2109
    }
H
hjxilinx 已提交
2110 2111
  
    if (QUERY_IS_JOIN_QUERY(type)) {
H
Haojun Liao 已提交
2112
      if (!TSDB_QUERY_HAS_TYPE(type, TSDB_QUERY_TYPE_SUBQUERY)) {
H
hjxilinx 已提交
2113
        tscHandleMasterJoinQuery(pSql);
H
Haojun Liao 已提交
2114 2115 2116 2117 2118 2119 2120 2121 2122
      } else { // for first stage sub query, iterate all vnodes to get all timestamp
        if (!TSDB_QUERY_HAS_TYPE(type, TSDB_QUERY_TYPE_JOIN_SEC_STAGE)) {
          tscProcessSql(pSql);
        } else { // secondary stage join query.
          if (tscIsTwoStageSTableQuery(pQueryInfo, 0)) {  // super table query
            tscHandleMasterSTableQuery(pSql);
          } else {
            tscProcessSql(pSql);
          }
H
hjxilinx 已提交
2123 2124
        }
      }
H
Haojun Liao 已提交
2125 2126

      return;
H
hjxilinx 已提交
2127 2128 2129
    } else if (tscIsTwoStageSTableQuery(pQueryInfo, 0)) {  // super table query
      tscHandleMasterSTableQuery(pSql);
      return;
S
slguan 已提交
2130
    }
H
hjxilinx 已提交
2131 2132
    
    tscProcessSql(pSql);
H
hzcheng 已提交
2133 2134
  }
}
S
slguan 已提交
2135

H
Haojun Liao 已提交
2136
int16_t tscGetJoinTagColIdByUid(STagCond* pTagCond, uint64_t uid) {
S
slguan 已提交
2137
  if (pTagCond->joinInfo.left.uid == uid) {
H
Haojun Liao 已提交
2138 2139 2140
    return pTagCond->joinInfo.left.tagColId;
  } else if (pTagCond->joinInfo.right.uid == uid) {
    return pTagCond->joinInfo.right.tagColId;
H
Haojun Liao 已提交
2141
  } else {
H
Haojun Liao 已提交
2142
    assert(0);
S
TD-1057  
Shengliang Guan 已提交
2143
    return -1;
S
slguan 已提交
2144 2145
  }
}
2146

H
Haojun Liao 已提交
2147 2148
bool tscIsUpdateQuery(SSqlObj* pSql) {
  if (pSql == NULL || pSql->signature != pSql) {
2149 2150
    terrno = TSDB_CODE_TSC_DISCONNECTED;
    return TSDB_CODE_TSC_DISCONNECTED;
2151 2152
  }

H
Haojun Liao 已提交
2153 2154
  SSqlCmd* pCmd = &pSql->cmd;
  return ((pCmd->command >= TSDB_SQL_INSERT && pCmd->command <= TSDB_SQL_DROP_DNODE) || TSDB_SQL_USE_DB == pCmd->command);
H
hjxilinx 已提交
2155
}
2156

Y
TD-934  
yihaoDeng 已提交
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
int32_t tscSQLSyntaxErrMsg(char* msg, const char* additionalInfo,  const char* sql) {
  const char* msgFormat1 = "syntax error near \'%s\'";
  const char* msgFormat2 = "syntax error near \'%s\' (%s)";
  const char* msgFormat3 = "%s";

  const char* prefix = "syntax error"; 
  const int32_t BACKWARD_CHAR_STEP = 0;

  if (sql == NULL) {
    assert(additionalInfo != NULL);
    sprintf(msg, msgFormat1, additionalInfo);
    return TSDB_CODE_TSC_SQL_SYNTAX_ERROR;
  }

  char buf[64] = {0};  // only extract part of sql string
  strncpy(buf, (sql - BACKWARD_CHAR_STEP), tListLen(buf) - 1);

  if (additionalInfo != NULL) {
    sprintf(msg, msgFormat2, buf, additionalInfo);
  } else {
    const char* msgFormat = (0 == strncmp(sql, prefix, strlen(prefix))) ? msgFormat3 : msgFormat1; 
    sprintf(msg, msgFormat, buf);
  }

  return TSDB_CODE_TSC_SQL_SYNTAX_ERROR;
  
}
H
Haojun Liao 已提交
2184

H
hjxilinx 已提交
2185 2186
int32_t tscInvalidSQLErrMsg(char* msg, const char* additionalInfo, const char* sql) {
  const char* msgFormat1 = "invalid SQL: %s";
Y
TD-934  
yihaoDeng 已提交
2187 2188
  const char* msgFormat2 = "invalid SQL: \'%s\' (%s)";
  const char* msgFormat3 = "invalid SQL: \'%s\'";
H
hjxilinx 已提交
2189

H
hjxilinx 已提交
2190
  const int32_t BACKWARD_CHAR_STEP = 0;
H
hjxilinx 已提交
2191

H
hjxilinx 已提交
2192 2193 2194
  if (sql == NULL) {
    assert(additionalInfo != NULL);
    sprintf(msg, msgFormat1, additionalInfo);
2195
    return TSDB_CODE_TSC_INVALID_SQL;
H
hjxilinx 已提交
2196
  }
H
hjxilinx 已提交
2197 2198

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

H
hjxilinx 已提交
2201 2202 2203
  if (additionalInfo != NULL) {
    sprintf(msg, msgFormat2, buf, additionalInfo);
  } else {
H
hjxilinx 已提交
2204
    sprintf(msg, msgFormat3, buf);  // no additional information for invalid sql error
H
hjxilinx 已提交
2205
  }
H
hjxilinx 已提交
2206

2207
  return TSDB_CODE_TSC_INVALID_SQL;
2208
}
H
hjxilinx 已提交
2209

H
hjxilinx 已提交
2210 2211
bool tscHasReachLimitation(SQueryInfo* pQueryInfo, SSqlRes* pRes) {
  assert(pQueryInfo != NULL && pQueryInfo->clauseLimit != 0);
H
Haojun Liao 已提交
2212
  return (pQueryInfo->clauseLimit > 0 && pRes->numOfClauseTotal >= pQueryInfo->clauseLimit);
H
hjxilinx 已提交
2213
}
2214 2215

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

/**
 *  If current vnode query does not return results anymore (pRes->numOfRows == 0), try the next vnode if exists,
2219
 *  while multi-vnode super table projection query and the result does not reach the limitation.
2220
 */
2221
bool hasMoreVnodesToTry(SSqlObj* pSql) {
2222 2223 2224 2225 2226
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;
  if (pCmd->command != TSDB_SQL_FETCH) {
    return false;
  }
2227

H
Haojun Liao 已提交
2228
  assert(pRes->completed);
2229 2230
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
Haojun Liao 已提交
2231

2232
  // for normal table, no need to try any more if results are all retrieved from one vnode
H
hjLiao 已提交
2233
  if (!UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo) || (pTableMetaInfo->vgroupList == NULL)) {
2234
    return false;
2235
  }
2236
  
2237
  int32_t numOfVgroups = pTableMetaInfo->vgroupList->numOfVgroups;
2238
  if (pTableMetaInfo->pVgroupTables != NULL) {
S
Shengliang Guan 已提交
2239
    numOfVgroups = (int32_t)taosArrayGetSize(pTableMetaInfo->pVgroupTables);
2240 2241
  }

2242 2243
  return tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) &&
         (!tscHasReachLimitation(pQueryInfo, pRes)) && (pTableMetaInfo->vgroupIndex < numOfVgroups - 1);
2244 2245
}

H
Haojun Liao 已提交
2246 2247 2248 2249
bool hasMoreClauseToTry(SSqlObj* pSql) {
  return pSql->cmd.clauseIndex < pSql->cmd.numOfClause - 1;
}

2250 2251 2252 2253 2254 2255
void tscTryQueryNextVnode(SSqlObj* pSql, __async_cb_func_t fp) {
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;

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

2256 2257 2258 2259
  /*
   * no result returned from the current virtual node anymore, try the next vnode if exists
   * if case of: multi-vnode super table projection query
   */
2260
  assert(pRes->numOfRows == 0 && tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) && !tscHasReachLimitation(pQueryInfo, pRes));
H
hjxilinx 已提交
2261
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
2262 2263
  
  int32_t totalVgroups = pTableMetaInfo->vgroupList->numOfVgroups;
H
Haojun Liao 已提交
2264
  if (++pTableMetaInfo->vgroupIndex < totalVgroups) {
2265
    tscDebug("%p results from vgroup index:%d completed, try next:%d. total vgroups:%d. current numOfRes:%" PRId64, pSql,
H
Haojun Liao 已提交
2266
             pTableMetaInfo->vgroupIndex - 1, pTableMetaInfo->vgroupIndex, totalVgroups, pRes->numOfClauseTotal);
2267

2268 2269 2270 2271 2272 2273
    /*
     * 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.
H
Haojun Liao 已提交
2274
     * Therefore, the pRes->numOfRows, as well as pRes->numOfClauseTotal, must be 0.
2275 2276 2277
     * The pRes->offset value will be updated by virtual node, during query execution.
     */
    if (pQueryInfo->clauseLimit >= 0) {
H
Haojun Liao 已提交
2278
      pQueryInfo->limit.limit = pQueryInfo->clauseLimit - pRes->numOfClauseTotal;
2279
    }
2280

2281 2282
    pQueryInfo->limit.offset = pRes->offset;
    assert((pRes->offset >= 0 && pRes->numOfRows == 0) || (pRes->offset == 0 && pRes->numOfRows >= 0));
2283
    
2284
    tscDebug("%p new query to next vgroup, index:%d, limit:%" PRId64 ", offset:%" PRId64 ", glimit:%" PRId64,
2285
        pSql, pTableMetaInfo->vgroupIndex, pQueryInfo->limit.limit, pQueryInfo->limit.offset, pQueryInfo->clauseLimit);
2286

2287 2288 2289 2290 2291 2292 2293 2294
    /*
     * 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;
2295

2296
    tscResetForNextRetrieve(pRes);
2297

2298
    // set the callback function
2299
    pSql->fp = fp;
H
Haojun Liao 已提交
2300 2301 2302
    tscProcessSql(pSql);
  } else {
    tscDebug("%p try all %d vnodes, query complete. current numOfRes:%" PRId64, pSql, totalVgroups, pRes->numOfClauseTotal);
2303 2304
  }
}
2305

H
Haojun Liao 已提交
2306
void tscTryQueryNextClause(SSqlObj* pSql, __async_cb_func_t fp) {
2307 2308 2309 2310 2311 2312
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;

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

H
hjxilinx 已提交
2313
  pCmd->clauseIndex++;
2314 2315 2316 2317
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);

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

2318
  //backup the total number of result first
H
Haojun Liao 已提交
2319
  int64_t num = pRes->numOfTotal + pRes->numOfClauseTotal;
H
hjxilinx 已提交
2320
  tscFreeSqlResult(pSql);
2321 2322 2323
  
  pRes->numOfTotal = num;
  
S
Shengliang Guan 已提交
2324
  taosTFree(pSql->pSubs);
2325
  pSql->numOfSubs = 0;
H
Haojun Liao 已提交
2326
  pSql->fp = fp;
2327

2328
  tscDebug("%p try data in the next subclause:%d, total subclause:%d", pSql, pCmd->clauseIndex, pCmd->numOfClause);
2329 2330 2331
  if (pCmd->command > TSDB_SQL_LOCAL) {
    tscProcessLocalCmd(pSql);
  } else {
H
Haojun Liao 已提交
2332
    tscDoQuery(pSql);
2333 2334
  }
}
H
hjxilinx 已提交
2335

weixin_48148422's avatar
weixin_48148422 已提交
2336 2337 2338
void* malloc_throw(size_t size) {
  void* p = malloc(size);
  if (p == NULL) {
2339
    THROW(TSDB_CODE_TSC_OUT_OF_MEMORY);
weixin_48148422's avatar
weixin_48148422 已提交
2340 2341 2342 2343 2344
  }
  return p;
}

void* calloc_throw(size_t nmemb, size_t size) {
weixin_48148422's avatar
weixin_48148422 已提交
2345
  void* p = calloc(nmemb, size);
weixin_48148422's avatar
weixin_48148422 已提交
2346
  if (p == NULL) {
2347
    THROW(TSDB_CODE_TSC_OUT_OF_MEMORY);
weixin_48148422's avatar
weixin_48148422 已提交
2348 2349 2350 2351 2352 2353 2354
  }
  return p;
}

char* strdup_throw(const char* str) {
  char* p = strdup(str);
  if (p == NULL) {
2355
    THROW(TSDB_CODE_TSC_OUT_OF_MEMORY);
weixin_48148422's avatar
weixin_48148422 已提交
2356 2357 2358
  }
  return p;
}
2359

2360
int tscSetMgmtEpSetFromCfg(const char *first, const char *second) {
2361
  // init mgmt ip set 
2362 2363 2364 2365
  tscMgmtEpSet.version = 0;
  SRpcEpSet *mgmtEpSet = &(tscMgmtEpSet.epSet);
  mgmtEpSet->numOfEps = 0;
  mgmtEpSet->inUse = 0;
2366 2367

  if (first && first[0] != 0) {
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
2368
    if (strlen(first) >= TSDB_EP_LEN) {
2369
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
2370 2371
      return -1;
    }
2372 2373
    taosGetFqdnPortFromEp(first, mgmtEpSet->fqdn[mgmtEpSet->numOfEps], &(mgmtEpSet->port[mgmtEpSet->numOfEps]));
    mgmtEpSet->numOfEps++;
2374 2375 2376
  }

  if (second && second[0] != 0) {
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
2377
    if (strlen(second) >= TSDB_EP_LEN) {
2378
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
2379 2380
      return -1;
    }
2381 2382
    taosGetFqdnPortFromEp(second, mgmtEpSet->fqdn[mgmtEpSet->numOfEps], &(mgmtEpSet->port[mgmtEpSet->numOfEps]));
    mgmtEpSet->numOfEps++;
2383 2384
  }

2385
  if (mgmtEpSet->numOfEps == 0) {
2386
    terrno = TSDB_CODE_TSC_INVALID_FQDN;
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
2387 2388
    return -1;
  }
2389 2390 2391

  return 0;
}
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406

bool tscSetSqlOwner(SSqlObj* pSql) {
  SSqlRes* pRes = &pSql->res;

  // set the sql object owner
  uint64_t threadId = taosGetPthreadId();
  if (atomic_val_compare_exchange_64(&pSql->owner, 0, threadId) != 0) {
    pRes->code = TSDB_CODE_QRY_IN_EXEC;
    return false;
  }

  return true;
}

void tscClearSqlOwner(SSqlObj* pSql) {
S
Shengliang Guan 已提交
2407
  assert(taosCheckPthreadValid(pSql->owner));
2408
  atomic_store_64(&pSql->owner, 0);
Y
TD-934  
yihaoDeng 已提交
2409
}