executil.c 70.5 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"
dengyihao's avatar
dengyihao 已提交
20
#include "query.h"
21
#include "tdatablock.h"
22
#include "thash.h"
23
#include "tmsg.h"
24
#include "ttime.h"
25

26
#include "executil.h"
27
#include "executorInt.h"
28
#include "querytask.h"
29
#include "storageapi.h"
D
dapan1121 已提交
30
#include "tcompression.h"
H
Haojun Liao 已提交
31 32 33 34 35 36 37

typedef struct tagFilterAssist {
  SHashObj* colHash;
  int32_t   index;
  SArray*   cInfoList;
} tagFilterAssist;

dengyihao's avatar
dengyihao 已提交
38 39 40 41 42 43 44
typedef enum {
  FILTER_NO_LOGIC = 1,
  FILTER_AND,
  FILTER_OTHER,
} FilterCondType;

static FilterCondType checkTagCond(SNode* cond);
D
dapan1121 已提交
45 46
static int32_t optimizeTbnameInCond(void* metaHandle, int64_t suid, SArray* list, SNode* pTagCond, SStorageAPI* pAPI);
static int32_t optimizeTbnameInCondImpl(void* metaHandle, SArray* list, SNode* pTagCond, SStorageAPI* pStoreAPI);
X
Xiaoyu Wang 已提交
47

D
dapan1121 已提交
48 49 50 51
static int32_t      getTableList(void* pVnode, SScanPhysiNode* pScanNode, SNode* pTagCond, SNode* pTagIndexCond,
                                 STableListInfo* pListInfo, uint8_t* digest, const char* idstr, SStorageAPI* pStorageAPI);
static SSDataBlock* createTagValBlockForFilter(SArray* pColList, int32_t numOfTables, SArray* pUidTagList, void* pVnode,
                                               SStorageAPI* pStorageAPI);
dengyihao's avatar
dengyihao 已提交
52

H
Haojun Liao 已提交
53 54
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; }
dengyihao's avatar
dengyihao 已提交
55

dengyihao's avatar
dengyihao 已提交
56 57
void initResultRowInfo(SResultRowInfo* pResultRowInfo) {
  pResultRowInfo->size = 0;
58
  pResultRowInfo->cur.pageId = -1;
59 60
}

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

63 64 65 66 67 68 69 70 71 72 73
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 已提交
74
// TODO refactor: use macro
75
SResultRowEntryInfo* getResultEntryInfo(const SResultRow* pRow, int32_t index, const int32_t* offset) {
dengyihao's avatar
dengyihao 已提交
76
  return (SResultRowEntryInfo*)((char*)pRow->pEntryInfo + offset[index]);
H
Haojun Liao 已提交
77 78
}

79 80 81
size_t getResultRowSize(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  int32_t rowSize = (numOfOutput * sizeof(SResultRowEntryInfo)) + sizeof(SResultRow);

dengyihao's avatar
dengyihao 已提交
82
  for (int32_t i = 0; i < numOfOutput; ++i) {
83 84 85
    rowSize += pCtx[i].resDataInfo.interBufSize;
  }

86 87
  rowSize += (numOfOutput * sizeof(bool));
  // expand rowSize to mark if col is null for top/bottom result(saveTupleData)
88
  return rowSize;
89 90
}

X
Xiaoyu Wang 已提交
91
static void freeEx(void* p) { taosMemoryFree(*(void**)p); }
H
Haojun Liao 已提交
92 93

void cleanupGroupResInfo(SGroupResInfo* pGroupResInfo) {
H
Haojun Liao 已提交
94
  taosMemoryFreeClear(pGroupResInfo->pBuf);
H
Haojun Liao 已提交
95
  if (pGroupResInfo->freeItem) {
X
Xiaoyu Wang 已提交
96
    //    taosArrayDestroy(pGroupResInfo->pRows);
97 98
    taosArrayDestroyEx(pGroupResInfo->pRows, freeEx);
    pGroupResInfo->freeItem = false;
H
Haojun Liao 已提交
99 100 101
    pGroupResInfo->pRows = NULL;
  } else {
    pGroupResInfo->pRows = taosArrayDestroy(pGroupResInfo->pRows);
H
Haojun Liao 已提交
102
  }
dengyihao's avatar
dengyihao 已提交
103
  pGroupResInfo->index = 0;
H
Haojun Liao 已提交
104 105
}

5
54liuyao 已提交
106
int32_t resultrowComparAsc(const void* p1, const void* p2) {
dengyihao's avatar
dengyihao 已提交
107 108
  SResKeyPos* pp1 = *(SResKeyPos**)p1;
  SResKeyPos* pp2 = *(SResKeyPos**)p2;
109 110

  if (pp1->groupId == pp2->groupId) {
dengyihao's avatar
dengyihao 已提交
111 112
    int64_t pts1 = *(int64_t*)pp1->key;
    int64_t pts2 = *(int64_t*)pp2->key;
113 114 115 116

    if (pts1 == pts2) {
      return 0;
    } else {
dengyihao's avatar
dengyihao 已提交
117
      return pts1 < pts2 ? -1 : 1;
118 119
    }
  } else {
dengyihao's avatar
dengyihao 已提交
120
    return pp1->groupId < pp2->groupId ? -1 : 1;
121 122 123
  }
}

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

126
void initGroupedResultInfo(SGroupResInfo* pGroupResInfo, SSHashObj* pHashmap, int32_t order) {
H
Haojun Liao 已提交
127 128 129
  if (pGroupResInfo->pRows != NULL) {
    taosArrayDestroy(pGroupResInfo->pRows);
  }
130 131 132 133
  if (pGroupResInfo->pBuf) {
    taosMemoryFree(pGroupResInfo->pBuf);
    pGroupResInfo->pBuf = NULL;
  }
H
Haojun Liao 已提交
134

135
  // extract the result rows information from the hash map
H
Haojun Liao 已提交
136 137
  int32_t size = tSimpleHashGetSize(pHashmap);

138
  void* pData = NULL;
H
Haojun Liao 已提交
139
  pGroupResInfo->pRows = taosArrayInit(size, POINTER_BYTES);
140

141 142
  size_t  keyLen = 0;
  int32_t iter = 0;
D
dapan1121 已提交
143
  int64_t bufLen = 0, offset = 0;
H
Haojun Liao 已提交
144

H
Haojun Liao 已提交
145
  // todo move away and record this during create window
146
  while ((pData = tSimpleHashIterate(pHashmap, pData, &iter)) != NULL) {
X
Xiaoyu Wang 已提交
147
    /*void* key = */ tSimpleHashGetKey(pData, &keyLen);
H
Haojun Liao 已提交
148 149
    bufLen += keyLen + sizeof(SResultRowPosition);
  }
150

H
Haojun Liao 已提交
151
  pGroupResInfo->pBuf = taosMemoryMalloc(bufLen);
H
Haojun Liao 已提交
152

H
Haojun Liao 已提交
153
  iter = 0;
154 155
  while ((pData = tSimpleHashIterate(pHashmap, pData, &iter)) != NULL) {
    void* key = tSimpleHashGetKey(pData, &keyLen);
156

X
Xiaoyu Wang 已提交
157
    SResKeyPos* p = (SResKeyPos*)(pGroupResInfo->pBuf + offset);
158

dengyihao's avatar
dengyihao 已提交
159 160
    p->groupId = *(uint64_t*)key;
    p->pos = *(SResultRowPosition*)pData;
161
    memcpy(p->key, (char*)key + sizeof(uint64_t), keyLen - sizeof(uint64_t));
162
    taosArrayPush(pGroupResInfo->pRows, &p);
H
Haojun Liao 已提交
163 164

    offset += keyLen + sizeof(struct SResultRowPosition);
165 166
  }

167
  if (order == TSDB_ORDER_ASC || order == TSDB_ORDER_DESC) {
dengyihao's avatar
dengyihao 已提交
168
    __compar_fn_t fn = (order == TSDB_ORDER_ASC) ? resultrowComparAsc : resultrowComparDesc;
169
    size = POINTER_BYTES;
H
Haojun Liao 已提交
170
    taosSort(pGroupResInfo->pRows->pData, taosArrayGetSize(pGroupResInfo->pRows), size, fn);
171 172
  }

H
Haojun Liao 已提交
173
  pGroupResInfo->index = 0;
H
Haojun Liao 已提交
174 175
}

H
Haojun Liao 已提交
176 177
void initMultiResInfoFromArrayList(SGroupResInfo* pGroupResInfo, SArray* pArrayList) {
  if (pGroupResInfo->pRows != NULL) {
178
    taosArrayDestroy(pGroupResInfo->pRows);
H
Haojun Liao 已提交
179 180
  }

H
Haojun Liao 已提交
181
  pGroupResInfo->freeItem = true;
182
  pGroupResInfo->pRows = pArrayList;
H
Haojun Liao 已提交
183
  pGroupResInfo->index = 0;
184
  ASSERT(pGroupResInfo->index <= getNumOfTotalRes(pGroupResInfo));
H
Haojun Liao 已提交
185 186
}

187
bool hasRemainResults(SGroupResInfo* pGroupResInfo) {
H
Haojun Liao 已提交
188 189 190 191 192 193 194 195 196 197 198 199
  if (pGroupResInfo->pRows == NULL) {
    return false;
  }

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

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

dengyihao's avatar
dengyihao 已提交
200
  return (int32_t)taosArrayGetSize(pGroupResInfo->pRows);
H
Haojun Liao 已提交
201 202
}

203
SArray* createSortInfo(SNodeList* pNodeList) {
204
  size_t numOfCols = 0;
205

206 207 208 209 210
  if (pNodeList != NULL) {
    numOfCols = LIST_LENGTH(pNodeList);
  } else {
    numOfCols = 0;
  }
211

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
  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;
}

H
Haojun Liao 已提交
232
SSDataBlock* createDataBlockFromDescNode(SDataBlockDescNode* pNode) {
233
  int32_t numOfCols = LIST_LENGTH(pNode->pSlots);
H
Haojun Liao 已提交
234

235
  SSDataBlock* pBlock = createDataBlock();
H
Haojun Liao 已提交
236

H
Haojun Liao 已提交
237
  pBlock->info.id.blockId = pNode->dataBlockId;
238
  pBlock->info.type = STREAM_INVALID;
5
54liuyao 已提交
239
  pBlock->info.calWin = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
240
  pBlock->info.watermark = INT64_MIN;
H
Haojun Liao 已提交
241

242
  for (int32_t i = 0; i < numOfCols; ++i) {
M
Minglei Jin 已提交
243
    SSlotDescNode*  pDescNode = (SSlotDescNode*)nodesListGetNode(pNode->pSlots, i);
dengyihao's avatar
dengyihao 已提交
244 245
    SColumnInfoData idata =
        createColumnInfoData(pDescNode->dataType.type, pDescNode->dataType.bytes, pDescNode->slotId);
246 247 248
    idata.info.scale = pDescNode->dataType.scale;
    idata.info.precision = pDescNode->dataType.precision;

249
    blockDataAppendColInfo(pBlock, &idata);
H
Haojun Liao 已提交
250 251
  }

252 253 254
  return pBlock;
}

wmmhello's avatar
wmmhello 已提交
255 256
EDealRes doTranslateTagExpr(SNode** pNode, void* pContext) {
  SMetaReader* mr = (SMetaReader*)pContext;
dengyihao's avatar
dengyihao 已提交
257
  if (nodeType(*pNode) == QUERY_NODE_COLUMN) {
wmmhello's avatar
wmmhello 已提交
258 259
    SColumnNode* pSColumnNode = *(SColumnNode**)pNode;

dengyihao's avatar
dengyihao 已提交
260
    SValueNode* res = (SValueNode*)nodesMakeNode(QUERY_NODE_VALUE);
wmmhello's avatar
wmmhello 已提交
261 262 263 264 265 266 267 268 269
    if (NULL == res) {
      return DEAL_RES_ERROR;
    }

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

    STagVal tagVal = {0};
    tagVal.cid = pSColumnNode->colId;
H
Haojun Liao 已提交
270
    const char* p = mr->pAPI->extractTagVal(mr->me.ctbEntry.pTags, pSColumnNode->node.resType.type, &tagVal);
wmmhello's avatar
wmmhello 已提交
271 272
    if (p == NULL) {
      res->node.resType.type = TSDB_DATA_TYPE_NULL;
dengyihao's avatar
dengyihao 已提交
273 274
    } else if (pSColumnNode->node.resType.type == TSDB_DATA_TYPE_JSON) {
      int32_t len = ((const STag*)p)->len;
wmmhello's avatar
wmmhello 已提交
275 276 277 278 279 280 281 282 283 284 285
      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 已提交
286 287 288 289
  } 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 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
      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;
}

D
dapan1121 已提交
309
int32_t isQualifiedTable(STableKeyInfo* info, SNode* pTagCond, void* metaHandle, bool* pQualified, SStorageAPI* pAPI) {
310
  int32_t     code = TSDB_CODE_SUCCESS;
dengyihao's avatar
dengyihao 已提交
311
  SMetaReader mr = {0};
312

H
Haojun Liao 已提交
313
  pAPI->metaReaderFn.initReader(&mr, metaHandle, 0, &pAPI->metaFn);
314
  code = pAPI->metaReaderFn.getEntryGetUidCache(&mr, info->uid);
315
  if (TSDB_CODE_SUCCESS != code) {
316
    pAPI->metaReaderFn.clearReader(&mr);
M
Minglei Jin 已提交
317
    *pQualified = false;
318

M
Minglei Jin 已提交
319
    return TSDB_CODE_SUCCESS;
320
  }
wmmhello's avatar
wmmhello 已提交
321

dengyihao's avatar
dengyihao 已提交
322
  SNode* pTagCondTmp = nodesCloneNode(pTagCond);
wmmhello's avatar
wmmhello 已提交
323 324

  nodesRewriteExprPostOrder(&pTagCondTmp, doTranslateTagExpr, &mr);
325
  pAPI->metaReaderFn.clearReader(&mr);
wmmhello's avatar
wmmhello 已提交
326

327 328
  SNode* pNew = NULL;
  code = scalarCalculateConstants(pTagCondTmp, &pNew);
wmmhello's avatar
wmmhello 已提交
329
  if (TSDB_CODE_SUCCESS != code) {
wmmhello's avatar
wmmhello 已提交
330
    terrno = code;
wmmhello's avatar
wmmhello 已提交
331
    nodesDestroyNode(pTagCondTmp);
332 333 334
    *pQualified = false;

    return code;
wmmhello's avatar
wmmhello 已提交
335 336
  }

dengyihao's avatar
dengyihao 已提交
337
  SValueNode* pValue = (SValueNode*)pNew;
338 339
  *pQualified = pValue->datum.b;

wmmhello's avatar
wmmhello 已提交
340
  nodesDestroyNode(pNew);
341
  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
342 343
}

wmmhello's avatar
wmmhello 已提交
344 345 346 347
static EDealRes getColumn(SNode** pNode, void* pContext) {
  SColumnNode* pSColumnNode = NULL;
  if (QUERY_NODE_COLUMN == nodeType((*pNode))) {
    pSColumnNode = *(SColumnNode**)pNode;
H
Haojun Liao 已提交
348
  } else if (QUERY_NODE_FUNCTION == nodeType((*pNode))) {
wmmhello's avatar
wmmhello 已提交
349 350 351 352 353 354 355 356 357 358 359 360
    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 已提交
361
    } else {
362
      return DEAL_RES_CONTINUE;
wmmhello's avatar
wmmhello 已提交
363
    }
H
Haojun Liao 已提交
364
  } else {
wmmhello's avatar
wmmhello 已提交
365
    return DEAL_RES_CONTINUE;
wmmhello's avatar
wmmhello 已提交
366
  }
wmmhello's avatar
wmmhello 已提交
367

H
Haojun Liao 已提交
368 369 370
  tagFilterAssist* pData = (tagFilterAssist*)pContext;
  void*            data = taosHashGet(pData->colHash, &pSColumnNode->colId, sizeof(pSColumnNode->colId));
  if (!data) {
wmmhello's avatar
wmmhello 已提交
371 372
    taosHashPut(pData->colHash, &pSColumnNode->colId, sizeof(pSColumnNode->colId), pNode, sizeof((*pNode)));
    pSColumnNode->slotId = pData->index++;
H
Haojun Liao 已提交
373 374 375
    SColumnInfo cInfo = {.colId = pSColumnNode->colId,
                         .type = pSColumnNode->node.resType.type,
                         .bytes = pSColumnNode->node.resType.bytes};
376 377 378
#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 已提交
379
    taosArrayPush(pData->cInfoList, &cInfo);
H
Haojun Liao 已提交
380
  } else {
381 382
    SColumnNode* col = *(SColumnNode**)data;
    pSColumnNode->slotId = col->slotId;
wmmhello's avatar
wmmhello 已提交
383 384
  }

wmmhello's avatar
wmmhello 已提交
385 386 387 388 389 390 391 392 393 394
  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 已提交
395 396 397
  pColumnData->info.type = pType->type;
  pColumnData->info.bytes = pType->bytes;
  pColumnData->info.scale = pType->scale;
wmmhello's avatar
wmmhello 已提交
398 399
  pColumnData->info.precision = pType->precision;

H
Haojun Liao 已提交
400
  int32_t code = colInfoDataEnsureCapacity(pColumnData, numOfRows, true);
wmmhello's avatar
wmmhello 已提交
401
  if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
402
    terrno = code;
wmmhello's avatar
wmmhello 已提交
403 404 405 406 407 408 409 410 411
    taosMemoryFree(pColumnData);
    return terrno;
  }

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

H
Haojun Liao 已提交
412 413 414 415 416 417 418 419
static void releaseColInfoData(void* pCol) {
  if (pCol) {
    SColumnInfoData* col = (SColumnInfoData*)pCol;
    colDataDestroy(col);
    taosMemoryFree(col);
  }
}

H
Haojun Liao 已提交
420
void freeItem(void* p) {
X
Xiaoyu Wang 已提交
421
  STUidTagInfo* pInfo = p;
H
Haojun Liao 已提交
422 423 424 425 426
  if (pInfo->pTagVal != NULL) {
    taosMemoryFree(pInfo->pTagVal);
  }
}

D
dapan1121 已提交
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
static void genTagFilterDigest(const SNode* pTagCond, T_MD5_CTX* pContext) {
  if (pTagCond == NULL) {
    return;
  }

  char*   payload = NULL;
  int32_t len = 0;
  nodesNodeToMsg(pTagCond, &payload, &len);

  tMD5Init(pContext);
  tMD5Update(pContext, (uint8_t*)payload, (uint32_t)len);
  tMD5Final(pContext);

  taosMemoryFree(payload);
}

D
dapan1121 已提交
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
static void genTbGroupDigest(const SNode* pGroup, uint8_t* filterDigest, T_MD5_CTX* pContext) {
  char*   payload = NULL;
  int32_t len = 0;
  nodesNodeToMsg(pGroup, &payload, &len);
  if (filterDigest[0]) {
    payload = taosMemoryRealloc(payload, len + tListLen(pContext->digest));
    memcpy(payload + len, filterDigest + 1, tListLen(pContext->digest));
    len += tListLen(pContext->digest);
  }

  tMD5Init(pContext);
  tMD5Update(pContext, (uint8_t*)payload, (uint32_t)len);
  tMD5Final(pContext);

  taosMemoryFree(payload);
}

460 461
int32_t getColInfoResultForGroupby(void* pVnode, SNodeList* group, STableListInfo* pTableListInfo, uint8_t* digest,
                                   SStorageAPI* pAPI) {
H
Haojun Liao 已提交
462 463 464 465 466
  int32_t      code = TSDB_CODE_SUCCESS;
  SArray*      pBlockList = NULL;
  SSDataBlock* pResBlock = NULL;
  void*        keyBuf = NULL;
  SArray*      groupData = NULL;
D
dapan1121 已提交
467
  SArray*      pUidTagList = NULL;
D
dapan1121 已提交
468
  SArray*      tableList = NULL;
H
Haojun Liao 已提交
469 470 471

  int32_t rows = taosArrayGetSize(pTableListInfo->pTableList);
  if (rows == 0) {
472
    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
473 474 475 476 477 478 479 480
  }

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

H
Haojun Liao 已提交
482 483 484 485 486 487 488 489 490 491 492 493 494
  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);
  }

D
dapan1121 已提交
495
  T_MD5_CTX context = {0};
D
dapan1121 已提交
496 497 498
  if (tsTagFilterCache) {
    SNodeListNode* listNode = (SNodeListNode*)nodesMakeNode(QUERY_NODE_NODE_LIST);
    listNode->pNodeList = group;
Y
yihaoDeng 已提交
499
    genTbGroupDigest((SNode*)listNode, digest, &context);
D
dapan1121 已提交
500
    nodesFree(listNode);
501

D
dapan1121 已提交
502 503
    pAPI->metaFn.metaGetCachedTbGroup(pVnode, pTableListInfo->idInfo.suid, context.digest, tListLen(context.digest),
                                      &tableList);
D
dapan1121 已提交
504 505 506
    if (tableList) {
      taosArrayDestroy(pTableListInfo->pTableList);
      pTableListInfo->pTableList = tableList;
Y
yihaoDeng 已提交
507 508
      qDebug("retrieve tb group list from cache, numOfTables:%d",
             (int32_t)taosArrayGetSize(pTableListInfo->pTableList));
D
dapan1121 已提交
509 510
      goto end;
    }
D
dapan1121 已提交
511
  }
Y
yihaoDeng 已提交
512

D
dapan1121 已提交
513
  pUidTagList = taosArrayInit(8, sizeof(STUidTagInfo));
H
Haojun Liao 已提交
514 515
  for (int32_t i = 0; i < rows; ++i) {
    STableKeyInfo* pkeyInfo = taosArrayGet(pTableListInfo->pTableList, i);
X
Xiaoyu Wang 已提交
516
    STUidTagInfo   info = {.uid = pkeyInfo->uid};
517
    taosArrayPush(pUidTagList, &info);
H
Haojun Liao 已提交
518 519
  }

520
  code = pAPI->metaFn.getTableTags(pVnode, pTableListInfo->idInfo.suid, pUidTagList);
H
Haojun Liao 已提交
521 522 523 524
  if (code != TSDB_CODE_SUCCESS) {
    goto end;
  }

525
  int32_t numOfTables = taosArrayGetSize(pUidTagList);
526
  pResBlock = createTagValBlockForFilter(ctx.cInfoList, numOfTables, pUidTagList, pVnode, pAPI);
H
Haojun Liao 已提交
527 528
  if (pResBlock == NULL) {
    code = terrno;
H
Haojun Liao 已提交
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
    goto end;
  }

  //  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;
      }
555

H
Haojun Liao 已提交
556 557 558 559
      default:
        code = TSDB_CODE_OPS_NOT_SUPPORT;
        goto end;
    }
560

H
Haojun Liao 已提交
561 562 563 564 565 566 567 568 569
    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);
    }
570

H
Haojun Liao 已提交
571 572 573 574
    if (code != TSDB_CODE_SUCCESS) {
      releaseColInfoData(output.columnData);
      goto end;
    }
575

H
Haojun Liao 已提交
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    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;
  }
594

H
Haojun Liao 已提交
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
  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)) {
D
dapan1121 已提交
621 622 623 624
          if (varDataTLen(data) > pValue->info.bytes) {
            code = TSDB_CODE_TDB_INVALID_TABLE_SCHEMA_VER;
            goto end;
          }
H
Haojun Liao 已提交
625 626 627 628 629 630 631 632 633 634 635 636 637
          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);
  }

D
dapan1121 已提交
638 639
  if (tsTagFilterCache) {
    tableList = taosArrayDup(pTableListInfo->pTableList, NULL);
D
dapan1121 已提交
640 641
    pAPI->metaFn.metaPutTbGroupToCache(pVnode, pTableListInfo->idInfo.suid, context.digest, tListLen(context.digest),
                                       tableList, taosArrayGetSize(tableList) * sizeof(STableKeyInfo));
D
dapan1121 已提交
642
  }
Y
yihaoDeng 已提交
643

H
Haojun Liao 已提交
644 645 646 647 648 649 650 651 652
  //  int64_t st2 = taosGetTimestampUs();
  //  qDebug("calculate tag block rows:%d, cost:%ld us", rows, st2-st1);

end:
  taosMemoryFreeClear(keyBuf);
  taosHashCleanup(ctx.colHash);
  taosArrayDestroy(ctx.cInfoList);
  blockDataDestroy(pResBlock);
  taosArrayDestroy(pBlockList);
H
Haojun Liao 已提交
653
  taosArrayDestroyEx(pUidTagList, freeItem);
H
Haojun Liao 已提交
654 655 656 657
  taosArrayDestroyP(groupData, releaseColInfoData);
  return code;
}

H
Haojun Liao 已提交
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
static int32_t nameComparFn(const void* p1, const void* p2) {
  const char* pName1 = *(const char**)p1;
  const char* pName2 = *(const char**)p2;

  int32_t ret = strcmp(pName1, pName2);
  if (ret == 0) {
    return 0;
  } else {
    return (ret > 0) ? 1 : -1;
  }
}

static SArray* getTableNameList(const SNodeListNode* pList) {
  int32_t    len = LIST_LENGTH(pList->pNodeList);
  SListCell* cell = pList->pNodeList->pHead;

  SArray* pTbList = taosArrayInit(len, POINTER_BYTES);
  for (int i = 0; i < pList->pNodeList->length; i++) {
    SValueNode* valueNode = (SValueNode*)cell->pNode;
    if (!IS_VAR_DATA_TYPE(valueNode->node.resType.type)) {
      terrno = TSDB_CODE_INVALID_PARA;
      taosArrayDestroy(pTbList);
      return NULL;
    }

    char* name = varDataVal(valueNode->datum.p);
    taosArrayPush(pTbList, &name);
    cell = cell->pNext;
  }

  size_t numOfTables = taosArrayGetSize(pTbList);

  // order the name
  taosArraySort(pTbList, nameComparFn);

  // remove the duplicates
  SArray* pNewList = taosArrayInit(taosArrayGetSize(pTbList), sizeof(void*));
  taosArrayPush(pNewList, taosArrayGet(pTbList, 0));

  for (int32_t i = 1; i < numOfTables; ++i) {
    char** name = taosArrayGetLast(pNewList);
    char** nameInOldList = taosArrayGet(pTbList, i);
    if (strcmp(*name, *nameInOldList) == 0) {
      continue;
    }

    taosArrayPush(pNewList, nameInOldList);
  }

  taosArrayDestroy(pTbList);
  return pNewList;
}

dengyihao's avatar
dengyihao 已提交
711
static int tableUidCompare(const void* a, const void* b) {
H
Haojun Liao 已提交
712 713 714
  uint64_t u1 = *(uint64_t*)a;
  uint64_t u2 = *(uint64_t*)b;

dengyihao's avatar
dengyihao 已提交
715 716 717
  if (u1 == u2) {
    return 0;
  }
H
Haojun Liao 已提交
718

dengyihao's avatar
dengyihao 已提交
719 720
  return u1 < u2 ? -1 : 1;
}
H
Haojun Liao 已提交
721

H
Haojun Liao 已提交
722
static int32_t filterTableInfoCompare(const void* a, const void* b) {
X
Xiaoyu Wang 已提交
723 724
  STUidTagInfo* p1 = (STUidTagInfo*)a;
  STUidTagInfo* p2 = (STUidTagInfo*)b;
H
Haojun Liao 已提交
725 726 727 728 729

  if (p1->uid == p2->uid) {
    return 0;
  }

X
Xiaoyu Wang 已提交
730 731 732
  return p1->uid < p2->uid ? -1 : 1;
}

dengyihao's avatar
dengyihao 已提交
733 734 735 736 737 738 739 740
static FilterCondType checkTagCond(SNode* cond) {
  if (nodeType(cond) == QUERY_NODE_OPERATOR) {
    return FILTER_NO_LOGIC;
  }
  if (nodeType(cond) != QUERY_NODE_LOGIC_CONDITION || ((SLogicConditionNode*)cond)->condType != LOGIC_COND_TYPE_AND) {
    return FILTER_AND;
  }
  return FILTER_OTHER;
H
Haojun Liao 已提交
741 742
}

743
static int32_t optimizeTbnameInCond(void* pVnode, int64_t suid, SArray* list, SNode* cond, SStorageAPI* pAPI) {
dengyihao's avatar
dengyihao 已提交
744
  int32_t ret = -1;
745 746 747
  int32_t ntype = nodeType(cond);

  if (ntype == QUERY_NODE_OPERATOR) {
748
    ret = optimizeTbnameInCondImpl(pVnode, list, cond, pAPI);
dengyihao's avatar
dengyihao 已提交
749 750
  }

751
  if (ntype != QUERY_NODE_LOGIC_CONDITION || ((SLogicConditionNode*)cond)->condType != LOGIC_COND_TYPE_AND) {
dengyihao's avatar
dengyihao 已提交
752
    return ret;
dengyihao's avatar
dengyihao 已提交
753 754
  }

dengyihao's avatar
dengyihao 已提交
755
  bool                 hasTbnameCond = false;
dengyihao's avatar
dengyihao 已提交
756
  SLogicConditionNode* pNode = (SLogicConditionNode*)cond;
dengyihao's avatar
dengyihao 已提交
757
  SNodeList*           pList = (SNodeList*)pNode->pParameterList;
dengyihao's avatar
dengyihao 已提交
758

dengyihao's avatar
dengyihao 已提交
759
  int32_t len = LIST_LENGTH(pList);
H
Haojun Liao 已提交
760 761 762
  if (len <= 0) {
    return ret;
  }
dengyihao's avatar
dengyihao 已提交
763

dengyihao's avatar
dengyihao 已提交
764
  SListCell* cell = pList->pHead;
dengyihao's avatar
dengyihao 已提交
765
  for (int i = 0; i < len; i++) {
dengyihao's avatar
dengyihao 已提交
766
    if (cell == NULL) break;
767
    if (optimizeTbnameInCondImpl(pVnode, list, cell->pNode, pAPI) == 0) {
dengyihao's avatar
dengyihao 已提交
768
      hasTbnameCond = true;
dengyihao's avatar
dengyihao 已提交
769
      break;
dengyihao's avatar
dengyihao 已提交
770 771 772
    }
    cell = cell->pNext;
  }
H
Haojun Liao 已提交
773

X
Xiaoyu Wang 已提交
774 775
  taosArraySort(list, filterTableInfoCompare);
  taosArrayRemoveDuplicate(list, filterTableInfoCompare, NULL);
dengyihao's avatar
dengyihao 已提交
776

dengyihao's avatar
dengyihao 已提交
777
  if (hasTbnameCond) {
778
    ret = pAPI->metaFn.getTableTagsByUid(pVnode, suid, list);
dengyihao's avatar
dengyihao 已提交
779
  }
H
Haojun Liao 已提交
780

dengyihao's avatar
dengyihao 已提交
781 782 783
  return ret;
}

784
// only return uid that does not contained in pExistedUidList
D
dapan1121 已提交
785 786
static int32_t optimizeTbnameInCondImpl(void* pVnode, SArray* pExistedUidList, SNode* pTagCond,
                                        SStorageAPI* pStoreAPI) {
dengyihao's avatar
dengyihao 已提交
787 788 789
  if (nodeType(pTagCond) != QUERY_NODE_OPERATOR) {
    return -1;
  }
790

dengyihao's avatar
dengyihao 已提交
791 792 793 794
  SOperatorNode* pNode = (SOperatorNode*)pTagCond;
  if (pNode->opType != OP_TYPE_IN) {
    return -1;
  }
795

dengyihao's avatar
dengyihao 已提交
796 797 798 799 800 801
  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);
H
Haojun Liao 已提交
802 803
    if (len <= 0) {
      return -1;
dengyihao's avatar
dengyihao 已提交
804 805
    }

dengyihao's avatar
dengyihao 已提交
806 807 808
    SArray*   pTbList = getTableNameList(pList);
    int32_t   numOfTables = taosArrayGetSize(pTbList);
    SHashObj* uHash = NULL;
H
Haojun Liao 已提交
809

X
Xiaoyu Wang 已提交
810
    size_t numOfExisted = taosArrayGetSize(pExistedUidList);  // len > 0 means there already have uids
811 812 813
    if (numOfExisted > 0) {
      uHash = taosHashInit(numOfExisted / 0.7, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
      for (int i = 0; i < numOfExisted; i++) {
814
        STUidTagInfo* pTInfo = taosArrayGet(pExistedUidList, i);
H
Haojun Liao 已提交
815
        taosHashPut(uHash, &pTInfo->uid, sizeof(uint64_t), &i, sizeof(i));
D
dapan1121 已提交
816 817
      }
    }
dengyihao's avatar
dengyihao 已提交
818

819 820
    for (int i = 0; i < numOfTables; i++) {
      char* name = taosArrayGetP(pTbList, i);
dengyihao's avatar
dengyihao 已提交
821 822

      uint64_t uid = 0;
823
      if (pStoreAPI->metaFn.getTableUidByName(pVnode, name, &uid) == 0) {
dengyihao's avatar
dengyihao 已提交
824
        ETableType tbType = TSDB_TABLE_MAX;
825
        if (pStoreAPI->metaFn.getTableTypeByName(pVnode, name, &tbType) == 0 && tbType == TSDB_CHILD_TABLE) {
D
dapan1121 已提交
826
          if (NULL == uHash || taosHashGet(uHash, &uid, sizeof(uid)) == NULL) {
827
            STUidTagInfo s = {.uid = uid, .name = name, .pTagVal = NULL};
H
Haojun Liao 已提交
828
            taosArrayPush(pExistedUidList, &s);
D
dapan1121 已提交
829
          }
dengyihao's avatar
dengyihao 已提交
830 831
        } else {
          taosArrayDestroy(pTbList);
D
dapan1121 已提交
832
          taosHashCleanup(uHash);
dengyihao's avatar
dengyihao 已提交
833 834
          return -1;
        }
dengyihao's avatar
dengyihao 已提交
835
      } else {
dengyihao's avatar
dengyihao 已提交
836
        //        qWarn("failed to get tableIds from by table name: %s, reason: %s", name, tstrerror(terrno));
dengyihao's avatar
dengyihao 已提交
837 838 839
        terrno = 0;
      }
    }
840

D
dapan1121 已提交
841
    taosHashCleanup(uHash);
dengyihao's avatar
dengyihao 已提交
842
    taosArrayDestroy(pTbList);
dengyihao's avatar
dengyihao 已提交
843
    return 0;
dengyihao's avatar
dengyihao 已提交
844
  }
H
Haojun Liao 已提交
845

dengyihao's avatar
dengyihao 已提交
846
  return -1;
dengyihao's avatar
dengyihao 已提交
847
}
H
Haojun Liao 已提交
848

D
dapan1121 已提交
849 850
static SSDataBlock* createTagValBlockForFilter(SArray* pColList, int32_t numOfTables, SArray* pUidTagList, void* pVnode,
                                               SStorageAPI* pStorageAPI) {
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
  SSDataBlock* pResBlock = createDataBlock();
  if (pResBlock == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

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

  int32_t code = blockDataEnsureCapacity(pResBlock, numOfTables);
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
H
Haojun Liao 已提交
866
    taosMemoryFree(pResBlock);
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
    return NULL;
  }

  pResBlock->info.rows = numOfTables;

  int32_t numOfCols = taosArrayGetSize(pResBlock->pDataBlock);

  for (int32_t i = 0; i < numOfTables; i++) {
    STUidTagInfo* p1 = taosArrayGet(pUidTagList, i);

    for (int32_t j = 0; j < numOfCols; j++) {
      SColumnInfoData* pColInfo = (SColumnInfoData*)taosArrayGet(pResBlock->pDataBlock, j);

      if (pColInfo->info.colId == -1) {  // tbname
        char str[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
H
Haojun Liao 已提交
882 883
        if (p1->name != NULL) {
          STR_TO_VARSTR(str, p1->name);
X
Xiaoyu Wang 已提交
884
        } else {  // name is not retrieved during filter
885
          pStorageAPI->metaFn.getTableNameByUid(pVnode, p1->uid, str);
H
Haojun Liao 已提交
886 887
        }

888
        colDataSetVal(pColInfo, i, str, false);
889 890 891 892 893 894 895
#if TAG_FILTER_DEBUG
        qDebug("tagfilter uid:%ld, tbname:%s", *uid, str + 2);
#endif
      } else {
        STagVal tagVal = {0};
        tagVal.cid = pColInfo->info.colId;
        if (p1->pTagVal == NULL) {
896
          colDataSetNULL(pColInfo, i);
H
Haojun Liao 已提交
897
        } else {
898
          const char* p = pStorageAPI->metaFn.extractTagVal(p1->pTagVal, pColInfo->info.type, &tagVal);
H
Haojun Liao 已提交
899 900 901 902 903 904 905 906 907 908

          if (p == NULL || (pColInfo->info.type == TSDB_DATA_TYPE_JSON && ((STag*)p)->nTag == 0)) {
            colDataSetNULL(pColInfo, i);
          } else if (pColInfo->info.type == TSDB_DATA_TYPE_JSON) {
            colDataSetVal(pColInfo, i, p, false);
          } else if (IS_VAR_DATA_TYPE(pColInfo->info.type)) {
            char* tmp = taosMemoryMalloc(tagVal.nData + VARSTR_HEADER_SIZE + 1);
            varDataSetLen(tmp, tagVal.nData);
            memcpy(tmp + VARSTR_HEADER_SIZE, tagVal.pData, tagVal.nData);
            colDataSetVal(pColInfo, i, tmp, false);
909
#if TAG_FILTER_DEBUG
H
Haojun Liao 已提交
910
            qDebug("tagfilter varch:%s", tmp + 2);
911
#endif
H
Haojun Liao 已提交
912 913 914
            taosMemoryFree(tmp);
          } else {
            colDataSetVal(pColInfo, i, (const char*)&tagVal.i64, false);
915
#if TAG_FILTER_DEBUG
H
Haojun Liao 已提交
916 917 918 919 920
            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));
            }
921
#endif
H
Haojun Liao 已提交
922
          }
923 924 925 926 927 928 929 930 931 932 933 934
        }
      }
    }
  }

  return pResBlock;
}

static void doSetQualifiedUid(SArray* pUidList, const SArray* pUidTagList, bool* pResultList) {
  taosArrayClear(pUidList);

  int32_t numOfTables = taosArrayGetSize(pUidTagList);
X
Xiaoyu Wang 已提交
935
  for (int32_t i = 0; i < numOfTables; ++i) {
936 937 938 939 940 941 942 943 944 945 946
    uint64_t uid = ((STUidTagInfo*)taosArrayGet(pUidTagList, i))->uid;
    qDebug("tagfilter get uid:%" PRId64 ", res:%d", uid, pResultList[i]);

    if (pResultList[i]) {
      taosArrayPush(pUidList, &uid);
    }
  }
}

static void copyExistedUids(SArray* pUidTagList, const SArray* pUidList) {
  int32_t numOfExisted = taosArrayGetSize(pUidList);
947 948 949 950
  if (numOfExisted == 0) {
    return;
  }

X
Xiaoyu Wang 已提交
951 952
  for (int32_t i = 0; i < numOfExisted; ++i) {
    uint64_t*    uid = taosArrayGet(pUidList, i);
953 954
    STUidTagInfo info = {.uid = *uid};
    taosArrayPush(pUidTagList, &info);
955 956 957
  }
}

958 959
static int32_t doFilterByTagCond(STableListInfo* pListInfo, SArray* pUidList, SNode* pTagCond, void* pVnode,
                                 SIdxFltStatus status, SStorageAPI* pAPI) {
960 961 962 963
  if (pTagCond == NULL) {
    return TSDB_CODE_SUCCESS;
  }

964
  terrno = TSDB_CODE_SUCCESS;
965 966 967 968 969

  int32_t      code = TSDB_CODE_SUCCESS;
  SArray*      pBlockList = NULL;
  SSDataBlock* pResBlock = NULL;
  SScalarParam output = {0};
970
  SArray*      pUidTagList = NULL;
971 972 973 974 975 976

  tagFilterAssist ctx = {0};
  ctx.colHash = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_SMALLINT), false, HASH_NO_LOCK);
  if (ctx.colHash == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
977 978
  }

979 980 981 982 983
  ctx.cInfoList = taosArrayInit(4, sizeof(SColumnInfo));
  if (ctx.cInfoList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }
984

985
  nodesRewriteExprPostOrder(&pTagCond, getColumn, (void*)&ctx);
986

987
  SDataType type = {.type = TSDB_DATA_TYPE_BOOL, .bytes = sizeof(bool)};
988

989
  //  int64_t stt = taosGetTimestampUs();
990
  pUidTagList = taosArrayInit(10, sizeof(STUidTagInfo));
991 992
  copyExistedUids(pUidTagList, pUidList);

X
Xiaoyu Wang 已提交
993 994
  FilterCondType condType = checkTagCond(pTagCond);

995
  int32_t filter = optimizeTbnameInCond(pVnode, pListInfo->idInfo.suid, pUidTagList, pTagCond, pAPI);
996
  if (filter == 0) {  // tbname in filter is activated, do nothing and return
997 998
    taosArrayClear(pUidList);

999 1000
    int32_t numOfRows = taosArrayGetSize(pUidTagList);
    taosArrayEnsureCap(pUidList, numOfRows);
X
Xiaoyu Wang 已提交
1001
    for (int32_t i = 0; i < numOfRows; ++i) {
1002 1003
      STUidTagInfo* pInfo = taosArrayGet(pUidTagList, i);
      taosArrayPush(pUidList, &pInfo->uid);
1004
    }
1005 1006
    terrno = 0;
  } else {
X
Xiaoyu Wang 已提交
1007
    if ((condType == FILTER_NO_LOGIC || condType == FILTER_AND) && status != SFLT_NOT_INDEX) {
1008
      code = pAPI->metaFn.getTableTagsByUid(pVnode, pListInfo->idInfo.suid, pUidTagList);
X
Xiaoyu Wang 已提交
1009
    } else {
1010
      code = pAPI->metaFn.getTableTags(pVnode, pListInfo->idInfo.suid, pUidTagList);
X
Xiaoyu Wang 已提交
1011
    }
1012
    if (code != TSDB_CODE_SUCCESS) {
1013
      qError("failed to get table tags from meta, reason:%s, suid:%" PRIu64, tstrerror(code), pListInfo->idInfo.suid);
1014 1015
      terrno = code;
      goto end;
1016 1017 1018
    }
  }

1019 1020 1021
  int32_t numOfTables = taosArrayGetSize(pUidTagList);
  if (numOfTables == 0) {
    goto end;
1022 1023
  }

1024
  pResBlock = createTagValBlockForFilter(ctx.cInfoList, numOfTables, pUidTagList, pVnode, pAPI);
H
Haojun Liao 已提交
1025 1026
  if (pResBlock == NULL) {
    code = terrno;
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
    goto end;
  }

  //  int64_t st1 = taosGetTimestampUs();
  //  qDebug("generate tag block rows:%d, cost:%ld us", rows, st1-st);
  pBlockList = taosArrayInit(2, POINTER_BYTES);
  taosArrayPush(pBlockList, &pResBlock);

  code = createResultData(&type, numOfTables, &output);
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1037
    terrno = code;
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
    goto end;
  }

  code = scalarCalculate(pTagCond, pBlockList, &output);
  if (code != TSDB_CODE_SUCCESS) {
    qError("failed to calculate scalar, reason:%s", tstrerror(code));
    terrno = code;
    goto end;
  }

X
Xiaoyu Wang 已提交
1048
  doSetQualifiedUid(pUidList, pUidTagList, (bool*)output.columnData->pData);
1049

X
Xiaoyu Wang 已提交
1050
end:
1051 1052 1053 1054
  taosHashCleanup(ctx.colHash);
  taosArrayDestroy(ctx.cInfoList);
  blockDataDestroy(pResBlock);
  taosArrayDestroy(pBlockList);
H
Haojun Liao 已提交
1055
  taosArrayDestroyEx(pUidTagList, freeItem);
1056 1057 1058

  colDataDestroy(output.columnData);
  taosMemoryFreeClear(output.columnData);
H
Haojun Liao 已提交
1059
  return code;
1060 1061
}

1062 1063
int32_t getTableList(void* pVnode, SScanPhysiNode* pScanNode, SNode* pTagCond, SNode* pTagIndexCond,
                     STableListInfo* pListInfo, uint8_t* digest, const char* idstr, SStorageAPI* pStorageAPI) {
1064
  int32_t code = TSDB_CODE_SUCCESS;
1065
  size_t  numOfTables = 0;
1066

1067 1068
  pListInfo->idInfo.suid = pScanNode->suid;
  pListInfo->idInfo.tableType = pScanNode->tableType;
1069

1070
  SArray* pUidList = taosArrayInit(8, sizeof(uint64_t));
dengyihao's avatar
dengyihao 已提交
1071

dengyihao's avatar
dengyihao 已提交
1072
  SIdxFltStatus status = SFLT_NOT_INDEX;
1073
  if (pScanNode->tableType != TSDB_SUPER_TABLE) {
1074
    pListInfo->idInfo.uid = pScanNode->uid;
1075
    if (pStorageAPI->metaFn.isTableExisted(pVnode, pScanNode->uid)) {
1076
      taosArrayPush(pUidList, &pScanNode->uid);
1077
    }
1078
    code = doFilterByTagCond(pListInfo, pUidList, pTagCond, pVnode, status, pStorageAPI);
1079
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1080
      goto _end;
H
Haojun Liao 已提交
1081
    }
1082 1083
  } else {
    T_MD5_CTX context = {0};
H
Haojun Liao 已提交
1084

1085 1086 1087 1088 1089
    if (tsTagFilterCache) {
      // try to retrieve the result from meta cache
      genTagFilterDigest(pTagCond, &context);

      bool acquired = false;
D
dapan1121 已提交
1090 1091
      pStorageAPI->metaFn.getCachedTableList(pVnode, pScanNode->suid, context.digest, tListLen(context.digest),
                                             pUidList, &acquired);
1092
      if (acquired) {
D
dapan1121 已提交
1093 1094
        digest[0] = 1;
        memcpy(digest + 1, context.digest, tListLen(context.digest));
1095
        qDebug("retrieve table uid list from cache, numOfTables:%d", (int32_t)taosArrayGetSize(pUidList));
1096 1097
        goto _end;
      }
wmmhello's avatar
wmmhello 已提交
1098 1099
    }

1100
    if (!pTagCond) {  // no tag filter condition exists, let's fetch all tables of this super table
1101
      pStorageAPI->metaFn.getChildTableList(pVnode, pScanNode->suid, pUidList);
1102
    } else {
H
Haojun Liao 已提交
1103 1104
      // failed to find the result in the cache, let try to calculate the results
      if (pTagIndexCond) {
1105
        void* pIndex = pStorageAPI->metaFn.getInvertIndex(pVnode);
1106

D
dapan1121 已提交
1107 1108 1109 1110
        SIndexMetaArg metaArg = {.metaEx = pVnode,
                                 .idx = pStorageAPI->metaFn.storeGetIndexInfo(pVnode),
                                 .ivtIdx = pIndex,
                                 .suid = pScanNode->uid};
H
Haojun Liao 已提交
1111

1112
        status = SFLT_NOT_INDEX;
H
Haojun Liao 已提交
1113
        code = doFilterTag(pTagIndexCond, &metaArg, pUidList, &status, &pStorageAPI->metaFilter);
H
Haojun Liao 已提交
1114
        if (code != 0 || status == SFLT_NOT_INDEX) {  // temporarily disable it for performance sake
D
dapan1121 已提交
1115
          qDebug("failed to get tableIds from index, suid:%" PRIu64, pScanNode->uid);
dengyihao's avatar
dengyihao 已提交
1116
        } else {
X
Xiaoyu Wang 已提交
1117
          qInfo("succ to get filter result, table num: %d", (int)taosArrayGetSize(pUidList));
H
Haojun Liao 已提交
1118
        }
wmmhello's avatar
wmmhello 已提交
1119 1120
      }
    }
1121

1122
    code = doFilterByTagCond(pListInfo, pUidList, pTagCond, pVnode, status, pStorageAPI);
1123
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1124
      goto _end;
wmmhello's avatar
wmmhello 已提交
1125 1126
    }

1127
    // let's add the filter results into meta-cache
1128
    numOfTables = taosArrayGetSize(pUidList);
1129

1130
    if (tsTagFilterCache) {
1131 1132
      size_t size = numOfTables * sizeof(uint64_t) + sizeof(int32_t);
      char*  pPayload = taosMemoryMalloc(size);
1133

1134
      *(int32_t*)pPayload = numOfTables;
1135
      if (numOfTables > 0) {
1136
        memcpy(pPayload + sizeof(int32_t), taosArrayGet(pUidList, 0), numOfTables * sizeof(uint64_t));
1137 1138
      }

D
dapan1121 已提交
1139
      pStorageAPI->metaFn.putCachedTableList(pVnode, pScanNode->suid, context.digest, tListLen(context.digest), pPayload, size, 1);
D
dapan1121 已提交
1140 1141
      digest[0] = 1;
      memcpy(digest + 1, context.digest, tListLen(context.digest));
1142
    }
wmmhello's avatar
wmmhello 已提交
1143 1144
  }

1145
_end:
1146
  numOfTables = taosArrayGetSize(pUidList);
H
Haojun Liao 已提交
1147
  for (int i = 0; i < numOfTables; i++) {
1148
    STableKeyInfo info = {.uid = *(uint64_t*)taosArrayGet(pUidList, i), .groupId = 0};
1149 1150

    void* p = taosArrayPush(pListInfo->pTableList, &info);
H
Haojun Liao 已提交
1151
    if (p == NULL) {
1152
      taosArrayDestroy(pUidList);
H
Haojun Liao 已提交
1153 1154 1155
      return TSDB_CODE_OUT_OF_MEMORY;
    }

X
Xiaoyu Wang 已提交
1156
    qTrace("tagfilter get uid:%" PRIu64 ", %s", info.uid, idstr);
1157 1158
  }

1159
  taosArrayDestroy(pUidList);
1160 1161
  return code;
}
H
Haojun Liao 已提交
1162

D
dapan1121 已提交
1163 1164
int32_t qGetTableList(int64_t suid, void* pVnode, void* node, SArray** tableList, void* pTaskInfo) {
  SSubplan*      pSubplan = (SSubplan*)node;
1165 1166 1167 1168
  SScanPhysiNode pNode = {0};
  pNode.suid = suid;
  pNode.uid = suid;
  pNode.tableType = TSDB_SUPER_TABLE;
1169
  STableListInfo* pTableListInfo = tableListCreate();
D
dapan1121 已提交
1170 1171 1172 1173
  uint8_t         digest[17] = {0};
  int             code =
      getTableList(pVnode, &pNode, pSubplan ? pSubplan->pTagCond : NULL, pSubplan ? pSubplan->pTagIndexCond : NULL,
                   pTableListInfo, digest, "qGetTableList", &((SExecTaskInfo*)pTaskInfo)->storageAPI);
1174 1175 1176 1177 1178 1179
  *tableList = pTableListInfo->pTableList;
  pTableListInfo->pTableList = NULL;
  tableListDestroy(pTableListInfo);
  return code;
}

1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
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;
}

1193
int32_t getGroupIdFromTagsVal(void* pVnode, uint64_t uid, SNodeList* pGroupNode, char* keyBuf, uint64_t* pGroupId,
D
dapan1121 已提交
1194
                              SStorageAPI* pAPI) {
M
Minglei Jin 已提交
1195
  SMetaReader mr = {0};
1196

H
Haojun Liao 已提交
1197
  pAPI->metaReaderFn.initReader(&mr, pVnode, 0, &pAPI->metaFn);
1198
  if (pAPI->metaReaderFn.getEntryGetUidCache(&mr, uid) != 0) {  // table not exist
1199
    pAPI->metaReaderFn.clearReader(&mr);
1200 1201
    return TSDB_CODE_PAR_TABLE_NOT_EXIST;
  }
1202 1203 1204 1205 1206

  SNodeList* groupNew = nodesCloneList(pGroupNode);

  nodesRewriteExprsPostOrder(groupNew, doTranslateTagExpr, &mr);
  char* isNull = (char*)keyBuf;
M
Minglei Jin 已提交
1207
  char* pStart = (char*)keyBuf + sizeof(int8_t) * LIST_LENGTH(pGroupNode);
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217

  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 {
      nodesDestroyList(groupNew);
1218
      pAPI->metaReaderFn.clearReader(&mr);
1219 1220 1221
      return code;
    }

1222
    ASSERT(nodeType(pNew) == QUERY_NODE_VALUE);
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
    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;
          nodesDestroyList(groupNew);
1235
          pAPI->metaReaderFn.clearReader(&mr);
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
          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 已提交
1251
  int32_t len = (int32_t)(pStart - (char*)keyBuf);
1252 1253 1254
  *pGroupId = calcGroupId(keyBuf, len);

  nodesDestroyList(groupNew);
1255
  pAPI->metaReaderFn.clearReader(&mr);
1256 1257 1258
  return TSDB_CODE_SUCCESS;
}

1259
SArray* extractPartitionColInfo(SNodeList* pNodeList) {
dengyihao's avatar
dengyihao 已提交
1260
  if (!pNodeList) {
1261 1262
    return NULL;
  }
H
Haojun Liao 已提交
1263

1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
  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 已提交
1285

1286
  return pList;
H
Haojun Liao 已提交
1287 1288
}

H
Haojun Liao 已提交
1289 1290
int32_t extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols,
                            int32_t type, SColMatchInfo* pMatchInfo) {
H
Haojun Liao 已提交
1291
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
1292 1293 1294 1295
  int32_t code = 0;

  pMatchInfo->matchType = type;

1296
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColMatchItem));
1297
  if (pList == NULL) {
H
Haojun Liao 已提交
1298 1299
    code = TSDB_CODE_OUT_OF_MEMORY;
    return code;
1300 1301 1302 1303
  }

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

H
Haojun Liao 已提交
1307
      SColMatchItem c = {.needOutput = true};
1308 1309
      c.colId = pColNode->colId;
      c.srcSlotId = pColNode->slotId;
H
Haojun Liao 已提交
1310
      c.dstSlotId = pNode->slotId;
1311
      c.dataType = pColNode->node.resType;
1312 1313
      taosArrayPush(pList, &c);
    }
1314 1315
  }

H
Haojun Liao 已提交
1316
  // set the output flag for each column in SColMatchInfo, according to the
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
  *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 已提交
1329
    SColMatchItem* info = NULL;
1330 1331
    for (int32_t j = 0; j < taosArrayGetSize(pList); ++j) {
      info = taosArrayGet(pList, j);
H
Haojun Liao 已提交
1332
      if (info->dstSlotId == pNode->slotId) {
1333 1334 1335
        break;
      }
    }
1336

1337 1338
    if (pNode->output) {
      (*numOfOutputCols) += 1;
H
Haojun Liao 已提交
1339 1340
    } else if (info != NULL) {
      // select distinct tbname from stb where tbname='abc';
H
Haojun Liao 已提交
1341
      info->needOutput = false;
1342
    }
1343
  }
1344

H
Haojun Liao 已提交
1345
  pMatchInfo->pList = pList;
H
Haojun Liao 已提交
1346
  return code;
1347 1348
}

1349 1350 1351 1352 1353 1354 1355 1356
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 已提交
1357
  tstrncpy(s.name, name, tListLen(s.name));
1358 1359 1360

  return s;
}
1361

H
Haojun Liao 已提交
1362
static SColumn* createColumn(int32_t blockId, int32_t slotId, int32_t colId, SDataType* pType, EColumnType colType) {
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
  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 已提交
1376
  pCol->colType = colType;
1377 1378 1379
  return pCol;
}

1380
void createExprFromOneNode(SExprInfo* pExp, SNode* pNode, int16_t slotId) {
1381 1382 1383 1384
  pExp->pExpr = taosMemoryCalloc(1, sizeof(tExprNode));
  pExp->pExpr->_function.num = 1;
  pExp->pExpr->_function.functionId = -1;

1385
  int32_t type = nodeType(pNode);
1386 1387 1388
  // it is a project query, or group by column
  if (type == QUERY_NODE_COLUMN) {
    pExp->pExpr->nodeType = QUERY_NODE_COLUMN;
1389
    SColumnNode* pColNode = (SColumnNode*)pNode;
1390 1391 1392 1393 1394

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

    SDataType* pType = &pColNode->node.resType;
1395 1396
    pExp->base.resSchema =
        createResSchema(pType->type, pType->bytes, slotId, pType->scale, pType->precision, pColNode->colName);
1397 1398 1399 1400 1401
    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;
1402
    SValueNode* pValNode = (SValueNode*)pNode;
1403 1404 1405 1406 1407

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

    SDataType* pType = &pValNode->node.resType;
1408 1409
    pExp->base.resSchema =
        createResSchema(pType->type, pType->bytes, slotId, pType->scale, pType->precision, pValNode->node.aliasName);
1410 1411 1412 1413
    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;
1414
    SFunctionNode* pFuncNode = (SFunctionNode*)pNode;
1415 1416

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

H
Haojun Liao 已提交
1420 1421 1422 1423
    tExprNode* pExprNode = pExp->pExpr;

    pExprNode->_function.functionId = pFuncNode->funcId;
    pExprNode->_function.pFunctNode = pFuncNode;
S
shenglian zhou 已提交
1424
    pExprNode->_function.functionType = pFuncNode->funcType;
H
Haojun Liao 已提交
1425 1426

    tstrncpy(pExprNode->_function.functionName, pFuncNode->functionName, tListLen(pExprNode->_function.functionName));
1427 1428 1429

#if 1
    // todo refactor: add the parameter for tbname function
H
Haojun Liao 已提交
1430
    const char* name = "tbname";
dengyihao's avatar
dengyihao 已提交
1431
    int32_t     len = strlen(name);
H
Haojun Liao 已提交
1432 1433 1434

    if (!pFuncNode->pParameterList && (memcmp(pExprNode->_function.functionName, name, len) == 0) &&
        pExprNode->_function.functionName[len] == 0) {
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
      pFuncNode->pParameterList = nodesMakeList();
      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;
1466
    SOperatorNode* pOpNode = (SOperatorNode*)pNode;
1467 1468 1469 1470

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

1471 1472 1473 1474
    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 已提交
1475 1476
  } else if (type == QUERY_NODE_CASE_WHEN) {
    pExp->pExpr->nodeType = QUERY_NODE_OPERATOR;
D
dapan1121 已提交
1477
    SCaseWhenNode* pCaseNode = (SCaseWhenNode*)pNode;
dengyihao's avatar
dengyihao 已提交
1478

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

D
dapan1121 已提交
1482
    SDataType* pType = &pCaseNode->node.resType;
dengyihao's avatar
dengyihao 已提交
1483 1484
    pExp->base.resSchema =
        createResSchema(pType->type, pType->bytes, slotId, pType->scale, pType->precision, pCaseNode->node.aliasName);
D
dapan1121 已提交
1485
    pExp->pExpr->_optrRoot.pRootNode = pNode;
1486
  } else {
1487
    ASSERT(0);
1488 1489 1490
  }
}

1491 1492 1493 1494
void createExprFromTargetNode(SExprInfo* pExp, STargetNode* pTargetNode) {
  createExprFromOneNode(pExp, pTargetNode->pExpr, pTargetNode->slotId);
}

5
54liuyao 已提交
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
SExprInfo* createExpr(SNodeList* pNodeList, int32_t* numOfExprs) {
  *numOfExprs = LIST_LENGTH(pNodeList);
  SExprInfo* pExprs = taosMemoryCalloc(*numOfExprs, sizeof(SExprInfo));

  for (int32_t i = 0; i < (*numOfExprs); ++i) {
    SExprInfo* pExp = &pExprs[i];
    createExprFromOneNode(pExp, nodesListGetNode(pNodeList, i), i + UD_TAG_COLUMN_INDEX);
  }

  return pExprs;
}

1507 1508 1509 1510 1511 1512 1513 1514
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;
1515 1516 1517 1518
  if (*numOfExprs == 0) {
    return NULL;
  }

1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
  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];
1530
    createExprFromTargetNode(pExp, pTargetNode);
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
  }

  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) {
S
Shengliang Guan 已提交
1543
    return TSDB_CODE_OUT_OF_MEMORY;
1544 1545
  }

Y
yihaoDeng 已提交
1546
  SHashObj* pSelectFuncs = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_ENTRY_LOCK);
1547
  for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
1548
    const char* pName = pCtx[i].pExpr->pExpr->_function.functionName;
1549
    if ((strcmp(pName, "_select_value") == 0) || (strcmp(pName, "_group_key") == 0)) {
1550 1551
      pValCtx[num++] = &pCtx[i];
    } else if (fmIsSelectFunc(pCtx[i].functionId)) {
G
Ganlin Zhao 已提交
1552
      void* data = taosHashGet(pSelectFuncs, pName, strlen(pName));
G
fix  
Ganlin Zhao 已提交
1553 1554 1555 1556 1557 1558 1559
      if (taosHashGetSize(pSelectFuncs) != 0 && data == NULL) {
        p = NULL;
        break;
      } else {
        taosHashPut(pSelectFuncs, pName, strlen(pName), &num, sizeof(num));
        p = &pCtx[i];
      }
1560 1561
    }
  }
G
fix  
Ganlin Zhao 已提交
1562
  taosHashCleanup(pSelectFuncs);
H
Haojun Liao 已提交
1563

1564 1565 1566
  if (p != NULL) {
    p->subsidiaries.pCtx = pValCtx;
    p->subsidiaries.num = num;
1567
  } else {
1568
    taosMemoryFreeClear(pValCtx);
1569
  }
1570 1571

  return TSDB_CODE_SUCCESS;
1572 1573
}

D
dapan1121 已提交
1574 1575
SqlFunctionCtx* createSqlFunctionCtx(SExprInfo* pExprInfo, int32_t numOfOutput, int32_t** rowEntryInfoOffset,
                                     SFunctionStateStore* pStore) {
1576 1577 1578 1579
  SqlFunctionCtx* pFuncCtx = (SqlFunctionCtx*)taosMemoryCalloc(numOfOutput, sizeof(SqlFunctionCtx));
  if (pFuncCtx == NULL) {
    return NULL;
  }
1580

1581 1582
  *rowEntryInfoOffset = taosMemoryCalloc(numOfOutput, sizeof(int32_t));
  if (*rowEntryInfoOffset == 0) {
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
    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;
1599
      pCtx->isPseudoFunc = fmIsWindowPseudoColumnFunc(pCtx->functionId);
1600
      pCtx->isNotNullFunc = fmIsNotNullOutputFunc(pCtx->functionId);
1601 1602 1603 1604 1605 1606 1607

      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;
1608
          pCtx->udfName = taosStrdup(udfName);
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
          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;
    pCtx->param = pFunct->pParam;
1637
    pCtx->saveHandle.currentPage = -1;
1638
    pCtx->pStore = pStore;
1639 1640 1641
  }

  for (int32_t i = 1; i < numOfOutput; ++i) {
dengyihao's avatar
dengyihao 已提交
1642 1643
    (*rowEntryInfoOffset)[i] = (int32_t)((*rowEntryInfoOffset)[i - 1] + sizeof(SResultRowEntryInfo) +
                                         pFuncCtx[i - 1].resDataInfo.interBufSize);
1644 1645 1646 1647
  }

  setSelectValueColumnInfo(pFuncCtx, numOfOutput);
  return pFuncCtx;
1648
}
1649 1650

// NOTE: sources columns are more than the destination SSDatablock columns.
1651 1652
// doFilter in table scan needs every column even its output is false
void relocateColumnData(SSDataBlock* pBlock, const SArray* pColMatchInfo, SArray* pCols, bool outputEveryColumn) {
1653 1654 1655 1656 1657
  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 已提交
1658
    SColMatchItem*   pmInfo = taosArrayGet(pColMatchInfo, j);
1659 1660

    if (p->info.colId == pmInfo->colId) {
H
Haojun Liao 已提交
1661
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, pmInfo->dstSlotId);
1662
      colDataAssign(pDst, p, pBlock->info.rows, &pBlock->info);
1663 1664 1665 1666 1667
      i++;
      j++;
    } else if (p->info.colId < pmInfo->colId) {
      i++;
    } else {
1668
      ASSERT(0);
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
    }
  }
}

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 已提交
1687

1688 1689 1690 1691 1692
  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;
1693 1694 1695 1696 1697 1698 1699
  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);
H
Haojun Liao 已提交
1700

1701
  pCond->colList = taosMemoryCalloc(pCond->numOfCols, sizeof(SColumnInfo));
dengyihao's avatar
dengyihao 已提交
1702
  pCond->pSlotList = taosMemoryMalloc(sizeof(int32_t) * pCond->numOfCols);
H
Haojun Liao 已提交
1703
  if (pCond->colList == NULL || pCond->pSlotList == NULL) {
S
Shengliang Guan 已提交
1704
    terrno = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
1705 1706
    taosMemoryFreeClear(pCond->colList);
    taosMemoryFreeClear(pCond->pSlotList);
1707 1708 1709 1710
    return terrno;
  }

  // TODO: get it from stable scan node
H
Haojun Liao 已提交
1711
  pCond->twindows = pTableScanNode->scanRange;
1712
  pCond->suid = pTableScanNode->scan.suid;
1713
  pCond->type = TIMEWINDOW_RANGE_CONTAINED;
H
Haojun Liao 已提交
1714
  pCond->startVersion = -1;
1715
  pCond->endVersion = -1;
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727

  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;
H
Haojun Liao 已提交
1728 1729

    pCond->pSlotList[j] = pNode->slotId;
1730 1731 1732 1733 1734 1735 1736
    j += 1;
  }

  pCond->numOfCols = j;
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1737 1738 1739 1740
void cleanupQueryTableDataCond(SQueryTableDataCond* pCond) {
  taosMemoryFreeClear(pCond->colList);
  taosMemoryFreeClear(pCond->pSlotList);
}
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753

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;
D
dapan1121 已提交
1754 1755 1756
    case FILL_MODE_NULL_F:
      type = TSDB_FILL_NULL_F;
      break;
1757 1758 1759 1760 1761 1762
    case FILL_MODE_NEXT:
      type = TSDB_FILL_NEXT;
      break;
    case FILL_MODE_VALUE:
      type = TSDB_FILL_SET_VALUE;
      break;
D
dapan1121 已提交
1763 1764 1765
    case FILL_MODE_VALUE_F:
      type = TSDB_FILL_SET_VALUE_F;
      break;
1766 1767 1768 1769 1770 1771 1772 1773 1774
    case FILL_MODE_LINEAR:
      type = TSDB_FILL_LINEAR;
      break;
    default:
      type = TSDB_FILL_NONE;
  }

  return type;
}
H
Haojun Liao 已提交
1775

1776
void getInitialStartTimeWindow(SInterval* pInterval, TSKEY ts, STimeWindow* w, bool ascQuery) {
H
Haojun Liao 已提交
1777
  if (ascQuery) {
1778
    *w = getAlignQueryTimeWindow(pInterval, ts);
H
Haojun Liao 已提交
1779 1780
  } else {
    // the start position of the first time window in the endpoint that spreads beyond the queried last timestamp
1781
    *w = getAlignQueryTimeWindow(pInterval, ts);
H
Haojun Liao 已提交
1782 1783 1784 1785

    int64_t key = w->skey;
    while (key < ts) {  // moving towards end
      key = taosTimeAdd(key, pInterval->sliding, pInterval->slidingUnit, pInterval->precision);
D
dapan1121 已提交
1786
      if (key > ts) {
H
Haojun Liao 已提交
1787 1788 1789 1790 1791 1792 1793 1794 1795
        break;
      }

      w->skey = key;
    }
  }
}

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

1798
  w.skey = taosTimeTruncate(ts, pInterval);
1799
  w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1;
H
Haojun Liao 已提交
1800 1801 1802
  return w;
}

1803
STimeWindow getFirstQualifiedTimeWindow(int64_t ts, STimeWindow* pWindow, SInterval* pInterval, int32_t order) {
1804
  int32_t factor = (order == TSDB_ORDER_ASC) ? -1 : 1;
H
Haojun Liao 已提交
1805 1806 1807

  STimeWindow win = *pWindow;
  STimeWindow save = win;
1808
  while (win.skey <= ts && win.ekey >= ts) {
H
Haojun Liao 已提交
1809 1810 1811 1812 1813 1814 1815 1816 1817
    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
1818
// todo refactor
H
Haojun Liao 已提交
1819 1820 1821 1822 1823 1824 1825 1826 1827
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;
  }

1828 1829 1830 1831
  SResultRow* pRow = getResultRowByPos(pBuf, &pResultRowInfo->cur, false);
  if (pRow) {
    w = pRow->win;
  }
1832

H
Haojun Liao 已提交
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
  // 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;
1845 1846
}

1847 1848
void getNextTimeWindow(const SInterval* pInterval, STimeWindow* tw, int32_t order) {
  int32_t factor = GET_FORWARD_DIRECTION_FACTOR(order);
H
Haojun Liao 已提交
1849
  if (!IS_CALENDAR_TIME_DURATION(pInterval->slidingUnit)) {
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
    tw->skey += pInterval->sliding * factor;
    tw->ekey = taosTimeAdd(tw->skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1;
    return;
  }

  // convert key to second
  int64_t key = convertTimePrecision(tw->skey, pInterval->precision, TSDB_TIME_PRECISION_MILLI) / 1000;

  int64_t duration = pInterval->sliding;
  if (pInterval->slidingUnit == 'y') {
    duration *= 12;
  }

  struct tm tm;
D
dapan1121 已提交
1864
  time_t    t = (time_t)key;
H
Haojun Liao 已提交
1865
  taosLocalTime(&t, &tm, NULL);
1866 1867 1868 1869 1870 1871 1872 1873 1874

  int mon = (int)(tm.tm_year * 12 + tm.tm_mon + duration * factor);
  tm.tm_year = mon / 12;
  tm.tm_mon = mon % 12;
  tw->skey = convertTimePrecision((int64_t)taosMktime(&tm) * 1000LL, TSDB_TIME_PRECISION_MILLI, pInterval->precision);

  tw->ekey = taosTimeAdd(tw->skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1;
}

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

1880 1881 1882 1883
bool hasSlimitOffsetInfo(SLimitInfo* pLimitInfo) {
  return (pLimitInfo->slimit.limit != -1 || pLimitInfo->slimit.offset != -1);
}

1884 1885 1886 1887 1888
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;
1889
  pLimitInfo->slimit = slimit;
1890 1891
  pLimitInfo->remainOffset = limit.offset;
  pLimitInfo->remainGroupOffset = slimit.offset;
1892
}
H
Haojun Liao 已提交
1893

1894 1895 1896 1897 1898
void resetLimitInfoForNextGroup(SLimitInfo* pLimitInfo) {
  pLimitInfo->numOfOutputRows = 0;
  pLimitInfo->remainOffset = pLimitInfo->limit.offset;
}

H
Haojun Liao 已提交
1899
uint64_t tableListGetSize(const STableListInfo* pTableList) {
1900
  ASSERT(taosArrayGetSize(pTableList->pTableList) == taosHashGetSize(pTableList->map));
H
Haojun Liao 已提交
1901 1902 1903
  return taosArrayGetSize(pTableList->pTableList);
}

Y
yihaoDeng 已提交
1904
uint64_t tableListGetSuid(const STableListInfo* pTableList) { return pTableList->idInfo.suid; }
H
Haojun Liao 已提交
1905 1906 1907 1908 1909 1910 1911 1912 1913

STableKeyInfo* tableListGetInfo(const STableListInfo* pTableList, int32_t index) {
  if (taosArrayGetSize(pTableList->pTableList) == 0) {
    return NULL;
  }

  return taosArrayGet(pTableList->pTableList, index);
}

1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
int32_t tableListFind(const STableListInfo* pTableList, uint64_t uid, int32_t startIndex) {
  int32_t numOfTables = taosArrayGetSize(pTableList->pTableList);
  if (startIndex >= numOfTables) {
    return -1;
  }

  for (int32_t i = startIndex; i < numOfTables; ++i) {
    STableKeyInfo* p = taosArrayGet(pTableList->pTableList, i);
    if (p->uid == uid) {
      return i;
    }
  }
  return -1;
}

1929 1930 1931 1932
void tableListGetSourceTableInfo(const STableListInfo* pTableList, uint64_t* psuid, uint64_t* uid, int32_t* type) {
  *psuid = pTableList->idInfo.suid;
  *uid = pTableList->idInfo.uid;
  *type = pTableList->idInfo.tableType;
1933 1934
}

H
Haojun Liao 已提交
1935 1936
uint64_t getTableGroupId(const STableListInfo* pTableList, uint64_t tableUid) {
  int32_t* slot = taosHashGet(pTableList->map, &tableUid, sizeof(tableUid));
1937
  ASSERT(pTableList->map != NULL && slot != NULL);
H
Haojun Liao 已提交
1938 1939

  STableKeyInfo* pKeyInfo = taosArrayGet(pTableList->pTableList, *slot);
1940
  ASSERT(pKeyInfo->uid == tableUid);
H
Haojun Liao 已提交
1941 1942 1943 1944

  return pKeyInfo->groupId;
}

H
Haojun Liao 已提交
1945
// TODO handle the group offset info, fix it, the rule of group output will be broken by this function
H
Haojun Liao 已提交
1946
int32_t tableListAddTableInfo(STableListInfo* pTableList, uint64_t uid, uint64_t gid) {
H
Haojun Liao 已提交
1947
  if (pTableList->map == NULL) {
1948
    pTableList->map = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_ENTRY_LOCK);
H
Haojun Liao 已提交
1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
  }

  STableKeyInfo keyInfo = {.uid = uid, .groupId = gid};
  taosArrayPush(pTableList->pTableList, &keyInfo);

  int32_t slot = (int32_t)taosArrayGetSize(pTableList->pTableList) - 1;
  taosHashPut(pTableList->map, &uid, sizeof(uid), &slot, sizeof(slot));

  qDebug("uid:%" PRIu64 ", groupId:%" PRIu64 " added into table list, slot:%d, total:%d", uid, gid, slot, slot + 1);
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1961
int32_t tableListGetGroupList(const STableListInfo* pTableList, int32_t ordinalGroupIndex, STableKeyInfo** pKeyInfo,
dengyihao's avatar
dengyihao 已提交
1962
                              int32_t* size) {
1963
  int32_t totalGroups = tableListGetOutputGroups(pTableList);
X
Xiaoyu Wang 已提交
1964
  int32_t numOfTables = tableListGetSize(pTableList);
1965 1966

  if (ordinalGroupIndex < 0 || ordinalGroupIndex >= totalGroups) {
H
Haojun Liao 已提交
1967 1968 1969 1970 1971
    return TSDB_CODE_INVALID_PARA;
  }

  // here handle two special cases:
  // 1. only one group exists, and 2. one table exists for each group.
1972 1973
  if (totalGroups == 1) {
    *size = numOfTables;
dengyihao's avatar
dengyihao 已提交
1974
    *pKeyInfo = (*size == 0) ? NULL : taosArrayGet(pTableList->pTableList, 0);
H
Haojun Liao 已提交
1975
    return TSDB_CODE_SUCCESS;
1976
  } else if (totalGroups == numOfTables) {
H
Haojun Liao 已提交
1977 1978 1979 1980 1981 1982
    *size = 1;
    *pKeyInfo = taosArrayGet(pTableList->pTableList, ordinalGroupIndex);
    return TSDB_CODE_SUCCESS;
  }

  int32_t offset = pTableList->groupOffset[ordinalGroupIndex];
1983
  if (ordinalGroupIndex < totalGroups - 1) {
1984
    *size = pTableList->groupOffset[ordinalGroupIndex + 1] - offset;
H
Haojun Liao 已提交
1985
  } else {
1986
    *size = numOfTables - offset;
H
Haojun Liao 已提交
1987 1988 1989 1990 1991 1992
  }

  *pKeyInfo = taosArrayGet(pTableList->pTableList, offset);
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1993
int32_t tableListGetOutputGroups(const STableListInfo* pTableList) { return pTableList->numOfOuputGroups; }
H
Haojun Liao 已提交
1994 1995 1996

bool oneTableForEachGroup(const STableListInfo* pTableList) { return pTableList->oneTableForEachGroup; }

H
Haojun Liao 已提交
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
STableListInfo* tableListCreate() {
  STableListInfo* pListInfo = taosMemoryCalloc(1, sizeof(STableListInfo));
  if (pListInfo == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  pListInfo->pTableList = taosArrayInit(4, sizeof(STableKeyInfo));
  if (pListInfo->pTableList == NULL) {
    goto _error;
  }

2009
  pListInfo->map = taosHashInit(1024, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_ENTRY_LOCK);
H
Haojun Liao 已提交
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
  if (pListInfo->map == NULL) {
    goto _error;
  }

  pListInfo->numOfOuputGroups = 1;
  return pListInfo;

_error:
  tableListDestroy(pListInfo);
  terrno = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
}

void* tableListDestroy(STableListInfo* pTableListInfo) {
2024 2025 2026
  if (pTableListInfo == NULL) {
    return NULL;
  }
H
Haojun Liao 已提交
2027

H
Haojun Liao 已提交
2028 2029
  pTableListInfo->pTableList = taosArrayDestroy(pTableListInfo->pTableList);
  taosMemoryFreeClear(pTableListInfo->groupOffset);
H
Haojun Liao 已提交
2030

H
Haojun Liao 已提交
2031 2032 2033 2034 2035 2036 2037 2038 2039
  taosHashCleanup(pTableListInfo->map);

  pTableListInfo->pTableList = NULL;
  pTableListInfo->map = NULL;
  taosMemoryFree(pTableListInfo);
  return NULL;
}

void tableListClear(STableListInfo* pTableListInfo) {
H
Haojun Liao 已提交
2040 2041 2042 2043
  if (pTableListInfo == NULL) {
    return;
  }

H
Haojun Liao 已提交
2044 2045 2046 2047 2048 2049 2050 2051
  taosArrayClear(pTableListInfo->pTableList);
  taosHashClear(pTableListInfo->map);
  taosMemoryFree(pTableListInfo->groupOffset);
  pTableListInfo->numOfOuputGroups = 1;
  pTableListInfo->oneTableForEachGroup = false;
}

static int32_t orderbyGroupIdComparFn(const void* p1, const void* p2) {
dengyihao's avatar
dengyihao 已提交
2052 2053
  STableKeyInfo* pInfo1 = (STableKeyInfo*)p1;
  STableKeyInfo* pInfo2 = (STableKeyInfo*)p2;
H
Haojun Liao 已提交
2054 2055 2056 2057

  if (pInfo1->groupId == pInfo2->groupId) {
    return 0;
  } else {
dengyihao's avatar
dengyihao 已提交
2058
    return pInfo1->groupId < pInfo2->groupId ? -1 : 1;
H
Haojun Liao 已提交
2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
  }
}

static int32_t sortTableGroup(STableListInfo* pTableListInfo) {
  taosArraySort(pTableListInfo->pTableList, orderbyGroupIdComparFn);
  int32_t size = taosArrayGetSize(pTableListInfo->pTableList);

  SArray* pList = taosArrayInit(4, sizeof(int32_t));

  STableKeyInfo* pInfo = taosArrayGet(pTableListInfo->pTableList, 0);
dengyihao's avatar
dengyihao 已提交
2069
  uint64_t       gid = pInfo->groupId;
2070

H
Haojun Liao 已提交
2071 2072
  int32_t start = 0;
  taosArrayPush(pList, &start);
2073

dengyihao's avatar
dengyihao 已提交
2074
  for (int32_t i = 1; i < size; ++i) {
H
Haojun Liao 已提交
2075 2076 2077 2078 2079 2080 2081 2082 2083
    pInfo = taosArrayGet(pTableListInfo->pTableList, i);
    if (pInfo->groupId != gid) {
      taosArrayPush(pList, &i);
      gid = pInfo->groupId;
    }
  }

  pTableListInfo->numOfOuputGroups = taosArrayGetSize(pList);
  pTableListInfo->groupOffset = taosMemoryMalloc(sizeof(int32_t) * pTableListInfo->numOfOuputGroups);
H
Haojun Liao 已提交
2084 2085 2086 2087 2088
  if (pTableListInfo->groupOffset == NULL) {
    taosArrayDestroy(pList);
    return TSDB_CODE_OUT_OF_MEMORY;
  }

H
Haojun Liao 已提交
2089 2090
  memcpy(pTableListInfo->groupOffset, taosArrayGet(pList, 0), sizeof(int32_t) * pTableListInfo->numOfOuputGroups);
  taosArrayDestroy(pList);
2091
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2092 2093
}

D
dapan1121 已提交
2094 2095
int32_t buildGroupIdMapForAllTables(STableListInfo* pTableListInfo, SReadHandle* pHandle, SScanPhysiNode* pScanNode,
                                    SNodeList* group, bool groupSort, uint8_t* digest, SStorageAPI* pAPI) {
H
Haojun Liao 已提交
2096 2097
  int32_t code = TSDB_CODE_SUCCESS;

dengyihao's avatar
dengyihao 已提交
2098
  bool   groupByTbname = groupbyTbname(group);
H
Haojun Liao 已提交
2099 2100 2101 2102
  size_t numOfTables = taosArrayGetSize(pTableListInfo->pTableList);
  if (group == NULL || groupByTbname) {
    for (int32_t i = 0; i < numOfTables; i++) {
      STableKeyInfo* info = taosArrayGet(pTableListInfo->pTableList, i);
dengyihao's avatar
dengyihao 已提交
2103
      info->groupId = groupByTbname ? info->uid : 0;
H
Haojun Liao 已提交
2104 2105 2106 2107 2108 2109 2110
    }

    pTableListInfo->oneTableForEachGroup = groupByTbname;

    if (groupSort && groupByTbname) {
      taosArraySort(pTableListInfo->pTableList, orderbyGroupIdComparFn);
      pTableListInfo->numOfOuputGroups = numOfTables;
2111 2112
    } else if (groupByTbname && pScanNode->groupOrderScan){
      pTableListInfo->numOfOuputGroups = numOfTables;
H
Haojun Liao 已提交
2113 2114 2115 2116
    } else {
      pTableListInfo->numOfOuputGroups = 1;
    }
  } else {
2117
    code = getColInfoResultForGroupby(pHandle->vnode, group, pTableListInfo, digest, pAPI);
H
Haojun Liao 已提交
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    if (groupSort) {
      code = sortTableGroup(pTableListInfo);
    }
  }

  // add all table entry in the hash map
  size_t size = taosArrayGetSize(pTableListInfo->pTableList);
dengyihao's avatar
dengyihao 已提交
2129
  for (int32_t i = 0; i < size; ++i) {
H
Haojun Liao 已提交
2130 2131 2132 2133 2134 2135 2136 2137 2138
    STableKeyInfo* p = taosArrayGet(pTableListInfo->pTableList, i);
    taosHashPut(pTableListInfo->map, &p->uid, sizeof(uint64_t), &i, sizeof(int32_t));
  }

  return code;
}

int32_t createScanTableListInfo(SScanPhysiNode* pScanNode, SNodeList* pGroupTags, bool groupSort, SReadHandle* pHandle,
                                STableListInfo* pTableListInfo, SNode* pTagCond, SNode* pTagIndexCond,
H
Haojun Liao 已提交
2139
                                SExecTaskInfo* pTaskInfo) {
dengyihao's avatar
dengyihao 已提交
2140
  int64_t     st = taosGetTimestampUs();
H
Haojun Liao 已提交
2141
  const char* idStr = GET_TASKID(pTaskInfo);
H
Haojun Liao 已提交
2142 2143 2144 2145 2146 2147

  if (pHandle == NULL) {
    qError("invalid handle, in creating operator tree, %s", idStr);
    return TSDB_CODE_INVALID_PARA;
  }

D
dapan1121 已提交
2148
  uint8_t digest[17] = {0};
D
dapan1121 已提交
2149 2150
  int32_t code = getTableList(pHandle->vnode, pScanNode, pTagCond, pTagIndexCond, pTableListInfo, digest, idStr,
                              &pTaskInfo->storageAPI);
H
Haojun Liao 已提交
2151 2152 2153 2154 2155
  if (code != TSDB_CODE_SUCCESS) {
    qError("failed to getTableList, code: %s", tstrerror(code));
    return code;
  }

H
Haojun Liao 已提交
2156
  int32_t numOfTables = taosArrayGetSize(pTableListInfo->pTableList);
H
Haojun Liao 已提交
2157 2158

  int64_t st1 = taosGetTimestampUs();
H
Haojun Liao 已提交
2159
  pTaskInfo->cost.extractListTime = (st1 - st) / 1000.0;
H
Haojun Liao 已提交
2160 2161
  qDebug("extract queried table list completed, %d tables, elapsed time:%.2f ms %s", numOfTables,
         pTaskInfo->cost.extractListTime, idStr);
H
Haojun Liao 已提交
2162

H
Haojun Liao 已提交
2163
  if (numOfTables == 0) {
H
Haojun Liao 已提交
2164 2165 2166 2167
    qDebug("no table qualified for query, %s" PRIx64, idStr);
    return TSDB_CODE_SUCCESS;
  }

D
dapan1121 已提交
2168 2169
  code = buildGroupIdMapForAllTables(pTableListInfo, pHandle, pScanNode, pGroupTags, groupSort, digest,
                                     &pTaskInfo->storageAPI);
H
Haojun Liao 已提交
2170 2171 2172 2173
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

dengyihao's avatar
dengyihao 已提交
2174
  pTaskInfo->cost.groupIdMapTime = (taosGetTimestampUs() - st1) / 1000.0;
H
Haojun Liao 已提交
2175
  qDebug("generate group id map completed, elapsed time:%.2f ms %s", pTaskInfo->cost.groupIdMapTime, idStr);
H
Haojun Liao 已提交
2176 2177

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2178
}
H
Haojun Liao 已提交
2179 2180 2181

void printDataBlock(SSDataBlock* pBlock, const char* flag) {
  if (!pBlock || pBlock->info.rows == 0) {
2182
    qDebug("===stream===%s: Block is Null or Empty", flag);
H
Haojun Liao 已提交
2183 2184 2185 2186 2187
    return;
  }
  char* pBuf = NULL;
  qDebug("%s", dumpBlockData(pBlock, flag, &pBuf));
  taosMemoryFree(pBuf);
dengyihao's avatar
dengyihao 已提交
2188
}