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

16 17
#include "function.h"
#include "functionMgt.h"
dengyihao's avatar
dengyihao 已提交
18 19
#include "index.h"
#include "os.h"
20
#include "tdatablock.h"
21
#include "thash.h"
22
#include "tmsg.h"
23
#include "ttime.h"
24

25 26
#include "executil.h"
#include "executorimpl.h"
H
Haojun Liao 已提交
27
#include "tcompression.h"
H
Haojun Liao 已提交
28

dengyihao's avatar
dengyihao 已提交
29 30
static int32_t removeInvalidTable(SArray* list, SHashObj* tags);
static int32_t optimizeTbnameInCond(void* metaHandle, int64_t suid, SArray* list, SNode* pTagCond, SHashObj* tags);
dengyihao's avatar
dengyihao 已提交
31
static int32_t optimizeTbnameInCondImpl(void* metaHandle, int64_t suid, SArray* list, SNode* pTagCond);
dengyihao's avatar
dengyihao 已提交
32

dengyihao's avatar
dengyihao 已提交
33 34
void initResultRowInfo(SResultRowInfo* pResultRowInfo) {
  pResultRowInfo->size = 0;
35
  pResultRowInfo->cur.pageId = -1;
36 37
}

dengyihao's avatar
dengyihao 已提交
38
void closeResultRow(SResultRow* pResultRow) { pResultRow->closed = true; }
39

40 41 42 43 44 45 46 47 48 49 50
void resetResultRow(SResultRow* pResultRow, size_t entrySize) {
  pResultRow->numOfRows = 0;
  pResultRow->closed = false;
  pResultRow->endInterp = false;
  pResultRow->startInterp = false;

  if (entrySize > 0) {
    memset(pResultRow->pEntryInfo, 0, entrySize);
  }
}

H
Haojun Liao 已提交
51
// TODO refactor: use macro
52
SResultRowEntryInfo* getResultEntryInfo(const SResultRow* pRow, int32_t index, const int32_t* offset) {
H
Haojun Liao 已提交
53
  assert(index >= 0 && offset != NULL);
dengyihao's avatar
dengyihao 已提交
54
  return (SResultRowEntryInfo*)((char*)pRow->pEntryInfo + offset[index]);
H
Haojun Liao 已提交
55 56
}

57 58 59
size_t getResultRowSize(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  int32_t rowSize = (numOfOutput * sizeof(SResultRowEntryInfo)) + sizeof(SResultRow);

dengyihao's avatar
dengyihao 已提交
60
  for (int32_t i = 0; i < numOfOutput; ++i) {
61 62 63
    rowSize += pCtx[i].resDataInfo.interBufSize;
  }

64 65
  rowSize += (numOfOutput * sizeof(bool));
  // expand rowSize to mark if col is null for top/bottom result(saveTupleData)
66
  return rowSize;
67 68
}

H
Haojun Liao 已提交
69 70 71
void cleanupGroupResInfo(SGroupResInfo* pGroupResInfo) {
  assert(pGroupResInfo != NULL);

72
  for (int32_t i = 0; i < taosArrayGetSize(pGroupResInfo->pRows); ++i) {
H
Haojun Liao 已提交
73 74 75 76 77
    SResKeyPos* pRes = taosArrayGetP(pGroupResInfo->pRows, i);
    taosMemoryFree(pRes);
  }

  pGroupResInfo->pRows = taosArrayDestroy(pGroupResInfo->pRows);
dengyihao's avatar
dengyihao 已提交
78
  pGroupResInfo->index = 0;
H
Haojun Liao 已提交
79 80
}

5
54liuyao 已提交
81
int32_t resultrowComparAsc(const void* p1, const void* p2) {
dengyihao's avatar
dengyihao 已提交
82 83
  SResKeyPos* pp1 = *(SResKeyPos**)p1;
  SResKeyPos* pp2 = *(SResKeyPos**)p2;
84 85

  if (pp1->groupId == pp2->groupId) {
dengyihao's avatar
dengyihao 已提交
86 87
    int64_t pts1 = *(int64_t*)pp1->key;
    int64_t pts2 = *(int64_t*)pp2->key;
88 89 90 91

    if (pts1 == pts2) {
      return 0;
    } else {
dengyihao's avatar
dengyihao 已提交
92
      return pts1 < pts2 ? -1 : 1;
93 94
    }
  } else {
dengyihao's avatar
dengyihao 已提交
95
    return pp1->groupId < pp2->groupId ? -1 : 1;
96 97 98
  }
}

dengyihao's avatar
dengyihao 已提交
99
static int32_t resultrowComparDesc(const void* p1, const void* p2) { return resultrowComparAsc(p2, p1); }
100

101
void initGroupedResultInfo(SGroupResInfo* pGroupResInfo, SSHashObj* pHashmap, int32_t order) {
H
Haojun Liao 已提交
102 103 104 105
  if (pGroupResInfo->pRows != NULL) {
    taosArrayDestroy(pGroupResInfo->pRows);
  }

106 107 108 109
  // extract the result rows information from the hash map
  void* pData = NULL;
  pGroupResInfo->pRows = taosArrayInit(10, POINTER_BYTES);

110 111 112 113
  size_t  keyLen = 0;
  int32_t iter = 0;
  while ((pData = tSimpleHashIterate(pHashmap, pData, &iter)) != NULL) {
    void* key = tSimpleHashGetKey(pData, &keyLen);
114 115 116

    SResKeyPos* p = taosMemoryMalloc(keyLen + sizeof(SResultRowPosition));

dengyihao's avatar
dengyihao 已提交
117 118
    p->groupId = *(uint64_t*)key;
    p->pos = *(SResultRowPosition*)pData;
119
    memcpy(p->key, (char*)key + sizeof(uint64_t), keyLen - sizeof(uint64_t));
120 121 122
    taosArrayPush(pGroupResInfo->pRows, &p);
  }

123
  if (order == TSDB_ORDER_ASC || order == TSDB_ORDER_DESC) {
dengyihao's avatar
dengyihao 已提交
124
    __compar_fn_t fn = (order == TSDB_ORDER_ASC) ? resultrowComparAsc : resultrowComparDesc;
dengyihao's avatar
dengyihao 已提交
125
    int32_t       size = POINTER_BYTES;
H
Haojun Liao 已提交
126
    taosSort(pGroupResInfo->pRows->pData, taosArrayGetSize(pGroupResInfo->pRows), size, fn);
127 128
  }

H
Haojun Liao 已提交
129
  pGroupResInfo->index = 0;
H
Haojun Liao 已提交
130 131 132
  assert(pGroupResInfo->index <= getNumOfTotalRes(pGroupResInfo));
}

H
Haojun Liao 已提交
133 134
void initMultiResInfoFromArrayList(SGroupResInfo* pGroupResInfo, SArray* pArrayList) {
  if (pGroupResInfo->pRows != NULL) {
5
54liuyao 已提交
135
    taosArrayDestroyP(pGroupResInfo->pRows, taosMemoryFree);
H
Haojun Liao 已提交
136 137
  }

138
  pGroupResInfo->pRows = pArrayList;
H
Haojun Liao 已提交
139 140 141 142
  pGroupResInfo->index = 0;
  ASSERT(pGroupResInfo->index <= getNumOfTotalRes(pGroupResInfo));
}

143
bool hasRemainResults(SGroupResInfo* pGroupResInfo) {
H
Haojun Liao 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156
  if (pGroupResInfo->pRows == NULL) {
    return false;
  }

  return pGroupResInfo->index < taosArrayGetSize(pGroupResInfo->pRows);
}

int32_t getNumOfTotalRes(SGroupResInfo* pGroupResInfo) {
  assert(pGroupResInfo != NULL);
  if (pGroupResInfo->pRows == 0) {
    return 0;
  }

dengyihao's avatar
dengyihao 已提交
157
  return (int32_t)taosArrayGetSize(pGroupResInfo->pRows);
H
Haojun Liao 已提交
158 159
}

160
SArray* createSortInfo(SNodeList* pNodeList) {
161
  size_t numOfCols = 0;
162

163 164 165 166 167
  if (pNodeList != NULL) {
    numOfCols = LIST_LENGTH(pNodeList);
  } else {
    numOfCols = 0;
  }
168

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
  SArray* pList = taosArrayInit(numOfCols, sizeof(SBlockOrderInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return pList;
  }

  for (int32_t i = 0; i < numOfCols; ++i) {
    SOrderByExprNode* pSortKey = (SOrderByExprNode*)nodesListGetNode(pNodeList, i);
    SBlockOrderInfo   bi = {0};
    bi.order = (pSortKey->order == ORDER_ASC) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
    bi.nullFirst = (pSortKey->nullOrder == NULL_ORDER_FIRST);

    SColumnNode* pColNode = (SColumnNode*)pSortKey->pExpr;
    bi.slotId = pColNode->slotId;
    taosArrayPush(pList, &bi);
  }

  return pList;
}

SSDataBlock* createResDataBlock(SDataBlockDescNode* pNode) {
  int32_t numOfCols = LIST_LENGTH(pNode->pSlots);
H
Haojun Liao 已提交
191

192
  SSDataBlock* pBlock = createDataBlock();
H
Haojun Liao 已提交
193

194 195
  pBlock->info.blockId = pNode->dataBlockId;
  pBlock->info.type = STREAM_INVALID;
5
54liuyao 已提交
196
  pBlock->info.calWin = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
197
  pBlock->info.watermark = INT64_MIN;
H
Haojun Liao 已提交
198

199
  for (int32_t i = 0; i < numOfCols; ++i) {
M
Minglei Jin 已提交
200
    SSlotDescNode*  pDescNode = (SSlotDescNode*)nodesListGetNode(pNode->pSlots, i);
dengyihao's avatar
dengyihao 已提交
201 202
    SColumnInfoData idata =
        createColumnInfoData(pDescNode->dataType.type, pDescNode->dataType.bytes, pDescNode->slotId);
203 204 205
    idata.info.scale = pDescNode->dataType.scale;
    idata.info.precision = pDescNode->dataType.precision;

206
    blockDataAppendColInfo(pBlock, &idata);
H
Haojun Liao 已提交
207 208
  }

209 210 211
  return pBlock;
}

wmmhello's avatar
wmmhello 已提交
212 213
EDealRes doTranslateTagExpr(SNode** pNode, void* pContext) {
  SMetaReader* mr = (SMetaReader*)pContext;
dengyihao's avatar
dengyihao 已提交
214
  if (nodeType(*pNode) == QUERY_NODE_COLUMN) {
wmmhello's avatar
wmmhello 已提交
215 216
    SColumnNode* pSColumnNode = *(SColumnNode**)pNode;

dengyihao's avatar
dengyihao 已提交
217
    SValueNode* res = (SValueNode*)nodesMakeNode(QUERY_NODE_VALUE);
wmmhello's avatar
wmmhello 已提交
218 219 220 221 222 223 224 225 226
    if (NULL == res) {
      return DEAL_RES_ERROR;
    }

    res->translate = true;
    res->node.resType = pSColumnNode->node.resType;

    STagVal tagVal = {0};
    tagVal.cid = pSColumnNode->colId;
227
    const char* p = metaGetTableTagVal(mr->me.ctbEntry.pTags, pSColumnNode->node.resType.type, &tagVal);
wmmhello's avatar
wmmhello 已提交
228 229
    if (p == NULL) {
      res->node.resType.type = TSDB_DATA_TYPE_NULL;
dengyihao's avatar
dengyihao 已提交
230 231
    } else if (pSColumnNode->node.resType.type == TSDB_DATA_TYPE_JSON) {
      int32_t len = ((const STag*)p)->len;
wmmhello's avatar
wmmhello 已提交
232 233 234 235 236 237 238 239 240 241 242
      res->datum.p = taosMemoryCalloc(len + 1, 1);
      memcpy(res->datum.p, p, len);
    } else if (IS_VAR_DATA_TYPE(pSColumnNode->node.resType.type)) {
      res->datum.p = taosMemoryCalloc(tagVal.nData + VARSTR_HEADER_SIZE + 1, 1);
      memcpy(varDataVal(res->datum.p), tagVal.pData, tagVal.nData);
      varDataSetLen(res->datum.p, tagVal.nData);
    } else {
      nodesSetValueNodeValue(res, &(tagVal.i64));
    }
    nodesDestroyNode(*pNode);
    *pNode = (SNode*)res;
dengyihao's avatar
dengyihao 已提交
243 244 245 246
  } else if (nodeType(*pNode) == QUERY_NODE_FUNCTION) {
    SFunctionNode* pFuncNode = *(SFunctionNode**)pNode;
    if (pFuncNode->funcType == FUNCTION_TYPE_TBNAME) {
      SValueNode* res = (SValueNode*)nodesMakeNode(QUERY_NODE_VALUE);
wmmhello's avatar
wmmhello 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
      if (NULL == res) {
        return DEAL_RES_ERROR;
      }

      res->translate = true;
      res->node.resType = pFuncNode->node.resType;

      int32_t len = strlen(mr->me.name);
      res->datum.p = taosMemoryCalloc(len + VARSTR_HEADER_SIZE + 1, 1);
      memcpy(varDataVal(res->datum.p), mr->me.name, len);
      varDataSetLen(res->datum.p, len);
      nodesDestroyNode(*pNode);
      *pNode = (SNode*)res;
    }
  }

  return DEAL_RES_CONTINUE;
}

H
Haojun Liao 已提交
266
int32_t isQualifiedTable(STableKeyInfo* info, SNode* pTagCond, void* metaHandle, bool* pQualified) {
267
  int32_t     code = TSDB_CODE_SUCCESS;
dengyihao's avatar
dengyihao 已提交
268
  SMetaReader mr = {0};
269

wmmhello's avatar
wmmhello 已提交
270
  metaReaderInit(&mr, metaHandle, 0);
271 272 273
  code = metaGetTableEntryByUid(&mr, info->uid);
  if (TSDB_CODE_SUCCESS != code) {
    metaReaderClear(&mr);
M
Minglei Jin 已提交
274
    *pQualified = false;
275

M
Minglei Jin 已提交
276
    return TSDB_CODE_SUCCESS;
277
  }
wmmhello's avatar
wmmhello 已提交
278

dengyihao's avatar
dengyihao 已提交
279
  SNode* pTagCondTmp = nodesCloneNode(pTagCond);
wmmhello's avatar
wmmhello 已提交
280 281 282 283

  nodesRewriteExprPostOrder(&pTagCondTmp, doTranslateTagExpr, &mr);
  metaReaderClear(&mr);

284 285
  SNode* pNew = NULL;
  code = scalarCalculateConstants(pTagCondTmp, &pNew);
wmmhello's avatar
wmmhello 已提交
286
  if (TSDB_CODE_SUCCESS != code) {
wmmhello's avatar
wmmhello 已提交
287
    terrno = code;
wmmhello's avatar
wmmhello 已提交
288
    nodesDestroyNode(pTagCondTmp);
289 290 291
    *pQualified = false;

    return code;
wmmhello's avatar
wmmhello 已提交
292 293 294
  }

  ASSERT(nodeType(pNew) == QUERY_NODE_VALUE);
dengyihao's avatar
dengyihao 已提交
295
  SValueNode* pValue = (SValueNode*)pNew;
wmmhello's avatar
wmmhello 已提交
296 297

  ASSERT(pValue->node.resType.type == TSDB_DATA_TYPE_BOOL);
298 299
  *pQualified = pValue->datum.b;

wmmhello's avatar
wmmhello 已提交
300
  nodesDestroyNode(pNew);
301
  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
302 303
}

H
Haojun Liao 已提交
304 305
typedef struct tagFilterAssist {
  SHashObj* colHash;
wmmhello's avatar
wmmhello 已提交
306
  int32_t   index;
H
Haojun Liao 已提交
307 308
  SArray*   cInfoList;
} tagFilterAssist;
wmmhello's avatar
wmmhello 已提交
309

wmmhello's avatar
wmmhello 已提交
310 311 312 313
static EDealRes getColumn(SNode** pNode, void* pContext) {
  SColumnNode* pSColumnNode = NULL;
  if (QUERY_NODE_COLUMN == nodeType((*pNode))) {
    pSColumnNode = *(SColumnNode**)pNode;
H
Haojun Liao 已提交
314
  } else if (QUERY_NODE_FUNCTION == nodeType((*pNode))) {
wmmhello's avatar
wmmhello 已提交
315 316 317 318 319 320 321 322 323 324 325 326
    SFunctionNode* pFuncNode = *(SFunctionNode**)(pNode);
    if (pFuncNode->funcType == FUNCTION_TYPE_TBNAME) {
      pSColumnNode = (SColumnNode*)nodesMakeNode(QUERY_NODE_COLUMN);
      if (NULL == pSColumnNode) {
        return DEAL_RES_ERROR;
      }
      pSColumnNode->colId = -1;
      pSColumnNode->colType = COLUMN_TYPE_TBNAME;
      pSColumnNode->node.resType.type = TSDB_DATA_TYPE_VARCHAR;
      pSColumnNode->node.resType.bytes = TSDB_TABLE_FNAME_LEN - 1 + VARSTR_HEADER_SIZE;
      nodesDestroyNode(*pNode);
      *pNode = (SNode*)pSColumnNode;
H
Haojun Liao 已提交
327
    } else {
328
      return DEAL_RES_CONTINUE;
wmmhello's avatar
wmmhello 已提交
329
    }
H
Haojun Liao 已提交
330
  } else {
wmmhello's avatar
wmmhello 已提交
331
    return DEAL_RES_CONTINUE;
wmmhello's avatar
wmmhello 已提交
332
  }
wmmhello's avatar
wmmhello 已提交
333

H
Haojun Liao 已提交
334 335 336
  tagFilterAssist* pData = (tagFilterAssist*)pContext;
  void*            data = taosHashGet(pData->colHash, &pSColumnNode->colId, sizeof(pSColumnNode->colId));
  if (!data) {
wmmhello's avatar
wmmhello 已提交
337 338
    taosHashPut(pData->colHash, &pSColumnNode->colId, sizeof(pSColumnNode->colId), pNode, sizeof((*pNode)));
    pSColumnNode->slotId = pData->index++;
H
Haojun Liao 已提交
339 340 341
    SColumnInfo cInfo = {.colId = pSColumnNode->colId,
                         .type = pSColumnNode->node.resType.type,
                         .bytes = pSColumnNode->node.resType.bytes};
342 343 344
#if TAG_FILTER_DEBUG
    qDebug("tagfilter build column info, slotId:%d, colId:%d, type:%d", pSColumnNode->slotId, cInfo.colId, cInfo.type);
#endif
wmmhello's avatar
wmmhello 已提交
345
    taosArrayPush(pData->cInfoList, &cInfo);
H
Haojun Liao 已提交
346
  } else {
347 348
    SColumnNode* col = *(SColumnNode**)data;
    pSColumnNode->slotId = col->slotId;
wmmhello's avatar
wmmhello 已提交
349 350
  }

wmmhello's avatar
wmmhello 已提交
351 352 353 354 355 356 357 358 359 360
  return DEAL_RES_CONTINUE;
}

static int32_t createResultData(SDataType* pType, int32_t numOfRows, SScalarParam* pParam) {
  SColumnInfoData* pColumnData = taosMemoryCalloc(1, sizeof(SColumnInfoData));
  if (pColumnData == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

H
Haojun Liao 已提交
361 362 363
  pColumnData->info.type = pType->type;
  pColumnData->info.bytes = pType->bytes;
  pColumnData->info.scale = pType->scale;
wmmhello's avatar
wmmhello 已提交
364 365 366 367
  pColumnData->info.precision = pType->precision;

  int32_t code = colInfoDataEnsureCapacity(pColumnData, numOfRows);
  if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
368
    terrno = code;
wmmhello's avatar
wmmhello 已提交
369 370 371 372 373 374 375 376 377
    taosMemoryFree(pColumnData);
    return terrno;
  }

  pParam->columnData = pColumnData;
  pParam->colAlloced = true;
  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
378
static SColumnInfoData* getColInfoResult(void* metaHandle, int64_t suid, SArray* uidList, SNode* pTagCond) {
H
Haojun Liao 已提交
379 380
  int32_t      code = TSDB_CODE_SUCCESS;
  SArray*      pBlockList = NULL;
wmmhello's avatar
wmmhello 已提交
381
  SSDataBlock* pResBlock = NULL;
H
Haojun Liao 已提交
382
  SHashObj*    tags = NULL;
wmmhello's avatar
wmmhello 已提交
383 384 385
  SScalarParam output = {0};

  tagFilterAssist ctx = {0};
wmmhello's avatar
wmmhello 已提交
386

wmmhello's avatar
wmmhello 已提交
387
  ctx.colHash = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_SMALLINT), false, HASH_NO_LOCK);
H
Haojun Liao 已提交
388
  if (ctx.colHash == NULL) {
wmmhello's avatar
wmmhello 已提交
389 390 391 392 393
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }
  ctx.index = 0;
  ctx.cInfoList = taosArrayInit(4, sizeof(SColumnInfo));
H
Haojun Liao 已提交
394
  if (ctx.cInfoList == NULL) {
wmmhello's avatar
wmmhello 已提交
395 396 397
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }
wmmhello's avatar
wmmhello 已提交
398

H
Haojun Liao 已提交
399
  nodesRewriteExprPostOrder(&pTagCond, getColumn, (void*)&ctx);
wmmhello's avatar
wmmhello 已提交
400 401 402 403 404 405 406 407 408 409 410 411 412

  pResBlock = createDataBlock();
  if (pResBlock == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }

  for (int32_t i = 0; i < taosArrayGetSize(ctx.cInfoList); ++i) {
    SColumnInfoData colInfo = {{0}, 0};
    colInfo.info = *(SColumnInfo*)taosArrayGet(ctx.cInfoList, i);
    blockDataAppendColInfo(pResBlock, &colInfo);
  }

H
Haojun Liao 已提交
413
  //  int64_t stt = taosGetTimestampUs();
414
  tags = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
415

dengyihao's avatar
dengyihao 已提交
416
  int32_t filter = optimizeTbnameInCond(metaHandle, suid, uidList, pTagCond, tags);
dengyihao's avatar
dengyihao 已提交
417 418 419 420 421 422 423
  if (filter == -1) {
    code = metaGetTableTags(metaHandle, suid, uidList, tags);
    if (code != TSDB_CODE_SUCCESS) {
      qError("failed to get table tags from meta, reason:%s, suid:%" PRIu64, tstrerror(code), suid);
      terrno = code;
      goto end;
    }
wmmhello's avatar
wmmhello 已提交
424 425
  }

426
  int32_t rows = taosArrayGetSize(uidList);
H
Haojun Liao 已提交
427
  if (rows == 0) {
428 429
    goto end;
  }
H
Haojun Liao 已提交
430 431
  //  int64_t stt1 = taosGetTimestampUs();
  //  qDebug("generate tag meta rows:%d, cost:%ld us", rows, stt1-stt);
wmmhello's avatar
wmmhello 已提交
432

433 434 435 436 437
  code = blockDataEnsureCapacity(pResBlock, rows);
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    goto end;
  }
wmmhello's avatar
wmmhello 已提交
438

H
Haojun Liao 已提交
439
  //  int64_t st = taosGetTimestampUs();
wmmhello's avatar
wmmhello 已提交
440
  for (int32_t i = 0; i < rows; i++) {
wmmhello's avatar
wmmhello 已提交
441
    int64_t* uid = taosArrayGet(uidList, i);
H
Haojun Liao 已提交
442
    for (int32_t j = 0; j < taosArrayGetSize(pResBlock->pDataBlock); j++) {
wmmhello's avatar
wmmhello 已提交
443
      SColumnInfoData* pColInfo = (SColumnInfoData*)taosArrayGet(pResBlock->pDataBlock, j);
444

H
Haojun Liao 已提交
445
      if (pColInfo->info.colId == -1) {  // tbname
446 447 448
        char str[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
        metaGetTableNameByUid(metaHandle, *uid, str);
        colDataAppend(pColInfo, i, str, false);
449
#if TAG_FILTER_DEBUG
H
Haojun Liao 已提交
450
        qDebug("tagfilter uid:%ld, tbname:%s", *uid, str + 2);
451
#endif
H
Haojun Liao 已提交
452 453 454
      } else {
        void* tag = taosHashGet(tags, uid, sizeof(int64_t));
        ASSERT(tag);
wmmhello's avatar
wmmhello 已提交
455 456 457 458
        STagVal tagVal = {0};
        tagVal.cid = pColInfo->info.colId;
        const char* p = metaGetTableTagVal(tag, pColInfo->info.type, &tagVal);

H
Haojun Liao 已提交
459
        if (p == NULL || (pColInfo->info.type == TSDB_DATA_TYPE_JSON && ((STag*)p)->nTag == 0)) {
wmmhello's avatar
wmmhello 已提交
460
          colDataAppend(pColInfo, i, p, true);
wmmhello's avatar
wmmhello 已提交
461 462
        } else if (pColInfo->info.type == TSDB_DATA_TYPE_JSON) {
          colDataAppend(pColInfo, i, p, false);
wmmhello's avatar
wmmhello 已提交
463
        } else if (IS_VAR_DATA_TYPE(pColInfo->info.type)) {
H
Haojun Liao 已提交
464
          char* tmp = taosMemoryCalloc(tagVal.nData + VARSTR_HEADER_SIZE + 1, 1);
wmmhello's avatar
wmmhello 已提交
465 466 467
          varDataSetLen(tmp, tagVal.nData);
          memcpy(tmp + VARSTR_HEADER_SIZE, tagVal.pData, tagVal.nData);
          colDataAppend(pColInfo, i, tmp, false);
468
#if TAG_FILTER_DEBUG
H
Haojun Liao 已提交
469
          qDebug("tagfilter varch:%s", tmp + 2);
470
#endif
wmmhello's avatar
wmmhello 已提交
471 472 473
          taosMemoryFree(tmp);
        } else {
          colDataAppend(pColInfo, i, (const char*)&tagVal.i64, false);
474
#if TAG_FILTER_DEBUG
H
Haojun Liao 已提交
475
          if (pColInfo->info.type == TSDB_DATA_TYPE_INT) {
476
            qDebug("tagfilter int:%d", *(int*)(&tagVal.i64));
H
Haojun Liao 已提交
477 478
          } else if (pColInfo->info.type == TSDB_DATA_TYPE_DOUBLE) {
            qDebug("tagfilter double:%f", *(double*)(&tagVal.i64));
479 480
          }
#endif
wmmhello's avatar
wmmhello 已提交
481
        }
wmmhello's avatar
wmmhello 已提交
482 483 484
      }
    }
  }
wmmhello's avatar
wmmhello 已提交
485 486
  pResBlock->info.rows = rows;

H
Haojun Liao 已提交
487 488
  //  int64_t st1 = taosGetTimestampUs();
  //  qDebug("generate tag block rows:%d, cost:%ld us", rows, st1-st);
wmmhello's avatar
wmmhello 已提交
489 490 491 492 493 494 495

  pBlockList = taosArrayInit(2, POINTER_BYTES);
  taosArrayPush(pBlockList, &pResBlock);

  SDataType type = {.type = TSDB_DATA_TYPE_BOOL, .bytes = sizeof(bool)};
  code = createResultData(&type, rows, &output);
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
496 497
    terrno = code;
    qError("failed to create result, reason:%s", tstrerror(code));
wmmhello's avatar
wmmhello 已提交
498 499 500 501
    goto end;
  }

  code = scalarCalculate(pTagCond, pBlockList, &output);
H
Haojun Liao 已提交
502 503
  if (code != TSDB_CODE_SUCCESS) {
    qError("failed to calculate scalar, reason:%s", tstrerror(code));
wmmhello's avatar
wmmhello 已提交
504
    terrno = code;
H
Haojun Liao 已提交
505
    goto end;
wmmhello's avatar
wmmhello 已提交
506
  }
H
Haojun Liao 已提交
507 508
  //  int64_t st2 = taosGetTimestampUs();
  //  qDebug("calculate tag block rows:%d, cost:%ld us", rows, st2-st1);
wmmhello's avatar
wmmhello 已提交
509 510

end:
511
  taosHashCleanup(tags);
wmmhello's avatar
wmmhello 已提交
512 513 514 515 516 517 518
  taosHashCleanup(ctx.colHash);
  taosArrayDestroy(ctx.cInfoList);
  blockDataDestroy(pResBlock);
  taosArrayDestroy(pBlockList);
  return output.columnData;
}

H
Haojun Liao 已提交
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
static void releaseColInfoData(void* pCol) {
  if (pCol) {
    SColumnInfoData* col = (SColumnInfoData*)pCol;
    colDataDestroy(col);
    taosMemoryFree(col);
  }
}

int32_t getColInfoResultForGroupby(void* metaHandle, SNodeList* group, STableListInfo* pTableListInfo) {
  int32_t      code = TSDB_CODE_SUCCESS;
  SArray*      pBlockList = NULL;
  SSDataBlock* pResBlock = NULL;
  SHashObj*    tags = NULL;
  SArray*      uidList = NULL;
  void*        keyBuf = NULL;
  SArray*      groupData = NULL;

  int32_t rows = taosArrayGetSize(pTableListInfo->pTableList);
  if (rows == 0) {
    return TDB_CODE_SUCCESS;
  }

  tagFilterAssist ctx = {0};
  ctx.colHash = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_SMALLINT), false, HASH_NO_LOCK);
  if (ctx.colHash == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }
  ctx.index = 0;
  ctx.cInfoList = taosArrayInit(4, sizeof(SColumnInfo));
  if (ctx.cInfoList == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }

  SNode* pNode = NULL;
  FOREACH(pNode, group) {
    nodesRewriteExprPostOrder(&pNode, getColumn, (void*)&ctx);
    REPLACE_NODE(pNode);
  }

  pResBlock = createDataBlock();
  if (pResBlock == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }

  for (int32_t i = 0; i < taosArrayGetSize(ctx.cInfoList); ++i) {
    SColumnInfoData colInfo = {{0}, 0};
    colInfo.info = *(SColumnInfo*)taosArrayGet(ctx.cInfoList, i);
    blockDataAppendColInfo(pResBlock, &colInfo);
  }

  uidList = taosArrayInit(rows, sizeof(uint64_t));
  for (int32_t i = 0; i < rows; ++i) {
    STableKeyInfo* pkeyInfo = taosArrayGet(pTableListInfo->pTableList, i);
    taosArrayPush(uidList, &pkeyInfo->uid);
  }

  //  int64_t stt = taosGetTimestampUs();
  tags = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
  code = metaGetTableTags(metaHandle, pTableListInfo->suid, uidList, tags);
  if (code != TSDB_CODE_SUCCESS) {
    goto end;
  }

  //  int64_t stt1 = taosGetTimestampUs();
  //  qDebug("generate tag meta rows:%d, cost:%ld us", rows, stt1-stt);

  code = blockDataEnsureCapacity(pResBlock, rows);
  if (code != TSDB_CODE_SUCCESS) {
    goto end;
  }

  //  int64_t st = taosGetTimestampUs();
  for (int32_t i = 0; i < rows; i++) {
    int64_t* uid = taosArrayGet(uidList, i);
    for (int32_t j = 0; j < taosArrayGetSize(pResBlock->pDataBlock); j++) {
      SColumnInfoData* pColInfo = (SColumnInfoData*)taosArrayGet(pResBlock->pDataBlock, j);

      if (pColInfo->info.colId == -1) {  // tbname
        char str[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
        metaGetTableNameByUid(metaHandle, *uid, str);
        colDataAppend(pColInfo, i, str, false);
#if TAG_FILTER_DEBUG
        qDebug("tagfilter uid:%ld, tbname:%s", *uid, str + 2);
#endif
      } else {
        void* tag = taosHashGet(tags, uid, sizeof(int64_t));
        ASSERT(tag);
        STagVal tagVal = {0};
        tagVal.cid = pColInfo->info.colId;
        const char* p = metaGetTableTagVal(tag, pColInfo->info.type, &tagVal);

        if (p == NULL || (pColInfo->info.type == TSDB_DATA_TYPE_JSON && ((STag*)p)->nTag == 0)) {
          colDataAppend(pColInfo, i, p, true);
        } else if (pColInfo->info.type == TSDB_DATA_TYPE_JSON) {
          colDataAppend(pColInfo, i, p, false);
        } else if (IS_VAR_DATA_TYPE(pColInfo->info.type)) {
          char* tmp = taosMemoryCalloc(tagVal.nData + VARSTR_HEADER_SIZE + 1, 1);
          varDataSetLen(tmp, tagVal.nData);
          memcpy(tmp + VARSTR_HEADER_SIZE, tagVal.pData, tagVal.nData);
          colDataAppend(pColInfo, i, tmp, false);
#if TAG_FILTER_DEBUG
          qDebug("tagfilter varch:%s", tmp + 2);
#endif
          taosMemoryFree(tmp);
        } else {
          colDataAppend(pColInfo, i, (const char*)&tagVal.i64, false);
#if TAG_FILTER_DEBUG
          if (pColInfo->info.type == TSDB_DATA_TYPE_INT) {
            qDebug("tagfilter int:%d", *(int*)(&tagVal.i64));
          } else if (pColInfo->info.type == TSDB_DATA_TYPE_DOUBLE) {
            qDebug("tagfilter double:%f", *(double*)(&tagVal.i64));
          }
#endif
        }
      }
    }
  }
  pResBlock->info.rows = rows;

  //  int64_t st1 = taosGetTimestampUs();
  //  qDebug("generate tag block rows:%d, cost:%ld us", rows, st1-st);

  pBlockList = taosArrayInit(2, POINTER_BYTES);
  taosArrayPush(pBlockList, &pResBlock);

  groupData = taosArrayInit(2, POINTER_BYTES);
  FOREACH(pNode, group) {
    SScalarParam output = {0};

    switch (nodeType(pNode)) {
      case QUERY_NODE_VALUE:
        break;
      case QUERY_NODE_COLUMN:
      case QUERY_NODE_OPERATOR:
      case QUERY_NODE_FUNCTION: {
        SExprNode* expNode = (SExprNode*)pNode;
        code = createResultData(&expNode->resType, rows, &output);
        if (code != TSDB_CODE_SUCCESS) {
          goto end;
        }
        break;
      }
      default:
        code = TSDB_CODE_OPS_NOT_SUPPORT;
        goto end;
    }
    if (nodeType(pNode) == QUERY_NODE_COLUMN) {
      SColumnNode*     pSColumnNode = (SColumnNode*)pNode;
      SColumnInfoData* pColInfo = (SColumnInfoData*)taosArrayGet(pResBlock->pDataBlock, pSColumnNode->slotId);
      code = colDataAssign(output.columnData, pColInfo, rows, NULL);
    } else if (nodeType(pNode) == QUERY_NODE_VALUE) {
      continue;
    } else {
      code = scalarCalculate(pNode, pBlockList, &output);
    }
    if (code != TSDB_CODE_SUCCESS) {
      releaseColInfoData(output.columnData);
      goto end;
    }
    taosArrayPush(groupData, &output.columnData);
  }

  int32_t keyLen = 0;
  SNode*  node;
  FOREACH(node, group) {
    SExprNode* pExpr = (SExprNode*)node;
    keyLen += pExpr->resType.bytes;
  }

  int32_t nullFlagSize = sizeof(int8_t) * LIST_LENGTH(group);
  keyLen += nullFlagSize;

  keyBuf = taosMemoryCalloc(1, keyLen);
  if (keyBuf == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }
  for (int i = 0; i < rows; i++) {
    STableKeyInfo* info = taosArrayGet(pTableListInfo->pTableList, i);

    char* isNull = (char*)keyBuf;
    char* pStart = (char*)keyBuf + sizeof(int8_t) * LIST_LENGTH(group);
    for (int j = 0; j < taosArrayGetSize(groupData); j++) {
      SColumnInfoData* pValue = (SColumnInfoData*)taosArrayGetP(groupData, j);

      if (colDataIsNull_s(pValue, i)) {
        isNull[j] = 1;
      } else {
        isNull[j] = 0;
        char* data = colDataGetData(pValue, i);
        if (pValue->info.type == TSDB_DATA_TYPE_JSON) {
          if (tTagIsJson(data)) {
            code = TSDB_CODE_QRY_JSON_IN_GROUP_ERROR;
            goto end;
          }
          if (tTagIsJsonNull(data)) {
            isNull[j] = 1;
            continue;
          }
          int32_t len = getJsonValueLen(data);
          memcpy(pStart, data, len);
          pStart += len;
        } else if (IS_VAR_DATA_TYPE(pValue->info.type)) {
          memcpy(pStart, data, varDataTLen(data));
          pStart += varDataTLen(data);
        } else {
          memcpy(pStart, data, pValue->info.bytes);
          pStart += pValue->info.bytes;
        }
      }
    }

    int32_t len = (int32_t)(pStart - (char*)keyBuf);
    info->groupId = calcGroupId(keyBuf, len);
    taosHashPut(pTableListInfo->map, &(info->uid), sizeof(uint64_t), &info->groupId, sizeof(uint64_t));
  }

  //  int64_t st2 = taosGetTimestampUs();
  //  qDebug("calculate tag block rows:%d, cost:%ld us", rows, st2-st1);

end:
  taosMemoryFreeClear(keyBuf);
  taosHashCleanup(tags);
  taosHashCleanup(ctx.colHash);
  taosArrayDestroy(ctx.cInfoList);
  blockDataDestroy(pResBlock);
  taosArrayDestroy(pBlockList);
  taosArrayDestroy(uidList);
  taosArrayDestroyP(groupData, releaseColInfoData);
  return code;
}

dengyihao's avatar
dengyihao 已提交
754
static int tableUidCompare(const void* a, const void* b) {
dengyihao's avatar
dengyihao 已提交
755 756
  int64_t u1 = *(uint64_t*)a;
  int64_t u2 = *(uint64_t*)b;
dengyihao's avatar
dengyihao 已提交
757 758 759 760 761
  if (u1 == u2) {
    return 0;
  }
  return u1 < u2 ? -1 : 1;
}
dengyihao's avatar
dengyihao 已提交
762 763
static int32_t optimizeTbnameInCond(void* metaHandle, int64_t suid, SArray* list, SNode* cond, SHashObj* tags) {
  int32_t ret = -1;
dengyihao's avatar
dengyihao 已提交
764
  if (nodeType(cond) == QUERY_NODE_OPERATOR) {
dengyihao's avatar
dengyihao 已提交
765 766 767 768 769
    ret = optimizeTbnameInCondImpl(metaHandle, suid, list, cond);
    if (ret != -1) {
      metaGetTableTagsByUids(metaHandle, suid, list, tags);
      removeInvalidTable(list, tags);
    }
dengyihao's avatar
dengyihao 已提交
770 771 772
  }

  if (nodeType(cond) != QUERY_NODE_LOGIC_CONDITION || ((SLogicConditionNode*)cond)->condType != LOGIC_COND_TYPE_AND) {
dengyihao's avatar
dengyihao 已提交
773
    return ret;
dengyihao's avatar
dengyihao 已提交
774 775
  }

dengyihao's avatar
dengyihao 已提交
776
  bool                 hasTbnameCond = false;
dengyihao's avatar
dengyihao 已提交
777
  SLogicConditionNode* pNode = (SLogicConditionNode*)cond;
dengyihao's avatar
dengyihao 已提交
778
  SNodeList*           pList = (SNodeList*)pNode->pParameterList;
dengyihao's avatar
dengyihao 已提交
779

dengyihao's avatar
dengyihao 已提交
780
  int32_t len = LIST_LENGTH(pList);
dengyihao's avatar
dengyihao 已提交
781
  if (len <= 0) return ret;
dengyihao's avatar
dengyihao 已提交
782

dengyihao's avatar
dengyihao 已提交
783
  SListCell* cell = pList->pHead;
dengyihao's avatar
dengyihao 已提交
784
  for (int i = 0; i < len; i++) {
dengyihao's avatar
dengyihao 已提交
785 786
    if (cell == NULL) break;
    if (optimizeTbnameInCondImpl(metaHandle, suid, list, cell->pNode) == 0) {
dengyihao's avatar
dengyihao 已提交
787
      hasTbnameCond = true;
dengyihao's avatar
dengyihao 已提交
788
      break;
dengyihao's avatar
dengyihao 已提交
789 790 791 792 793 794
    }
    cell = cell->pNext;
  }
  taosArraySort(list, tableUidCompare);
  taosArrayRemoveDuplicate(list, tableUidCompare, NULL);

dengyihao's avatar
dengyihao 已提交
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
  if (hasTbnameCond) {
    ret = metaGetTableTagsByUids(metaHandle, suid, list, tags);
    removeInvalidTable(list, tags);
  }
  return ret;
}

/*
 * handle invalid uid
 */
static int32_t removeInvalidTable(SArray* uids, SHashObj* tags) {
  if (taosArrayGetSize(uids) <= 0) return 0;

  SArray* validUid = taosArrayInit(taosArrayGetSize(uids), sizeof(int64_t));

  for (int32_t i = 0; i < taosArrayGetSize(uids); i++) {
    int64_t* uid = taosArrayGet(uids, i);
    if (taosHashGet(tags, uid, sizeof(int64_t)) != NULL) {
      taosArrayPush(validUid, uid);
    }
  }
  taosArraySwap(uids, validUid);
  taosArrayDestroy(validUid);
  return 0;
dengyihao's avatar
dengyihao 已提交
819 820
}
static int32_t optimizeTbnameInCondImpl(void* metaHandle, int64_t suid, SArray* list, SNode* pTagCond) {
dengyihao's avatar
dengyihao 已提交
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
  if (nodeType(pTagCond) != QUERY_NODE_OPERATOR) {
    return -1;
  }
  SOperatorNode* pNode = (SOperatorNode*)pTagCond;
  if (pNode->opType != OP_TYPE_IN) {
    return -1;
  }
  if ((pNode->pLeft != NULL && nodeType(pNode->pLeft) == QUERY_NODE_COLUMN &&
       ((SColumnNode*)pNode->pLeft)->colType == COLUMN_TYPE_TBNAME) &&
      (pNode->pRight != NULL && nodeType(pNode->pRight) == QUERY_NODE_NODE_LIST)) {
    SNodeListNode* pList = (SNodeListNode*)pNode->pRight;

    int32_t len = LIST_LENGTH(pList->pNodeList);
    if (len <= 0) return -1;

    SListCell* cell = pList->pNodeList->pHead;

    SArray* pTbList = taosArrayInit(len, sizeof(void*));
    for (int i = 0; i < pList->pNodeList->length; i++) {
      SValueNode* valueNode = (SValueNode*)cell->pNode;
      if (!IS_VAR_DATA_TYPE(valueNode->node.resType.type)) {
        taosArrayDestroy(pTbList);
        return -1;
      }
      char* name = varDataVal(valueNode->datum.p);
      taosArrayPush(pTbList, &name);
      cell = cell->pNext;
    }

    for (int i = 0; i < taosArrayGetSize(pTbList); i++) {
      char*    name = taosArrayGetP(pTbList, i);
      uint64_t uid = 0;
      if (metaGetTableUidByName(metaHandle, name, &uid) == 0) {
dengyihao's avatar
dengyihao 已提交
854 855 856 857 858 859 860
        ETableType tbType = TSDB_TABLE_MAX;
        if (metaGetTableTypeByName(metaHandle, name, &tbType) == 0 && tbType == TSDB_CHILD_TABLE) {
          taosArrayPush(list, &uid);
        } else {
          taosArrayDestroy(pTbList);
          return -1;
        }
dengyihao's avatar
dengyihao 已提交
861
      } else {
dengyihao's avatar
dengyihao 已提交
862
        qWarn("failed to get tableIds from by table name: %s, reason: %s", name, tstrerror(terrno));
dengyihao's avatar
dengyihao 已提交
863 864 865 866
        terrno = 0;
      }
    }
    taosArrayDestroy(pTbList);
dengyihao's avatar
dengyihao 已提交
867
    return 0;
dengyihao's avatar
dengyihao 已提交
868
  }
dengyihao's avatar
dengyihao 已提交
869
  return -1;
dengyihao's avatar
dengyihao 已提交
870
}
871 872
int32_t getTableList(void* metaHandle, void* pVnode, SScanPhysiNode* pScanNode, SNode* pTagCond, SNode* pTagIndexCond,
                     STableListInfo* pListInfo) {
873
  int32_t code = TSDB_CODE_SUCCESS;
874

875
  pListInfo->pTableList = taosArrayInit(8, sizeof(STableKeyInfo));
876 877 878
  if (pListInfo->pTableList == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
879 880

  uint64_t tableUid = pScanNode->uid;
D
dapan1121 已提交
881
  pListInfo->suid = pScanNode->suid;
882
  SArray* res = taosArrayInit(8, sizeof(uint64_t));
dengyihao's avatar
dengyihao 已提交
883

884
  if (pScanNode->tableType == TSDB_SUPER_TABLE) {
wmmhello's avatar
wmmhello 已提交
885
    if (pTagIndexCond) {
886 887 888
      SIndexMetaArg metaArg = {
          .metaEx = metaHandle, .idx = tsdbGetIdx(metaHandle), .ivtIdx = tsdbGetIvtIdx(metaHandle), .suid = tableUid};

H
Haojun Liao 已提交
889
      //      int64_t stt = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
890 891 892
      SIdxFltStatus status = SFLT_NOT_INDEX;
      code = doFilterTag(pTagIndexCond, &metaArg, res, &status);
      if (code != 0 || status == SFLT_NOT_INDEX) {
wmmhello's avatar
wmmhello 已提交
893
        qError("failed to get tableIds from index, reason:%s, suid:%" PRIu64, tstrerror(code), tableUid);
894
        code = TDB_CODE_SUCCESS;
895
      }
H
Haojun Liao 已提交
896
    } else if (!pTagCond) {
wmmhello's avatar
wmmhello 已提交
897
      vnodeGetCtbIdList(pVnode, pScanNode->suid, res);
wmmhello's avatar
wmmhello 已提交
898
    }
L
Liu Jicong 已提交
899
  } else {  // Create one table group.
H
Haojun Liao 已提交
900
    if (metaIsTableExist(metaHandle, tableUid)) {
901 902
      taosArrayPush(res, &tableUid);
    }
H
Haojun Liao 已提交
903
  }
904

905
  if (pTagCond) {
H
Haojun Liao 已提交
906
    terrno = TDB_CODE_SUCCESS;
907
    SColumnInfoData* pColInfoData = getColInfoResult(metaHandle, pListInfo->suid, res, pTagCond);
H
Haojun Liao 已提交
908
    if (terrno != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
909
      colDataDestroy(pColInfoData);
wmmhello's avatar
wmmhello 已提交
910
      taosMemoryFreeClear(pColInfoData);
911
      taosArrayDestroy(res);
H
Haojun Liao 已提交
912
      qError("failed to getColInfoResult, code: %s", tstrerror(terrno));
wmmhello's avatar
wmmhello 已提交
913 914 915
      return terrno;
    }

wmmhello's avatar
wmmhello 已提交
916
    int32_t i = 0;
wmmhello's avatar
wmmhello 已提交
917 918 919 920
    int32_t j = 0;
    int32_t len = taosArrayGetSize(res);
    while (i < taosArrayGetSize(res) && j < len && pColInfoData) {
      void* var = POINTER_SHIFT(pColInfoData->pData, j * pColInfoData->info.bytes);
921

wmmhello's avatar
wmmhello 已提交
922
      int64_t* uid = taosArrayGet(res, i);
923
      qDebug("tagfilter get uid:%" PRId64 ", res:%d", *uid, *(bool*)var);
wmmhello's avatar
wmmhello 已提交
924
      if (*(bool*)var == false) {
925
        taosArrayRemove(res, i);
wmmhello's avatar
wmmhello 已提交
926
        j++;
wmmhello's avatar
wmmhello 已提交
927 928 929
        continue;
      }
      i++;
wmmhello's avatar
wmmhello 已提交
930
      j++;
wmmhello's avatar
wmmhello 已提交
931
    }
wmmhello's avatar
wmmhello 已提交
932
    colDataDestroy(pColInfoData);
wmmhello's avatar
wmmhello 已提交
933
    taosMemoryFreeClear(pColInfoData);
wmmhello's avatar
wmmhello 已提交
934 935
  }

H
Haojun Liao 已提交
936 937
  size_t numOfTables = taosArrayGetSize(res);
  for (int i = 0; i < numOfTables; i++) {
938
    STableKeyInfo info = {.uid = *(uint64_t*)taosArrayGet(res, i), .groupId = 0};
dengyihao's avatar
dengyihao 已提交
939
    void*         p = taosArrayPush(pListInfo->pTableList, &info);
H
Haojun Liao 已提交
940 941 942 943 944
    if (p == NULL) {
      taosArrayDestroy(res);
      return TSDB_CODE_OUT_OF_MEMORY;
    }

945
    qDebug("tagfilter get uid:%" PRId64 "", info.uid);
946 947 948 949
  }

  taosArrayDestroy(res);

wmmhello's avatar
wmmhello 已提交
950
  pListInfo->pGroupList = taosArrayInit(4, POINTER_BYTES);
951
  if (pListInfo->pGroupList == NULL) {
952 953
    return TSDB_CODE_OUT_OF_MEMORY;
  }
wmmhello's avatar
wmmhello 已提交
954

dengyihao's avatar
dengyihao 已提交
955
  // put into list as default group, remove it if grouping sorting is required later
wmmhello's avatar
wmmhello 已提交
956
  taosArrayPush(pListInfo->pGroupList, &pListInfo->pTableList);
957 958
  return code;
}
H
Haojun Liao 已提交
959

960 961 962 963 964 965 966 967 968 969 970 971 972
size_t getTableTagsBufLen(const SNodeList* pGroups) {
  size_t keyLen = 0;

  SNode* node;
  FOREACH(node, pGroups) {
    SExprNode* pExpr = (SExprNode*)node;
    keyLen += pExpr->resType.bytes;
  }

  keyLen += sizeof(int8_t) * LIST_LENGTH(pGroups);
  return keyLen;
}

H
Haojun Liao 已提交
973
int32_t getGroupIdFromTagsVal(void* pMeta, uint64_t uid, SNodeList* pGroupNode, char* keyBuf, uint64_t* pGroupId) {
M
Minglei Jin 已提交
974
  SMetaReader mr = {0};
975
  metaReaderInit(&mr, pMeta, 0);
H
Haojun Liao 已提交
976
  if (metaGetTableEntryByUid(&mr, uid) != 0) {  // table not exist
977 978 979
    metaReaderClear(&mr);
    return TSDB_CODE_PAR_TABLE_NOT_EXIST;
  }
980 981 982 983 984

  SNodeList* groupNew = nodesCloneList(pGroupNode);

  nodesRewriteExprsPostOrder(groupNew, doTranslateTagExpr, &mr);
  char* isNull = (char*)keyBuf;
M
Minglei Jin 已提交
985
  char* pStart = (char*)keyBuf + sizeof(int8_t) * LIST_LENGTH(pGroupNode);
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030

  SNode*  pNode;
  int32_t index = 0;
  FOREACH(pNode, groupNew) {
    SNode*  pNew = NULL;
    int32_t code = scalarCalculateConstants(pNode, &pNew);
    if (TSDB_CODE_SUCCESS == code) {
      REPLACE_NODE(pNew);
    } else {
      taosMemoryFree(keyBuf);
      nodesDestroyList(groupNew);
      metaReaderClear(&mr);
      return code;
    }

    ASSERT(nodeType(pNew) == QUERY_NODE_VALUE);
    SValueNode* pValue = (SValueNode*)pNew;

    if (pValue->node.resType.type == TSDB_DATA_TYPE_NULL || pValue->isNull) {
      isNull[index++] = 1;
      continue;
    } else {
      isNull[index++] = 0;
      char* data = nodesGetValueFromNode(pValue);
      if (pValue->node.resType.type == TSDB_DATA_TYPE_JSON) {
        if (tTagIsJson(data)) {
          terrno = TSDB_CODE_QRY_JSON_IN_GROUP_ERROR;
          taosMemoryFree(keyBuf);
          nodesDestroyList(groupNew);
          metaReaderClear(&mr);
          return terrno;
        }
        int32_t len = getJsonValueLen(data);
        memcpy(pStart, data, len);
        pStart += len;
      } else if (IS_VAR_DATA_TYPE(pValue->node.resType.type)) {
        memcpy(pStart, data, varDataTLen(data));
        pStart += varDataTLen(data);
      } else {
        memcpy(pStart, data, pValue->node.resType.bytes);
        pStart += pValue->node.resType.bytes;
      }
    }
  }

M
Minglei Jin 已提交
1031
  int32_t len = (int32_t)(pStart - (char*)keyBuf);
1032 1033 1034 1035 1036 1037 1038
  *pGroupId = calcGroupId(keyBuf, len);

  nodesDestroyList(groupNew);
  metaReaderClear(&mr);
  return TSDB_CODE_SUCCESS;
}

1039
SArray* extractPartitionColInfo(SNodeList* pNodeList) {
dengyihao's avatar
dengyihao 已提交
1040
  if (!pNodeList) {
1041 1042
    return NULL;
  }
H
Haojun Liao 已提交
1043

1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
  size_t  numOfCols = LIST_LENGTH(pNodeList);
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnNode* pColNode = (SColumnNode*)nodesListGetNode(pNodeList, i);

    // todo extract method
    SColumn c = {0};
    c.slotId = pColNode->slotId;
    c.colId = pColNode->colId;
    c.type = pColNode->node.resType.type;
    c.bytes = pColNode->node.resType.bytes;
    c.precision = pColNode->node.resType.precision;
    c.scale = pColNode->node.resType.scale;

    taosArrayPush(pList, &c);
  }
H
Haojun Liao 已提交
1065

1066
  return pList;
H
Haojun Liao 已提交
1067 1068
}

H
Haojun Liao 已提交
1069 1070 1071 1072 1073 1074 1075
int32_t extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols,
                            int32_t type, SColMatchInfo* pMatchInfo) {
  size_t numOfCols = LIST_LENGTH(pNodeList);
  int32_t code = 0;

  pMatchInfo->matchType = type;

1076 1077
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColMatchInfo));
  if (pList == NULL) {
H
Haojun Liao 已提交
1078 1079
    code = TSDB_CODE_OUT_OF_MEMORY;
    return code;
1080 1081 1082 1083
  }

  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
1084 1085 1086
    if (nodeType(pNode->pExpr) == QUERY_NODE_COLUMN) {
      SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

H
Haojun Liao 已提交
1087
      SColMatchItem c = {.needOutput = true};
1088 1089
      c.colId = pColNode->colId;
      c.srcSlotId = pColNode->slotId;
H
Haojun Liao 已提交
1090
      c.dstSlotId = pNode->slotId;
1091 1092
      taosArrayPush(pList, &c);
    }
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
  }

  *numOfOutputCols = 0;
  int32_t num = LIST_LENGTH(pOutputNodeList->pSlots);
  for (int32_t i = 0; i < num; ++i) {
    SSlotDescNode* pNode = (SSlotDescNode*)nodesListGetNode(pOutputNodeList->pSlots, i);

    // todo: add reserve flag check
    // it is a column reserved for the arithmetic expression calculation
    if (pNode->slotId >= numOfCols) {
      (*numOfOutputCols) += 1;
      continue;
    }

H
Haojun Liao 已提交
1107
    SColMatchItem* info = NULL;
1108 1109
    for (int32_t j = 0; j < taosArrayGetSize(pList); ++j) {
      info = taosArrayGet(pList, j);
H
Haojun Liao 已提交
1110
      if (info->dstSlotId == pNode->slotId) {
1111 1112 1113
        break;
      }
    }
1114

1115 1116
    if (pNode->output) {
      (*numOfOutputCols) += 1;
H
Haojun Liao 已提交
1117 1118
    } else if (info != NULL) {
      // select distinct tbname from stb where tbname='abc';
H
Haojun Liao 已提交
1119
      info->needOutput = false;
1120
    }
1121
  }
1122

H
Haojun Liao 已提交
1123
  pMatchInfo->pList = pList;
H
Haojun Liao 已提交
1124
  return code;
1125 1126
}

1127 1128 1129 1130 1131 1132 1133 1134
static SResSchema createResSchema(int32_t type, int32_t bytes, int32_t slotId, int32_t scale, int32_t precision,
                                  const char* name) {
  SResSchema s = {0};
  s.scale = scale;
  s.type = type;
  s.bytes = bytes;
  s.slotId = slotId;
  s.precision = precision;
H
Haojun Liao 已提交
1135
  tstrncpy(s.name, name, tListLen(s.name));
1136 1137 1138

  return s;
}
1139

H
Haojun Liao 已提交
1140
static SColumn* createColumn(int32_t blockId, int32_t slotId, int32_t colId, SDataType* pType, EColumnType colType) {
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
  SColumn* pCol = taosMemoryCalloc(1, sizeof(SColumn));
  if (pCol == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  pCol->slotId = slotId;
  pCol->colId = colId;
  pCol->bytes = pType->bytes;
  pCol->type = pType->type;
  pCol->scale = pType->scale;
  pCol->precision = pType->precision;
  pCol->dataBlockId = blockId;
H
Haojun Liao 已提交
1154
  pCol->colType = colType;
1155 1156 1157
  return pCol;
}

1158
void createExprFromOneNode(SExprInfo* pExp, SNode* pNode, int16_t slotId) {
1159 1160 1161 1162
  pExp->pExpr = taosMemoryCalloc(1, sizeof(tExprNode));
  pExp->pExpr->_function.num = 1;
  pExp->pExpr->_function.functionId = -1;

1163
  int32_t type = nodeType(pNode);
1164 1165 1166
  // it is a project query, or group by column
  if (type == QUERY_NODE_COLUMN) {
    pExp->pExpr->nodeType = QUERY_NODE_COLUMN;
1167
    SColumnNode* pColNode = (SColumnNode*)pNode;
1168 1169 1170 1171 1172

    pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
    pExp->base.numOfParams = 1;

    SDataType* pType = &pColNode->node.resType;
1173 1174
    pExp->base.resSchema =
        createResSchema(pType->type, pType->bytes, slotId, pType->scale, pType->precision, pColNode->colName);
1175 1176 1177 1178 1179
    pExp->base.pParam[0].pCol =
        createColumn(pColNode->dataBlockId, pColNode->slotId, pColNode->colId, pType, pColNode->colType);
    pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
  } else if (type == QUERY_NODE_VALUE) {
    pExp->pExpr->nodeType = QUERY_NODE_VALUE;
1180
    SValueNode* pValNode = (SValueNode*)pNode;
1181 1182 1183 1184 1185

    pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
    pExp->base.numOfParams = 1;

    SDataType* pType = &pValNode->node.resType;
1186 1187
    pExp->base.resSchema =
        createResSchema(pType->type, pType->bytes, slotId, pType->scale, pType->precision, pValNode->node.aliasName);
1188 1189 1190 1191
    pExp->base.pParam[0].type = FUNC_PARAM_TYPE_VALUE;
    nodesValueNodeToVariant(pValNode, &pExp->base.pParam[0].param);
  } else if (type == QUERY_NODE_FUNCTION) {
    pExp->pExpr->nodeType = QUERY_NODE_FUNCTION;
1192
    SFunctionNode* pFuncNode = (SFunctionNode*)pNode;
1193 1194

    SDataType* pType = &pFuncNode->node.resType;
1195 1196
    pExp->base.resSchema =
        createResSchema(pType->type, pType->bytes, slotId, pType->scale, pType->precision, pFuncNode->node.aliasName);
1197

H
Haojun Liao 已提交
1198 1199 1200 1201 1202 1203
    tExprNode* pExprNode = pExp->pExpr;

    pExprNode->_function.functionId = pFuncNode->funcId;
    pExprNode->_function.pFunctNode = pFuncNode;

    tstrncpy(pExprNode->_function.functionName, pFuncNode->functionName, tListLen(pExprNode->_function.functionName));
1204 1205 1206

#if 1
    // todo refactor: add the parameter for tbname function
H
Haojun Liao 已提交
1207
    const char* name = "tbname";
dengyihao's avatar
dengyihao 已提交
1208
    int32_t     len = strlen(name);
H
Haojun Liao 已提交
1209 1210 1211

    if (!pFuncNode->pParameterList && (memcmp(pExprNode->_function.functionName, name, len) == 0) &&
        pExprNode->_function.functionName[len] == 0) {
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
      pFuncNode->pParameterList = nodesMakeList();
      ASSERT(LIST_LENGTH(pFuncNode->pParameterList) == 0);
      SValueNode* res = (SValueNode*)nodesMakeNode(QUERY_NODE_VALUE);
      if (NULL == res) {  // todo handle error
      } else {
        res->node.resType = (SDataType){.bytes = sizeof(int64_t), .type = TSDB_DATA_TYPE_BIGINT};
        nodesListAppend(pFuncNode->pParameterList, (SNode*)res);
      }
    }
#endif

    int32_t numOfParam = LIST_LENGTH(pFuncNode->pParameterList);

    pExp->base.pParam = taosMemoryCalloc(numOfParam, sizeof(SFunctParam));
    pExp->base.numOfParams = numOfParam;

    for (int32_t j = 0; j < numOfParam; ++j) {
      SNode* p1 = nodesListGetNode(pFuncNode->pParameterList, j);
      if (p1->type == QUERY_NODE_COLUMN) {
        SColumnNode* pcn = (SColumnNode*)p1;

        pExp->base.pParam[j].type = FUNC_PARAM_TYPE_COLUMN;
        pExp->base.pParam[j].pCol =
            createColumn(pcn->dataBlockId, pcn->slotId, pcn->colId, &pcn->node.resType, pcn->colType);
      } else if (p1->type == QUERY_NODE_VALUE) {
        SValueNode* pvn = (SValueNode*)p1;
        pExp->base.pParam[j].type = FUNC_PARAM_TYPE_VALUE;
        nodesValueNodeToVariant(pvn, &pExp->base.pParam[j].param);
      }
    }
  } else if (type == QUERY_NODE_OPERATOR) {
    pExp->pExpr->nodeType = QUERY_NODE_OPERATOR;
1244
    SOperatorNode* pOpNode = (SOperatorNode*)pNode;
1245 1246 1247 1248

    pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
    pExp->base.numOfParams = 1;

1249 1250 1251 1252
    SDataType* pType = &pOpNode->node.resType;
    pExp->base.resSchema =
        createResSchema(pType->type, pType->bytes, slotId, pType->scale, pType->precision, pOpNode->node.aliasName);
    pExp->pExpr->_optrRoot.pRootNode = pNode;
D
dapan1121 已提交
1253 1254
  } else if (type == QUERY_NODE_CASE_WHEN) {
    pExp->pExpr->nodeType = QUERY_NODE_OPERATOR;
D
dapan1121 已提交
1255
    SCaseWhenNode* pCaseNode = (SCaseWhenNode*)pNode;
dengyihao's avatar
dengyihao 已提交
1256

D
dapan1121 已提交
1257 1258
    pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
    pExp->base.numOfParams = 1;
dengyihao's avatar
dengyihao 已提交
1259

D
dapan1121 已提交
1260
    SDataType* pType = &pCaseNode->node.resType;
dengyihao's avatar
dengyihao 已提交
1261 1262
    pExp->base.resSchema =
        createResSchema(pType->type, pType->bytes, slotId, pType->scale, pType->precision, pCaseNode->node.aliasName);
D
dapan1121 已提交
1263
    pExp->pExpr->_optrRoot.pRootNode = pNode;
1264 1265 1266 1267 1268
  } else {
    ASSERT(0);
  }
}

1269 1270 1271 1272
void createExprFromTargetNode(SExprInfo* pExp, STargetNode* pTargetNode) {
  createExprFromOneNode(pExp, pTargetNode->pExpr, pTargetNode->slotId);
}

1273 1274 1275 1276 1277 1278 1279 1280
SExprInfo* createExprInfo(SNodeList* pNodeList, SNodeList* pGroupKeys, int32_t* numOfExprs) {
  int32_t numOfFuncs = LIST_LENGTH(pNodeList);
  int32_t numOfGroupKeys = 0;
  if (pGroupKeys != NULL) {
    numOfGroupKeys = LIST_LENGTH(pGroupKeys);
  }

  *numOfExprs = numOfFuncs + numOfGroupKeys;
1281 1282 1283 1284
  if (*numOfExprs == 0) {
    return NULL;
  }

1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
  SExprInfo* pExprs = taosMemoryCalloc(*numOfExprs, sizeof(SExprInfo));

  for (int32_t i = 0; i < (*numOfExprs); ++i) {
    STargetNode* pTargetNode = NULL;
    if (i < numOfFuncs) {
      pTargetNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    } else {
      pTargetNode = (STargetNode*)nodesListGetNode(pGroupKeys, i - numOfFuncs);
    }

    SExprInfo* pExp = &pExprs[i];
1296
    createExprFromTargetNode(pExp, pTargetNode);
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
  }

  return pExprs;
}

// set the output buffer for the selectivity + tag query
static int32_t setSelectValueColumnInfo(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  int32_t num = 0;

  SqlFunctionCtx*  p = NULL;
  SqlFunctionCtx** pValCtx = taosMemoryCalloc(numOfOutput, POINTER_BYTES);
  if (pValCtx == NULL) {
    return TSDB_CODE_QRY_OUT_OF_MEMORY;
  }

  for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
1313
    const char* pName = pCtx[i].pExpr->pExpr->_function.functionName;
1314
    if ((strcmp(pName, "_select_value") == 0) || (strcmp(pName, "_group_key") == 0)) {
1315 1316 1317 1318 1319
      pValCtx[num++] = &pCtx[i];
    } else if (fmIsSelectFunc(pCtx[i].functionId)) {
      p = &pCtx[i];
    }
  }
H
Haojun Liao 已提交
1320

1321 1322 1323
  if (p != NULL) {
    p->subsidiaries.pCtx = pValCtx;
    p->subsidiaries.num = num;
1324
  } else {
1325
    taosMemoryFreeClear(pValCtx);
1326
  }
1327 1328

  return TSDB_CODE_SUCCESS;
1329 1330
}

1331
SqlFunctionCtx* createSqlFunctionCtx(SExprInfo* pExprInfo, int32_t numOfOutput, int32_t** rowEntryInfoOffset) {
1332 1333 1334 1335
  SqlFunctionCtx* pFuncCtx = (SqlFunctionCtx*)taosMemoryCalloc(numOfOutput, sizeof(SqlFunctionCtx));
  if (pFuncCtx == NULL) {
    return NULL;
  }
1336

1337 1338
  *rowEntryInfoOffset = taosMemoryCalloc(numOfOutput, sizeof(int32_t));
  if (*rowEntryInfoOffset == 0) {
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
    taosMemoryFreeClear(pFuncCtx);
    return NULL;
  }

  for (int32_t i = 0; i < numOfOutput; ++i) {
    SExprInfo* pExpr = &pExprInfo[i];

    SExprBasicInfo* pFunct = &pExpr->base;
    SqlFunctionCtx* pCtx = &pFuncCtx[i];

    pCtx->functionId = -1;
    pCtx->pExpr = pExpr;

    if (pExpr->pExpr->nodeType == QUERY_NODE_FUNCTION) {
      SFuncExecEnv env = {0};
      pCtx->functionId = pExpr->pExpr->_function.pFunctNode->funcId;

      if (fmIsAggFunc(pCtx->functionId) || fmIsIndefiniteRowsFunc(pCtx->functionId)) {
        bool isUdaf = fmIsUserDefinedFunc(pCtx->functionId);
        if (!isUdaf) {
          fmGetFuncExecFuncs(pCtx->functionId, &pCtx->fpSet);
        } else {
          char* udfName = pExpr->pExpr->_function.pFunctNode->functionName;
H
Haojun Liao 已提交
1362
          tstrncpy(pCtx->udfName, udfName, TSDB_FUNC_NAME_LEN);
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
          fmGetUdafExecFuncs(pCtx->functionId, &pCtx->fpSet);
        }
        pCtx->fpSet.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
      } else {
        fmGetScalarFuncExecFuncs(pCtx->functionId, &pCtx->sfp);
        if (pCtx->sfp.getEnv != NULL) {
          pCtx->sfp.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
        }
      }
      pCtx->resDataInfo.interBufSize = env.calcMemSize;
    } else if (pExpr->pExpr->nodeType == QUERY_NODE_COLUMN || pExpr->pExpr->nodeType == QUERY_NODE_OPERATOR ||
               pExpr->pExpr->nodeType == QUERY_NODE_VALUE) {
      // for simple column, the result buffer needs to hold at least one element.
      pCtx->resDataInfo.interBufSize = pFunct->resSchema.bytes;
    }

    pCtx->input.numOfInputCols = pFunct->numOfParams;
    pCtx->input.pData = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
    pCtx->input.pColumnDataAgg = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);

    pCtx->pTsOutput = NULL;
    pCtx->resDataInfo.bytes = pFunct->resSchema.bytes;
    pCtx->resDataInfo.type = pFunct->resSchema.type;
    pCtx->order = TSDB_ORDER_ASC;
    pCtx->start.key = INT64_MIN;
    pCtx->end.key = INT64_MIN;
    pCtx->numOfParams = pExpr->base.numOfParams;
H
Haojun Liao 已提交
1390
    pCtx->isStream = false;
1391 1392

    pCtx->param = pFunct->pParam;
1393
    pCtx->saveHandle.currentPage = -1;
1394 1395 1396
  }

  for (int32_t i = 1; i < numOfOutput; ++i) {
dengyihao's avatar
dengyihao 已提交
1397 1398
    (*rowEntryInfoOffset)[i] = (int32_t)((*rowEntryInfoOffset)[i - 1] + sizeof(SResultRowEntryInfo) +
                                         pFuncCtx[i - 1].resDataInfo.interBufSize);
1399 1400 1401 1402
  }

  setSelectValueColumnInfo(pFuncCtx, numOfOutput);
  return pFuncCtx;
1403
}
1404 1405

// NOTE: sources columns are more than the destination SSDatablock columns.
1406 1407
// doFilter in table scan needs every column even its output is false
void relocateColumnData(SSDataBlock* pBlock, const SArray* pColMatchInfo, SArray* pCols, bool outputEveryColumn) {
1408 1409 1410 1411 1412
  size_t numOfSrcCols = taosArrayGetSize(pCols);

  int32_t i = 0, j = 0;
  while (i < numOfSrcCols && j < taosArrayGetSize(pColMatchInfo)) {
    SColumnInfoData* p = taosArrayGet(pCols, i);
H
Haojun Liao 已提交
1413 1414
    SColMatchItem*   pmInfo = taosArrayGet(pColMatchInfo, j);
/*    if (!outputEveryColumn && pmInfo->reserved) {
1415 1416
      j++;
      continue;
H
Haojun Liao 已提交
1417
    }*/
1418 1419

    if (p->info.colId == pmInfo->colId) {
H
Haojun Liao 已提交
1420
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, pmInfo->dstSlotId);
1421
      colDataAssign(pDst, p, pBlock->info.rows, &pBlock->info);
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
      i++;
      j++;
    } else if (p->info.colId < pmInfo->colId) {
      i++;
    } else {
      ASSERT(0);
    }
  }
}

SInterval extractIntervalInfo(const STableScanPhysiNode* pTableScanNode) {
  SInterval interval = {
      .interval = pTableScanNode->interval,
      .sliding = pTableScanNode->sliding,
      .intervalUnit = pTableScanNode->intervalUnit,
      .slidingUnit = pTableScanNode->slidingUnit,
      .offset = pTableScanNode->offset,
  };

  return interval;
}

SColumn extractColumnFromColumnNode(SColumnNode* pColNode) {
  SColumn c = {0};
H
Haojun Liao 已提交
1446

1447 1448 1449 1450 1451
  c.slotId = pColNode->slotId;
  c.colId = pColNode->colId;
  c.type = pColNode->node.resType.type;
  c.bytes = pColNode->node.resType.bytes;
  c.scale = pColNode->node.resType.scale;
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
  c.precision = pColNode->node.resType.precision;
  return c;
}

int32_t initQueryTableDataCond(SQueryTableDataCond* pCond, const STableScanPhysiNode* pTableScanNode) {
  pCond->order = pTableScanNode->scanSeq[0] > 0 ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
  pCond->numOfCols = LIST_LENGTH(pTableScanNode->scan.pScanCols);
  pCond->colList = taosMemoryCalloc(pCond->numOfCols, sizeof(SColumnInfo));
  if (pCond->colList == NULL) {
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return terrno;
  }

  // pCond->twindow = pTableScanNode->scanRange;
  // TODO: get it from stable scan node
H
Haojun Liao 已提交
1467
  pCond->twindows = pTableScanNode->scanRange;
1468
  pCond->suid = pTableScanNode->scan.suid;
1469
  pCond->type = TIMEWINDOW_RANGE_CONTAINED;
H
Haojun Liao 已提交
1470
  pCond->startVersion = -1;
1471
  pCond->endVersion = -1;
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
  //  pCond->type = pTableScanNode->scanFlag;

  int32_t j = 0;
  for (int32_t i = 0; i < pCond->numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pTableScanNode->scan.pScanCols, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
    if (pColNode->colType == COLUMN_TYPE_TAG) {
      continue;
    }

    pCond->colList[j].type = pColNode->node.resType.type;
    pCond->colList[j].bytes = pColNode->node.resType.bytes;
    pCond->colList[j].colId = pColNode->colId;
    j += 1;
  }

  pCond->numOfCols = j;
  return TSDB_CODE_SUCCESS;
}

1492
void cleanupQueryTableDataCond(SQueryTableDataCond* pCond) { taosMemoryFreeClear(pCond->colList); }
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520

int32_t convertFillType(int32_t mode) {
  int32_t type = TSDB_FILL_NONE;
  switch (mode) {
    case FILL_MODE_PREV:
      type = TSDB_FILL_PREV;
      break;
    case FILL_MODE_NONE:
      type = TSDB_FILL_NONE;
      break;
    case FILL_MODE_NULL:
      type = TSDB_FILL_NULL;
      break;
    case FILL_MODE_NEXT:
      type = TSDB_FILL_NEXT;
      break;
    case FILL_MODE_VALUE:
      type = TSDB_FILL_SET_VALUE;
      break;
    case FILL_MODE_LINEAR:
      type = TSDB_FILL_LINEAR;
      break;
    default:
      type = TSDB_FILL_NONE;
  }

  return type;
}
H
Haojun Liao 已提交
1521 1522 1523

static void getInitialStartTimeWindow(SInterval* pInterval, TSKEY ts, STimeWindow* w, bool ascQuery) {
  if (ascQuery) {
1524
    *w = getAlignQueryTimeWindow(pInterval, pInterval->precision, ts);
H
Haojun Liao 已提交
1525 1526
  } else {
    // the start position of the first time window in the endpoint that spreads beyond the queried last timestamp
1527
    *w = getAlignQueryTimeWindow(pInterval, pInterval->precision, ts);
H
Haojun Liao 已提交
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541

    int64_t key = w->skey;
    while (key < ts) {  // moving towards end
      key = taosTimeAdd(key, pInterval->sliding, pInterval->slidingUnit, pInterval->precision);
      if (key >= ts) {
        break;
      }

      w->skey = key;
    }
  }
}

static STimeWindow doCalculateTimeWindow(int64_t ts, SInterval* pInterval) {
1542
  STimeWindow w = {0};
H
Haojun Liao 已提交
1543

1544 1545
  w.skey = taosTimeTruncate(ts, pInterval, pInterval->precision);
  w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1;
H
Haojun Liao 已提交
1546 1547 1548
  return w;
}

1549
STimeWindow getFirstQualifiedTimeWindow(int64_t ts, STimeWindow* pWindow, SInterval* pInterval, int32_t order) {
1550
  int32_t factor = (order == TSDB_ORDER_ASC) ? -1 : 1;
H
Haojun Liao 已提交
1551 1552 1553

  STimeWindow win = *pWindow;
  STimeWindow save = win;
1554
  while (win.skey <= ts && win.ekey >= ts) {
H
Haojun Liao 已提交
1555 1556 1557 1558 1559 1560 1561 1562 1563
    save = win;
    win.skey = taosTimeAdd(win.skey, factor * pInterval->sliding, pInterval->slidingUnit, pInterval->precision);
    win.ekey = taosTimeAdd(win.ekey, factor * pInterval->sliding, pInterval->slidingUnit, pInterval->precision);
  }

  return save;
}

// get the correct time window according to the handled timestamp
1564
// todo refactor
H
Haojun Liao 已提交
1565 1566 1567 1568 1569 1570 1571 1572 1573
STimeWindow getActiveTimeWindow(SDiskbasedBuf* pBuf, SResultRowInfo* pResultRowInfo, int64_t ts, SInterval* pInterval,
                                int32_t order) {
  STimeWindow w = {0};
  if (pResultRowInfo->cur.pageId == -1) {  // the first window, from the previous stored value
    getInitialStartTimeWindow(pInterval, ts, &w, (order == TSDB_ORDER_ASC));
    w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1;
    return w;
  }

1574
  w = getResultRowByPos(pBuf, &pResultRowInfo->cur, false)->win;
H
Haojun Liao 已提交
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587

  // in case of typical time window, we can calculate time window directly.
  if (w.skey > ts || w.ekey < ts) {
    w = doCalculateTimeWindow(ts, pInterval);
  }

  if (pInterval->interval != pInterval->sliding) {
    // it is an sliding window query, in which sliding value is not equalled to
    // interval value, and we need to find the first qualified time window.
    w = getFirstQualifiedTimeWindow(ts, &w, pInterval, order);
  }

  return w;
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
}

bool hasLimitOffsetInfo(SLimitInfo* pLimitInfo) {
  return (pLimitInfo->limit.limit != -1 || pLimitInfo->limit.offset != -1 || pLimitInfo->slimit.limit != -1 ||
          pLimitInfo->slimit.offset != -1);
}

static int64_t getLimit(const SNode* pLimit) { return NULL == pLimit ? -1 : ((SLimitNode*)pLimit)->limit; }
static int64_t getOffset(const SNode* pLimit) { return NULL == pLimit ? -1 : ((SLimitNode*)pLimit)->offset; }

void initLimitInfo(const SNode* pLimit, const SNode* pSLimit, SLimitInfo* pLimitInfo) {
  SLimit limit = {.limit = getLimit(pLimit), .offset = getOffset(pLimit)};
  SLimit slimit = {.limit = getLimit(pSLimit), .offset = getOffset(pSLimit)};

  pLimitInfo->limit = limit;
1603
  pLimitInfo->slimit = slimit;
1604 1605
  pLimitInfo->remainOffset = limit.offset;
  pLimitInfo->remainGroupOffset = slimit.offset;
1606
}