executil.c 46.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
void initResultRowInfo(SResultRowInfo* pResultRowInfo) {
  pResultRowInfo->size = 0;
31
  pResultRowInfo->cur.pageId = -1;
32 33
}

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

H
Haojun Liao 已提交
36
// TODO refactor: use macro
37
SResultRowEntryInfo* getResultEntryInfo(const SResultRow* pRow, int32_t index, const int32_t* offset) {
H
Haojun Liao 已提交
38
  assert(index >= 0 && offset != NULL);
dengyihao's avatar
dengyihao 已提交
39
  return (SResultRowEntryInfo*)((char*)pRow->pEntryInfo + offset[index]);
H
Haojun Liao 已提交
40 41
}

42 43 44
size_t getResultRowSize(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  int32_t rowSize = (numOfOutput * sizeof(SResultRowEntryInfo)) + sizeof(SResultRow);

dengyihao's avatar
dengyihao 已提交
45
  for (int32_t i = 0; i < numOfOutput; ++i) {
46 47 48
    rowSize += pCtx[i].resDataInfo.interBufSize;
  }

dengyihao's avatar
dengyihao 已提交
49
  rowSize +=
50
      (numOfOutput * sizeof(bool));  // expand rowSize to mark if col is null for top/bottom result(doSaveTupleData)
51
  return rowSize;
52 53
}

H
Haojun Liao 已提交
54 55 56
void cleanupGroupResInfo(SGroupResInfo* pGroupResInfo) {
  assert(pGroupResInfo != NULL);

57
  for (int32_t i = 0; i < taosArrayGetSize(pGroupResInfo->pRows); ++i) {
H
Haojun Liao 已提交
58 59 60 61 62
    SResKeyPos* pRes = taosArrayGetP(pGroupResInfo->pRows, i);
    taosMemoryFree(pRes);
  }

  pGroupResInfo->pRows = taosArrayDestroy(pGroupResInfo->pRows);
dengyihao's avatar
dengyihao 已提交
63
  pGroupResInfo->index = 0;
H
Haojun Liao 已提交
64 65
}

5
54liuyao 已提交
66
int32_t resultrowComparAsc(const void* p1, const void* p2) {
dengyihao's avatar
dengyihao 已提交
67 68
  SResKeyPos* pp1 = *(SResKeyPos**)p1;
  SResKeyPos* pp2 = *(SResKeyPos**)p2;
69 70

  if (pp1->groupId == pp2->groupId) {
dengyihao's avatar
dengyihao 已提交
71 72
    int64_t pts1 = *(int64_t*)pp1->key;
    int64_t pts2 = *(int64_t*)pp2->key;
73 74 75 76

    if (pts1 == pts2) {
      return 0;
    } else {
dengyihao's avatar
dengyihao 已提交
77
      return pts1 < pts2 ? -1 : 1;
78 79
    }
  } else {
dengyihao's avatar
dengyihao 已提交
80
    return pp1->groupId < pp2->groupId ? -1 : 1;
81 82 83
  }
}

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

86
void initGroupedResultInfo(SGroupResInfo* pGroupResInfo, SSHashObj* pHashmap, int32_t order) {
H
Haojun Liao 已提交
87 88 89 90
  if (pGroupResInfo->pRows != NULL) {
    taosArrayDestroy(pGroupResInfo->pRows);
  }

91 92 93 94
  // extract the result rows information from the hash map
  void* pData = NULL;
  pGroupResInfo->pRows = taosArrayInit(10, POINTER_BYTES);

95 96 97 98
  size_t  keyLen = 0;
  int32_t iter = 0;
  while ((pData = tSimpleHashIterate(pHashmap, pData, &iter)) != NULL) {
    void* key = tSimpleHashGetKey(pData, &keyLen);
99 100 101

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

dengyihao's avatar
dengyihao 已提交
102 103
    p->groupId = *(uint64_t*)key;
    p->pos = *(SResultRowPosition*)pData;
104
    memcpy(p->key, (char*)key + sizeof(uint64_t), keyLen - sizeof(uint64_t));
105 106 107
    taosArrayPush(pGroupResInfo->pRows, &p);
  }

108
  if (order == TSDB_ORDER_ASC || order == TSDB_ORDER_DESC) {
dengyihao's avatar
dengyihao 已提交
109
    __compar_fn_t fn = (order == TSDB_ORDER_ASC) ? resultrowComparAsc : resultrowComparDesc;
wafwerar's avatar
wafwerar 已提交
110
    taosSort(pGroupResInfo->pRows->pData, taosArrayGetSize(pGroupResInfo->pRows), POINTER_BYTES, fn);
111 112
  }

H
Haojun Liao 已提交
113
  pGroupResInfo->index = 0;
H
Haojun Liao 已提交
114 115 116
  assert(pGroupResInfo->index <= getNumOfTotalRes(pGroupResInfo));
}

H
Haojun Liao 已提交
117 118
void initMultiResInfoFromArrayList(SGroupResInfo* pGroupResInfo, SArray* pArrayList) {
  if (pGroupResInfo->pRows != NULL) {
5
54liuyao 已提交
119
    taosArrayDestroyP(pGroupResInfo->pRows, taosMemoryFree);
H
Haojun Liao 已提交
120 121
  }

122
  pGroupResInfo->pRows = pArrayList;
H
Haojun Liao 已提交
123 124 125 126
  pGroupResInfo->index = 0;
  ASSERT(pGroupResInfo->index <= getNumOfTotalRes(pGroupResInfo));
}

127
bool hasRemainResults(SGroupResInfo* pGroupResInfo) {
H
Haojun Liao 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140
  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 已提交
141
  return (int32_t)taosArrayGetSize(pGroupResInfo->pRows);
H
Haojun Liao 已提交
142 143
}

144
SArray* createSortInfo(SNodeList* pNodeList) {
145
  size_t numOfCols = 0;
146

147 148 149 150 151
  if (pNodeList != NULL) {
    numOfCols = LIST_LENGTH(pNodeList);
  } else {
    numOfCols = 0;
  }
152

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
  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 已提交
175

176
  SSDataBlock* pBlock = createDataBlock();
H
Haojun Liao 已提交
177

178 179
  pBlock->info.blockId = pNode->dataBlockId;
  pBlock->info.type = STREAM_INVALID;
5
54liuyao 已提交
180
  pBlock->info.calWin = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
181
  pBlock->info.watermark = INT64_MIN;
H
Haojun Liao 已提交
182

183
  for (int32_t i = 0; i < numOfCols; ++i) {
M
Minglei Jin 已提交
184
    SSlotDescNode*  pDescNode = (SSlotDescNode*)nodesListGetNode(pNode->pSlots, i);
dengyihao's avatar
dengyihao 已提交
185 186
    SColumnInfoData idata =
        createColumnInfoData(pDescNode->dataType.type, pDescNode->dataType.bytes, pDescNode->slotId);
187 188 189
    idata.info.scale = pDescNode->dataType.scale;
    idata.info.precision = pDescNode->dataType.precision;

190
    blockDataAppendColInfo(pBlock, &idata);
H
Haojun Liao 已提交
191 192
  }

193 194 195
  return pBlock;
}

wmmhello's avatar
wmmhello 已提交
196 197
EDealRes doTranslateTagExpr(SNode** pNode, void* pContext) {
  SMetaReader* mr = (SMetaReader*)pContext;
dengyihao's avatar
dengyihao 已提交
198
  if (nodeType(*pNode) == QUERY_NODE_COLUMN) {
wmmhello's avatar
wmmhello 已提交
199 200
    SColumnNode* pSColumnNode = *(SColumnNode**)pNode;

dengyihao's avatar
dengyihao 已提交
201
    SValueNode* res = (SValueNode*)nodesMakeNode(QUERY_NODE_VALUE);
wmmhello's avatar
wmmhello 已提交
202 203 204 205 206 207 208 209 210
    if (NULL == res) {
      return DEAL_RES_ERROR;
    }

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

    STagVal tagVal = {0};
    tagVal.cid = pSColumnNode->colId;
211
    const char* p = metaGetTableTagVal(mr->me.ctbEntry.pTags, pSColumnNode->node.resType.type, &tagVal);
wmmhello's avatar
wmmhello 已提交
212 213
    if (p == NULL) {
      res->node.resType.type = TSDB_DATA_TYPE_NULL;
dengyihao's avatar
dengyihao 已提交
214 215
    } else if (pSColumnNode->node.resType.type == TSDB_DATA_TYPE_JSON) {
      int32_t len = ((const STag*)p)->len;
wmmhello's avatar
wmmhello 已提交
216 217 218 219 220 221 222 223 224 225 226
      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 已提交
227 228 229 230
  } 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 已提交
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
      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 已提交
250
int32_t isQualifiedTable(STableKeyInfo* info, SNode* pTagCond, void* metaHandle, bool* pQualified) {
251
  int32_t     code = TSDB_CODE_SUCCESS;
dengyihao's avatar
dengyihao 已提交
252
  SMetaReader mr = {0};
253

wmmhello's avatar
wmmhello 已提交
254
  metaReaderInit(&mr, metaHandle, 0);
255 256 257
  code = metaGetTableEntryByUid(&mr, info->uid);
  if (TSDB_CODE_SUCCESS != code) {
    metaReaderClear(&mr);
M
Minglei Jin 已提交
258
    *pQualified = false;
259

M
Minglei Jin 已提交
260
    return TSDB_CODE_SUCCESS;
261
  }
wmmhello's avatar
wmmhello 已提交
262

dengyihao's avatar
dengyihao 已提交
263
  SNode* pTagCondTmp = nodesCloneNode(pTagCond);
wmmhello's avatar
wmmhello 已提交
264 265 266 267

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

268 269
  SNode* pNew = NULL;
  code = scalarCalculateConstants(pTagCondTmp, &pNew);
wmmhello's avatar
wmmhello 已提交
270
  if (TSDB_CODE_SUCCESS != code) {
wmmhello's avatar
wmmhello 已提交
271
    terrno = code;
wmmhello's avatar
wmmhello 已提交
272
    nodesDestroyNode(pTagCondTmp);
273 274 275
    *pQualified = false;

    return code;
wmmhello's avatar
wmmhello 已提交
276 277 278
  }

  ASSERT(nodeType(pNew) == QUERY_NODE_VALUE);
dengyihao's avatar
dengyihao 已提交
279
  SValueNode* pValue = (SValueNode*)pNew;
wmmhello's avatar
wmmhello 已提交
280 281

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

wmmhello's avatar
wmmhello 已提交
284
  nodesDestroyNode(pNew);
285
  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
286 287
}

288 289
typedef struct tagFilterAssist {
  SHashObj* colHash;
wmmhello's avatar
wmmhello 已提交
290
  int32_t   index;
291 292
  SArray*   cInfoList;
} tagFilterAssist;
wmmhello's avatar
wmmhello 已提交
293

wmmhello's avatar
wmmhello 已提交
294 295 296 297
static EDealRes getColumn(SNode** pNode, void* pContext) {
  SColumnNode* pSColumnNode = NULL;
  if (QUERY_NODE_COLUMN == nodeType((*pNode))) {
    pSColumnNode = *(SColumnNode**)pNode;
298
  } else if (QUERY_NODE_FUNCTION == nodeType((*pNode))) {
wmmhello's avatar
wmmhello 已提交
299 300 301 302 303 304 305 306 307 308 309 310
    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;
311
    } else {
312
      return DEAL_RES_CONTINUE;
wmmhello's avatar
wmmhello 已提交
313
    }
314
  } else {
wmmhello's avatar
wmmhello 已提交
315
    return DEAL_RES_CONTINUE;
wmmhello's avatar
wmmhello 已提交
316
  }
wmmhello's avatar
wmmhello 已提交
317

318 319 320
  tagFilterAssist* pData = (tagFilterAssist*)pContext;
  void*            data = taosHashGet(pData->colHash, &pSColumnNode->colId, sizeof(pSColumnNode->colId));
  if (!data) {
wmmhello's avatar
wmmhello 已提交
321 322
    taosHashPut(pData->colHash, &pSColumnNode->colId, sizeof(pSColumnNode->colId), pNode, sizeof((*pNode)));
    pSColumnNode->slotId = pData->index++;
323 324 325
    SColumnInfo cInfo = {.colId = pSColumnNode->colId,
                         .type = pSColumnNode->node.resType.type,
                         .bytes = pSColumnNode->node.resType.bytes};
326 327 328
#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 已提交
329
    taosArrayPush(pData->cInfoList, &cInfo);
330
  } else {
331 332
    SColumnNode* col = *(SColumnNode**)data;
    pSColumnNode->slotId = col->slotId;
wmmhello's avatar
wmmhello 已提交
333 334
  }

wmmhello's avatar
wmmhello 已提交
335 336 337 338 339 340 341 342 343 344
  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;
  }

345 346 347
  pColumnData->info.type = pType->type;
  pColumnData->info.bytes = pType->bytes;
  pColumnData->info.scale = pType->scale;
wmmhello's avatar
wmmhello 已提交
348 349 350 351
  pColumnData->info.precision = pType->precision;

  int32_t code = colInfoDataEnsureCapacity(pColumnData, numOfRows);
  if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
352
    terrno = code;
wmmhello's avatar
wmmhello 已提交
353 354 355 356 357 358 359 360 361
    taosMemoryFree(pColumnData);
    return terrno;
  }

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

362 363 364
static SColumnInfoData* getColInfoResult(void* metaHandle, uint64_t suid, SArray* uidList, SNode* pTagCond) {
  int32_t      code = TSDB_CODE_SUCCESS;
  SArray*      pBlockList = NULL;
wmmhello's avatar
wmmhello 已提交
365
  SSDataBlock* pResBlock = NULL;
366
  SHashObj*    tags = NULL;
wmmhello's avatar
wmmhello 已提交
367 368 369
  SScalarParam output = {0};

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

wmmhello's avatar
wmmhello 已提交
371
  ctx.colHash = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_SMALLINT), false, HASH_NO_LOCK);
372
  if (ctx.colHash == NULL) {
wmmhello's avatar
wmmhello 已提交
373 374 375 376 377
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }
  ctx.index = 0;
  ctx.cInfoList = taosArrayInit(4, sizeof(SColumnInfo));
378
  if (ctx.cInfoList == NULL) {
wmmhello's avatar
wmmhello 已提交
379 380 381
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }
wmmhello's avatar
wmmhello 已提交
382

383
  nodesRewriteExprPostOrder(&pTagCond, getColumn, (void*)&ctx);
wmmhello's avatar
wmmhello 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396

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

397
  //  int64_t stt = taosGetTimestampUs();
398
  tags = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
399
  code = metaGetTableTags(metaHandle, suid, uidList, tags);
wmmhello's avatar
wmmhello 已提交
400
  if (code != TSDB_CODE_SUCCESS) {
401
    qError("failed to get table tags from meta, reason:%s, suid:%" PRIu64, tstrerror(code), suid);
wmmhello's avatar
wmmhello 已提交
402 403 404 405
    terrno = code;
    goto end;
  }

406
  int32_t rows = taosArrayGetSize(uidList);
407
  if (rows == 0) {
408 409
    goto end;
  }
410 411
  //  int64_t stt1 = taosGetTimestampUs();
  //  qDebug("generate tag meta rows:%d, cost:%ld us", rows, stt1-stt);
wmmhello's avatar
wmmhello 已提交
412

413 414 415 416 417
  code = blockDataEnsureCapacity(pResBlock, rows);
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    goto end;
  }
wmmhello's avatar
wmmhello 已提交
418

419
  //  int64_t st = taosGetTimestampUs();
wmmhello's avatar
wmmhello 已提交
420
  for (int32_t i = 0; i < rows; i++) {
wmmhello's avatar
wmmhello 已提交
421
    int64_t* uid = taosArrayGet(uidList, i);
422
    for (int32_t j = 0; j < taosArrayGetSize(pResBlock->pDataBlock); j++) {
wmmhello's avatar
wmmhello 已提交
423
      SColumnInfoData* pColInfo = (SColumnInfoData*)taosArrayGet(pResBlock->pDataBlock, j);
424

425
      if (pColInfo->info.colId == -1) {  // tbname
426 427 428
        char str[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
        metaGetTableNameByUid(metaHandle, *uid, str);
        colDataAppend(pColInfo, i, str, false);
429
#if TAG_FILTER_DEBUG
430
        qDebug("tagfilter uid:%ld, tbname:%s", *uid, str + 2);
431
#endif
432
      } else {
wmmhello's avatar
wmmhello 已提交
433 434
        void* tag = taosHashGet(tags, uid, sizeof(int64_t));
        ASSERT(tag);
wmmhello's avatar
wmmhello 已提交
435 436 437 438
        STagVal tagVal = {0};
        tagVal.cid = pColInfo->info.colId;
        const char* p = metaGetTableTagVal(tag, pColInfo->info.type, &tagVal);

439
        if (p == NULL || (pColInfo->info.type == TSDB_DATA_TYPE_JSON && ((STag*)p)->nTag == 0)) {
wmmhello's avatar
wmmhello 已提交
440
          colDataAppend(pColInfo, i, p, true);
wmmhello's avatar
wmmhello 已提交
441 442
        } else if (pColInfo->info.type == TSDB_DATA_TYPE_JSON) {
          colDataAppend(pColInfo, i, p, false);
wmmhello's avatar
wmmhello 已提交
443
        } else if (IS_VAR_DATA_TYPE(pColInfo->info.type)) {
444
          char* tmp = taosMemoryCalloc(tagVal.nData + VARSTR_HEADER_SIZE + 1, 1);
wmmhello's avatar
wmmhello 已提交
445 446 447
          varDataSetLen(tmp, tagVal.nData);
          memcpy(tmp + VARSTR_HEADER_SIZE, tagVal.pData, tagVal.nData);
          colDataAppend(pColInfo, i, tmp, false);
448
#if TAG_FILTER_DEBUG
449
          qDebug("tagfilter varch:%s", tmp + 2);
450
#endif
wmmhello's avatar
wmmhello 已提交
451 452 453
          taosMemoryFree(tmp);
        } else {
          colDataAppend(pColInfo, i, (const char*)&tagVal.i64, false);
454
#if TAG_FILTER_DEBUG
455
          if (pColInfo->info.type == TSDB_DATA_TYPE_INT) {
456
            qDebug("tagfilter int:%d", *(int*)(&tagVal.i64));
457 458
          } else if (pColInfo->info.type == TSDB_DATA_TYPE_DOUBLE) {
            qDebug("tagfilter double:%f", *(double*)(&tagVal.i64));
459 460
          }
#endif
wmmhello's avatar
wmmhello 已提交
461
        }
wmmhello's avatar
wmmhello 已提交
462 463 464
      }
    }
  }
wmmhello's avatar
wmmhello 已提交
465 466
  pResBlock->info.rows = rows;

467 468
  //  int64_t st1 = taosGetTimestampUs();
  //  qDebug("generate tag block rows:%d, cost:%ld us", rows, st1-st);
wmmhello's avatar
wmmhello 已提交
469 470 471 472 473 474 475

  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) {
wmmhello's avatar
wmmhello 已提交
476
    terrno = code;
477
    qError("failed to create result, reason:%s", tstrerror(code));
wmmhello's avatar
wmmhello 已提交
478
    terrno = code;
wmmhello's avatar
wmmhello 已提交
479 480 481 482
    goto end;
  }

  code = scalarCalculate(pTagCond, pBlockList, &output);
483
  if (code != TSDB_CODE_SUCCESS) {
484
    qError("failed to calculate scalar, reason:%s", tstrerror(code));
wmmhello's avatar
wmmhello 已提交
485
    terrno = code;
wmmhello's avatar
wmmhello 已提交
486
    goto end;
wmmhello's avatar
wmmhello 已提交
487
  }
488 489
  //  int64_t st2 = taosGetTimestampUs();
  //  qDebug("calculate tag block rows:%d, cost:%ld us", rows, st2-st1);
wmmhello's avatar
wmmhello 已提交
490 491

end:
492
  taosHashCleanup(tags);
wmmhello's avatar
wmmhello 已提交
493 494 495 496 497 498 499
  taosHashCleanup(ctx.colHash);
  taosArrayDestroy(ctx.cInfoList);
  blockDataDestroy(pResBlock);
  taosArrayDestroy(pBlockList);
  return output.columnData;
}

wmmhello's avatar
wmmhello 已提交
500
static void releaseColInfoData(void* pCol) {
501 502
  if (pCol) {
    SColumnInfoData* col = (SColumnInfoData*)pCol;
wmmhello's avatar
wmmhello 已提交
503 504 505 506 507
    colDataDestroy(col);
    taosMemoryFree(col);
  }
}

508 509 510 511 512 513 514 515
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;
wmmhello's avatar
wmmhello 已提交
516 517

  int32_t rows = taosArrayGetSize(pTableListInfo->pTableList);
518
  if (rows == 0) {
wmmhello's avatar
wmmhello 已提交
519 520 521 522 523
    return TDB_CODE_SUCCESS;
  }

  tagFilterAssist ctx = {0};
  ctx.colHash = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_SMALLINT), false, HASH_NO_LOCK);
524
  if (ctx.colHash == NULL) {
wmmhello's avatar
wmmhello 已提交
525 526 527 528 529
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }
  ctx.index = 0;
  ctx.cInfoList = taosArrayInit(4, sizeof(SColumnInfo));
530
  if (ctx.cInfoList == NULL) {
wmmhello's avatar
wmmhello 已提交
531 532 533 534
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }

535
  SNode* pNode = NULL;
wmmhello's avatar
wmmhello 已提交
536
  FOREACH(pNode, group) {
537
    nodesRewriteExprPostOrder(&pNode, getColumn, (void*)&ctx);
wmmhello's avatar
wmmhello 已提交
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
    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);
  }

559
  //  int64_t stt = taosGetTimestampUs();
wmmhello's avatar
wmmhello 已提交
560 561 562 563 564 565
  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;
  }

566 567
  //  int64_t stt1 = taosGetTimestampUs();
  //  qDebug("generate tag meta rows:%d, cost:%ld us", rows, stt1-stt);
wmmhello's avatar
wmmhello 已提交
568 569 570 571 572 573

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

574
  //  int64_t st = taosGetTimestampUs();
wmmhello's avatar
wmmhello 已提交
575 576
  for (int32_t i = 0; i < rows; i++) {
    int64_t* uid = taosArrayGet(uidList, i);
577
    for (int32_t j = 0; j < taosArrayGetSize(pResBlock->pDataBlock); j++) {
wmmhello's avatar
wmmhello 已提交
578 579
      SColumnInfoData* pColInfo = (SColumnInfoData*)taosArrayGet(pResBlock->pDataBlock, j);

580
      if (pColInfo->info.colId == -1) {  // tbname
wmmhello's avatar
wmmhello 已提交
581 582 583 584
        char str[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
        metaGetTableNameByUid(metaHandle, *uid, str);
        colDataAppend(pColInfo, i, str, false);
#if TAG_FILTER_DEBUG
585
        qDebug("tagfilter uid:%ld, tbname:%s", *uid, str + 2);
wmmhello's avatar
wmmhello 已提交
586
#endif
587
      } else {
wmmhello's avatar
wmmhello 已提交
588 589 590 591 592 593
        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);

594
        if (p == NULL || (pColInfo->info.type == TSDB_DATA_TYPE_JSON && ((STag*)p)->nTag == 0)) {
wmmhello's avatar
wmmhello 已提交
595 596 597 598
          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)) {
599
          char* tmp = taosMemoryCalloc(tagVal.nData + VARSTR_HEADER_SIZE + 1, 1);
wmmhello's avatar
wmmhello 已提交
600 601 602 603
          varDataSetLen(tmp, tagVal.nData);
          memcpy(tmp + VARSTR_HEADER_SIZE, tagVal.pData, tagVal.nData);
          colDataAppend(pColInfo, i, tmp, false);
#if TAG_FILTER_DEBUG
604
          qDebug("tagfilter varch:%s", tmp + 2);
wmmhello's avatar
wmmhello 已提交
605 606 607 608 609
#endif
          taosMemoryFree(tmp);
        } else {
          colDataAppend(pColInfo, i, (const char*)&tagVal.i64, false);
#if TAG_FILTER_DEBUG
610
          if (pColInfo->info.type == TSDB_DATA_TYPE_INT) {
wmmhello's avatar
wmmhello 已提交
611
            qDebug("tagfilter int:%d", *(int*)(&tagVal.i64));
612 613
          } else if (pColInfo->info.type == TSDB_DATA_TYPE_DOUBLE) {
            qDebug("tagfilter double:%f", *(double*)(&tagVal.i64));
wmmhello's avatar
wmmhello 已提交
614 615 616 617 618 619 620 621
          }
#endif
        }
      }
    }
  }
  pResBlock->info.rows = rows;

622 623
  //  int64_t st1 = taosGetTimestampUs();
  //  qDebug("generate tag block rows:%d, cost:%ld us", rows, st1-st);
wmmhello's avatar
wmmhello 已提交
624 625 626 627 628 629 630 631 632 633

  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:
wmmhello's avatar
wmmhello 已提交
634 635
        break;
      case QUERY_NODE_COLUMN:
wmmhello's avatar
wmmhello 已提交
636
      case QUERY_NODE_OPERATOR:
637
      case QUERY_NODE_FUNCTION: {
wmmhello's avatar
wmmhello 已提交
638 639 640 641 642 643 644 645
        SExprNode* expNode = (SExprNode*)pNode;
        code = createResultData(&expNode->resType, rows, &output);
        if (code != TSDB_CODE_SUCCESS) {
          goto end;
        }
        break;
      }
      default:
wmmhello's avatar
wmmhello 已提交
646 647 648
        code = TSDB_CODE_OPS_NOT_SUPPORT;
        goto end;
    }
649 650
    if (nodeType(pNode) == QUERY_NODE_COLUMN) {
      SColumnNode*     pSColumnNode = (SColumnNode*)pNode;
wmmhello's avatar
wmmhello 已提交
651 652
      SColumnInfoData* pColInfo = (SColumnInfoData*)taosArrayGet(pResBlock->pDataBlock, pSColumnNode->slotId);
      code = colDataAssign(output.columnData, pColInfo, rows, NULL);
653
    } else if (nodeType(pNode) == QUERY_NODE_VALUE) {
wmmhello's avatar
wmmhello 已提交
654
      continue;
655
    } else {
wmmhello's avatar
wmmhello 已提交
656
      code = scalarCalculate(pNode, pBlockList, &output);
wmmhello's avatar
wmmhello 已提交
657
    }
658
    if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
659 660 661 662 663 664 665
      releaseColInfoData(output.columnData);
      goto end;
    }
    taosArrayPush(groupData, &output.columnData);
  }

  int32_t keyLen = 0;
666
  SNode*  node;
wmmhello's avatar
wmmhello 已提交
667 668 669 670 671 672 673 674 675 676 677 678 679
  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;
  }
680
  for (int i = 0; i < rows; i++) {
wmmhello's avatar
wmmhello 已提交
681 682 683 684
    STableKeyInfo* info = taosArrayGet(pTableListInfo->pTableList, i);

    char* isNull = (char*)keyBuf;
    char* pStart = (char*)keyBuf + sizeof(int8_t) * LIST_LENGTH(group);
685
    for (int j = 0; j < taosArrayGetSize(groupData); j++) {
wmmhello's avatar
wmmhello 已提交
686 687
      SColumnInfoData* pValue = (SColumnInfoData*)taosArrayGetP(groupData, j);

wmmhello's avatar
wmmhello 已提交
688
      if (colDataIsNull_s(pValue, i)) {
wmmhello's avatar
wmmhello 已提交
689 690 691 692
        isNull[j] = 1;
      } else {
        isNull[j] = 0;
        char* data = colDataGetData(pValue, i);
wmmhello's avatar
wmmhello 已提交
693 694 695 696 697
        if (pValue->info.type == TSDB_DATA_TYPE_JSON) {
          if (tTagIsJson(data)) {
            code = TSDB_CODE_QRY_JSON_IN_GROUP_ERROR;
            goto end;
          }
698
          if (tTagIsJsonNull(data)) {
wmmhello's avatar
wmmhello 已提交
699 700 701 702 703 704 705
            isNull[j] = 1;
            continue;
          }
          int32_t len = getJsonValueLen(data);
          memcpy(pStart, data, len);
          pStart += len;
        } else if (IS_VAR_DATA_TYPE(pValue->info.type)) {
wmmhello's avatar
wmmhello 已提交
706 707 708 709
          memcpy(pStart, data, varDataTLen(data));
          pStart += varDataTLen(data);
        } else {
          memcpy(pStart, data, pValue->info.bytes);
wmmhello's avatar
wmmhello 已提交
710
          pStart += pValue->info.bytes;
wmmhello's avatar
wmmhello 已提交
711 712 713 714 715 716 717 718 719
        }
      }
    }

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

720 721
  //  int64_t st2 = taosGetTimestampUs();
  //  qDebug("calculate tag block rows:%d, cost:%ld us", rows, st2-st1);
wmmhello's avatar
wmmhello 已提交
722

723
end:
wmmhello's avatar
wmmhello 已提交
724 725 726 727 728 729 730 731 732 733 734
  taosMemoryFreeClear(keyBuf);
  taosHashCleanup(tags);
  taosHashCleanup(ctx.colHash);
  taosArrayDestroy(ctx.cInfoList);
  blockDataDestroy(pResBlock);
  taosArrayDestroy(pBlockList);
  taosArrayDestroy(uidList);
  taosArrayDestroyP(groupData, releaseColInfoData);
  return code;
}

735 736
int32_t getTableList(void* metaHandle, void* pVnode, SScanPhysiNode* pScanNode, SNode* pTagCond, SNode* pTagIndexCond,
                     STableListInfo* pListInfo) {
737
  int32_t code = TSDB_CODE_SUCCESS;
738

739
  pListInfo->pTableList = taosArrayInit(8, sizeof(STableKeyInfo));
740 741 742
  if (pListInfo->pTableList == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
743 744

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

748
  if (pScanNode->tableType == TSDB_SUPER_TABLE) {
wmmhello's avatar
wmmhello 已提交
749
    if (pTagIndexCond) {
750 751 752
      SIndexMetaArg metaArg = {
          .metaEx = metaHandle, .idx = tsdbGetIdx(metaHandle), .ivtIdx = tsdbGetIvtIdx(metaHandle), .suid = tableUid};

753
      //      int64_t stt = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
754 755 756
      SIdxFltStatus status = SFLT_NOT_INDEX;
      code = doFilterTag(pTagIndexCond, &metaArg, res, &status);
      if (code != 0 || status == SFLT_NOT_INDEX) {
wmmhello's avatar
wmmhello 已提交
757
        qError("failed to get tableIds from index, reason:%s, suid:%" PRIu64, tstrerror(code), tableUid);
758
        code = TDB_CODE_SUCCESS;
759 760
      }

761 762 763
      //      int64_t stt1 = taosGetTimestampUs();
      //      qDebug("generate table list, cost:%ld us", stt1-stt);
    } else if (!pTagCond) {
wmmhello's avatar
wmmhello 已提交
764
      vnodeGetCtbIdList(pVnode, pScanNode->suid, res);
wmmhello's avatar
wmmhello 已提交
765
    }
L
Liu Jicong 已提交
766
  } else {  // Create one table group.
767
    if (metaIsTableExist(metaHandle, tableUid)) {
768 769
      taosArrayPush(res, &tableUid);
    }
H
Haojun Liao 已提交
770
  }
771

772
  if (pTagCond) {
wmmhello's avatar
wmmhello 已提交
773
    terrno = TDB_CODE_SUCCESS;
774
    SColumnInfoData* pColInfoData = getColInfoResult(metaHandle, pListInfo->suid, res, pTagCond);
775
    if (terrno != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
776
      colDataDestroy(pColInfoData);
wmmhello's avatar
wmmhello 已提交
777
      taosMemoryFreeClear(pColInfoData);
778
      taosArrayDestroy(res);
779
      qError("failed to getColInfoResult, code: %s", tstrerror(terrno));
wmmhello's avatar
wmmhello 已提交
780 781 782
      return terrno;
    }

wmmhello's avatar
wmmhello 已提交
783
    int32_t i = 0;
wmmhello's avatar
wmmhello 已提交
784 785 786 787
    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);
788

wmmhello's avatar
wmmhello 已提交
789
      int64_t* uid = taosArrayGet(res, i);
790
      qDebug("tagfilter get uid:%ld, res:%d", *uid, *(bool*)var);
wmmhello's avatar
wmmhello 已提交
791
      if (*(bool*)var == false) {
792
        taosArrayRemove(res, i);
wmmhello's avatar
wmmhello 已提交
793
        j++;
wmmhello's avatar
wmmhello 已提交
794 795 796
        continue;
      }
      i++;
wmmhello's avatar
wmmhello 已提交
797
      j++;
wmmhello's avatar
wmmhello 已提交
798
    }
wmmhello's avatar
wmmhello 已提交
799
    colDataDestroy(pColInfoData);
wmmhello's avatar
wmmhello 已提交
800
    taosMemoryFreeClear(pColInfoData);
wmmhello's avatar
wmmhello 已提交
801 802
  }

803 804 805
  for (int i = 0; i < taosArrayGetSize(res); i++) {
    STableKeyInfo info = {.uid = *(uint64_t*)taosArrayGet(res, i), .groupId = 0};
    taosArrayPush(pListInfo->pTableList, &info);
806
    qDebug("tagfilter get uid:%ld", info.uid);
807 808 809 810
  }

  taosArrayDestroy(res);

wmmhello's avatar
wmmhello 已提交
811
  pListInfo->pGroupList = taosArrayInit(4, POINTER_BYTES);
812
  if (pListInfo->pGroupList == NULL) {
813 814
    return TSDB_CODE_OUT_OF_MEMORY;
  }
wmmhello's avatar
wmmhello 已提交
815

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

821 822 823 824 825 826 827 828 829 830 831 832 833
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 已提交
834
int32_t getGroupIdFromTagsVal(void* pMeta, uint64_t uid, SNodeList* pGroupNode, char* keyBuf, uint64_t* pGroupId) {
M
Minglei Jin 已提交
835
  SMetaReader mr = {0};
836
  metaReaderInit(&mr, pMeta, 0);
837
  if (metaGetTableEntryByUid(&mr, uid) != 0) {  // table not exist
838 839 840
    metaReaderClear(&mr);
    return TSDB_CODE_PAR_TABLE_NOT_EXIST;
  }
841 842 843 844 845

  SNodeList* groupNew = nodesCloneList(pGroupNode);

  nodesRewriteExprsPostOrder(groupNew, doTranslateTagExpr, &mr);
  char* isNull = (char*)keyBuf;
M
Minglei Jin 已提交
846
  char* pStart = (char*)keyBuf + sizeof(int8_t) * LIST_LENGTH(pGroupNode);
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891

  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 已提交
892
  int32_t len = (int32_t)(pStart - (char*)keyBuf);
893 894 895 896 897 898 899
  *pGroupId = calcGroupId(keyBuf, len);

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

900
SArray* extractPartitionColInfo(SNodeList* pNodeList) {
dengyihao's avatar
dengyihao 已提交
901
  if (!pNodeList) {
902 903
    return NULL;
  }
H
Haojun Liao 已提交
904

905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
  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 已提交
926

927
  return pList;
H
Haojun Liao 已提交
928 929
}

930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols,
                            int32_t type) {
  size_t  numOfCols = LIST_LENGTH(pNodeList);
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColMatchInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

    SColMatchInfo c = {0};
    c.output = true;
dengyihao's avatar
dengyihao 已提交
945
    c.colId = pColNode->colId;
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
    c.srcSlotId = pColNode->slotId;
    c.matchType = type;
    c.targetSlotId = pNode->slotId;
    taosArrayPush(pList, &c);
  }

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

964 965 966 967 968 969 970
    SColMatchInfo* info = NULL;
    for (int32_t j = 0; j < taosArrayGetSize(pList); ++j) {
      info = taosArrayGet(pList, j);
      if (info->targetSlotId == pNode->slotId) {
        break;
      }
    }
971

972 973 974 975 976
    if (pNode->output) {
      (*numOfOutputCols) += 1;
    } else {
      info->output = false;
    }
977
  }
978 979

  return pList;
980 981
}

982 983 984 985 986 987 988 989 990 991 992 993
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;
  strncpy(s.name, name, tListLen(s.name));

  return s;
}
994

995
static SColumn* createColumn(int32_t blockId, int32_t slotId, int32_t colId, SDataType* pType, EColumnType colType) {
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
  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;
1009
  pCol->colType = colType;
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
  return pCol;
}

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;
1021 1022 1023 1024
  if (*numOfExprs == 0) {
    return NULL;
  }

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
  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];

    pExp->pExpr = taosMemoryCalloc(1, sizeof(tExprNode));
    pExp->pExpr->_function.num = 1;
    pExp->pExpr->_function.functionId = -1;

    int32_t type = nodeType(pTargetNode->pExpr);
    // it is a project query, or group by column
    if (type == QUERY_NODE_COLUMN) {
      pExp->pExpr->nodeType = QUERY_NODE_COLUMN;
      SColumnNode* pColNode = (SColumnNode*)pTargetNode->pExpr;

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

      SDataType* pType = &pColNode->node.resType;
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pColNode->colName);
1053 1054
      pExp->base.pParam[0].pCol =
          createColumn(pColNode->dataBlockId, pColNode->slotId, pColNode->colId, pType, pColNode->colType);
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
    } else if (type == QUERY_NODE_VALUE) {
      pExp->pExpr->nodeType = QUERY_NODE_VALUE;
      SValueNode* pValNode = (SValueNode*)pTargetNode->pExpr;

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

      SDataType* pType = &pValNode->node.resType;
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pValNode->node.aliasName);
      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;
      SFunctionNode* pFuncNode = (SFunctionNode*)pTargetNode->pExpr;

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

      pExp->pExpr->_function.functionId = pFuncNode->funcId;
      pExp->pExpr->_function.pFunctNode = pFuncNode;

      strncpy(pExp->pExpr->_function.functionName, pFuncNode->functionName,
              tListLen(pExp->pExpr->_function.functionName));
#if 1
      // todo refactor: add the parameter for tbname function
C
Cary Xu 已提交
1083
      if (!pFuncNode->pParameterList && (strcmp(pExp->pExpr->_function.functionName, "tbname") == 0)) {
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
        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;
1106 1107
          pExp->base.pParam[j].pCol =
              createColumn(pcn->dataBlockId, pcn->slotId, pcn->colId, &pcn->node.resType, pcn->colType);
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
        } 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;
      SOperatorNode* pNode = (SOperatorNode*)pTargetNode->pExpr;

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

      SDataType* pType = &pNode->node.resType;
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pNode->node.aliasName);
      pExp->pExpr->_optrRoot.pRootNode = pTargetNode->pExpr;
    } else {
      ASSERT(0);
    }
  }

  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 已提交
1144
    const char* pName = pCtx[i].pExpr->pExpr->_function.functionName;
1145
    if ((strcmp(pName, "_select_value") == 0) || (strcmp(pName, "_group_key") == 0)) {
1146 1147 1148 1149 1150
      pValCtx[num++] = &pCtx[i];
    } else if (fmIsSelectFunc(pCtx[i].functionId)) {
      p = &pCtx[i];
    }
  }
H
Haojun Liao 已提交
1151

1152 1153 1154
  if (p != NULL) {
    p->subsidiaries.pCtx = pValCtx;
    p->subsidiaries.num = num;
1155
  } else {
1156
    taosMemoryFreeClear(pValCtx);
1157
  }
1158 1159

  return TSDB_CODE_SUCCESS;
1160 1161
}

1162
SqlFunctionCtx* createSqlFunctionCtx(SExprInfo* pExprInfo, int32_t numOfOutput, int32_t** rowEntryInfoOffset) {
1163 1164 1165 1166
  SqlFunctionCtx* pFuncCtx = (SqlFunctionCtx*)taosMemoryCalloc(numOfOutput, sizeof(SqlFunctionCtx));
  if (pFuncCtx == NULL) {
    return NULL;
  }
1167

1168 1169
  *rowEntryInfoOffset = taosMemoryCalloc(numOfOutput, sizeof(int32_t));
  if (*rowEntryInfoOffset == 0) {
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
    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->curBufPage = -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;
          strncpy(pCtx->udfName, udfName, strlen(udfName));
          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;
5
54liuyao 已提交
1222
    pCtx->isStream = false;
1223 1224 1225 1226 1227

    pCtx->param = pFunct->pParam;
  }

  for (int32_t i = 1; i < numOfOutput; ++i) {
dengyihao's avatar
dengyihao 已提交
1228 1229
    (*rowEntryInfoOffset)[i] = (int32_t)((*rowEntryInfoOffset)[i - 1] + sizeof(SResultRowEntryInfo) +
                                         pFuncCtx[i - 1].resDataInfo.interBufSize);
1230 1231 1232 1233
  }

  setSelectValueColumnInfo(pFuncCtx, numOfOutput);
  return pFuncCtx;
1234
}
1235 1236

// NOTE: sources columns are more than the destination SSDatablock columns.
1237 1238
// doFilter in table scan needs every column even its output is false
void relocateColumnData(SSDataBlock* pBlock, const SArray* pColMatchInfo, SArray* pCols, bool outputEveryColumn) {
1239 1240 1241 1242 1243 1244
  size_t numOfSrcCols = taosArrayGetSize(pCols);

  int32_t i = 0, j = 0;
  while (i < numOfSrcCols && j < taosArrayGetSize(pColMatchInfo)) {
    SColumnInfoData* p = taosArrayGet(pCols, i);
    SColMatchInfo*   pmInfo = taosArrayGet(pColMatchInfo, j);
1245
    if (!outputEveryColumn && pmInfo->reserved) {
1246 1247 1248 1249 1250 1251
      j++;
      continue;
    }

    if (p->info.colId == pmInfo->colId) {
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, pmInfo->targetSlotId);
1252
      colDataAssign(pDst, p, pBlock->info.rows, &pBlock->info);
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
      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 已提交
1277

1278 1279 1280 1281 1282
  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;
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
  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 已提交
1298
  pCond->twindows = pTableScanNode->scanRange;
1299
  pCond->suid = pTableScanNode->scan.suid;
1300
  pCond->type = TIMEWINDOW_RANGE_CONTAINED;
H
Haojun Liao 已提交
1301
  pCond->startVersion = -1;
1302
  pCond->endVersion = -1;
wmmhello's avatar
wmmhello 已提交
1303
  pCond->schemaVersion = -1;
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
  //  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;
}

1324
void cleanupQueryTableDataCond(SQueryTableDataCond* pCond) { taosMemoryFree(pCond->colList); }
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352

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 已提交
1353 1354 1355

static void getInitialStartTimeWindow(SInterval* pInterval, TSKEY ts, STimeWindow* w, bool ascQuery) {
  if (ascQuery) {
1356
    *w = getAlignQueryTimeWindow(pInterval, pInterval->precision, ts);
H
Haojun Liao 已提交
1357 1358
  } else {
    // the start position of the first time window in the endpoint that spreads beyond the queried last timestamp
1359
    *w = getAlignQueryTimeWindow(pInterval, pInterval->precision, ts);
H
Haojun Liao 已提交
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373

    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) {
1374
  STimeWindow w = {0};
H
Haojun Liao 已提交
1375

1376 1377
  w.skey = taosTimeTruncate(ts, pInterval, pInterval->precision);
  w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1;
H
Haojun Liao 已提交
1378 1379 1380
  return w;
}

1381
STimeWindow getFirstQualifiedTimeWindow(int64_t ts, STimeWindow* pWindow, SInterval* pInterval, int32_t order) {
1382
  int32_t factor = (order == TSDB_ORDER_ASC) ? -1 : 1;
H
Haojun Liao 已提交
1383 1384 1385

  STimeWindow win = *pWindow;
  STimeWindow save = win;
1386
  while (win.skey <= ts && win.ekey >= ts) {
H
Haojun Liao 已提交
1387 1388 1389 1390 1391 1392 1393 1394 1395
    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
1396
// todo refactor
H
Haojun Liao 已提交
1397 1398 1399 1400 1401 1402 1403 1404 1405
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;
  }

1406
  w = getResultRowByPos(pBuf, &pResultRowInfo->cur, false)->win;
H
Haojun Liao 已提交
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419

  // 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;
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
}

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;
1435
  pLimitInfo->slimit = slimit;
1436 1437
  pLimitInfo->remainOffset = limit.offset;
  pLimitInfo->remainGroupOffset = slimit.offset;
1438
}