executorimpl.c 167.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * 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/>.
 */
15

H
Haojun Liao 已提交
16 17
#include "filter.h"
#include "function.h"
18 19
#include "functionMgt.h"
#include "os.h"
H
Haojun Liao 已提交
20
#include "querynodes.h"
21
#include "tfill.h"
dengyihao's avatar
dengyihao 已提交
22
#include "tname.h"
X
Xiaoyu Wang 已提交
23
#include "tref.h"
24

H
Haojun Liao 已提交
25
#include "tdatablock.h"
26
#include "tglobal.h"
H
Haojun Liao 已提交
27
#include "tmsg.h"
H
Haojun Liao 已提交
28
#include "tsort.h"
29
#include "ttime.h"
H
Haojun Liao 已提交
30

31
#include "executorimpl.h"
dengyihao's avatar
dengyihao 已提交
32
#include "index.h"
33
#include "query.h"
34 35
#include "tcompare.h"
#include "tcompression.h"
H
Haojun Liao 已提交
36
#include "thash.h"
37
#include "ttypes.h"
dengyihao's avatar
dengyihao 已提交
38
#include "vnode.h"
39

H
Haojun Liao 已提交
40
#define IS_MAIN_SCAN(runtime)          ((runtime)->scanFlag == MAIN_SCAN)
41 42 43 44 45 46
#define SET_REVERSE_SCAN_FLAG(runtime) ((runtime)->scanFlag = REVERSE_SCAN)

#define GET_FORWARD_DIRECTION_FACTOR(ord) (((ord) == TSDB_ORDER_ASC) ? QUERY_ASC_FORWARD_STEP : QUERY_DESC_FORWARD_STEP)

#if 0
static UNUSED_FUNC void *u_malloc (size_t __size) {
wafwerar's avatar
wafwerar 已提交
47
  uint32_t v = taosRand();
48 49 50 51

  if (v % 1000 <= 0) {
    return NULL;
  } else {
wafwerar's avatar
wafwerar 已提交
52
    return taosMemoryMalloc(__size);
53 54 55 56
  }
}

static UNUSED_FUNC void* u_calloc(size_t num, size_t __size) {
wafwerar's avatar
wafwerar 已提交
57
  uint32_t v = taosRand();
58 59 60
  if (v % 1000 <= 0) {
    return NULL;
  } else {
wafwerar's avatar
wafwerar 已提交
61
    return taosMemoryCalloc(num, __size);
62 63 64 65
  }
}

static UNUSED_FUNC void* u_realloc(void* p, size_t __size) {
wafwerar's avatar
wafwerar 已提交
66
  uint32_t v = taosRand();
67 68 69
  if (v % 5 <= 1) {
    return NULL;
  } else {
wafwerar's avatar
wafwerar 已提交
70
    return taosMemoryRealloc(p, __size);
71 72 73 74 75 76 77 78
  }
}

#define calloc  u_calloc
#define malloc  u_malloc
#define realloc u_realloc
#endif

X
Xiaoyu Wang 已提交
79
#define CLEAR_QUERY_STATUS(q, st)   ((q)->status &= (~(st)))
80 81
#define QUERY_IS_INTERVAL_QUERY(_q) ((_q)->interval.interval > 0)

L
Liu Jicong 已提交
82 83 84
int32_t getMaximumIdleDurationSec() { return tsShellActivityTimer * 2; }

static int32_t getExprFunctionId(SExprInfo* pExprInfo) {
85
  assert(pExprInfo != NULL && pExprInfo->pExpr != NULL && pExprInfo->pExpr->nodeType == TEXPR_UNARYEXPR_NODE);
86
  return 0;
87 88 89 90
}

static void doSetTagValueToResultBuf(char* output, const char* val, int16_t type, int16_t bytes);

91
static void setBlockStatisInfo(SqlFunctionCtx* pCtx, SExprInfo* pExpr, SSDataBlock* pSDataBlock);
92

X
Xiaoyu Wang 已提交
93
static void releaseQueryBuf(size_t numOfTables);
94 95 96 97 98

static void destroySFillOperatorInfo(void* param, int32_t numOfOutput);
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput);
static void destroyOrderOperatorInfo(void* param, int32_t numOfOutput);
static void destroyAggOperatorInfo(void* param, int32_t numOfOutput);
X
Xiaoyu Wang 已提交
99

H
Haojun Liao 已提交
100
static void destroyIntervalOperatorInfo(void* param, int32_t numOfOutput);
H
Haojun Liao 已提交
101 102
static void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput);

103 104
static void destroyOperatorInfo(SOperatorInfo* pOperator);

105
void doSetOperatorCompleted(SOperatorInfo* pOperator) {
106
  pOperator->status = OP_EXEC_DONE;
107

108
  pOperator->cost.totalCost = (taosGetTimestampUs() - pOperator->pTaskInfo->cost.start * 1000) / 1000.0;
H
Haojun Liao 已提交
109
  if (pOperator->pTaskInfo != NULL) {
110
    setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
111 112
  }
}
113

H
Haojun Liao 已提交
114
int32_t operatorDummyOpenFn(SOperatorInfo* pOperator) {
115
  OPTR_SET_OPENED(pOperator);
116
  pOperator->cost.openCost = 0;
H
Haojun Liao 已提交
117
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
118 119
}

120
SOperatorFpSet createOperatorFpSet(__optr_open_fn_t openFn, __optr_fn_t nextFn, __optr_fn_t streamFn,
L
Liu Jicong 已提交
121
                                   __optr_fn_t cleanup, __optr_close_fn_t closeFn, __optr_encode_fn_t encode,
122
                                   __optr_decode_fn_t decode, __optr_explain_fn_t explain) {
123 124 125 126 127 128 129 130 131 132 133 134 135 136
  SOperatorFpSet fpSet = {
      ._openFn = openFn,
      .getNextFn = nextFn,
      .getStreamResFn = streamFn,
      .cleanupFn = cleanup,
      .closeFn = closeFn,
      .encodeResultRow = encode,
      .decodeResultRow = decode,
      .getExplainFn = explain,
  };

  return fpSet;
}

H
Haojun Liao 已提交
137
void operatorDummyCloseFn(void* param, int32_t numOfCols) {}
H
Haojun Liao 已提交
138

X
Xiaoyu Wang 已提交
139 140 141
static int32_t doCopyToSDataBlock(SExecTaskInfo* taskInfo, SSDataBlock* pBlock, SExprInfo* pExprInfo,
                                  SDiskbasedBuf* pBuf, SGroupResInfo* pGroupResInfo, const int32_t* rowCellOffset,
                                  SqlFunctionCtx* pCtx, int32_t numOfExprs);
H
Haojun Liao 已提交
142

143
static void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size);
L
Liu Jicong 已提交
144 145
static void doSetTableGroupOutputBuf(SOperatorInfo* pOperator, SAggOperatorInfo* pAggInfo, int32_t numOfOutput,
                                     uint64_t groupId);
146

L
Liu Jicong 已提交
147 148
// setup the output buffer for each operator
static bool hasNull(SColumn* pColumn, SColumnDataAgg* pStatis) {
dengyihao's avatar
dengyihao 已提交
149 150
  if (TSDB_COL_IS_TAG(pColumn->flag) || TSDB_COL_IS_UD_COL(pColumn->flag) ||
      pColumn->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
151 152 153 154 155 156 157 158 159 160
    return false;
  }

  if (pStatis != NULL && pStatis->numOfNull == 0) {
    return false;
  }

  return true;
}

161
#if 0
L
Liu Jicong 已提交
162 163
static bool chkResultRowFromKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, char* pData,
                                int16_t bytes, bool masterscan, uint64_t uid) {
164 165 166
  bool existed = false;
  SET_RES_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid);

L
Liu Jicong 已提交
167 168
  SResultRow** p1 =
      (SResultRow**)taosHashGet(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
169 170 171 172 173 174 175 176 177 178 179

  // in case of repeat scan/reverse scan, no new time window added.
  if (QUERY_IS_INTERVAL_QUERY(pRuntimeEnv->pQueryAttr)) {
    if (!masterscan) {  // the *p1 may be NULL in case of sliding+offset exists.
      return p1 != NULL;
    }

    if (p1 != NULL) {
      if (pResultRowInfo->size == 0) {
        existed = false;
      } else if (pResultRowInfo->size == 1) {
dengyihao's avatar
dengyihao 已提交
180
        //        existed = (pResultRowInfo->pResult[0] == (*p1));
181 182
      } else {  // check if current pResultRowInfo contains the existed pResultRow
        SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid, pResultRowInfo);
L
Liu Jicong 已提交
183 184
        int64_t* index =
            taosHashGet(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
185 186 187 188 189 190 191 192 193 194 195 196 197
        if (index != NULL) {
          existed = true;
        } else {
          existed = false;
        }
      }
    }

    return existed;
  }

  return p1 != NULL;
}
198
#endif
199

200
SResultRow* getNewResultRow(SDiskbasedBuf* pResultBuf, int64_t tableGroupId, int32_t interBufSize) {
L
Liu Jicong 已提交
201
  SFilePage* pData = NULL;
202 203 204 205 206 207 208 209 210 211 212 213 214

  // in the first scan, new space needed for results
  int32_t pageId = -1;
  SIDList list = getDataBufPagesIdList(pResultBuf, tableGroupId);

  if (taosArrayGetSize(list) == 0) {
    pData = getNewBufPage(pResultBuf, tableGroupId, &pageId);
    pData->num = sizeof(SFilePage);
  } else {
    SPageInfo* pi = getLastPageInfo(list);
    pData = getBufPage(pResultBuf, getPageId(pi));
    pageId = getPageId(pi);

wmmhello's avatar
wmmhello 已提交
215
    if (pData->num + interBufSize > getBufPageSize(pResultBuf)) {
216 217 218 219 220 221 222 223 224 225 226 227 228 229
      // release current page first, and prepare the next one
      releaseBufPageInfo(pResultBuf, pi);

      pData = getNewBufPage(pResultBuf, tableGroupId, &pageId);
      if (pData != NULL) {
        pData->num = sizeof(SFilePage);
      }
    }
  }

  if (pData == NULL) {
    return NULL;
  }

230 231
  setBufPageDirty(pData, true);

232 233 234 235 236
  // set the number of rows in current disk page
  SResultRow* pResultRow = (SResultRow*)((char*)pData + pData->num);
  pResultRow->pageId = pageId;
  pResultRow->offset = (int32_t)pData->num;

wmmhello's avatar
wmmhello 已提交
237
  pData->num += interBufSize;
238 239 240 241

  return pResultRow;
}

242 243 244 245 246 247 248
/**
 * the struct of key in hash table
 * +----------+---------------+
 * | group id |   key data    |
 * | 8 bytes  | actual length |
 * +----------+---------------+
 */
249 250 251
SResultRow* doSetResultOutBufByKey(SDiskbasedBuf* pResultBuf, SResultRowInfo* pResultRowInfo, char* pData,
                                   int16_t bytes, bool masterscan, uint64_t groupId, SExecTaskInfo* pTaskInfo,
                                   bool isIntervalQuery, SAggSupporter* pSup) {
252
  SET_RES_WINDOW_KEY(pSup->keyBuf, pData, bytes, groupId);
H
Haojun Liao 已提交
253

dengyihao's avatar
dengyihao 已提交
254 255
  SResultRowPosition* p1 =
      (SResultRowPosition*)taosHashGet(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
H
Haojun Liao 已提交
256

257 258
  SResultRow* pResult = NULL;

H
Haojun Liao 已提交
259 260
  // in case of repeat scan/reverse scan, no new time window added.
  if (isIntervalQuery) {
261 262
    if (masterscan && p1 != NULL) {  // the *p1 may be NULL in case of sliding+offset exists.
      pResult = getResultRowByPos(pResultBuf, p1);
263
      ASSERT(pResult->pageId == p1->pageId && pResult->offset == p1->offset);
H
Haojun Liao 已提交
264 265
    }
  } else {
dengyihao's avatar
dengyihao 已提交
266 267
    // In case of group by column query, the required SResultRow object must be existInCurrentResusltRowInfo in the
    // pResultRowInfo object.
H
Haojun Liao 已提交
268
    if (p1 != NULL) {
269
      // todo
270
      pResult = getResultRowByPos(pResultBuf, p1);
271
      ASSERT(pResult->pageId == p1->pageId && pResult->offset == p1->offset);
H
Haojun Liao 已提交
272 273 274
    }
  }

L
Liu Jicong 已提交
275
  // 1. close current opened time window
276
  if (pResultRowInfo->cur.pageId != -1 && ((pResult == NULL) || (pResult->pageId != pResultRowInfo->cur.pageId &&
L
Liu Jicong 已提交
277
                                                                 pResult->offset != pResultRowInfo->cur.offset))) {
278
    SResultRowPosition pos = pResultRowInfo->cur;
X
Xiaoyu Wang 已提交
279
    SFilePage*         pPage = getBufPage(pResultBuf, pos.pageId);
280 281 282 283 284
    releaseBufPage(pResultBuf, pPage);
  }

  // allocate a new buffer page
  if (pResult == NULL) {
H
Haojun Liao 已提交
285
    ASSERT(pSup->resultRowSize > 0);
286 287
    pResult = getNewResultRow(pResultBuf, groupId, pSup->resultRowSize);

288
    initResultRow(pResult);
H
Haojun Liao 已提交
289

290 291
    // add a new result set for a new group
    SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
X
Xiaoyu Wang 已提交
292 293
    taosHashPut(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pos,
                sizeof(SResultRowPosition));
H
Haojun Liao 已提交
294 295
  }

296 297 298
  // 2. set the new time window to be the new active time window
  pResultRowInfo->cur = (SResultRowPosition){.pageId = pResult->pageId, .offset = pResult->offset};

H
Haojun Liao 已提交
299
  // too many time window in query
300
  if (taosHashGetSize(pSup->pResultRowHashTable) > MAX_INTERVAL_TIME_WINDOW) {
H
Haojun Liao 已提交
301 302 303
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_TOO_MANY_TIMEWINDOW);
  }

H
Haojun Liao 已提交
304
  return pResult;
H
Haojun Liao 已提交
305 306
}

307
// a new buffer page for each table. Needs to opt this design
L
Liu Jicong 已提交
308
static int32_t addNewWindowResultBuf(SResultRow* pWindowRes, SDiskbasedBuf* pResultBuf, int32_t tid, uint32_t size) {
309 310 311 312
  if (pWindowRes->pageId != -1) {
    return 0;
  }

L
Liu Jicong 已提交
313
  SFilePage* pData = NULL;
314 315 316 317 318 319

  // in the first scan, new space needed for results
  int32_t pageId = -1;
  SIDList list = getDataBufPagesIdList(pResultBuf, tid);

  if (taosArrayGetSize(list) == 0) {
H
Haojun Liao 已提交
320
    pData = getNewBufPage(pResultBuf, tid, &pageId);
321
    pData->num = sizeof(SFilePage);
322 323
  } else {
    SPageInfo* pi = getLastPageInfo(list);
324
    pData = getBufPage(pResultBuf, getPageId(pi));
325
    pageId = getPageId(pi);
326

327
    if (pData->num + size > getBufPageSize(pResultBuf)) {
328
      // release current page first, and prepare the next one
329
      releaseBufPageInfo(pResultBuf, pi);
330

H
Haojun Liao 已提交
331
      pData = getNewBufPage(pResultBuf, tid, &pageId);
332
      if (pData != NULL) {
333
        pData->num = sizeof(SFilePage);
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
      }
    }
  }

  if (pData == NULL) {
    return -1;
  }

  // set the number of rows in current disk page
  if (pWindowRes->pageId == -1) {  // not allocated yet, allocate new buffer
    pWindowRes->pageId = pageId;
    pWindowRes->offset = (int32_t)pData->num;

    pData->num += size;
    assert(pWindowRes->pageId >= 0);
  }

  return 0;
}

354
//  query_range_start, query_range_end, window_duration, window_start, window_end
355
void initExecTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pQueryWindow) {
356 357 358
  pColData->info.type = TSDB_DATA_TYPE_TIMESTAMP;
  pColData->info.bytes = sizeof(int64_t);

359
  colInfoDataEnsureCapacity(pColData, 0, 5);
360 361 362 363 364 365 366 367 368
  colDataAppendInt64(pColData, 0, &pQueryWindow->skey);
  colDataAppendInt64(pColData, 1, &pQueryWindow->ekey);

  int64_t interval = 0;
  colDataAppendInt64(pColData, 2, &interval);  // this value may be variable in case of 'n' and 'y'.
  colDataAppendInt64(pColData, 3, &pQueryWindow->skey);
  colDataAppendInt64(pColData, 4, &pQueryWindow->ekey);
}

X
Xiaoyu Wang 已提交
369 370 371
void doApplyFunctions(SExecTaskInfo* taskInfo, SqlFunctionCtx* pCtx, STimeWindow* pWin,
                      SColumnInfoData* pTimeWindowData, int32_t offset, int32_t forwardStep, TSKEY* tsCol,
                      int32_t numOfTotal, int32_t numOfOutput, int32_t order) {
372
  for (int32_t k = 0; k < numOfOutput; ++k) {
H
Haojun Liao 已提交
373
    // keep it temporarily
374
    // todo no need this??
dengyihao's avatar
dengyihao 已提交
375 376
    bool    hasAgg = pCtx[k].input.colDataAggIsSet;
    int32_t numOfRows = pCtx[k].input.numOfRows;
H
Haojun Liao 已提交
377
    int32_t startOffset = pCtx[k].input.startRowIndex;
378

379
    pCtx[k].input.startRowIndex = offset;
380
    pCtx[k].input.numOfRows = forwardStep;
381 382 383

    // not a whole block involved in query processing, statistics data can not be used
    // NOTE: the original value of isSet have been changed here
384 385
    if (pCtx[k].input.colDataAggIsSet && forwardStep < numOfTotal) {
      pCtx[k].input.colDataAggIsSet = false;
386 387
    }

388 389
    if (fmIsWindowPseudoColumnFunc(pCtx[k].functionId)) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
390 391

      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);
392

393
      SColumnInfoData idata = {0};
dengyihao's avatar
dengyihao 已提交
394
      idata.info.type = TSDB_DATA_TYPE_BIGINT;
395
      idata.info.bytes = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
dengyihao's avatar
dengyihao 已提交
396
      idata.pData = p;
397 398 399 400

      SScalarParam out = {.columnData = &idata};
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
      pCtx[k].sfp.process(&tw, 1, &out);
401
      pEntryInfo->numOfRes = 1;
402 403 404 405 406 407 408 409 410 411
    } else {
      int32_t code = TSDB_CODE_SUCCESS;
      if (functionNeedToExecute(&pCtx[k]) && pCtx[k].fpSet.process != NULL) {
        code = pCtx[k].fpSet.process(&pCtx[k]);

        if (code != TSDB_CODE_SUCCESS) {
          qError("%s apply functions error, code: %s", GET_TASKID(taskInfo), tstrerror(code));
          taskInfo->code = code;
          longjmp(taskInfo->env, code);
        }
412
      }
413

414 415 416 417 418
      // restore it
      pCtx[k].input.colDataAggIsSet = hasAgg;
      pCtx[k].input.startRowIndex = startOffset;
      pCtx[k].input.numOfRows = numOfRows;
    }
419 420 421
  }
}

dengyihao's avatar
dengyihao 已提交
422
static int32_t doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
423
                                   int32_t scanFlag, bool createDummyCol);
424

dengyihao's avatar
dengyihao 已提交
425 426
static void doSetInputDataBlockInfo(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock,
                                    int32_t order) {
427
  for (int32_t i = 0; i < pOperator->exprSupp.numOfExprs; ++i) {
428
    pCtx[i].order = order;
429
    pCtx[i].input.numOfRows = pBlock->info.rows;
430
    setBlockStatisInfo(&pCtx[i], &pOperator->exprSupp.pExprInfo[i], pBlock);
431 432 433
  }
}

X
Xiaoyu Wang 已提交
434 435
void setInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
                       int32_t scanFlag, bool createDummyCol) {
436
  if (pBlock->pBlockAgg != NULL) {
H
Haojun Liao 已提交
437
    doSetInputDataBlockInfo(pOperator, pCtx, pBlock, order);
438
  } else {
439
    doSetInputDataBlock(pOperator, pCtx, pBlock, order, scanFlag, createDummyCol);
H
Haojun Liao 已提交
440
  }
441 442
}

L
Liu Jicong 已提交
443 444
static int32_t doCreateConstantValColumnInfo(SInputColumnInfoData* pInput, SFunctParam* pFuncParam, int32_t paramIndex,
                                             int32_t numOfRows) {
445 446 447 448 449 450 451 452
  SColumnInfoData* pColInfo = NULL;
  if (pInput->pData[paramIndex] == NULL) {
    pColInfo = taosMemoryCalloc(1, sizeof(SColumnInfoData));
    if (pColInfo == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }

    // Set the correct column info (data type and bytes)
453 454
    pColInfo->info.type = pFuncParam->param.nType;
    pColInfo->info.bytes = pFuncParam->param.nLen;
455 456

    pInput->pData[paramIndex] = pColInfo;
457 458
  } else {
    pColInfo = pInput->pData[paramIndex];
459 460
  }

461
  colInfoDataEnsureCapacity(pColInfo, 0, numOfRows);
462

463
  int8_t type = pFuncParam->param.nType;
464 465
  if (type == TSDB_DATA_TYPE_BIGINT || type == TSDB_DATA_TYPE_UBIGINT) {
    int64_t v = pFuncParam->param.i;
dengyihao's avatar
dengyihao 已提交
466
    for (int32_t i = 0; i < numOfRows; ++i) {
467 468 469 470
      colDataAppendInt64(pColInfo, i, &v);
    }
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
dengyihao's avatar
dengyihao 已提交
471
    for (int32_t i = 0; i < numOfRows; ++i) {
472 473
      colDataAppendDouble(pColInfo, i, &v);
    }
474
  } else if (type == TSDB_DATA_TYPE_VARCHAR) {
L
Liu Jicong 已提交
475
    char* tmp = taosMemoryMalloc(pFuncParam->param.nLen + VARSTR_HEADER_SIZE);
476
    STR_WITH_SIZE_TO_VARSTR(tmp, pFuncParam->param.pz, pFuncParam->param.nLen);
L
Liu Jicong 已提交
477
    for (int32_t i = 0; i < numOfRows; ++i) {
478 479
      colDataAppend(pColInfo, i, tmp, false);
    }
480 481 482 483 484
  }

  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
485
static int32_t doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
X
Xiaoyu Wang 已提交
486
                                   int32_t scanFlag, bool createDummyCol) {
487 488
  int32_t code = TSDB_CODE_SUCCESS;

489
  for (int32_t i = 0; i < pOperator->exprSupp.numOfExprs; ++i) {
L
Liu Jicong 已提交
490
    pCtx[i].order = order;
491 492
    pCtx[i].input.numOfRows = pBlock->info.rows;

L
Liu Jicong 已提交
493
    pCtx[i].pSrcBlock = pBlock;
X
Xiaoyu Wang 已提交
494
    pCtx[i].scanFlag = scanFlag;
H
Haojun Liao 已提交
495

496
    SInputColumnInfoData* pInput = &pCtx[i].input;
497
    pInput->uid = pBlock->info.uid;
C
Cary Xu 已提交
498
    pInput->colDataAggIsSet = false;
499

500
    SExprInfo* pOneExpr = &pOperator->exprSupp.pExprInfo[i];
501
    for (int32_t j = 0; j < pOneExpr->base.numOfParams; ++j) {
dengyihao's avatar
dengyihao 已提交
502
      SFunctParam* pFuncParam = &pOneExpr->base.pParam[j];
G
Ganlin Zhao 已提交
503 504
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
dengyihao's avatar
dengyihao 已提交
505
        pInput->pData[j] = taosArrayGet(pBlock->pDataBlock, slotId);
506 507 508
        pInput->totalRows = pBlock->info.rows;
        pInput->numOfRows = pBlock->info.rows;
        pInput->startRowIndex = 0;
509

510
        // NOTE: the last parameter is the primary timestamp column
511 512 513
        if (fmIsTimelineFunc(pCtx[i].functionId) && (j == pOneExpr->base.numOfParams - 1)) {
          pInput->pPTS = pInput->pData[j];
        }
514 515
        ASSERT(pInput->pData[j] != NULL);
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
516 517 518
        // todo avoid case: top(k, 12), 12 is the value parameter.
        // sum(11), 11 is also the value parameter.
        if (createDummyCol && pOneExpr->base.numOfParams == 1) {
519 520 521 522
          pInput->totalRows = pBlock->info.rows;
          pInput->numOfRows = pBlock->info.rows;
          pInput->startRowIndex = 0;

523
          code = doCreateConstantValColumnInfo(pInput, pFuncParam, j, pBlock->info.rows);
524 525 526
          if (code != TSDB_CODE_SUCCESS) {
            return code;
          }
527
        }
G
Ganlin Zhao 已提交
528 529
      }
    }
H
Haojun Liao 已提交
530
  }
531 532

  return code;
H
Haojun Liao 已提交
533 534
}

535
static int32_t doAggregateImpl(SOperatorInfo* pOperator, TSKEY startTs, SqlFunctionCtx* pCtx) {
536
  for (int32_t k = 0; k < pOperator->exprSupp.numOfExprs; ++k) {
H
Haojun Liao 已提交
537
    if (functionNeedToExecute(&pCtx[k])) {
538
      // todo add a dummy funtion to avoid process check
539 540 541 542 543 544 545 546
      if (pCtx[k].fpSet.process == NULL) {
        continue;
      }

      int32_t code = pCtx[k].fpSet.process(&pCtx[k]);
      if (code != TSDB_CODE_SUCCESS) {
        qError("%s aggregate function error happens, code: %s", GET_TASKID(pOperator->pTaskInfo), tstrerror(code));
        return code;
547
      }
548 549
    }
  }
550 551

  return TSDB_CODE_SUCCESS;
552 553
}

H
Haojun Liao 已提交
554
static void setPseudoOutputColInfo(SSDataBlock* pResult, SqlFunctionCtx* pCtx, SArray* pPseudoList) {
dengyihao's avatar
dengyihao 已提交
555
  size_t num = (pPseudoList != NULL) ? taosArrayGetSize(pPseudoList) : 0;
H
Haojun Liao 已提交
556 557 558 559 560
  for (int32_t i = 0; i < num; ++i) {
    pCtx[i].pOutput = taosArrayGet(pResult->pDataBlock, i);
  }
}

561
int32_t projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBlock* pSrcBlock, SqlFunctionCtx* pCtx,
X
Xiaoyu Wang 已提交
562
                              int32_t numOfOutput, SArray* pPseudoList) {
H
Haojun Liao 已提交
563
  setPseudoOutputColInfo(pResult, pCtx, pPseudoList);
H
Haojun Liao 已提交
564
  pResult->info.groupId = pSrcBlock->info.groupId;
H
Haojun Liao 已提交
565

dengyihao's avatar
dengyihao 已提交
566 567
  // if the source equals to the destination, it is to create a new column as the result of scalar function or some
  // operators.
568 569
  bool createNewColModel = (pResult == pSrcBlock);

570 571
  int32_t numOfRows = 0;

572
  for (int32_t k = 0; k < numOfOutput; ++k) {
dengyihao's avatar
dengyihao 已提交
573
    int32_t         outputSlotId = pExpr[k].base.resSchema.slotId;
574 575
    SqlFunctionCtx* pfCtx = &pCtx[k];

L
Liu Jicong 已提交
576
    if (pExpr[k].pExpr->nodeType == QUERY_NODE_COLUMN) {  // it is a project query
577
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
578
      if (pResult->info.rows > 0 && !createNewColModel) {
X
Xiaoyu Wang 已提交
579 580
        colDataMergeCol(pColInfoData, pResult->info.rows, &pResult->info.capacity, pfCtx->input.pData[0],
                        pfCtx->input.numOfRows);
581 582 583
      } else {
        colDataAssign(pColInfoData, pfCtx->input.pData[0], pfCtx->input.numOfRows);
      }
584

585
      numOfRows = pfCtx->input.numOfRows;
586
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_VALUE) {
587
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
588

dengyihao's avatar
dengyihao 已提交
589
      int32_t offset = createNewColModel ? 0 : pResult->info.rows;
590
      for (int32_t i = 0; i < pSrcBlock->info.rows; ++i) {
dengyihao's avatar
dengyihao 已提交
591 592 593
        colDataAppend(pColInfoData, i + offset,
                      taosVariantGet(&pExpr[k].base.pParam[0].param, pExpr[k].base.pParam[0].param.nType),
                      TSDB_DATA_TYPE_NULL == pExpr[k].base.pParam[0].param.nType);
594
      }
595 596

      numOfRows = pSrcBlock->info.rows;
H
Haojun Liao 已提交
597
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_OPERATOR) {
598 599 600
      SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
      taosArrayPush(pBlockList, &pSrcBlock);

601
      SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
602
      SColumnInfoData  idata = {.info = pResColData->info, .hasNull = true};
603

604
      SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
605
      int32_t      code = scalarCalculate(pExpr[k].pExpr->_optrRoot.pRootNode, pBlockList, &dest);
606 607 608 609
      if (code != TSDB_CODE_SUCCESS) {
        taosArrayDestroy(pBlockList);
        return code;
      }
610

dengyihao's avatar
dengyihao 已提交
611
      int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
612
      ASSERT(pResult->info.capacity > 0);
613
      colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
614 615

      numOfRows = dest.numOfRows;
616 617
      taosArrayDestroy(pBlockList);
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_FUNCTION) {
618
      ASSERT(!fmIsAggFunc(pfCtx->functionId));
619

620 621
      // _rowts/_c0, not tbname column
      if (fmIsPseudoColumnFunc(pfCtx->functionId) && (!fmIsScanPseudoColumnFunc(pfCtx->functionId))) {
H
Haojun Liao 已提交
622
        // do nothing
623 624 625 626 627 628 629 630 631 632 633 634 635 636
      } else if (fmIsIndefiniteRowsFunc(pfCtx->functionId)) {
        SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[k]);
        pfCtx->fpSet.init(&pCtx[k], pResInfo);

        pfCtx->pOutput = taosArrayGet(pResult->pDataBlock, outputSlotId);
        pfCtx->offset = createNewColModel ? 0 : pResult->info.rows;  // set the start offset

        // set the timestamp(_rowts) output buffer
        if (taosArrayGetSize(pPseudoList) > 0) {
          int32_t* outputColIndex = taosArrayGet(pPseudoList, 0);
          pfCtx->pTsOutput = (SColumnInfoData*)pCtx[*outputColIndex].pOutput;
        }

        numOfRows = pfCtx->fpSet.process(pfCtx);
H
Haojun Liao 已提交
637 638 639
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
640

641
        SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
642
        SColumnInfoData  idata = {.info = pResColData->info, .hasNull = true};
H
Haojun Liao 已提交
643

644
        SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
645
        int32_t      code = scalarCalculate((SNode*)pExpr[k].pExpr->_function.pFunctNode, pBlockList, &dest);
646 647 648 649
        if (code != TSDB_CODE_SUCCESS) {
          taosArrayDestroy(pBlockList);
          return code;
        }
650

dengyihao's avatar
dengyihao 已提交
651
        int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
652
        ASSERT(pResult->info.capacity > 0);
653
        colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
654 655

        numOfRows = dest.numOfRows;
H
Haojun Liao 已提交
656 657
        taosArrayDestroy(pBlockList);
      }
658
    } else {
659
      ASSERT(0);
660 661
    }
  }
662

663 664 665
  if (!createNewColModel) {
    pResult->info.rows += numOfRows;
  }
666 667

  return TSDB_CODE_SUCCESS;
668 669
}

670 671 672
static void setResultRowKey(SResultRow* pResultRow, char* pData, int16_t type) {
  if (IS_VAR_DATA_TYPE(type)) {
    // todo disable this
673

674 675 676 677 678 679 680 681 682
    //    if (pResultRow->key == NULL) {
    //      pResultRow->key = taosMemoryMalloc(varDataTLen(pData));
    //      varDataCopy(pResultRow->key, pData);
    //    } else {
    //      ASSERT(memcmp(pResultRow->key, pData, varDataTLen(pData)) == 0);
    //    }
  } else {
    int64_t v = -1;
    GET_TYPED_DATA(v, int64_t, type, pData);
683

684 685
    pResultRow->win.skey = v;
    pResultRow->win.ekey = v;
686 687 688
  }
}

5
54liuyao 已提交
689
bool functionNeedToExecute(SqlFunctionCtx* pCtx) {
690
  struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
691

692 693 694 695 696
  // in case of timestamp column, always generated results.
  int32_t functionId = pCtx->functionId;
  if (functionId == -1) {
    return false;
  }
697

698 699
  if (pCtx->scanFlag == REPEAT_SCAN) {
    return fmIsRepeatScanFunc(pCtx->functionId);
700 701
  }

702 703
  if (isRowEntryCompleted(pResInfo)) {
    return false;
704 705
  }

706 707 708
  return true;
}

709 710 711 712 713 714 715
static int32_t doCreateConstantValColumnAggInfo(SInputColumnInfoData* pInput, SFunctParam* pFuncParam, int32_t type,
                                                int32_t paramIndex, int32_t numOfRows) {
  if (pInput->pData[paramIndex] == NULL) {
    pInput->pData[paramIndex] = taosMemoryCalloc(1, sizeof(SColumnInfoData));
    if (pInput->pData[paramIndex] == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
716

717 718 719
    // Set the correct column info (data type and bytes)
    pInput->pData[paramIndex]->info.type = type;
    pInput->pData[paramIndex]->info.bytes = tDataTypes[type].bytes;
720
  }
H
Haojun Liao 已提交
721

722 723 724 725 726 727
  SColumnDataAgg* da = NULL;
  if (pInput->pColumnDataAgg[paramIndex] == NULL) {
    da = taosMemoryCalloc(1, sizeof(SColumnDataAgg));
    pInput->pColumnDataAgg[paramIndex] = da;
    if (da == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
728 729
    }
  } else {
730
    da = pInput->pColumnDataAgg[paramIndex];
731 732
  }

733
  ASSERT(!IS_VAR_DATA_TYPE(type));
734

735 736 737 738 739 740
  if (type == TSDB_DATA_TYPE_BIGINT) {
    int64_t v = pFuncParam->param.i;
    *da = (SColumnDataAgg){.numOfNull = 0, .min = v, .max = v, .maxIndex = 0, .minIndex = 0, .sum = v * numOfRows};
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
    *da = (SColumnDataAgg){.numOfNull = 0, .maxIndex = 0, .minIndex = 0};
741

742 743 744 745 746 747 748 749 750 751 752 753
    *(double*)&da->min = v;
    *(double*)&da->max = v;
    *(double*)&da->sum = v * numOfRows;
  } else if (type == TSDB_DATA_TYPE_BOOL) {  // todo validate this data type
    bool v = pFuncParam->param.i;

    *da = (SColumnDataAgg){.numOfNull = 0, .maxIndex = 0, .minIndex = 0};
    *(bool*)&da->min = 0;
    *(bool*)&da->max = v;
    *(bool*)&da->sum = v * numOfRows;
  } else if (type == TSDB_DATA_TYPE_TIMESTAMP) {
    // do nothing
754
  } else {
755
    ASSERT(0);
756 757
  }

758 759
  return TSDB_CODE_SUCCESS;
}
760 761 762 763 764 765 766 767 768 769 770

void setBlockStatisInfo(SqlFunctionCtx* pCtx, SExprInfo* pExprInfo, SSDataBlock* pBlock) {
  int32_t numOfRows = pBlock->info.rows;

  SInputColumnInfoData* pInput = &pCtx->input;
  pInput->numOfRows = numOfRows;
  pInput->totalRows = numOfRows;

  if (pBlock->pBlockAgg != NULL) {
    pInput->colDataAggIsSet = true;

771 772
    for (int32_t j = 0; j < pExprInfo->base.numOfParams; ++j) {
      SFunctParam* pFuncParam = &pExprInfo->base.pParam[j];
773

774 775
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
776 777 778 779
        pInput->pColumnDataAgg[j] = pBlock->pBlockAgg[slotId];
        if (pInput->pColumnDataAgg[j] == NULL) {
          pInput->colDataAggIsSet = false;
        }
780 781 782 783

        // Here we set the column info data since the data type for each column data is required, but
        // the data in the corresponding SColumnInfoData will not be used.
        pInput->pData[j] = taosArrayGet(pBlock->pDataBlock, slotId);
784 785
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
        doCreateConstantValColumnAggInfo(pInput, pFuncParam, pFuncParam->param.nType, j, pBlock->info.rows);
786 787
      }
    }
788
  } else {
789
    pInput->colDataAggIsSet = false;
790 791 792
  }

  // set the statistics data for primary time stamp column
793 794 795 796 797
  //  if (pCtx->functionId == FUNCTION_SPREAD && pColumn->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
  //    pCtx->isAggSet = true;
  //    pCtx->agg.min = pBlock->info.window.skey;
  //    pCtx->agg.max = pBlock->info.window.ekey;
  //  }
798 799
}

L
Liu Jicong 已提交
800
bool isTaskKilled(SExecTaskInfo* pTaskInfo) {
801 802
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
L
Liu Jicong 已提交
803 804
  if (pTaskInfo->owner != 0 &&
      ((taosGetTimestampSec() - pTaskInfo->cost.start / 1000) > 10 * getMaximumIdleDurationSec())
805 806
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
    assert(pTaskInfo->cost.start != 0);
L
Liu Jicong 已提交
807 808 809
    //    qDebug("QInfo:%" PRIu64 " retrieve not arrive beyond %d ms, abort current query execution, start:%" PRId64
    //           ", current:%d", pQInfo->qId, 1, pQInfo->startExecTs, taosGetTimestampSec());
    //    return true;
810 811 812 813 814
  }

  return false;
}

L
Liu Jicong 已提交
815
void setTaskKilled(SExecTaskInfo* pTaskInfo) { pTaskInfo->code = TSDB_CODE_TSC_QUERY_CANCELLED; }
816 817

/////////////////////////////////////////////////////////////////////////////////////////////
L
Liu Jicong 已提交
818
// todo refactor : return window
819
void getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key, STimeWindow* win) {
H
Haojun Liao 已提交
820
  win->skey = taosTimeTruncate(key, pInterval, precision);
821 822

  /*
H
Haojun Liao 已提交
823
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
824 825
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
826 827
  win->ekey = taosTimeAdd(win->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
  if (win->ekey < win->skey) {
828 829 830 831
    win->ekey = INT64_MAX;
  }
}

832
#if 0
L
Liu Jicong 已提交
833
static int32_t updateBlockLoadStatus(STaskAttr* pQuery, int32_t status) {
834

835 836 837
  bool hasFirstLastFunc = false;
  bool hasOtherFunc = false;

838
  if (status == BLK_DATA_DATA_LOAD || status == BLK_DATA_FILTEROUT) {
839 840 841 842 843
    return status;
  }

  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
    int32_t functionId = getExprFunctionId(&pQuery->pExpr1[i]);
844

845 846 847 848 849 850 851 852 853 854
    if (functionId == FUNCTION_TS || functionId == FUNCTION_TS_DUMMY || functionId == FUNCTION_TAG ||
        functionId == FUNCTION_TAG_DUMMY) {
      continue;
    }

    if (functionId == FUNCTION_FIRST_DST || functionId == FUNCTION_LAST_DST) {
      hasFirstLastFunc = true;
    } else {
      hasOtherFunc = true;
    }
855

856 857
  }

858
  if (hasFirstLastFunc && status == BLK_DATA_NOT_LOAD) {
L
Liu Jicong 已提交
859
    if (!hasOtherFunc) {
860
      return BLK_DATA_FILTEROUT;
861
    } else {
862
      return BLK_DATA_DATA_LOAD;
863 864 865 866 867 868
    }
  }

  return status;
}

869 870
#endif

L
Liu Jicong 已提交
871 872
// static void updateDataCheckOrder(SQInfo *pQInfo, SQueryTableReq* pQueryMsg, bool stableQuery) {
//   STaskAttr* pQueryAttr = pQInfo->runtimeEnv.pQueryAttr;
H
Haojun Liao 已提交
873
//
L
Liu Jicong 已提交
874 875 876 877
//   // in case of point-interpolation query, use asc order scan
//   char msg[] = "QInfo:0x%"PRIx64" scan order changed for %s query, old:%d, new:%d, qrange exchanged, old qrange:%"
//   PRId64
//                "-%" PRId64 ", new qrange:%" PRId64 "-%" PRId64;
H
Haojun Liao 已提交
878
//
L
Liu Jicong 已提交
879 880 881 882 883
//   // todo handle the case the the order irrelevant query type mixed up with order critical query type
//   // descending order query for last_row query
//   if (isFirstLastRowQuery(pQueryAttr)) {
//     //qDebug("QInfo:0x%"PRIx64" scan order changed for last_row query, old:%d, new:%d", pQInfo->qId,
//     pQueryAttr->order.order, TSDB_ORDER_ASC);
H
Haojun Liao 已提交
884
//
L
Liu Jicong 已提交
885 886
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
wafwerar's avatar
wafwerar 已提交
887
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
888
//     }
H
Haojun Liao 已提交
889
//
L
Liu Jicong 已提交
890 891 892
//     pQueryAttr->needReverseScan = false;
//     return;
//   }
H
Haojun Liao 已提交
893
//
L
Liu Jicong 已提交
894 895 896
//   if (pQueryAttr->groupbyColumn && pQueryAttr->order.order == TSDB_ORDER_DESC) {
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
wafwerar's avatar
wafwerar 已提交
897
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
898
//     }
H
Haojun Liao 已提交
899
//
L
Liu Jicong 已提交
900 901 902 903
//     pQueryAttr->needReverseScan = false;
//     doUpdateLastKey(pQueryAttr);
//     return;
//   }
H
Haojun Liao 已提交
904
//
L
Liu Jicong 已提交
905 906 907 908 909 910
//   if (pQueryAttr->pointInterpQuery && pQueryAttr->interval.interval == 0) {
//     if (!QUERY_IS_ASC_QUERY(pQueryAttr)) {
//       //qDebug(msg, pQInfo->qId, "interp", pQueryAttr->order.order, TSDB_ORDER_ASC, pQueryAttr->window.skey,
//       pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey); TSWAP(pQueryAttr->window.skey,
//       pQueryAttr->window.ekey, TSKEY);
//     }
H
Haojun Liao 已提交
911
//
L
Liu Jicong 已提交
912 913 914
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     return;
//   }
H
Haojun Liao 已提交
915
//
L
Liu Jicong 已提交
916 917 918 919
//   if (pQueryAttr->interval.interval == 0) {
//     if (onlyFirstQuery(pQueryAttr)) {
//       if (!QUERY_IS_ASC_QUERY(pQueryAttr)) {
//         //qDebug(msg, pQInfo->qId, "only-first", pQueryAttr->order.order, TSDB_ORDER_ASC, pQueryAttr->window.skey,
H
Haojun Liao 已提交
920 921
////               pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey);
//
wafwerar's avatar
wafwerar 已提交
922
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
923 924 925 926 927 928 929 930 931 932
//        doUpdateLastKey(pQueryAttr);
//      }
//
//      pQueryAttr->order.order = TSDB_ORDER_ASC;
//      pQueryAttr->needReverseScan = false;
//    } else if (onlyLastQuery(pQueryAttr) && notContainSessionOrStateWindow(pQueryAttr)) {
//      if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//        //qDebug(msg, pQInfo->qId, "only-last", pQueryAttr->order.order, TSDB_ORDER_DESC, pQueryAttr->window.skey,
////               pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey);
//
wafwerar's avatar
wafwerar 已提交
933
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
934 935 936 937 938 939 940 941 942 943 944 945
//        doUpdateLastKey(pQueryAttr);
//      }
//
//      pQueryAttr->order.order = TSDB_ORDER_DESC;
//      pQueryAttr->needReverseScan = false;
//    }
//
//  } else {  // interval query
//    if (stableQuery) {
//      if (onlyFirstQuery(pQueryAttr)) {
//        if (!QUERY_IS_ASC_QUERY(pQueryAttr)) {
//          //qDebug(msg, pQInfo->qId, "only-first stable", pQueryAttr->order.order, TSDB_ORDER_ASC,
L
Liu Jicong 已提交
946 947
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
948
//
wafwerar's avatar
wafwerar 已提交
949
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
950 951 952 953 954 955 956 957
//          doUpdateLastKey(pQueryAttr);
//        }
//
//        pQueryAttr->order.order = TSDB_ORDER_ASC;
//        pQueryAttr->needReverseScan = false;
//      } else if (onlyLastQuery(pQueryAttr)) {
//        if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//          //qDebug(msg, pQInfo->qId, "only-last stable", pQueryAttr->order.order, TSDB_ORDER_DESC,
L
Liu Jicong 已提交
958 959
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
960
//
wafwerar's avatar
wafwerar 已提交
961
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
962 963 964 965 966 967 968 969 970
//          doUpdateLastKey(pQueryAttr);
//        }
//
//        pQueryAttr->order.order = TSDB_ORDER_DESC;
//        pQueryAttr->needReverseScan = false;
//      }
//    }
//  }
//}
971

L
Liu Jicong 已提交
972 973 974
// static FORCE_INLINE bool doFilterByBlockStatistics(STaskRuntimeEnv* pRuntimeEnv, SDataStatis *pDataStatis,
// SqlFunctionCtx *pCtx, int32_t numOfRows) {
//   STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
975
//
L
Liu Jicong 已提交
976 977 978
//   if (pDataStatis == NULL || pQueryAttr->pFilters == NULL) {
//     return true;
//   }
979
//
L
Liu Jicong 已提交
980 981
//   return filterRangeExecute(pQueryAttr->pFilters, pDataStatis, pQueryAttr->numOfCols, numOfRows);
// }
982
#if 0
H
Haojun Liao 已提交
983
static bool overlapWithTimeWindow(STaskAttr* pQueryAttr, SDataBlockInfo* pBlockInfo) {
984 985
  STimeWindow w = {0};

dengyihao's avatar
dengyihao 已提交
986 987
  TSKEY sk = TMIN(pQueryAttr->window.skey, pQueryAttr->window.ekey);
  TSKEY ek = TMAX(pQueryAttr->window.skey, pQueryAttr->window.ekey);
988

989
  if (true) {
L
Liu Jicong 已提交
990
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.skey, sk, ek, &w);
991 992 993 994 995 996
    assert(w.ekey >= pBlockInfo->window.skey);

    if (w.ekey < pBlockInfo->window.ekey) {
      return true;
    }

L
Liu Jicong 已提交
997 998
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
999 1000 1001 1002 1003 1004 1005 1006 1007 1008
      if (w.skey > pBlockInfo->window.ekey) {
        break;
      }

      assert(w.ekey > pBlockInfo->window.ekey);
      if (w.skey <= pBlockInfo->window.ekey && w.skey > pBlockInfo->window.skey) {
        return true;
      }
    }
  } else {
L
Liu Jicong 已提交
1009
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
1010 1011 1012 1013 1014 1015
    assert(w.skey <= pBlockInfo->window.ekey);

    if (w.skey > pBlockInfo->window.skey) {
      return true;
    }

L
Liu Jicong 已提交
1016 1017
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
      if (w.ekey < pBlockInfo->window.skey) {
        break;
      }

      assert(w.skey < pBlockInfo->window.skey);
      if (w.ekey < pBlockInfo->window.ekey && w.ekey >= pBlockInfo->window.skey) {
        return true;
      }
    }
  }

  return false;
}
1031
#endif
1032 1033

static uint32_t doFilterByBlockTimeWindow(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
1034
  SqlFunctionCtx* pCtx = pTableScanInfo->pCtx;
1035
  uint32_t        status = BLK_DATA_NOT_LOAD;
1036 1037 1038 1039

  int32_t numOfOutput = pTableScanInfo->numOfOutput;
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;
H
Haojun Liao 已提交
1040
    int32_t colId = pTableScanInfo->pExpr[i].base.pParam[0].pCol->colId;
1041 1042 1043

    // group by + first/last should not apply the first/last block filter
    if (functionId < 0) {
1044
      status |= BLK_DATA_DATA_LOAD;
1045 1046
      return status;
    } else {
L
Liu Jicong 已提交
1047
      //      status |= aAggs[functionId].dataReqFunc(&pTableScanInfo->pCtx[i], &pBlock->info.window, colId);
1048
      //      if ((status & BLK_DATA_DATA_LOAD) == BLK_DATA_DATA_LOAD) {
L
Liu Jicong 已提交
1049 1050
      //        return status;
      //      }
1051 1052 1053 1054 1055 1056
    }
  }

  return status;
}

L
Liu Jicong 已提交
1057 1058
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
1059
  *status = BLK_DATA_NOT_LOAD;
1060

H
Haojun Liao 已提交
1061
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
1062
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
1063

L
Liu Jicong 已提交
1064 1065
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
1066

H
Haojun Liao 已提交
1067
  STaskCostInfo* pCost = &pTaskInfo->cost;
1068

1069 1070
//  pCost->totalBlocks += 1;
//  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
1071
#if 0
1072 1073 1074
  // Calculate all time windows that are overlapping or contain current data block.
  // If current data block is contained by all possible time window, do not load current data block.
  if (/*pQueryAttr->pFilters || */pQueryAttr->groupbyColumn || pQueryAttr->sw.gap > 0 ||
H
Haojun Liao 已提交
1075
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
1076
    (*status) = BLK_DATA_DATA_LOAD;
1077 1078 1079
  }

  // check if this data block is required to load
1080
  if ((*status) != BLK_DATA_DATA_LOAD) {
1081 1082 1083 1084 1085 1086 1087
    bool needFilter = true;

    // the pCtx[i] result is belonged to previous time window since the outputBuf has not been set yet,
    // the filter result may be incorrect. So in case of interval query, we need to set the correct time output buffer
    if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
      SResultRow* pResult = NULL;

H
Haojun Liao 已提交
1088
      bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1089 1090 1091 1092 1093 1094
      TSKEY k = ascQuery? pBlock->info.window.skey : pBlock->info.window.ekey;

      STimeWindow win = getActiveTimeWindow(pTableScanInfo->pResultRowInfo, k, pQueryAttr);
      if (pQueryAttr->pointInterpQuery) {
        needFilter = chkWindowOutputBufByKey(pRuntimeEnv, pTableScanInfo->pResultRowInfo, &win, masterScan, &pResult, groupId,
                                    pTableScanInfo->pCtx, pTableScanInfo->numOfOutput,
1095
                                    pTableScanInfo->rowEntryInfoOffset);
1096 1097 1098
      } else {
        if (setResultOutputBufByKey(pRuntimeEnv, pTableScanInfo->pResultRowInfo, pBlock->info.uid, &win, masterScan, &pResult, groupId,
                                    pTableScanInfo->pCtx, pTableScanInfo->numOfOutput,
1099
                                    pTableScanInfo->rowEntryInfoOffset) != TSDB_CODE_SUCCESS) {
1100 1101 1102 1103 1104
          longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
        }
      }
    } else if (pQueryAttr->stableQuery && (!pQueryAttr->tsCompQuery) && (!pQueryAttr->diffQuery)) { // stable aggregate, not interval aggregate or normal column aggregate
      doSetTableGroupOutputBuf(pRuntimeEnv, pTableScanInfo->pResultRowInfo, pTableScanInfo->pCtx,
1105
                               pTableScanInfo->rowEntryInfoOffset, pTableScanInfo->numOfOutput,
1106 1107 1108 1109 1110 1111
                               pRuntimeEnv->current->groupIndex);
    }

    if (needFilter) {
      (*status) = doFilterByBlockTimeWindow(pTableScanInfo, pBlock);
    } else {
1112
      (*status) = BLK_DATA_DATA_LOAD;
1113 1114 1115 1116
    }
  }

  SDataBlockInfo* pBlockInfo = &pBlock->info;
H
Haojun Liao 已提交
1117
//  *status = updateBlockLoadStatus(pRuntimeEnv->pQueryAttr, *status);
1118

1119
  if ((*status) == BLK_DATA_NOT_LOAD || (*status) == BLK_DATA_FILTEROUT) {
1120 1121
    //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//           pBlockInfo->window.ekey, pBlockInfo->rows);
1122
    pCost->skipBlocks += 1;
1123
  } else if ((*status) == BLK_DATA_SMA_LOAD) {
1124 1125
    // this function never returns error?
    pCost->loadBlockStatis += 1;
1126
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1127 1128

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
1129
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1130 1131 1132
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
1133
    assert((*status) == BLK_DATA_DATA_LOAD);
1134 1135 1136

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
1137
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1138 1139 1140 1141 1142 1143

    if (pQueryAttr->topBotQuery && pBlock->pBlockAgg != NULL) {
      { // set previous window
        if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
          SResultRow* pResult = NULL;

H
Haojun Liao 已提交
1144
          bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1145 1146 1147 1148 1149
          TSKEY k = ascQuery? pBlock->info.window.skey : pBlock->info.window.ekey;

          STimeWindow win = getActiveTimeWindow(pTableScanInfo->pResultRowInfo, k, pQueryAttr);
          if (setResultOutputBufByKey(pRuntimeEnv, pTableScanInfo->pResultRowInfo, pBlock->info.uid, &win, masterScan, &pResult, groupId,
                                      pTableScanInfo->pCtx, pTableScanInfo->numOfOutput,
1150
                                      pTableScanInfo->rowEntryInfoOffset) != TSDB_CODE_SUCCESS) {
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
            longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
          }
        }
      }
      bool load = false;
      for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
        int32_t functionId = pTableScanInfo->pCtx[i].functionId;
        if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM) {
//          load = topbot_datablock_filter(&pTableScanInfo->pCtx[i], (char*)&(pBlock->pBlockAgg[i].min),
//                                         (char*)&(pBlock->pBlockAgg[i].max));
          if (!load) { // current block has been discard due to filter applied
1162
            pCost->skipBlocks += 1;
1163 1164
            //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId,
//                   pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
1165
            (*status) = BLK_DATA_FILTEROUT;
1166 1167 1168 1169 1170 1171 1172 1173
            return TSDB_CODE_SUCCESS;
          }
        }
      }
    }

    // current block has been discard due to filter applied
//    if (!doFilterByBlockStatistics(pRuntimeEnv, pBlock->pBlockAgg, pTableScanInfo->pCtx, pBlockInfo->rows)) {
1174
//      pCost->skipBlocks += 1;
1175 1176
//      qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//             pBlockInfo->window.ekey, pBlockInfo->rows);
1177
//      (*status) = BLK_DATA_FILTEROUT;
1178 1179 1180 1181 1182
//      return TSDB_CODE_SUCCESS;
//    }

    pCost->totalCheckedRows += pBlockInfo->rows;
    pCost->loadBlocks += 1;
1183
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1184 1185 1186 1187 1188 1189 1190
//    if (pBlock->pDataBlock == NULL) {
//      return terrno;
//    }

//    if (pQueryAttr->pFilters != NULL) {
//      filterSetColFieldData(pQueryAttr->pFilters, pBlock->info.numOfCols, pBlock->pDataBlock);
//    }
1191

1192 1193 1194 1195
//    if (pQueryAttr->pFilters != NULL || pRuntimeEnv->pTsBuf != NULL) {
//      filterColRowsInDataBlock(pRuntimeEnv, pBlock, ascQuery);
//    }
  }
H
Haojun Liao 已提交
1196
#endif
1197 1198 1199
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1200
static void updateTableQueryInfoForReverseScan(STableQueryInfo* pTableQueryInfo) {
1201 1202 1203 1204
  if (pTableQueryInfo == NULL) {
    return;
  }

wafwerar's avatar
wafwerar 已提交
1205
  //  TSWAP(pTableQueryInfo->win.skey, pTableQueryInfo->win.ekey);
L
Liu Jicong 已提交
1206
  //  pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
1207

L
Liu Jicong 已提交
1208 1209
  //  SWITCH_ORDER(pTableQueryInfo->cur.order);
  //  pTableQueryInfo->cur.vgroupIndex = -1;
1210 1211

  // set the index to be the end slot of result rows array
dengyihao's avatar
dengyihao 已提交
1212 1213 1214 1215 1216 1217
  //  SResultRowInfo* pResultRowInfo = &pTableQueryInfo->resInfo;
  //  if (pResultRowInfo->size > 0) {
  //    pResultRowInfo->curPos = pResultRowInfo->size - 1;
  //  } else {
  //    pResultRowInfo->curPos = -1;
  //  }
1218 1219
}

H
Haojun Liao 已提交
1220
void initResultRow(SResultRow* pResultRow) {
X
Xiaoyu Wang 已提交
1221
  //  pResultRow->pEntryInfo = (struct SResultRowEntryInfo*)((char*)pResultRow + sizeof(SResultRow));
1222 1223 1224 1225 1226
}

/*
 * The start of each column SResultRowEntryInfo is denote by RowCellInfoOffset.
 * Note that in case of top/bottom query, the whole multiple rows of result is treated as only one row of results.
H
Haojun Liao 已提交
1227 1228 1229
 * +------------+-----------------result column 1------------+------------------result column 2-----------+
 * | SResultRow | SResultRowEntryInfo | intermediate buffer1 | SResultRowEntryInfo | intermediate buffer 2|
 * +------------+--------------------------------------------+--------------------------------------------+
1230 1231
 *           offset[0]                                  offset[1]                                   offset[2]
 */
1232
// TODO refactor: some function move away
L
Liu Jicong 已提交
1233 1234 1235
void setFunctionResultOutput(SOperatorInfo* pOperator, SOptrBasicInfo* pInfo, SAggSupporter* pSup, int32_t stage,
                             int32_t numOfExprs) {
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
1236 1237
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
  int32_t*        rowEntryInfoOffset = pOperator->exprSupp.rowEntryInfoOffset;
H
Haojun Liao 已提交
1238

H
Haojun Liao 已提交
1239
  SResultRowInfo* pResultRowInfo = &pInfo->resultRowInfo;
1240
  initResultRowInfo(pResultRowInfo);
H
Haojun Liao 已提交
1241

L
Liu Jicong 已提交
1242 1243
  int64_t     tid = 0;
  int64_t     groupId = 0;
1244 1245
  SResultRow* pRow = doSetResultOutBufByKey(pSup->pResultBuf, pResultRowInfo, (char*)&tid, sizeof(tid), true, groupId,
                                            pTaskInfo, false, pSup);
H
Haojun Liao 已提交
1246

1247
  for (int32_t i = 0; i < numOfExprs; ++i) {
1248
    struct SResultRowEntryInfo* pEntry = getResultEntryInfo(pRow, i, rowEntryInfoOffset);
H
Haojun Liao 已提交
1249 1250
    cleanupResultRowEntry(pEntry);

L
Liu Jicong 已提交
1251
    pCtx[i].resultInfo = pEntry;
1252
    pCtx[i].scanFlag = stage;
H
Haojun Liao 已提交
1253 1254
  }

1255
  initCtxOutputBuffer(pCtx, numOfExprs);
H
Haojun Liao 已提交
1256 1257
}

H
Haojun Liao 已提交
1258
void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size) {
1259 1260
  for (int32_t j = 0; j < size; ++j) {
    struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[j]);
dengyihao's avatar
dengyihao 已提交
1261 1262
    if (isRowEntryInitialized(pResInfo) || fmIsPseudoColumnFunc(pCtx[j].functionId) || pCtx[j].functionId == -1 ||
        fmIsScalarFunc(pCtx[j].functionId)) {
1263 1264 1265
      continue;
    }

H
Haojun Liao 已提交
1266
    pCtx[j].fpSet.init(&pCtx[j], pCtx[j].resultInfo);
1267 1268 1269
  }
}

L
Liu Jicong 已提交
1270
void setTaskStatus(SExecTaskInfo* pTaskInfo, int8_t status) {
1271
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
1272
    pTaskInfo->status = status;
1273 1274
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
1275
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
1276
    pTaskInfo->status |= status;
1277 1278 1279
  }
}

L
Liu Jicong 已提交
1280
void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo) {
1281 1282 1283 1284
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
1285
  //  taosVariantDestroy(&pTableQueryInfo->tag);
dengyihao's avatar
dengyihao 已提交
1286
  //  cleanupResultRowInfo(&pTableQueryInfo->resInfo);
1287 1288
}

1289
void setResultRowInitCtx(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowEntryInfoOffset) {
1290
  for (int32_t i = 0; i < numOfOutput; ++i) {
1291
    pCtx[i].resultInfo = getResultEntryInfo(pResult, i, rowEntryInfoOffset);
1292 1293 1294 1295 1296

    struct SResultRowEntryInfo* pResInfo = pCtx[i].resultInfo;
    if (isRowEntryCompleted(pResInfo) && isRowEntryInitialized(pResInfo)) {
      continue;
    }
1297 1298 1299 1300 1301

    if (fmIsWindowPseudoColumnFunc(pCtx[i].functionId)) {
      continue;
    }

1302 1303 1304 1305 1306 1307
    if (!pResInfo->initialized) {
      if (pCtx[i].functionId != -1) {
        pCtx[i].fpSet.init(&pCtx[i], pResInfo);
      } else {
        pResInfo->initialized = true;
      }
1308 1309 1310 1311
    }
  }
}

H
Haojun Liao 已提交
1312
static void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const int8_t* rowRes, bool keep);
1313

1314
void doFilter(const SNode* pFilterNode, SSDataBlock* pBlock) {
1315 1316 1317 1318 1319
  if (pFilterNode == NULL) {
    return;
  }

  SFilterInfo* filter = NULL;
H
Haojun Liao 已提交
1320

H
Haojun Liao 已提交
1321
  // todo move to the initialization function
H
Haojun Liao 已提交
1322
  int32_t code = filterInitFromNode((SNode*)pFilterNode, &filter, 0);
1323 1324 1325 1326 1327

  SFilterColumnParam param1 = {.numOfCols = pBlock->info.numOfCols, .pDataBlock = pBlock->pDataBlock};
  code = filterSetDataFromSlotId(filter, &param1);

  int8_t* rowRes = NULL;
1328

1329
  // todo the keep seems never to be True??
1330
  bool keep = filterExecute(filter, pBlock, &rowRes, NULL, param1.numOfCols);
D
dapan1121 已提交
1331
  filterFreeInfo(filter);
1332

H
Haojun Liao 已提交
1333
  extractQualifiedTupleByFilterResult(pBlock, rowRes, keep);
1334
  blockDataUpdateTsWindow(pBlock, 0);
1335 1336
}

H
Haojun Liao 已提交
1337
void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const int8_t* rowRes, bool keep) {
1338 1339 1340 1341 1342
  if (keep) {
    return;
  }

  if (rowRes != NULL) {
1343
    int32_t totalRows = pBlock->info.rows;
1344
    SSDataBlock* px = createOneDataBlock(pBlock, true);
1345 1346

    for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
1347 1348
      SColumnInfoData* pSrc = taosArrayGet(px->pDataBlock, i);
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, i);
1349
      // it is a reserved column for scalar function, and no data in this column yet.
1350
      if (pDst->pData == NULL) {
1351 1352 1353
        continue;
      }

1354 1355
      colInfoDataCleanup(pDst, pBlock->info.rows);

1356
      int32_t numOfRows = 0;
1357
      for (int32_t j = 0; j < totalRows; ++j) {
D
dapan1121 已提交
1358 1359 1360
        if (rowRes[j] == 0) {
          continue;
        }
1361

D
dapan1121 已提交
1362
        if (colDataIsNull_s(pSrc, j)) {
1363
          colDataAppendNULL(pDst, numOfRows);
D
dapan1121 已提交
1364
        } else {
1365
          colDataAppend(pDst, numOfRows, colDataGetData(pSrc, j), false);
D
dapan1121 已提交
1366
        }
1367
        numOfRows += 1;
H
Haojun Liao 已提交
1368
      }
1369

1370 1371 1372 1373 1374
      if (pBlock->info.rows == totalRows) {
        pBlock->info.rows = numOfRows;
      } else {
        ASSERT(pBlock->info.rows == numOfRows);
      }
1375
    }
1376

dengyihao's avatar
dengyihao 已提交
1377
    blockDataDestroy(px);  // fix memory leak
1378 1379 1380
  } else {
    // do nothing
    pBlock->info.rows = 0;
1381 1382 1383
  }
}

L
Liu Jicong 已提交
1384 1385
void doSetTableGroupOutputBuf(SOperatorInfo* pOperator, SAggOperatorInfo* pAggInfo, int32_t numOfOutput,
                              uint64_t groupId) {
1386
  // for simple group by query without interval, all the tables belong to one group result.
L
Liu Jicong 已提交
1387
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
1388
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
1389 1390
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
  int32_t*        rowEntryInfoOffset = pOperator->exprSupp.rowEntryInfoOffset;
1391

1392
  SResultRow* pResultRow = doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, (char*)&groupId,
L
Liu Jicong 已提交
1393
                                                  sizeof(groupId), true, groupId, pTaskInfo, false, &pAggInfo->aggSup);
L
Liu Jicong 已提交
1394
  assert(pResultRow != NULL);
1395 1396 1397 1398 1399 1400

  /*
   * not assign result buffer yet, add new result buffer
   * all group belong to one result set, and each group result has different group id so set the id to be one
   */
  if (pResultRow->pageId == -1) {
dengyihao's avatar
dengyihao 已提交
1401 1402
    int32_t ret =
        addNewWindowResultBuf(pResultRow, pAggInfo->aggSup.pResultBuf, groupId, pAggInfo->binfo.pRes->info.rowSize);
1403 1404 1405 1406 1407
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

1408
  setResultRowInitCtx(pResultRow, pCtx, numOfOutput, rowEntryInfoOffset);
1409 1410
}

1411
void setExecutionContext(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId, SAggOperatorInfo* pAggInfo) {
H
Haojun Liao 已提交
1412
  if (pAggInfo->groupId != INT32_MIN && pAggInfo->groupId == groupId) {
1413 1414 1415
    return;
  }

1416
  doSetTableGroupOutputBuf(pOperator, pAggInfo, numOfOutput, groupId);
1417 1418

  // record the current active group id
H
Haojun Liao 已提交
1419
  pAggInfo->groupId = groupId;
1420 1421
}

1422 1423
static void doUpdateNumOfRows(SResultRow* pRow, int32_t numOfExprs, const int32_t* rowCellOffset) {
  for (int32_t j = 0; j < numOfExprs; ++j) {
1424
    struct SResultRowEntryInfo* pResInfo = getResultEntryInfo(pRow, j, rowCellOffset);
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
    if (!isRowEntryInitialized(pResInfo)) {
      continue;
    }

    if (pRow->numOfRows < pResInfo->numOfRes) {
      pRow->numOfRows = pResInfo->numOfRes;
    }
  }
}

1435
int32_t finalizeResultRowIntoResultDataBlock(SDiskbasedBuf* pBuf, SResultRowPosition* resultRowPosition,
S
shenglian zhou 已提交
1436 1437 1438
                                             SqlFunctionCtx* pCtx, SExprInfo* pExprInfo, int32_t numOfExprs,
                                             const int32_t* rowCellOffset, SSDataBlock* pBlock,
                                             SExecTaskInfo* pTaskInfo) {
1439 1440 1441 1442 1443 1444 1445 1446 1447
  SFilePage*  page = getBufPage(pBuf, resultRowPosition->pageId);
  SResultRow* pRow = (SResultRow*)((char*)page + resultRowPosition->offset);

  doUpdateNumOfRows(pRow, numOfExprs, rowCellOffset);
  if (pRow->numOfRows == 0) {
    releaseBufPage(pBuf, page);
    return 0;
  }

1448 1449 1450 1451 1452 1453 1454
  while (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
    int32_t code = blockDataEnsureCapacity(pBlock, pBlock->info.capacity * 1.25);
    if (TAOS_FAILED(code)) {
      releaseBufPage(pBuf, page);
      qError("%s ensure result data capacity failed, code %s", GET_TASKID(pTaskInfo), tstrerror(code));
      longjmp(pTaskInfo->env, code);
    }
1455 1456 1457 1458 1459
  }

  for (int32_t j = 0; j < numOfExprs; ++j) {
    int32_t slotId = pExprInfo[j].base.resSchema.slotId;

1460
    pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowCellOffset);
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
    if (pCtx[j].fpSet.finalize) {
      int32_t code = pCtx[j].fpSet.finalize(&pCtx[j], pBlock);
      if (TAOS_FAILED(code)) {
        qError("%s build result data block error, code %s", GET_TASKID(pTaskInfo), tstrerror(code));
        longjmp(pTaskInfo->env, code);
      }
    } else if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
      // do nothing, todo refactor
    } else {
      // expand the result into multiple rows. E.g., _wstartts, top(k, 20)
      // the _wstartts needs to copy to 20 following rows, since the results of top-k expands to 20 different rows.
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId);
      char*            in = GET_ROWCELL_INTERBUF(pCtx[j].resultInfo);
      for (int32_t k = 0; k < pRow->numOfRows; ++k) {
        colDataAppend(pColInfoData, pBlock->info.rows + k, in, pCtx[j].resultInfo->isNullRes);
      }
    }
  }

  releaseBufPage(pBuf, page);
1481
  pBlock->info.rows += pRow->numOfRows;
1482 1483 1484 1485

  return 0;
}

X
Xiaoyu Wang 已提交
1486 1487 1488
int32_t doCopyToSDataBlock(SExecTaskInfo* pTaskInfo, SSDataBlock* pBlock, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf,
                           SGroupResInfo* pGroupResInfo, const int32_t* rowCellOffset, SqlFunctionCtx* pCtx,
                           int32_t numOfExprs) {
1489
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
1490
  int32_t start = pGroupResInfo->index;
1491

1492
  for (int32_t i = start; i < numOfRows; i += 1) {
L
Liu Jicong 已提交
1493 1494
    SResKeyPos* pPos = taosArrayGetP(pGroupResInfo->pRows, i);
    SFilePage*  page = getBufPage(pBuf, pPos->pos.pageId);
1495

1496
    SResultRow* pRow = (SResultRow*)((char*)page + pPos->pos.offset);
1497 1498

    doUpdateNumOfRows(pRow, numOfExprs, rowCellOffset);
1499 1500
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
1501
      releaseBufPage(pBuf, page);
1502 1503 1504
      continue;
    }

1505 1506 1507 1508 1509
    if (pBlock->info.groupId == 0) {
      pBlock->info.groupId = pPos->groupId;
    } else {
      // current value belongs to different group, it can't be packed into one datablock
      if (pBlock->info.groupId != pPos->groupId) {
1510
        releaseBufPage(pBuf, page);
1511 1512 1513 1514
        break;
      }
    }

1515
    if (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
1516
      releaseBufPage(pBuf, page);
1517 1518 1519 1520 1521
      break;
    }

    pGroupResInfo->index += 1;

1522
    for (int32_t j = 0; j < numOfExprs; ++j) {
1523 1524
      int32_t slotId = pExprInfo[j].base.resSchema.slotId;

1525
      pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowCellOffset);
1526
      if (pCtx[j].fpSet.finalize) {
1527
        int32_t code = pCtx[j].fpSet.finalize(&pCtx[j], pBlock);
1528
        if (TAOS_FAILED(code)) {
1529 1530
          qError("%s build result data block error, code %s", GET_TASKID(pTaskInfo), tstrerror(code));
          longjmp(pTaskInfo->env, code);
1531
        }
1532 1533
      } else if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
        // do nothing, todo refactor
1534
      } else {
1535 1536
        // expand the result into multiple rows. E.g., _wstartts, top(k, 20)
        // the _wstartts needs to copy to 20 following rows, since the results of top-k expands to 20 different rows.
X
Xiaoyu Wang 已提交
1537 1538
        SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId);
        char*            in = GET_ROWCELL_INTERBUF(pCtx[j].resultInfo);
1539
        if (pCtx[j].increase) {
L
Liu Jicong 已提交
1540
          int64_t ts = *(int64_t*)in;
1541
          for (int32_t k = 0; k < pRow->numOfRows; ++k) {
L
Liu Jicong 已提交
1542
            colDataAppend(pColInfoData, pBlock->info.rows + k, (const char*)&ts, pCtx[j].resultInfo->isNullRes);
1543 1544 1545 1546 1547 1548
            ts++;
          }
        } else {
          for (int32_t k = 0; k < pRow->numOfRows; ++k) {
            colDataAppend(pColInfoData, pBlock->info.rows + k, in, pCtx[j].resultInfo->isNullRes);
          }
X
Xiaoyu Wang 已提交
1549
        }
1550
      }
1551 1552
    }

1553
    releaseBufPage(pBuf, page);
1554 1555
    pBlock->info.rows += pRow->numOfRows;
    if (pBlock->info.rows >= pBlock->info.capacity) {  // output buffer is full
1556 1557 1558 1559
      break;
    }
  }

X
Xiaoyu Wang 已提交
1560 1561
  qDebug("%s result generated, rows:%d, groupId:%" PRIu64, GET_TASKID(pTaskInfo), pBlock->info.rows,
         pBlock->info.groupId);
1562
  blockDataUpdateTsWindow(pBlock, 0);
1563 1564 1565
  return 0;
}

X
Xiaoyu Wang 已提交
1566 1567
void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SGroupResInfo* pGroupResInfo,
                            SDiskbasedBuf* pBuf) {
1568 1569
  SExprInfo*     pExprInfo = pOperator->exprSupp.pExprInfo;
  int32_t        numOfExprs = pOperator->exprSupp.numOfExprs;
1570 1571
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

1572
  int32_t*        rowCellOffset = pOperator->exprSupp.rowEntryInfoOffset;
X
Xiaoyu Wang 已提交
1573
  SSDataBlock*    pBlock = pbInfo->pRes;
1574
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
1575

1576
  blockDataCleanup(pBlock);
1577
  if (!hasDataInGroupInfo(pGroupResInfo)) {
1578 1579 1580
    return;
  }

1581 1582
  // clear the existed group id
  pBlock->info.groupId = 0;
1583
  doCopyToSDataBlock(pTaskInfo, pBlock, pExprInfo, pBuf, pGroupResInfo, rowCellOffset, pCtx, numOfExprs);
1584 1585
}

L
Liu Jicong 已提交
1586
static void updateNumOfRowsInResultRows(SqlFunctionCtx* pCtx, int32_t numOfOutput, SResultRowInfo* pResultRowInfo,
1587
                                        int32_t* rowEntryInfoOffset) {
1588
  // update the number of result for each, only update the number of rows for the corresponding window result.
L
Liu Jicong 已提交
1589 1590 1591
  //  if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
  //    return;
  //  }
H
Haojun Liao 已提交
1592
#if 0
1593
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
L
Liu Jicong 已提交
1594
    SResultRow* pResult = pResultRowInfo->pResult[i];
1595 1596 1597 1598 1599 1600 1601

    for (int32_t j = 0; j < numOfOutput; ++j) {
      int32_t functionId = pCtx[j].functionId;
      if (functionId == FUNCTION_TS || functionId == FUNCTION_TAG || functionId == FUNCTION_TAGPRJ) {
        continue;
      }

1602
      SResultRowEntryInfo* pCell = getResultEntryInfo(pResult, j, rowEntryInfoOffset);
1603
      pResult->numOfRows = (uint16_t)(TMAX(pResult->numOfRows, pCell->numOfRes));
1604 1605
    }
  }
H
Haojun Liao 已提交
1606
#endif
1607 1608
}

L
Liu Jicong 已提交
1609
static int32_t compressQueryColData(SColumnInfoData* pColRes, int32_t numOfRows, char* data, int8_t compressed) {
1610 1611
  int32_t colSize = pColRes->info.bytes * numOfRows;
  return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data,
L
Liu Jicong 已提交
1612
                                                      colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0);
1613 1614
}

1615 1616 1617
int32_t doFillTimeIntervalGapsInResults(struct SFillInfo* pFillInfo, SSDataBlock* pBlock, int32_t capacity) {
  int32_t numOfRows = (int32_t)taosFillResultDataBlock(pFillInfo, pBlock, capacity - pBlock->info.rows);
  pBlock->info.rows += numOfRows;
1618

1619
  return pBlock->info.rows;
1620 1621
}

L
Liu Jicong 已提交
1622 1623
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
1624

L
Liu Jicong 已提交
1625 1626 1627
  //  uint64_t hashSize = taosHashGetMemSize(pQInfo->runtimeEnv.pResultRowHashTable);
  //  hashSize += taosHashGetMemSize(pRuntimeEnv->tableqinfoGroupInfo.map);
  //  pSummary->hashSize = hashSize;
1628 1629 1630 1631

  // add the merge time
  pSummary->elapsedTime += pSummary->firstStageMergeTime;

L
Liu Jicong 已提交
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
  //  SResultRowPool* p = pTaskInfo->pool;
  //  if (p != NULL) {
  //    pSummary->winInfoSize = getResultRowPoolMemSize(p);
  //    pSummary->numOfTimeWindows = getNumOfAllocatedResultRows(p);
  //  } else {
  //    pSummary->winInfoSize = 0;
  //    pSummary->numOfTimeWindows = 0;
  //  }
  //
  //  calculateOperatorProfResults(pQInfo);

1643 1644
  SFileBlockLoadRecorder* pRecorder = pSummary->pRecoder;
  if (pSummary->pRecoder != NULL) {
X
Xiaoyu Wang 已提交
1645 1646
    qDebug("%s :cost summary: elapsed time:%" PRId64 " us, first merge:%" PRId64
           " us, total blocks:%d, "
1647 1648 1649 1650
           "load block statis:%d, load data block:%d, total rows:%" PRId64 ", check rows:%" PRId64,
           GET_TASKID(pTaskInfo), pSummary->elapsedTime, pSummary->firstStageMergeTime, pRecorder->totalBlocks,
           pRecorder->loadBlockStatis, pRecorder->loadBlocks, pRecorder->totalRows, pRecorder->totalCheckedRows);
  }
L
Liu Jicong 已提交
1651 1652 1653
  // qDebug("QInfo:0x%"PRIx64" :cost summary: winResPool size:%.2f Kb, numOfWin:%"PRId64", tableInfoSize:%.2f Kb,
  // hashTable:%.2f Kb", pQInfo->qId, pSummary->winInfoSize/1024.0,
  //      pSummary->numOfTimeWindows, pSummary->tableInfoSize/1024.0, pSummary->hashSize/1024.0);
1654 1655
}

L
Liu Jicong 已提交
1656 1657 1658
// static void updateOffsetVal(STaskRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
1659
//
L
Liu Jicong 已提交
1660
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
1661
//
L
Liu Jicong 已提交
1662 1663 1664 1665
//   if (pQueryAttr->limit.offset == pBlockInfo->rows) {  // current block will ignore completed
//     pTableQueryInfo->lastKey = QUERY_IS_ASC_QUERY(pQueryAttr) ? pBlockInfo->window.ekey + step :
//     pBlockInfo->window.skey + step; pQueryAttr->limit.offset = 0; return;
//   }
1666
//
L
Liu Jicong 已提交
1667 1668 1669 1670 1671
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     pQueryAttr->pos = (int32_t)pQueryAttr->limit.offset;
//   } else {
//     pQueryAttr->pos = pBlockInfo->rows - (int32_t)pQueryAttr->limit.offset - 1;
//   }
1672
//
L
Liu Jicong 已提交
1673
//   assert(pQueryAttr->pos >= 0 && pQueryAttr->pos <= pBlockInfo->rows - 1);
1674
//
L
Liu Jicong 已提交
1675 1676
//   SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//   SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
1677
//
L
Liu Jicong 已提交
1678 1679
//   // update the pQueryAttr->limit.offset value, and pQueryAttr->pos value
//   TSKEY *keys = (TSKEY *) pColInfoData->pData;
1680
//
L
Liu Jicong 已提交
1681 1682 1683
//   // update the offset value
//   pTableQueryInfo->lastKey = keys[pQueryAttr->pos];
//   pQueryAttr->limit.offset = 0;
1684
//
L
Liu Jicong 已提交
1685
//   int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
1686
//
L
Liu Jicong 已提交
1687 1688 1689 1690
//   //qDebug("QInfo:0x%"PRIx64" check data block, brange:%" PRId64 "-%" PRId64 ", numBlocksOfStep:%d, numOfRes:%d,
//   lastKey:%"PRId64, GET_TASKID(pRuntimeEnv),
//          pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows, numOfRes, pQuery->current->lastKey);
// }
1691

L
Liu Jicong 已提交
1692 1693
// void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
1694
//
L
Liu Jicong 已提交
1695 1696 1697
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//     return;
//   }
1698
//
L
Liu Jicong 已提交
1699 1700
//   pQueryAttr->pos = 0;
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
1701
//
L
Liu Jicong 已提交
1702 1703
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//   TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
1704
//
L
Liu Jicong 已提交
1705 1706 1707 1708 1709
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pTsdbReadHandle)) {
//     if (isTaskKilled(pRuntimeEnv->qinfo)) {
//       longjmp(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
//     }
1710
//
L
Liu Jicong 已提交
1711
//     tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
1712
//
L
Liu Jicong 已提交
1713 1714 1715 1716
//     if (pQueryAttr->limit.offset > blockInfo.rows) {
//       pQueryAttr->limit.offset -= blockInfo.rows;
//       pTableQueryInfo->lastKey = (QUERY_IS_ASC_QUERY(pQueryAttr)) ? blockInfo.window.ekey : blockInfo.window.skey;
//       pTableQueryInfo->lastKey += step;
1717
//
L
Liu Jicong 已提交
1718 1719 1720 1721 1722 1723 1724
//       //qDebug("QInfo:0x%"PRIx64" skip rows:%d, offset:%" PRId64, GET_TASKID(pRuntimeEnv), blockInfo.rows,
//              pQuery->limit.offset);
//     } else {  // find the appropriated start position in current block
//       updateOffsetVal(pRuntimeEnv, &blockInfo);
//       break;
//     }
//   }
1725
//
L
Liu Jicong 已提交
1726 1727 1728 1729 1730 1731 1732 1733 1734
//   if (terrno != TSDB_CODE_SUCCESS) {
//     longjmp(pRuntimeEnv->env, terrno);
//   }
// }

// static TSKEY doSkipIntervalProcess(STaskRuntimeEnv* pRuntimeEnv, STimeWindow* win, SDataBlockInfo* pBlockInfo,
// STableQueryInfo* pTableQueryInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
1735
//
L
Liu Jicong 已提交
1736 1737 1738
//   assert(pQueryAttr->limit.offset == 0);
//   STimeWindow tw = *win;
//   getNextTimeWindow(pQueryAttr, &tw);
1739
//
L
Liu Jicong 已提交
1740 1741
//   if ((tw.skey <= pBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) ||
//       (tw.ekey >= pBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
1742
//
L
Liu Jicong 已提交
1743 1744 1745 1746
//     // load the data block and check data remaining in current data block
//     // TODO optimize performance
//     SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//     SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
1747
//
L
Liu Jicong 已提交
1748 1749 1750 1751
//     tw = *win;
//     int32_t startPos =
//         getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1);
//     assert(startPos >= 0);
1752
//
L
Liu Jicong 已提交
1753 1754
//     // set the abort info
//     pQueryAttr->pos = startPos;
1755
//
L
Liu Jicong 已提交
1756 1757 1758 1759
//     // reset the query start timestamp
//     pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
//     pQueryAttr->window.skey = pTableQueryInfo->win.skey;
//     TSKEY key = pTableQueryInfo->win.skey;
1760
//
L
Liu Jicong 已提交
1761 1762
//     pWindowResInfo->prevSKey = tw.skey;
//     int32_t index = pRuntimeEnv->resultRowInfo.curIndex;
1763
//
L
Liu Jicong 已提交
1764 1765
//     int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//     pRuntimeEnv->resultRowInfo.curIndex = index;  // restore the window index
1766
//
L
Liu Jicong 已提交
1767 1768 1769 1770
//     //qDebug("QInfo:0x%"PRIx64" check data block, brange:%" PRId64 "-%" PRId64 ", numOfRows:%d, numOfRes:%d,
//     lastKey:%" PRId64,
//            GET_TASKID(pRuntimeEnv), pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows, numOfRes,
//            pQueryAttr->current->lastKey);
1771
//
L
Liu Jicong 已提交
1772 1773 1774 1775 1776
//     return key;
//   } else {  // do nothing
//     pQueryAttr->window.skey      = tw.skey;
//     pWindowResInfo->prevSKey = tw.skey;
//     pTableQueryInfo->lastKey = tw.skey;
1777
//
L
Liu Jicong 已提交
1778 1779
//     return tw.skey;
//   }
1780
//
L
Liu Jicong 已提交
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
//   return true;
// }

// static bool skipTimeInterval(STaskRuntimeEnv *pRuntimeEnv, TSKEY* start) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     assert(*start <= pRuntimeEnv->current->lastKey);
//   } else {
//     assert(*start >= pRuntimeEnv->current->lastKey);
//   }
1791
//
L
Liu Jicong 已提交
1792 1793 1794 1795 1796
//   // if queried with value filter, do NOT forward query start position
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0 || pRuntimeEnv->pTsBuf != NULL ||
//   pRuntimeEnv->pFillInfo != NULL) {
//     return true;
//   }
1797
//
L
Liu Jicong 已提交
1798 1799 1800 1801 1802 1803 1804
//   /*
//    * 1. for interval without interpolation query we forward pQueryAttr->interval.interval at a time for
//    *    pQueryAttr->limit.offset times. Since hole exists, pQueryAttr->interval.interval*pQueryAttr->limit.offset
//    value is
//    *    not valid. otherwise, we only forward pQueryAttr->limit.offset number of points
//    */
//   assert(pRuntimeEnv->resultRowInfo.prevSKey == TSKEY_INITIAL_VAL);
1805
//
L
Liu Jicong 已提交
1806 1807
//   STimeWindow w = TSWINDOW_INITIALIZER;
//   bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
1808
//
L
Liu Jicong 已提交
1809 1810
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//   STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
1811
//
L
Liu Jicong 已提交
1812 1813 1814
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pRuntimeEnv->pTsdbReadHandle)) {
//     tsdbRetrieveDataBlockInfo(pRuntimeEnv->pTsdbReadHandle, &blockInfo);
1815
//
L
Liu Jicong 已提交
1816 1817 1818 1819 1820 1821 1822 1823 1824
//     if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//       if (pWindowResInfo->prevSKey == TSKEY_INITIAL_VAL) {
//         getAlignQueryTimeWindow(pQueryAttr, blockInfo.window.skey, blockInfo.window.skey, pQueryAttr->window.ekey,
//         &w); pWindowResInfo->prevSKey = w.skey;
//       }
//     } else {
//       getAlignQueryTimeWindow(pQueryAttr, blockInfo.window.ekey, pQueryAttr->window.ekey, blockInfo.window.ekey, &w);
//       pWindowResInfo->prevSKey = w.skey;
//     }
1825
//
L
Liu Jicong 已提交
1826 1827
//     // the first time window
//     STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQueryAttr);
1828
//
L
Liu Jicong 已提交
1829 1830
//     while (pQueryAttr->limit.offset > 0) {
//       STimeWindow tw = win;
1831
//
L
Liu Jicong 已提交
1832 1833 1834
//       if ((win.ekey <= blockInfo.window.ekey && ascQuery) || (win.ekey >= blockInfo.window.skey && !ascQuery)) {
//         pQueryAttr->limit.offset -= 1;
//         pWindowResInfo->prevSKey = win.skey;
1835
//
L
Liu Jicong 已提交
1836 1837 1838 1839 1840 1841
//         // current time window is aligned with blockInfo.window.ekey
//         // restart it from next data block by set prevSKey to be TSKEY_INITIAL_VAL;
//         if ((win.ekey == blockInfo.window.ekey && ascQuery) || (win.ekey == blockInfo.window.skey && !ascQuery)) {
//           pWindowResInfo->prevSKey = TSKEY_INITIAL_VAL;
//         }
//       }
1842
//
L
Liu Jicong 已提交
1843 1844 1845 1846
//       if (pQueryAttr->limit.offset == 0) {
//         *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//         return true;
//       }
1847
//
L
Liu Jicong 已提交
1848 1849
//       // current window does not ended in current data block, try next data block
//       getNextTimeWindow(pQueryAttr, &tw);
1850
//
L
Liu Jicong 已提交
1851 1852 1853 1854 1855 1856 1857 1858 1859
//       /*
//        * If the next time window still starts from current data block,
//        * load the primary timestamp column first, and then find the start position for the next queried time window.
//        * Note that only the primary timestamp column is required.
//        * TODO: Optimize for this cases. All data blocks are not needed to be loaded, only if the first actually
//        required
//        * time window resides in current data block.
//        */
//       if ((tw.skey <= blockInfo.window.ekey && ascQuery) || (tw.ekey >= blockInfo.window.skey && !ascQuery)) {
1860
//
L
Liu Jicong 已提交
1861 1862
//         SArray *pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//         SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
1863
//
L
Liu Jicong 已提交
1864 1865 1866
//         if ((win.ekey > blockInfo.window.ekey && ascQuery) || (win.ekey < blockInfo.window.skey && !ascQuery)) {
//           pQueryAttr->limit.offset -= 1;
//         }
1867
//
L
Liu Jicong 已提交
1868 1869 1870 1871 1872 1873 1874 1875
//         if (pQueryAttr->limit.offset == 0) {
//           *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//           return true;
//         } else {
//           tw = win;
//           int32_t startPos =
//               getNextQualifiedWindow(pQueryAttr, &tw, &blockInfo, pColInfoData->pData, binarySearchForKey, -1);
//           assert(startPos >= 0);
1876
//
L
Liu Jicong 已提交
1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
//           // set the abort info
//           pQueryAttr->pos = startPos;
//           pTableQueryInfo->lastKey = ((TSKEY *)pColInfoData->pData)[startPos];
//           pWindowResInfo->prevSKey = tw.skey;
//           win = tw;
//         }
//       } else {
//         break;  // offset is not 0, and next time window begins or ends in the next block.
//       }
//     }
//   }
1888
//
L
Liu Jicong 已提交
1889 1890 1891 1892
//   // check for error
//   if (terrno != TSDB_CODE_SUCCESS) {
//     longjmp(pRuntimeEnv->env, terrno);
//   }
1893
//
L
Liu Jicong 已提交
1894 1895
//   return true;
// }
1896

1897
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
1898
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
1899
    assert(p->numOfDownstream == 0);
1900 1901
  }

wafwerar's avatar
wafwerar 已提交
1902
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
1903 1904 1905 1906 1907 1908 1909
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  memcpy(p->pDownstream, pDownstream, num * POINTER_BYTES);
  p->numOfDownstream = num;
  return TSDB_CODE_SUCCESS;
1910 1911
}

wmmhello's avatar
wmmhello 已提交
1912
static void doDestroyTableList(STableListInfo* pTableqinfoList);
1913

1914
static void doTableQueryInfoTimeWindowCheck(SExecTaskInfo* pTaskInfo, STableQueryInfo* pTableQueryInfo, int32_t order) {
H
Haojun Liao 已提交
1915 1916
#if 0
    if (order == TSDB_ORDER_ASC) {
1917 1918
    assert(
        (pTableQueryInfo->win.skey <= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
1919 1920
        (pTableQueryInfo->lastKey >= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey >= pTaskInfo->window.skey && pTableQueryInfo->win.ekey <= pTaskInfo->window.ekey));
1921 1922 1923
  } else {
    assert(
        (pTableQueryInfo->win.skey >= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
1924 1925
        (pTableQueryInfo->lastKey <= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey <= pTaskInfo->window.skey && pTableQueryInfo->win.ekey >= pTaskInfo->window.ekey));
1926
  }
H
Haojun Liao 已提交
1927
#endif
1928 1929
}

1930 1931 1932 1933
typedef struct SFetchRspHandleWrapper {
  uint32_t exchangeId;
  int32_t  sourceIndex;
} SFetchRspHandleWrapper;
1934

1935
int32_t loadRemoteDataCallback(void* param, const SDataBuf* pMsg, int32_t code) {
X
Xiaoyu Wang 已提交
1936
  SFetchRspHandleWrapper* pWrapper = (SFetchRspHandleWrapper*)param;
1937 1938 1939 1940 1941 1942 1943

  SExchangeInfo* pExchangeInfo = taosAcquireRef(exchangeObjRefPool, pWrapper->exchangeId);
  if (pExchangeInfo == NULL) {
    qWarn("failed to acquire exchange operator, since it may have been released");
    return TSDB_CODE_SUCCESS;
  }

X
Xiaoyu Wang 已提交
1944
  int32_t          index = pWrapper->sourceIndex;
1945
  SSourceDataInfo* pSourceDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, index);
1946

H
Haojun Liao 已提交
1947 1948
  if (code == TSDB_CODE_SUCCESS) {
    pSourceDataInfo->pRsp = pMsg->pData;
1949

H
Haojun Liao 已提交
1950 1951
    SRetrieveTableRsp* pRsp = pSourceDataInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
dengyihao's avatar
dengyihao 已提交
1952
    pRsp->compLen = htonl(pRsp->compLen);
1953
    pRsp->numOfCols = htonl(pRsp->numOfCols);
dengyihao's avatar
dengyihao 已提交
1954
    pRsp->useconds = htobe64(pRsp->useconds);
1955

1956
    ASSERT(pRsp != NULL);
1957
    qDebug("%s fetch rsp received, index:%d, rows:%d", pSourceDataInfo->taskId, index, pRsp->numOfRows);
H
Haojun Liao 已提交
1958 1959 1960
  } else {
    pSourceDataInfo->code = code;
  }
H
Haojun Liao 已提交
1961

H
Haojun Liao 已提交
1962
  pSourceDataInfo->status = EX_SOURCE_DATA_READY;
1963 1964 1965 1966 1967

  tsem_post(&pExchangeInfo->ready);
  taosReleaseRef(exchangeObjRefPool, pWrapper->exchangeId);

  taosMemoryFree(pWrapper);
wmmhello's avatar
wmmhello 已提交
1968
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1969 1970 1971 1972
}

static void destroySendMsgInfo(SMsgSendInfo* pMsgBody) {
  assert(pMsgBody != NULL);
wafwerar's avatar
wafwerar 已提交
1973 1974
  taosMemoryFreeClear(pMsgBody->msgInfo.pData);
  taosMemoryFreeClear(pMsgBody);
H
Haojun Liao 已提交
1975 1976
}

S
Shengliang Guan 已提交
1977
void qProcessFetchRsp(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
S
Shengliang Guan 已提交
1978 1979
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
  assert(pMsg->info.ahandle != NULL);
H
Haojun Liao 已提交
1980 1981 1982 1983

  SDataBuf buf = {.len = pMsg->contLen, .pData = NULL};

  if (pMsg->contLen > 0) {
wafwerar's avatar
wafwerar 已提交
1984
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
H
Haojun Liao 已提交
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
    if (buf.pData == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      pMsg->code = TSDB_CODE_OUT_OF_MEMORY;
    } else {
      memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
    }
  }

  pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
  rpcFreeCont(pMsg->pCont);
  destroySendMsgInfo(pSendInfo);
1996 1997
}

L
Liu Jicong 已提交
1998
static int32_t doSendFetchDataRequest(SExchangeInfo* pExchangeInfo, SExecTaskInfo* pTaskInfo, int32_t sourceIndex) {
1999
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
2000

wafwerar's avatar
wafwerar 已提交
2001
  SResFetchReq* pMsg = taosMemoryCalloc(1, sizeof(SResFetchReq));
2002 2003 2004 2005
  if (NULL == pMsg) {
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
  }
2006

L
Liu Jicong 已提交
2007 2008
  SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, sourceIndex);
  SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, sourceIndex);
2009

2010 2011
  ASSERT(pDataInfo->status == EX_SOURCE_DATA_NOT_READY);

L
Liu Jicong 已提交
2012 2013
  qDebug("%s build fetch msg and send to vgId:%d, ep:%s, taskId:0x%" PRIx64 ", %d/%" PRIzu, GET_TASKID(pTaskInfo),
         pSource->addr.nodeId, pSource->addr.epSet.eps[0].fqdn, pSource->taskId, sourceIndex, totalSources);
2014 2015 2016 2017 2018 2019 2020

  pMsg->header.vgId = htonl(pSource->addr.nodeId);
  pMsg->sId = htobe64(pSource->schedId);
  pMsg->taskId = htobe64(pSource->taskId);
  pMsg->queryId = htobe64(pTaskInfo->id.queryId);

  // send the fetch remote task result reques
wafwerar's avatar
wafwerar 已提交
2021
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
2022
  if (NULL == pMsgSendInfo) {
wafwerar's avatar
wafwerar 已提交
2023
    taosMemoryFreeClear(pMsg);
2024 2025 2026
    qError("%s prepare message %d failed", GET_TASKID(pTaskInfo), (int32_t)sizeof(SMsgSendInfo));
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
H
Haojun Liao 已提交
2027 2028
  }

2029
  SFetchRspHandleWrapper* pWrapper = taosMemoryCalloc(1, sizeof(SFetchRspHandleWrapper));
X
Xiaoyu Wang 已提交
2030
  pWrapper->exchangeId = pExchangeInfo->self;
2031 2032 2033
  pWrapper->sourceIndex = sourceIndex;

  pMsgSendInfo->param = pWrapper;
2034 2035 2036 2037
  pMsgSendInfo->msgInfo.pData = pMsg;
  pMsgSendInfo->msgInfo.len = sizeof(SResFetchReq);
  pMsgSendInfo->msgType = TDMT_VND_FETCH;
  pMsgSendInfo->fp = loadRemoteDataCallback;
2038

2039
  int64_t transporterId = 0;
L
Liu Jicong 已提交
2040
  int32_t code = asyncSendMsgToServer(pExchangeInfo->pTransporter, &pSource->addr.epSet, &transporterId, pMsgSendInfo);
2041 2042 2043
  return TSDB_CODE_SUCCESS;
}

2044
int32_t extractDataBlockFromFetchRsp(SSDataBlock* pRes, SLoadRemoteDataInfo* pLoadInfo, int32_t numOfRows, char* pData,
L
Liu Jicong 已提交
2045 2046
                                     int32_t compLen, int32_t numOfOutput, int64_t startTs, uint64_t* total,
                                     SArray* pColList) {
H
Haojun Liao 已提交
2047
  if (pColList == NULL) {  // data from other sources
2048
    blockCompressDecode(pRes, numOfOutput, numOfRows, pData);
2049
    pRes->info.rows = numOfRows;
H
Haojun Liao 已提交
2050
  } else {  // extract data according to pColList
2051
    ASSERT(numOfOutput == taosArrayGetSize(pColList));
2052 2053 2054 2055 2056
    char* pStart = pData;

    int32_t numOfCols = htonl(*(int32_t*)pStart);
    pStart += sizeof(int32_t);

2057
    // todo refactor:extract method
2058
    SSysTableSchema* pSchema = (SSysTableSchema*)pStart;
dengyihao's avatar
dengyihao 已提交
2059
    for (int32_t i = 0; i < numOfCols; ++i) {
2060 2061 2062 2063 2064 2065 2066
      SSysTableSchema* p = (SSysTableSchema*)pStart;

      p->colId = htons(p->colId);
      p->bytes = htonl(p->bytes);
      pStart += sizeof(SSysTableSchema);
    }

H
Haojun Liao 已提交
2067 2068 2069 2070
    SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
    pBlock->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));
    pBlock->info.numOfCols = numOfCols;

dengyihao's avatar
dengyihao 已提交
2071
    for (int32_t i = 0; i < numOfCols; ++i) {
2072
      SColumnInfoData idata = {0};
2073

X
Xiaoyu Wang 已提交
2074
      idata.info.type = pSchema[i].type;
2075 2076
      idata.info.bytes = pSchema[i].bytes;
      idata.info.colId = pSchema[i].colId;
X
Xiaoyu Wang 已提交
2077
      idata.hasNull = true;
2078

H
Haojun Liao 已提交
2079
      taosArrayPush(pBlock->pDataBlock, &idata);
2080
      if (IS_VAR_DATA_TYPE(idata.info.type)) {
H
Haojun Liao 已提交
2081
        pBlock->info.hasVarCol = true;
2082 2083 2084
      }
    }

2085
    blockCompressDecode(pBlock, numOfCols, numOfRows, pStart);
2086

H
Haojun Liao 已提交
2087
    // data from mnode
2088
    pRes->info.rows = numOfRows;
2089
    relocateColumnData(pRes, pColList, pBlock->pDataBlock, false);
H
Haojun Liao 已提交
2090 2091
    taosArrayDestroy(pBlock->pDataBlock);
    taosMemoryFree(pBlock);
X
Xiaoyu Wang 已提交
2092
    //    blockDataDestroy(pBlock);
2093
  }
2094

2095 2096
  // todo move this to time window aggregator, since the primary timestamp may not be known by exchange operator.
  blockDataUpdateTsWindow(pRes, 0);
2097

2098
  int64_t el = taosGetTimestampUs() - startTs;
2099

H
Haojun Liao 已提交
2100 2101
  pLoadInfo->totalRows += numOfRows;
  pLoadInfo->totalSize += compLen;
2102

H
Haojun Liao 已提交
2103 2104 2105
  if (total != NULL) {
    *total += numOfRows;
  }
2106

H
Haojun Liao 已提交
2107
  pLoadInfo->totalElapsed += el;
2108 2109
  return TSDB_CODE_SUCCESS;
}
2110

L
Liu Jicong 已提交
2111 2112
static void* setAllSourcesCompleted(SOperatorInfo* pOperator, int64_t startTs) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
2113
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
2114

2115
  int64_t              el = taosGetTimestampUs() - startTs;
H
Haojun Liao 已提交
2116
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2117

H
Haojun Liao 已提交
2118
  pLoadInfo->totalElapsed += el;
H
Haojun Liao 已提交
2119

2120
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
L
Liu Jicong 已提交
2121 2122 2123
  qDebug("%s all %" PRIzu " sources are exhausted, total rows: %" PRIu64 " bytes:%" PRIu64 ", elapsed:%.2f ms",
         GET_TASKID(pTaskInfo), totalSources, pLoadInfo->totalRows, pLoadInfo->totalSize,
         pLoadInfo->totalElapsed / 1000.0);
2124 2125 2126 2127 2128

  doSetOperatorCompleted(pOperator);
  return NULL;
}

L
Liu Jicong 已提交
2129 2130
static SSDataBlock* concurrentlyLoadRemoteDataImpl(SOperatorInfo* pOperator, SExchangeInfo* pExchangeInfo,
                                                   SExecTaskInfo* pTaskInfo) {
2131 2132 2133 2134 2135 2136 2137 2138
  int32_t code = 0;
  int64_t startTs = taosGetTimestampUs();
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);

  while (1) {
    int32_t completed = 0;
    for (int32_t i = 0; i < totalSources; ++i) {
      SSourceDataInfo* pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, i);
2139
      if (pDataInfo->status == EX_SOURCE_DATA_EXHAUSTED) {
2140
        completed += 1;
H
Haojun Liao 已提交
2141 2142
        continue;
      }
2143

2144
      if (pDataInfo->status != EX_SOURCE_DATA_READY) {
2145 2146 2147
        continue;
      }

2148 2149 2150 2151 2152
      if (pDataInfo->code != TSDB_CODE_SUCCESS) {
        code = pDataInfo->code;
        goto _error;
      }

L
Liu Jicong 已提交
2153
      SRetrieveTableRsp*     pRsp = pDataInfo->pRsp;
X
Xiaoyu Wang 已提交
2154
      SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, i);
2155

L
Liu Jicong 已提交
2156
      SSDataBlock*         pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
2157
      SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2158
      if (pRsp->numOfRows == 0) {
2159
        qDebug("%s vgId:%d, taskId:0x%" PRIx64 " index:%d completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
X
Xiaoyu Wang 已提交
2160
               ", completed:%d try next %d/%" PRIzu,
2161 2162
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, i, pDataInfo->totalRows,
               pExchangeInfo->loadInfo.totalRows, completed + 1, i + 1, totalSources);
2163
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2164
        completed += 1;
D
dapan1121 已提交
2165
        taosMemoryFreeClear(pDataInfo->pRsp);
2166 2167
        continue;
      }
H
Haojun Liao 已提交
2168

H
Haojun Liao 已提交
2169
      SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
2170 2171 2172
      code =
          extractDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
                                       pTableRsp->compLen, pTableRsp->numOfCols, startTs, &pDataInfo->totalRows, NULL);
2173
      if (code != 0) {
2174
        taosMemoryFreeClear(pDataInfo->pRsp);
2175 2176 2177
        goto _error;
      }

2178
      if (pRsp->completed == 1) {
X
Xiaoyu Wang 已提交
2179 2180 2181
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64
               " index:%d completed, numOfRows:%d, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64 ", totalBytes:%" PRIu64
               ", completed:%d try next %d/%" PRIzu,
2182 2183 2184
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, i, pRes->info.rows, pDataInfo->totalRows,
               pLoadInfo->totalRows, pLoadInfo->totalSize, completed + 1, i + 1, totalSources);
        completed += 1;
2185
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2186
      } else {
dengyihao's avatar
dengyihao 已提交
2187 2188
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64
               ", totalBytes:%" PRIu64,
H
Haojun Liao 已提交
2189 2190
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows,
               pLoadInfo->totalSize);
2191 2192
      }

2193 2194
      taosMemoryFreeClear(pDataInfo->pRsp);

2195 2196
      if (pDataInfo->status != EX_SOURCE_DATA_EXHAUSTED) {
        pDataInfo->status = EX_SOURCE_DATA_NOT_READY;
2197 2198
        code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
        if (code != TSDB_CODE_SUCCESS) {
2199
          taosMemoryFreeClear(pDataInfo->pRsp);
2200 2201 2202 2203 2204 2205 2206
          goto _error;
        }
      }

      return pExchangeInfo->pResult;
    }

2207
    if (completed == totalSources) {
2208 2209 2210 2211 2212 2213 2214 2215 2216
      return setAllSourcesCompleted(pOperator, startTs);
    }
  }

_error:
  pTaskInfo->code = code;
  return NULL;
}

L
Liu Jicong 已提交
2217 2218 2219
static int32_t prepareConcurrentlyLoad(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2220

L
Liu Jicong 已提交
2221
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
2222 2223 2224
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
2225
  for (int32_t i = 0; i < totalSources; ++i) {
2226 2227
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2228 2229
      pTaskInfo->code = code;
      return code;
2230 2231 2232 2233
    }
  }

  int64_t endTs = taosGetTimestampUs();
2234
  qDebug("%s send all fetch requests to %" PRIzu " sources completed, elapsed:%.2fms", GET_TASKID(pTaskInfo),
X
Xiaoyu Wang 已提交
2235
         totalSources, (endTs - startTs) / 1000.0);
2236

2237
  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
2238
  pOperator->cost.openCost = taosGetTimestampUs() - startTs;
2239

2240
  tsem_wait(&pExchangeInfo->ready);
H
Haojun Liao 已提交
2241
  return TSDB_CODE_SUCCESS;
2242 2243
}

L
Liu Jicong 已提交
2244 2245 2246
static SSDataBlock* seqLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2247

L
Liu Jicong 已提交
2248
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
2249
  int64_t startTs = taosGetTimestampUs();
2250

L
Liu Jicong 已提交
2251
  while (1) {
2252 2253
    if (pExchangeInfo->current >= totalSources) {
      return setAllSourcesCompleted(pOperator, startTs);
2254
    }
2255

2256 2257 2258
    doSendFetchDataRequest(pExchangeInfo, pTaskInfo, pExchangeInfo->current);
    tsem_wait(&pExchangeInfo->ready);

dengyihao's avatar
dengyihao 已提交
2259
    SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, pExchangeInfo->current);
X
Xiaoyu Wang 已提交
2260
    SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, pExchangeInfo->current);
2261

H
Haojun Liao 已提交
2262
    if (pDataInfo->code != TSDB_CODE_SUCCESS) {
dengyihao's avatar
dengyihao 已提交
2263 2264
      qError("%s vgId:%d, taskID:0x%" PRIx64 " error happens, code:%s", GET_TASKID(pTaskInfo), pSource->addr.nodeId,
             pSource->taskId, tstrerror(pDataInfo->code));
H
Haojun Liao 已提交
2265 2266 2267 2268
      pOperator->pTaskInfo->code = pDataInfo->code;
      return NULL;
    }

L
Liu Jicong 已提交
2269
    SRetrieveTableRsp*   pRsp = pDataInfo->pRsp;
H
Haojun Liao 已提交
2270
    SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2271
    if (pRsp->numOfRows == 0) {
dengyihao's avatar
dengyihao 已提交
2272 2273
      qDebug("%s vgId:%d, taskID:0x%" PRIx64 " %d of total completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
             " try next",
2274
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pExchangeInfo->current + 1,
H
Haojun Liao 已提交
2275
             pDataInfo->totalRows, pLoadInfo->totalRows);
H
Haojun Liao 已提交
2276

2277
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2278
      pExchangeInfo->current += 1;
D
dapan1121 已提交
2279
      taosMemoryFreeClear(pDataInfo->pRsp);
2280 2281
      continue;
    }
H
Haojun Liao 已提交
2282

L
Liu Jicong 已提交
2283
    SSDataBlock*       pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
2284
    SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
2285
    int32_t            code =
2286
        extractDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
L
Liu Jicong 已提交
2287
                                     pTableRsp->compLen, pTableRsp->numOfCols, startTs, &pDataInfo->totalRows, NULL);
2288 2289

    if (pRsp->completed == 1) {
H
Haojun Liao 已提交
2290
      qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, rowsOfSource:%" PRIu64
L
Liu Jicong 已提交
2291 2292 2293
             ", totalRows:%" PRIu64 ", totalBytes:%" PRIu64 " try next %d/%" PRIzu,
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pDataInfo->totalRows,
             pLoadInfo->totalRows, pLoadInfo->totalSize, pExchangeInfo->current + 1, totalSources);
2294

2295
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2296 2297
      pExchangeInfo->current += 1;
    } else {
L
Liu Jicong 已提交
2298 2299 2300 2301
      qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64
             ", totalBytes:%" PRIu64,
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows,
             pLoadInfo->totalSize);
2302 2303
    }

2304
    pOperator->resultInfo.totalRows += pRes->info.rows;
2305
    taosMemoryFreeClear(pDataInfo->pRsp);
2306 2307
    return pExchangeInfo->pResult;
  }
2308 2309
}

L
Liu Jicong 已提交
2310
static int32_t prepareLoadRemoteData(SOperatorInfo* pOperator) {
2311
  if (OPTR_IS_OPENED(pOperator)) {
H
Haojun Liao 已提交
2312 2313 2314
    return TSDB_CODE_SUCCESS;
  }

2315 2316
  int64_t st = taosGetTimestampUs();

L
Liu Jicong 已提交
2317
  SExchangeInfo* pExchangeInfo = pOperator->info;
2318
  if (!pExchangeInfo->seqLoadData) {
H
Haojun Liao 已提交
2319 2320 2321 2322 2323 2324
    int32_t code = prepareConcurrentlyLoad(pOperator);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

2325
  OPTR_SET_OPENED(pOperator);
2326
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
2327 2328 2329
  return TSDB_CODE_SUCCESS;
}

2330
static SSDataBlock* doLoadRemoteData(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2331 2332
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2333

2334
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
2335
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2336 2337
    return NULL;
  }
2338

L
Liu Jicong 已提交
2339
  size_t               totalSources = taosArrayGetSize(pExchangeInfo->pSources);
H
Haojun Liao 已提交
2340
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
H
Haojun Liao 已提交
2341

2342
  if (pOperator->status == OP_EXEC_DONE) {
L
Liu Jicong 已提交
2343 2344 2345
    qDebug("%s all %" PRIzu " source(s) are exhausted, total rows:%" PRIu64 " bytes:%" PRIu64 ", elapsed:%.2f ms",
           GET_TASKID(pTaskInfo), totalSources, pLoadInfo->totalRows, pLoadInfo->totalSize,
           pLoadInfo->totalElapsed / 1000.0);
2346 2347 2348 2349 2350 2351
    return NULL;
  }

  if (pExchangeInfo->seqLoadData) {
    return seqLoadRemoteData(pOperator);
  } else {
2352
    return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
2353
  }
H
Haojun Liao 已提交
2354
}
2355

2356
static int32_t initDataSource(int32_t numOfSources, SExchangeInfo* pInfo, const char* id) {
2357
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
H
Haojun Liao 已提交
2358 2359
  if (pInfo->pSourceDataInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
2360 2361
  }

L
Liu Jicong 已提交
2362
  for (int32_t i = 0; i < numOfSources; ++i) {
2363
    SSourceDataInfo dataInfo = {0};
H
Haojun Liao 已提交
2364
    dataInfo.status = EX_SOURCE_DATA_NOT_READY;
2365
    dataInfo.taskId = id;
L
Liu Jicong 已提交
2366
    dataInfo.index = i;
X
Xiaoyu Wang 已提交
2367
    SSourceDataInfo* pDs = taosArrayPush(pInfo->pSourceDataInfo, &dataInfo);
2368
    if (pDs == NULL) {
H
Haojun Liao 已提交
2369 2370 2371 2372 2373 2374 2375 2376
      taosArrayDestroy(pInfo->pSourceDataInfo);
      return TSDB_CODE_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
}

2377
static int32_t initExchangeOperator(SExchangePhysiNode* pExNode, SExchangeInfo* pInfo, const char* id) {
2378
  size_t numOfSources = LIST_LENGTH(pExNode->pSrcEndPoints);
H
Haojun Liao 已提交
2379

2380
  if (numOfSources == 0) {
X
Xiaoyu Wang 已提交
2381
    qError("%s invalid number: %d of sources in exchange operator", id, (int32_t)numOfSources);
2382 2383 2384
    return TSDB_CODE_INVALID_PARA;
  }

H
Haojun Liao 已提交
2385
  pInfo->pSources = taosArrayInit(numOfSources, sizeof(SDownstreamSourceNode));
H
Haojun Liao 已提交
2386 2387
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
  if (pInfo->pSourceDataInfo == NULL || pInfo->pSources == NULL) {
2388
    return TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
2389 2390
  }

L
Liu Jicong 已提交
2391
  for (int32_t i = 0; i < numOfSources; ++i) {
2392
    SNodeListNode* pNode = (SNodeListNode*)nodesListGetNode((SNodeList*)pExNode->pSrcEndPoints, i);
H
Haojun Liao 已提交
2393 2394
    taosArrayPush(pInfo->pSources, pNode);
  }
2395

2396 2397
  pInfo->self = taosAddRef(exchangeObjRefPool, pInfo);

2398
  return initDataSource(numOfSources, pInfo, id);
2399 2400 2401 2402 2403 2404
}

SOperatorInfo* createExchangeOperatorInfo(void* pTransporter, SExchangePhysiNode* pExNode, SExecTaskInfo* pTaskInfo) {
  SExchangeInfo* pInfo = taosMemoryCalloc(1, sizeof(SExchangeInfo));
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
H
Haojun Liao 已提交
2405
    goto _error;
2406
  }
H
Haojun Liao 已提交
2407

2408
  int32_t code = initExchangeOperator(pExNode, pInfo, GET_TASKID(pTaskInfo));
2409 2410 2411
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2412 2413

  tsem_init(&pInfo->ready, 0, 0);
2414

X
Xiaoyu Wang 已提交
2415
  pInfo->seqLoadData = false;
2416
  pInfo->pTransporter = pTransporter;
X
Xiaoyu Wang 已提交
2417 2418
  pInfo->pResult = createResDataBlock(pExNode->node.pOutputDataBlockDesc);
  pOperator->name = "ExchangeOperator";
X
Xiaoyu Wang 已提交
2419
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_EXCHANGE;
X
Xiaoyu Wang 已提交
2420 2421 2422
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
2423
  pOperator->exprSupp.numOfExprs = pInfo->pResult->info.numOfCols;
X
Xiaoyu Wang 已提交
2424
  pOperator->pTaskInfo = pTaskInfo;
2425

L
Liu Jicong 已提交
2426 2427
  pOperator->fpSet = createOperatorFpSet(prepareLoadRemoteData, doLoadRemoteData, NULL, NULL,
                                         destroyExchangeOperatorInfo, NULL, NULL, NULL);
2428
  return pOperator;
H
Haojun Liao 已提交
2429

L
Liu Jicong 已提交
2430
_error:
H
Haojun Liao 已提交
2431
  if (pInfo != NULL) {
2432
    doDestroyExchangeOperatorInfo(pInfo);
H
Haojun Liao 已提交
2433 2434
  }

wafwerar's avatar
wafwerar 已提交
2435 2436
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
2437
  pTaskInfo->code = code;
H
Haojun Liao 已提交
2438
  return NULL;
2439 2440
}

dengyihao's avatar
dengyihao 已提交
2441 2442
static int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                                const char* pKey);
2443

2444
static void destroySortedMergeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
2445
  SSortedMergeOperatorInfo* pInfo = (SSortedMergeOperatorInfo*)param;
H
Haojun Liao 已提交
2446
  taosArrayDestroy(pInfo->pSortInfo);
2447 2448 2449
  taosArrayDestroy(pInfo->groupInfo);

  if (pInfo->pSortHandle != NULL) {
H
Haojun Liao 已提交
2450
    tsortDestroySortHandle(pInfo->pSortHandle);
2451 2452
  }

H
Haojun Liao 已提交
2453
  blockDataDestroy(pInfo->binfo.pRes);
H
Haojun Liao 已提交
2454
  cleanupAggSup(&pInfo->aggSup);
2455
}
H
Haojun Liao 已提交
2456

L
Liu Jicong 已提交
2457
static bool needToMerge(SSDataBlock* pBlock, SArray* groupInfo, char** buf, int32_t rowIndex) {
2458 2459 2460 2461
  size_t size = taosArrayGetSize(groupInfo);
  if (size == 0) {
    return true;
  }
2462

2463 2464
  for (int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(groupInfo, i);
2465

2466
    SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, *index);
L
Liu Jicong 已提交
2467
    bool             isNull = colDataIsNull(pColInfo, rowIndex, pBlock->info.rows, NULL);
2468

2469 2470 2471
    if ((isNull && buf[i] != NULL) || (!isNull && buf[i] == NULL)) {
      return false;
    }
2472

2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485
    char* pCell = colDataGetData(pColInfo, rowIndex);
    if (IS_VAR_DATA_TYPE(pColInfo->info.type)) {
      if (varDataLen(pCell) != varDataLen(buf[i])) {
        return false;
      } else {
        if (memcmp(varDataVal(pCell), varDataVal(buf[i]), varDataLen(pCell)) != 0) {
          return false;
        }
      }
    } else {
      if (memcmp(pCell, buf[i], pColInfo->info.bytes) != 0) {
        return false;
      }
2486 2487 2488
    }
  }

2489
  return 0;
2490 2491
}

L
Liu Jicong 已提交
2492 2493 2494
static void doMergeResultImpl(SSortedMergeOperatorInfo* pInfo, SqlFunctionCtx* pCtx, int32_t numOfExpr,
                              int32_t rowIndex) {
  for (int32_t j = 0; j < numOfExpr; ++j) {  // TODO set row index
X
Xiaoyu Wang 已提交
2495
                                             //    pCtx[j].startRow = rowIndex;
2496 2497
  }

2498 2499
  for (int32_t j = 0; j < numOfExpr; ++j) {
    int32_t functionId = pCtx[j].functionId;
L
Liu Jicong 已提交
2500 2501 2502 2503 2504 2505 2506 2507 2508
    //    pCtx[j].fpSet->addInput(&pCtx[j]);

    //    if (functionId < 0) {
    //      SUdfInfo* pUdfInfo = taosArrayGet(pInfo->udfInfo, -1 * functionId - 1);
    //      doInvokeUdf(pUdfInfo, &pCtx[j], 0, TSDB_UDF_FUNC_MERGE);
    //    } else {
    //      assert(!TSDB_FUNC_IS_SCALAR(functionId));
    //      aAggs[functionId].mergeFunc(&pCtx[j]);
    //    }
2509
  }
2510
}
2511

L
Liu Jicong 已提交
2512 2513
static void doFinalizeResultImpl(SqlFunctionCtx* pCtx, int32_t numOfExpr) {
  for (int32_t j = 0; j < numOfExpr; ++j) {
2514 2515 2516 2517
    int32_t functionId = pCtx[j].functionId;
    //    if (functionId == FUNC_TAG_DUMMY || functionId == FUNC_TS_DUMMY) {
    //      continue;
    //    }
2518

2519 2520 2521 2522
    //    if (functionId < 0) {
    //      SUdfInfo* pUdfInfo = taosArrayGet(pInfo->udfInfo, -1 * functionId - 1);
    //      doInvokeUdf(pUdfInfo, &pCtx[j], 0, TSDB_UDF_FUNC_FINALIZE);
    //    } else {
dengyihao's avatar
dengyihao 已提交
2523
    //    pCtx[j].fpSet.finalize(&pCtx[j]);
2524 2525
  }
}
2526

2527
static bool saveCurrentTuple(char** rowColData, SArray* pColumnList, SSDataBlock* pBlock, int32_t rowIndex) {
L
Liu Jicong 已提交
2528
  int32_t size = (int32_t)taosArrayGetSize(pColumnList);
2529

L
Liu Jicong 已提交
2530 2531
  for (int32_t i = 0; i < size; ++i) {
    int32_t*         index = taosArrayGet(pColumnList, i);
2532
    SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, *index);
H
Haojun Liao 已提交
2533

2534 2535 2536
    char* data = colDataGetData(pColInfo, rowIndex);
    memcpy(rowColData[i], data, colDataGetLength(pColInfo, rowIndex));
  }
2537

2538 2539
  return true;
}
2540

2541 2542
static void doMergeImpl(SOperatorInfo* pOperator, int32_t numOfExpr, SSDataBlock* pBlock) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
2543

2544
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
L
Liu Jicong 已提交
2545
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
X
Xiaoyu Wang 已提交
2546
    //    pCtx[i].size = 1;
2547
  }
2548

L
Liu Jicong 已提交
2549
  for (int32_t i = 0; i < pBlock->info.rows; ++i) {
2550 2551 2552 2553 2554 2555 2556 2557 2558
    if (!pInfo->hasGroupVal) {
      ASSERT(i == 0);
      doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
      pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
    } else {
      if (needToMerge(pBlock, pInfo->groupInfo, pInfo->groupVal, i)) {
        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
      } else {
        doFinalizeResultImpl(pCtx, numOfExpr);
2559 2560
        int32_t numOfRows = getNumOfResult(pOperator->exprSupp.pCtx, pOperator->exprSupp.numOfExprs, NULL);
        //        setTagValueForMultipleRows(pCtx, pOperator->exprSupp.numOfExprs, numOfRows);
2561

2562
        // TODO check for available buffer;
H
Haojun Liao 已提交
2563

2564 2565 2566 2567 2568
        // next group info data
        pInfo->binfo.pRes->info.rows += numOfRows;
        for (int32_t j = 0; j < numOfExpr; ++j) {
          if (pCtx[j].functionId < 0) {
            continue;
2569
          }
2570

H
Haojun Liao 已提交
2571
          pCtx[j].fpSet.process(&pCtx[j]);
2572
        }
2573 2574 2575

        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
        pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
H
Haojun Liao 已提交
2576
      }
2577 2578 2579 2580
    }
  }
}

2581 2582
static SSDataBlock* doMerge(SOperatorInfo* pOperator) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
2583
  SSortHandle*              pHandle = pInfo->pSortHandle;
2584

2585
  SSDataBlock* pDataBlock = createOneDataBlock(pInfo->binfo.pRes, false);
2586
  blockDataEnsureCapacity(pDataBlock, pOperator->resultInfo.capacity);
2587

L
Liu Jicong 已提交
2588
  while (1) {
2589
    blockDataCleanup(pDataBlock);
2590
    while (1) {
H
Haojun Liao 已提交
2591
      STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
2592 2593
      if (pTupleHandle == NULL) {
        break;
2594
      }
2595

2596 2597
      // build datablock for merge for one group
      appendOneRowToDataBlock(pDataBlock, pTupleHandle);
2598
      if (pDataBlock->info.rows >= pOperator->resultInfo.capacity) {
2599 2600
        break;
      }
2601
    }
2602

2603 2604 2605
    if (pDataBlock->info.rows == 0) {
      break;
    }
2606

2607
    setInputDataBlock(pOperator, pOperator->exprSupp.pCtx, pDataBlock, TSDB_ORDER_ASC, MAIN_SCAN, true);
L
Liu Jicong 已提交
2608 2609
    //  updateOutputBuf(&pInfo->binfo, &pAggInfo->bufCapacity, pBlock->info.rows * pAggInfo->resultRowFactor,
    //  pOperator->pRuntimeEnv, true);
2610
    doMergeImpl(pOperator, pOperator->exprSupp.numOfExprs, pDataBlock);
2611 2612
    // flush to tuple store, and after all data have been handled, return to upstream node or sink node
  }
2613

2614 2615 2616
  doFinalizeResultImpl(pOperator->exprSupp.pCtx, pOperator->exprSupp.numOfExprs);
  int32_t numOfRows = getNumOfResult(pOperator->exprSupp.pCtx, pOperator->exprSupp.numOfExprs, NULL);
  //        setTagValueForMultipleRows(pCtx, pOperator->exprSupp.numOfExprs, numOfRows);
2617

2618
  // TODO check for available buffer;
2619

2620 2621
  // next group info data
  pInfo->binfo.pRes->info.rows += numOfRows;
L
Liu Jicong 已提交
2622
  return (pInfo->binfo.pRes->info.rows > 0) ? pInfo->binfo.pRes : NULL;
2623
}
2624

L
Liu Jicong 已提交
2625 2626
SSDataBlock* getSortedMergeBlockData(SSortHandle* pHandle, SSDataBlock* pDataBlock, int32_t capacity,
                                     SArray* pColMatchInfo, SSortedMergeOperatorInfo* pInfo) {
2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
  blockDataCleanup(pDataBlock);

  SSDataBlock* p = tsortGetSortedDataBlock(pHandle);
  if (p == NULL) {
    return NULL;
  }

  blockDataEnsureCapacity(p, capacity);

  while (1) {
2637
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
2638 2639 2640 2641
    if (pTupleHandle == NULL) {
      break;
    }

2642
    appendOneRowToDataBlock(p, pTupleHandle);
2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
    if (p->info.rows >= capacity) {
      break;
    }
  }

  if (p->info.rows > 0) {
    int32_t numOfCols = taosArrayGetSize(pColMatchInfo);
    for (int32_t i = 0; i < numOfCols; ++i) {
      SColMatchInfo* pmInfo = taosArrayGet(pColMatchInfo, i);
      ASSERT(pmInfo->matchType == COL_MATCH_FROM_SLOT_ID);

      SColumnInfoData* pSrc = taosArrayGet(p->pDataBlock, pmInfo->srcSlotId);
      SColumnInfoData* pDst = taosArrayGet(pDataBlock->pDataBlock, pmInfo->targetSlotId);
      colDataAssign(pDst, pSrc, p->info.rows);
    }

    pDataBlock->info.rows = p->info.rows;
    pDataBlock->info.capacity = p->info.rows;
  }

  blockDataDestroy(p);
  return (pDataBlock->info.rows > 0) ? pDataBlock : NULL;
}

2667
static SSDataBlock* doSortedMerge(SOperatorInfo* pOperator) {
2668 2669
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
2670 2671
  }

L
Liu Jicong 已提交
2672
  SExecTaskInfo*            pTaskInfo = pOperator->pTaskInfo;
2673
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
2674
  if (pOperator->status == OP_RES_TO_RETURN) {
2675
    return getSortedMergeBlockData(pInfo->pSortHandle, pInfo->binfo.pRes, pOperator->resultInfo.capacity, NULL, pInfo);
2676 2677
  }

2678
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
L
Liu Jicong 已提交
2679 2680
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, SORT_MULTISOURCE_MERGE, pInfo->bufPageSize, numOfBufPage,
                                             pInfo->binfo.pRes, "GET_TASKID(pTaskInfo)");
H
Haojun Liao 已提交
2681

2682
  tsortSetFetchRawDataFp(pInfo->pSortHandle, loadNextDataBlock, NULL, NULL);
2683

L
Liu Jicong 已提交
2684
  for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
wmmhello's avatar
wmmhello 已提交
2685
    SSortSource* ps = taosMemoryCalloc(1, sizeof(SSortSource));
H
Haojun Liao 已提交
2686
    ps->param = pOperator->pDownstream[i];
H
Haojun Liao 已提交
2687
    tsortAddSource(pInfo->pSortHandle, ps);
2688 2689
  }

H
Haojun Liao 已提交
2690
  int32_t code = tsortOpen(pInfo->pSortHandle);
2691
  if (code != TSDB_CODE_SUCCESS) {
2692
    longjmp(pTaskInfo->env, terrno);
2693 2694
  }

H
Haojun Liao 已提交
2695
  pOperator->status = OP_RES_TO_RETURN;
2696
  return doMerge(pOperator);
2697
}
2698

L
Liu Jicong 已提交
2699 2700
static int32_t initGroupCol(SExprInfo* pExprInfo, int32_t numOfCols, SArray* pGroupInfo,
                            SSortedMergeOperatorInfo* pInfo) {
2701 2702
  if (pGroupInfo == NULL || taosArrayGetSize(pGroupInfo) == 0) {
    return 0;
H
Haojun Liao 已提交
2703 2704
  }

2705 2706 2707 2708 2709 2710 2711 2712
  int32_t len = 0;
  SArray* plist = taosArrayInit(3, sizeof(SColumn));
  pInfo->groupInfo = taosArrayInit(3, sizeof(int32_t));

  if (plist == NULL || pInfo->groupInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

L
Liu Jicong 已提交
2713 2714
  size_t numOfGroupCol = taosArrayGetSize(pInfo->groupInfo);
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
2715
    SColumn* pCol = taosArrayGet(pGroupInfo, i);
L
Liu Jicong 已提交
2716
    for (int32_t j = 0; j < numOfCols; ++j) {
H
Haojun Liao 已提交
2717
      SExprInfo* pe = &pExprInfo[j];
2718
      if (pe->base.resSchema.slotId == pCol->colId) {
2719 2720
        taosArrayPush(plist, pCol);
        taosArrayPush(pInfo->groupInfo, &j);
H
Haojun Liao 已提交
2721
        len += pCol->bytes;
2722 2723
        break;
      }
H
Haojun Liao 已提交
2724 2725 2726
    }
  }

2727
  ASSERT(taosArrayGetSize(pGroupInfo) == taosArrayGetSize(plist));
H
Haojun Liao 已提交
2728

wafwerar's avatar
wafwerar 已提交
2729
  pInfo->groupVal = taosMemoryCalloc(1, (POINTER_BYTES * numOfGroupCol + len));
2730 2731 2732 2733
  if (pInfo->groupVal == NULL) {
    taosArrayDestroy(plist);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
2734

2735
  int32_t offset = 0;
L
Liu Jicong 已提交
2736 2737
  char*   start = (char*)(pInfo->groupVal + (POINTER_BYTES * numOfGroupCol));
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
2738 2739
    pInfo->groupVal[i] = start + offset;
    SColumn* pCol = taosArrayGet(plist, i);
H
Haojun Liao 已提交
2740
    offset += pCol->bytes;
2741
  }
H
Haojun Liao 已提交
2742

2743
  taosArrayDestroy(plist);
H
Haojun Liao 已提交
2744

2745 2746
  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
2747

L
Liu Jicong 已提交
2748 2749 2750
SOperatorInfo* createSortedMergeOperatorInfo(SOperatorInfo** downstream, int32_t numOfDownstream, SExprInfo* pExprInfo,
                                             int32_t num, SArray* pSortInfo, SArray* pGroupInfo,
                                             SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
2751
  SSortedMergeOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortedMergeOperatorInfo));
L
Liu Jicong 已提交
2752
  SOperatorInfo*            pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2753
  if (pInfo == NULL || pOperator == NULL) {
2754
    goto _error;
2755
  }
H
Haojun Liao 已提交
2756

2757 2758 2759 2760 2761
  int32_t code = initExprSupp(&pOperator->exprSupp, pExprInfo, num);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

2762
  initResultRowInfo(&pInfo->binfo.resultRowInfo);
H
Haojun Liao 已提交
2763

2764
  if (pOperator->exprSupp.pCtx == NULL || pInfo->binfo.pRes == NULL) {
2765 2766
    goto _error;
  }
H
Haojun Liao 已提交
2767

2768
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
2769
  code = doInitAggInfoSup(&pInfo->aggSup, pOperator->exprSupp.pCtx, num, keyBufSize, pTaskInfo->id.str);
2770 2771 2772
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
2773

2774
  setFunctionResultOutput(pOperator, &pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, num);
H
Haojun Liao 已提交
2775
  code = initGroupCol(pExprInfo, num, pGroupInfo, pInfo);
2776 2777 2778
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
2779

L
Liu Jicong 已提交
2780 2781 2782 2783 2784
  //  pInfo->resultRowFactor = (int32_t)(getRowNumForMultioutput(pRuntimeEnv->pQueryAttr,
  //      pRuntimeEnv->pQueryAttr->topBotQuery, false));
  pInfo->sortBufSize = 1024 * 16;  // 1MB
  pInfo->bufPageSize = 1024;
  pInfo->pSortInfo = pSortInfo;
H
Haojun Liao 已提交
2785

2786
  pOperator->resultInfo.capacity = blockDataGetCapacityInRow(pInfo->binfo.pRes, pInfo->bufPageSize);
H
Haojun Liao 已提交
2787

L
Liu Jicong 已提交
2788
  pOperator->name = "SortedMerge";
X
Xiaoyu Wang 已提交
2789
  // pOperator->operatorType = OP_SortedMerge;
2790 2791 2792
  pOperator->blocking = true;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
L
Liu Jicong 已提交
2793
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
2794

2795 2796
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doSortedMerge, NULL, NULL, destroySortedMergeOperatorInfo,
                                         NULL, NULL, NULL);
2797 2798 2799
  code = appendDownstream(pOperator, downstream, numOfDownstream);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
2800
  }
H
Haojun Liao 已提交
2801

2802
  return pOperator;
H
Haojun Liao 已提交
2803

L
Liu Jicong 已提交
2804
_error:
2805
  if (pInfo != NULL) {
H
Haojun Liao 已提交
2806
    destroySortedMergeOperatorInfo(pInfo, num);
H
Haojun Liao 已提交
2807 2808
  }

wafwerar's avatar
wafwerar 已提交
2809 2810
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
2811 2812
  terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
2813 2814
}

X
Xiaoyu Wang 已提交
2815
int32_t getTableScanInfo(SOperatorInfo* pOperator, int32_t* order, int32_t* scanFlag) {
2816
  // todo add more information about exchange operation
2817
  int32_t type = pOperator->operatorType;
X
Xiaoyu Wang 已提交
2818
  if (type == QUERY_NODE_PHYSICAL_PLAN_EXCHANGE || type == QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN ||
2819 2820
      type == QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN || type == QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN ||
      type == QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN) {
2821 2822 2823
    *order = TSDB_ORDER_ASC;
    *scanFlag = MAIN_SCAN;
    return TSDB_CODE_SUCCESS;
2824
  } else if (type == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
2825 2826 2827 2828 2829
    STableScanInfo* pTableScanInfo = pOperator->info;
    *order = pTableScanInfo->cond.order;
    *scanFlag = pTableScanInfo->scanFlag;
    return TSDB_CODE_SUCCESS;
  } else {
H
Haojun Liao 已提交
2830
    if (pOperator->pDownstream == NULL || pOperator->pDownstream[0] == NULL) {
2831
      return TSDB_CODE_INVALID_PARA;
H
Haojun Liao 已提交
2832
    } else {
2833
      return getTableScanInfo(pOperator->pDownstream[0], order, scanFlag);
2834 2835 2836
    }
  }
}
2837 2838

// this is a blocking operator
L
Liu Jicong 已提交
2839
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
2840 2841
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
2842 2843
  }

H
Haojun Liao 已提交
2844
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
2845
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
2846

2847 2848
  SExprSupp*     pSup = &pOperator->exprSupp;
  SOperatorInfo* downstream = pOperator->pDownstream[0];
2849

2850 2851
  int64_t st = taosGetTimestampUs();

2852 2853 2854
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;

H
Haojun Liao 已提交
2855
  while (1) {
2856
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
2857 2858 2859 2860
    if (pBlock == NULL) {
      break;
    }

2861 2862 2863 2864
    int32_t code = getTableScanInfo(pOperator, &order, &scanFlag);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
2865

2866
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
2867 2868 2869
    if (pAggInfo->scalarExprSup.pExprInfo != NULL) {
      SExprSupp* pSup1 = &pAggInfo->scalarExprSup;
      code = projectApplyFunctions(pSup1->pExprInfo, pBlock, pBlock, pSup1->pCtx, pSup1->numOfExprs, NULL);
2870
      if (code != TSDB_CODE_SUCCESS) {
2871
        longjmp(pTaskInfo->env, code);
2872
      }
2873 2874
    }

2875
    // the pDataBlock are always the same one, no need to call this again
2876 2877 2878
    setExecutionContext(pOperator, pOperator->exprSupp.numOfExprs, pBlock->info.groupId, pAggInfo);
    setInputDataBlock(pOperator, pSup->pCtx, pBlock, order, scanFlag, true);
    code = doAggregateImpl(pOperator, 0, pSup->pCtx);
2879 2880 2881
    if (code != 0) {
      longjmp(pTaskInfo->env, code);
    }
2882

dengyihao's avatar
dengyihao 已提交
2883
#if 0  // test for encode/decode result info
2884
    if(pOperator->fpSet.encodeResultRow){
2885 2886
      char *result = NULL;
      int32_t length = 0;
2887 2888
      pOperator->fpSet.encodeResultRow(pOperator, &result, &length);
      SAggSupporter* pSup = &pAggInfo->aggSup;
2889 2890
      taosHashClear(pSup->pResultRowHashTable);
      pInfo->resultRowInfo.size = 0;
2891
      pOperator->fpSet.decodeResultRow(pOperator, result);
2892 2893 2894
      if(result){
        taosMemoryFree(result);
      }
2895
    }
2896
#endif
2897 2898
  }

H
Haojun Liao 已提交
2899
  closeAllResultRows(&pAggInfo->binfo.resultRowInfo);
2900
  initGroupedResultInfo(&pAggInfo->groupResInfo, pAggInfo->aggSup.pResultRowHashTable, 0);
H
Haojun Liao 已提交
2901
  OPTR_SET_OPENED(pOperator);
2902

2903
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
2904 2905 2906
  return TSDB_CODE_SUCCESS;
}

2907
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2908
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
2909 2910 2911 2912 2913 2914
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

L
Liu Jicong 已提交
2915
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2916
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
H
Haojun Liao 已提交
2917
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
2918
    doSetOperatorCompleted(pOperator);
H
Haojun Liao 已提交
2919 2920 2921
    return NULL;
  }

H
Haojun Liao 已提交
2922
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
2923
  doBuildResultDatablock(pOperator, pInfo, &pAggInfo->groupResInfo, pAggInfo->aggSup.pResultBuf);
2924
  if (pInfo->pRes->info.rows == 0 || !hasDataInGroupInfo(&pAggInfo->groupResInfo)) {
H
Haojun Liao 已提交
2925 2926
    doSetOperatorCompleted(pOperator);
  }
2927

2928
  size_t rows = blockDataGetNumOfRows(pInfo->pRes);
2929 2930
  pOperator->resultInfo.totalRows += rows;

2931
  return (rows == 0) ? NULL : pInfo->pRes;
2932 2933
}

wmmhello's avatar
wmmhello 已提交
2934
int32_t aggEncodeResultRow(SOperatorInfo* pOperator, char** result, int32_t* length) {
2935
  if (result == NULL || length == NULL) {
wmmhello's avatar
wmmhello 已提交
2936 2937 2938
    return TSDB_CODE_TSC_INVALID_INPUT;
  }
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)(pOperator->info);
2939 2940 2941 2942 2943
  SAggSupporter*  pSup = (SAggSupporter*)POINTER_SHIFT(pOperator->info, sizeof(SOptrBasicInfo));
  int32_t         size = taosHashGetSize(pSup->pResultRowHashTable);
  size_t          keyLen = sizeof(uint64_t) * 2;  // estimate the key length
  int32_t         totalSize =
      sizeof(int32_t) + sizeof(int32_t) + size * (sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize);
wmmhello's avatar
wmmhello 已提交
2944

wmmhello's avatar
wmmhello 已提交
2945
  *result = (char*)taosMemoryCalloc(1, totalSize);
L
Liu Jicong 已提交
2946
  if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
2947
    return TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
2948
  }
wmmhello's avatar
wmmhello 已提交
2949

wmmhello's avatar
wmmhello 已提交
2950
  int32_t offset = sizeof(int32_t);
wmmhello's avatar
wmmhello 已提交
2951 2952
  *(int32_t*)(*result + offset) = size;
  offset += sizeof(int32_t);
2953 2954

  // prepare memory
2955
  SResultRowPosition* pos = &pInfo->resultRowInfo.cur;
dengyihao's avatar
dengyihao 已提交
2956 2957
  void*               pPage = getBufPage(pSup->pResultBuf, pos->pageId);
  SResultRow*         pRow = (SResultRow*)((char*)pPage + pos->offset);
2958 2959 2960
  setBufPageDirty(pPage, true);
  releaseBufPage(pSup->pResultBuf, pPage);

dengyihao's avatar
dengyihao 已提交
2961
  void* pIter = taosHashIterate(pSup->pResultRowHashTable, NULL);
wmmhello's avatar
wmmhello 已提交
2962
  while (pIter) {
dengyihao's avatar
dengyihao 已提交
2963
    void*               key = taosHashGetKey(pIter, &keyLen);
2964
    SResultRowPosition* p1 = (SResultRowPosition*)pIter;
2965

dengyihao's avatar
dengyihao 已提交
2966
    pPage = (SFilePage*)getBufPage(pSup->pResultBuf, p1->pageId);
2967
    pRow = (SResultRow*)((char*)pPage + p1->offset);
2968 2969
    setBufPageDirty(pPage, true);
    releaseBufPage(pSup->pResultBuf, pPage);
wmmhello's avatar
wmmhello 已提交
2970 2971 2972

    // recalculate the result size
    int32_t realTotalSize = offset + sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize;
L
Liu Jicong 已提交
2973
    if (realTotalSize > totalSize) {
wmmhello's avatar
wmmhello 已提交
2974
      char* tmp = (char*)taosMemoryRealloc(*result, realTotalSize);
L
Liu Jicong 已提交
2975
      if (tmp == NULL) {
wafwerar's avatar
wafwerar 已提交
2976
        taosMemoryFree(*result);
wmmhello's avatar
wmmhello 已提交
2977
        *result = NULL;
wmmhello's avatar
wmmhello 已提交
2978
        return TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
2979
      } else {
wmmhello's avatar
wmmhello 已提交
2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991
        *result = tmp;
      }
    }
    // save key
    *(int32_t*)(*result + offset) = keyLen;
    offset += sizeof(int32_t);
    memcpy(*result + offset, key, keyLen);
    offset += keyLen;

    // save value
    *(int32_t*)(*result + offset) = pSup->resultRowSize;
    offset += sizeof(int32_t);
2992
    memcpy(*result + offset, pRow, pSup->resultRowSize);
wmmhello's avatar
wmmhello 已提交
2993 2994 2995 2996 2997
    offset += pSup->resultRowSize;

    pIter = taosHashIterate(pSup->pResultRowHashTable, pIter);
  }

wmmhello's avatar
wmmhello 已提交
2998 2999 3000 3001
  *(int32_t*)(*result) = offset;
  *length = offset;

  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
3002 3003
}

3004
int32_t aggDecodeResultRow(SOperatorInfo* pOperator, char* result) {
3005
  if (result == NULL) {
wmmhello's avatar
wmmhello 已提交
3006
    return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3007
  }
wmmhello's avatar
wmmhello 已提交
3008
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)(pOperator->info);
3009
  SAggSupporter*  pSup = (SAggSupporter*)POINTER_SHIFT(pOperator->info, sizeof(SOptrBasicInfo));
wmmhello's avatar
wmmhello 已提交
3010 3011

  //  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
3012
  int32_t length = *(int32_t*)(result);
wmmhello's avatar
wmmhello 已提交
3013
  int32_t offset = sizeof(int32_t);
3014 3015 3016 3017

  int32_t count = *(int32_t*)(result + offset);
  offset += sizeof(int32_t);

L
Liu Jicong 已提交
3018
  while (count-- > 0 && length > offset) {
wmmhello's avatar
wmmhello 已提交
3019 3020 3021
    int32_t keyLen = *(int32_t*)(result + offset);
    offset += sizeof(int32_t);

L
Liu Jicong 已提交
3022
    uint64_t    tableGroupId = *(uint64_t*)(result + offset);
3023
    SResultRow* resultRow = getNewResultRow(pSup->pResultBuf, tableGroupId, pSup->resultRowSize);
L
Liu Jicong 已提交
3024
    if (!resultRow) {
wmmhello's avatar
wmmhello 已提交
3025
      return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3026
    }
3027

wmmhello's avatar
wmmhello 已提交
3028
    // add a new result set for a new group
3029 3030
    SResultRowPosition pos = {.pageId = resultRow->pageId, .offset = resultRow->offset};
    taosHashPut(pSup->pResultRowHashTable, result + offset, keyLen, &pos, sizeof(SResultRowPosition));
wmmhello's avatar
wmmhello 已提交
3031 3032 3033

    offset += keyLen;
    int32_t valueLen = *(int32_t*)(result + offset);
L
Liu Jicong 已提交
3034
    if (valueLen != pSup->resultRowSize) {
wmmhello's avatar
wmmhello 已提交
3035
      return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045
    }
    offset += sizeof(int32_t);
    int32_t pageId = resultRow->pageId;
    int32_t pOffset = resultRow->offset;
    memcpy(resultRow, result + offset, valueLen);
    resultRow->pageId = pageId;
    resultRow->offset = pOffset;
    offset += valueLen;

    initResultRow(resultRow);
dengyihao's avatar
dengyihao 已提交
3046
    pInfo->resultRowInfo.cur = (SResultRowPosition){.pageId = resultRow->pageId, .offset = resultRow->offset};
wmmhello's avatar
wmmhello 已提交
3047 3048
  }

L
Liu Jicong 已提交
3049
  if (offset != length) {
wmmhello's avatar
wmmhello 已提交
3050
    return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3051
  }
wmmhello's avatar
wmmhello 已提交
3052
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
3053 3054
}

3055 3056
enum {
  PROJECT_RETRIEVE_CONTINUE = 0x1,
L
Liu Jicong 已提交
3057
  PROJECT_RETRIEVE_DONE = 0x2,
3058 3059 3060 3061 3062
};

static int32_t handleLimitOffset(SOperatorInfo* pOperator, SSDataBlock* pBlock) {
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
L
Liu Jicong 已提交
3063
  SSDataBlock*          pRes = pInfo->pRes;
3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111

  if (pProjectInfo->curSOffset > 0) {
    if (pProjectInfo->groupId == 0) {  // it is the first group
      pProjectInfo->groupId = pBlock->info.groupId;
      blockDataCleanup(pInfo->pRes);
      return PROJECT_RETRIEVE_CONTINUE;
    } else if (pProjectInfo->groupId != pBlock->info.groupId) {
      pProjectInfo->curSOffset -= 1;

      // ignore data block in current group
      if (pProjectInfo->curSOffset > 0) {
        blockDataCleanup(pInfo->pRes);
        return PROJECT_RETRIEVE_CONTINUE;
      }
    }

    // set current group id of the project operator
    pProjectInfo->groupId = pBlock->info.groupId;
  }

  if (pProjectInfo->groupId != 0 && pProjectInfo->groupId != pBlock->info.groupId) {
    pProjectInfo->curGroupOutput += 1;
    if ((pProjectInfo->slimit.limit > 0) && (pProjectInfo->slimit.limit <= pProjectInfo->curGroupOutput)) {
      pOperator->status = OP_EXEC_DONE;
      blockDataCleanup(pRes);

      return PROJECT_RETRIEVE_DONE;
    }

    // reset the value for a new group data
    pProjectInfo->curOffset = 0;
    pProjectInfo->curOutput = 0;
  }

  // here we reach the start position, according to the limit/offset requirements.

  // set current group id
  pProjectInfo->groupId = pBlock->info.groupId;

  if (pProjectInfo->curOffset >= pRes->info.rows) {
    pProjectInfo->curOffset -= pRes->info.rows;
    blockDataCleanup(pRes);
    return PROJECT_RETRIEVE_CONTINUE;
  } else if (pProjectInfo->curOffset < pRes->info.rows && pProjectInfo->curOffset > 0) {
    blockDataTrimFirstNRows(pRes, pProjectInfo->curOffset);
    pProjectInfo->curOffset = 0;
  }

3112 3113 3114
  // check for the limitation in each group
  if (pProjectInfo->limit.limit > 0 && pProjectInfo->curOutput + pRes->info.rows >= pProjectInfo->limit.limit) {
    pRes->info.rows = (int32_t)(pProjectInfo->limit.limit - pProjectInfo->curOutput);
3115
    if (pProjectInfo->slimit.limit > 0 && pProjectInfo->slimit.limit <= pProjectInfo->curGroupOutput) {
3116 3117 3118
      pOperator->status = OP_EXEC_DONE;
    }

3119
    return PROJECT_RETRIEVE_DONE;
3120
  }
3121

3122
  // todo optimize performance
3123 3124
  // If there are slimit/soffset value exists, multi-round result can not be packed into one group, since the
  // they may not belong to the same group the limit/offset value is not valid in this case.
L
Liu Jicong 已提交
3125 3126
  if (pRes->info.rows >= pOperator->resultInfo.threshold || pProjectInfo->slimit.offset != -1 ||
      pProjectInfo->slimit.limit != -1) {
3127
    return PROJECT_RETRIEVE_DONE;
L
Liu Jicong 已提交
3128
  } else {  // not full enough, continue to accumulate the output data in the buffer.
3129 3130 3131 3132
    return PROJECT_RETRIEVE_CONTINUE;
  }
}

3133
static SSDataBlock* doProjectOperation(SOperatorInfo* pOperator) {
3134
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
L
Liu Jicong 已提交
3135
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
3136

L
Liu Jicong 已提交
3137
  SExprSupp*   pSup = &pOperator->exprSupp;
3138
  SSDataBlock* pRes = pInfo->pRes;
3139
  blockDataCleanup(pRes);
3140

3141
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3142 3143 3144
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
3145

H
Haojun Liao 已提交
3146
#if 0
3147 3148 3149 3150 3151
  if (pProjectInfo->existDataBlock) {  // TODO refactor
    SSDataBlock* pBlock = pProjectInfo->existDataBlock;
    pProjectInfo->existDataBlock = NULL;

    // the pDataBlock are always the same one, no need to call this again
H
Haojun Liao 已提交
3152
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, TSDB_ORDER_ASC);
3153

H
Haojun Liao 已提交
3154
    blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);
3155
    projectApplyFunctions(pOperator->exprSupp.pExprInfo, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->exprSupp.numOfExprs);
L
Liu Jicong 已提交
3156
    if (pRes->info.rows >= pProjectInfo->binfo.capacity * 0.8) {
3157 3158
      copyTsColoum(pRes, pInfo->pCtx, pOperator->exprSupp.numOfExprs);
      resetResultRowEntryResult(pInfo->pCtx, pOperator->exprSupp.numOfExprs);
3159 3160 3161
      return pRes;
    }
  }
H
Haojun Liao 已提交
3162
#endif
3163

3164
  int64_t st = 0;
3165 3166 3167
  int32_t order = 0;
  int32_t scanFlag = 0;

3168 3169 3170 3171
  if (pOperator->cost.openCost == 0) {
    st = taosGetTimestampUs();
  }

H
Haojun Liao 已提交
3172 3173
  SOperatorInfo* downstream = pOperator->pDownstream[0];

L
Liu Jicong 已提交
3174
  while (1) {
H
Haojun Liao 已提交
3175
    // The downstream exec may change the value of the newgroup, so use a local variable instead.
3176
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
3177
    if (pBlock == NULL) {
3178
      doSetOperatorCompleted(pOperator);
3179 3180 3181 3182
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
3183
    int32_t code = getTableScanInfo(pOperator->pDownstream[0], &order, &scanFlag);
3184 3185 3186
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
3187

3188
    doFilter(pProjectInfo->pFilterNode, pBlock);
3189

3190
    setInputDataBlock(pOperator, pSup->pCtx, pBlock, order, scanFlag, false);
3191 3192
    blockDataEnsureCapacity(pInfo->pRes, pInfo->pRes->info.rows + pBlock->info.rows);

3193
    code = projectApplyFunctions(pSup->pExprInfo, pInfo->pRes, pBlock, pSup->pCtx, pSup->numOfExprs,
X
Xiaoyu Wang 已提交
3194
                                 pProjectInfo->pPseudoColInfo);
3195 3196
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
3197 3198
    }

3199 3200
    int32_t status = handleLimitOffset(pOperator, pBlock);
    if (status == PROJECT_RETRIEVE_CONTINUE) {
H
Haojun Liao 已提交
3201
      continue;
L
Liu Jicong 已提交
3202
    } else if (status == PROJECT_RETRIEVE_DONE) {
3203 3204 3205
      break;
    }
  }
dengyihao's avatar
dengyihao 已提交
3206

H
Haojun Liao 已提交
3207
  pProjectInfo->curOutput += pInfo->pRes->info.rows;
H
Haojun Liao 已提交
3208

3209 3210 3211 3212
  size_t rows = pInfo->pRes->info.rows;
  pOperator->resultInfo.totalRows += rows;

  if (pOperator->cost.openCost == 0) {
3213
    pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
3214 3215
  }

3216
  return (rows > 0) ? pInfo->pRes : NULL;
3217 3218
}

L
Liu Jicong 已提交
3219 3220
static void doHandleRemainBlockForNewGroupImpl(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo, bool* newgroup,
                                               SExecTaskInfo* pTaskInfo) {
3221
  pInfo->totalInputRows = pInfo->existNewGroupBlock->info.rows;
H
Haojun Liao 已提交
3222

L
Liu Jicong 已提交
3223 3224
  int64_t ekey = Q_STATUS_EQUAL(pTaskInfo->status, TASK_COMPLETED) ? pTaskInfo->window.ekey
                                                                   : pInfo->existNewGroupBlock->info.window.ekey;
3225 3226
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

3227
  taosFillSetStartInfo(pInfo->pFillInfo, pInfo->existNewGroupBlock->info.rows, ekey);
3228 3229
  taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->existNewGroupBlock);

3230
  doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pResultInfo->capacity);
3231 3232 3233 3234
  pInfo->existNewGroupBlock = NULL;
  *newgroup = true;
}

L
Liu Jicong 已提交
3235 3236
static void doHandleRemainBlockFromNewGroup(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo, bool* newgroup,
                                            SExecTaskInfo* pTaskInfo) {
3237 3238
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
    *newgroup = false;
3239
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, (int32_t)pResultInfo->capacity);
H
Haojun Liao 已提交
3240
    if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult)) {
3241 3242 3243 3244 3245 3246
      return;
    }
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
3247
    doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
3248 3249 3250
  }
}

3251
static SSDataBlock* doFill(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
3252 3253
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
3254

H
Haojun Liao 已提交
3255
  SResultInfo* pResultInfo = &pOperator->resultInfo;
3256 3257 3258
  SSDataBlock* pResBlock = pInfo->pRes;

  blockDataCleanup(pResBlock);
3259 3260 3261 3262
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

3263
  // todo handle different group data interpolation
X
Xiaoyu Wang 已提交
3264 3265
  bool  n = false;
  bool* newgroup = &n;
3266
  doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
3267 3268
  if (pResBlock->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult && pResBlock->info.rows > 0)) {
    return pResBlock;
H
Haojun Liao 已提交
3269
  }
3270

H
Haojun Liao 已提交
3271
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
3272
  while (1) {
3273
    SSDataBlock* pBlock = pDownstream->fpSet.getNextFn(pDownstream);
3274 3275 3276 3277 3278 3279 3280 3281 3282 3283
    if (*newgroup) {
      assert(pBlock != NULL);
    }

    if (*newgroup && pInfo->totalInputRows > 0) {  // there are already processed current group data block
      pInfo->existNewGroupBlock = pBlock;
      *newgroup = false;

      // Fill the previous group data block, before handle the data block of new group.
      // Close the fill operation for previous group data block
3284
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
3285 3286 3287 3288 3289 3290 3291
    } else {
      if (pBlock == NULL) {
        if (pInfo->totalInputRows == 0) {
          pOperator->status = OP_EXEC_DONE;
          return NULL;
        }

3292
        taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
3293 3294 3295 3296 3297 3298 3299
      } else {
        pInfo->totalInputRows += pBlock->info.rows;
        taosFillSetStartInfo(pInfo->pFillInfo, pBlock->info.rows, pBlock->info.window.ekey);
        taosFillSetInputDataBlock(pInfo->pFillInfo, pBlock);
      }
    }

3300 3301
    blockDataEnsureCapacity(pResBlock, pOperator->resultInfo.capacity);
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pResBlock, pOperator->resultInfo.capacity);
3302 3303

    // current group has no more result to return
3304
    if (pResBlock->info.rows > 0) {
3305 3306
      // 1. The result in current group not reach the threshold of output result, continue
      // 2. If multiple group results existing in one SSDataBlock is not allowed, return immediately
3307 3308
      if (pResBlock->info.rows > pResultInfo->threshold || pBlock == NULL || (!pInfo->multigroupResult)) {
        return pResBlock;
3309 3310
      }

3311
      doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
3312 3313
      if (pResBlock->info.rows > pOperator->resultInfo.threshold || pBlock == NULL) {
        return pResBlock;
3314 3315 3316
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
3317
      doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
3318 3319
      if (pResBlock->info.rows > pResultInfo->threshold) {
        return pResBlock;
3320 3321 3322 3323 3324 3325 3326
      }
    } else {
      return NULL;
    }
  }
}

H
Haojun Liao 已提交
3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337
static void destroyExprInfo(SExprInfo* pExpr, int32_t numOfExprs) {
  for (int32_t i = 0; i < numOfExprs; ++i) {
    SExprInfo* pExprInfo = &pExpr[i];
    if (pExprInfo->pExpr->nodeType == QUERY_NODE_COLUMN) {
      taosMemoryFree(pExprInfo->base.pParam[0].pCol);
    }
    taosMemoryFree(pExprInfo->base.pParam);
    taosMemoryFree(pExprInfo->pExpr);
  }
}

3338 3339 3340 3341 3342
static void destroyOperatorInfo(SOperatorInfo* pOperator) {
  if (pOperator == NULL) {
    return;
  }

3343
  if (pOperator->fpSet.closeFn != NULL) {
3344
    pOperator->fpSet.closeFn(pOperator->info, pOperator->exprSupp.numOfExprs);
3345 3346
  }

H
Haojun Liao 已提交
3347
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
3348
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
3349
      destroyOperatorInfo(pOperator->pDownstream[i]);
3350 3351
    }

wafwerar's avatar
wafwerar 已提交
3352
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
3353
    pOperator->numOfDownstream = 0;
3354 3355
  }

3356 3357
  if (pOperator->exprSupp.pExprInfo != NULL) {
    destroyExprInfo(pOperator->exprSupp.pExprInfo, pOperator->exprSupp.numOfExprs);
H
Haojun Liao 已提交
3358 3359
  }

3360
  taosMemoryFreeClear(pOperator->exprSupp.pExprInfo);
wafwerar's avatar
wafwerar 已提交
3361 3362
  taosMemoryFreeClear(pOperator->info);
  taosMemoryFreeClear(pOperator);
3363 3364
}

3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379
int32_t getBufferPgSize(int32_t rowSize, uint32_t* defaultPgsz, uint32_t* defaultBufsz) {
  *defaultPgsz = 4096;
  while (*defaultPgsz < rowSize * 4) {
    *defaultPgsz <<= 1u;
  }

  // at least four pages need to be in buffer
  *defaultBufsz = 4096 * 256;
  if ((*defaultBufsz) <= (*defaultPgsz)) {
    (*defaultBufsz) = (*defaultPgsz) * 4;
  }

  return 0;
}

dengyihao's avatar
dengyihao 已提交
3380 3381
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                         const char* pKey) {
3382 3383
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

dengyihao's avatar
dengyihao 已提交
3384 3385
  pAggSup->resultRowSize = getResultRowSize(pCtx, numOfOutput);
  pAggSup->keyBuf = taosMemoryCalloc(1, keyBufSize + POINTER_BYTES + sizeof(int64_t));
3386 3387
  pAggSup->pResultRowHashTable = taosHashInit(10, hashFn, true, HASH_NO_LOCK);

H
Haojun Liao 已提交
3388
  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowHashTable == NULL) {
3389 3390 3391
    return TSDB_CODE_OUT_OF_MEMORY;
  }

dengyihao's avatar
dengyihao 已提交
3392
  uint32_t defaultPgsz = 0;
3393 3394
  uint32_t defaultBufsz = 0;
  getBufferPgSize(pAggSup->resultRowSize, &defaultPgsz, &defaultBufsz);
H
Haojun Liao 已提交
3395

3396
  int32_t code = createDiskbasedBuf(&pAggSup->pResultBuf, defaultPgsz, defaultBufsz, pKey, TD_TMP_DIR_PATH);
H
Haojun Liao 已提交
3397 3398 3399 3400
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

3401 3402 3403
  return TSDB_CODE_SUCCESS;
}

3404
void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
3405
  taosMemoryFreeClear(pAggSup->keyBuf);
3406
  taosHashCleanup(pAggSup->pResultRowHashTable);
H
Haojun Liao 已提交
3407
  destroyDiskbasedBuf(pAggSup->pResultBuf);
3408 3409
}

L
Liu Jicong 已提交
3410 3411
int32_t initAggInfo(SExprSupp* pSup, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols, size_t keyBufSize,
                    const char* pkey) {
3412 3413 3414 3415 3416
  int32_t code = initExprSupp(pSup, pExprInfo, numOfCols);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

3417
  doInitAggInfoSup(pAggSup, pSup->pCtx, numOfCols, keyBufSize, pkey);
L
Liu Jicong 已提交
3418
  for (int32_t i = 0; i < numOfCols; ++i) {
3419
    pSup->pCtx[i].pBuf = pAggSup->pResultBuf;
3420 3421
  }

3422
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
3423 3424
}

3425 3426 3427 3428 3429 3430 3431 3432 3433
void initResultSizeInfo(SOperatorInfo* pOperator, int32_t numOfRows) {
  pOperator->resultInfo.capacity = numOfRows;
  pOperator->resultInfo.threshold = numOfRows * 0.75;

  if (pOperator->resultInfo.threshold == 0) {
    pOperator->resultInfo.capacity = numOfRows;
  }
}

3434 3435 3436 3437 3438
void initBasicInfo(SOptrBasicInfo* pInfo, SSDataBlock* pBlock) {
  pInfo->pRes = pBlock;
  initResultRowInfo(&pInfo->resultRowInfo);
}

3439
int32_t initExprSupp(SExprSupp* pSup, SExprInfo* pExprInfo, int32_t numOfExpr) {
3440 3441 3442 3443
  pSup->pExprInfo = pExprInfo;
  pSup->numOfExprs = numOfExpr;
  if (pSup->pExprInfo != NULL) {
    pSup->pCtx = createSqlFunctionCtx(pExprInfo, numOfExpr, &pSup->rowEntryInfoOffset);
3444 3445 3446
    if (pSup->pCtx == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
3447
  }
3448 3449

  return TSDB_CODE_SUCCESS;
3450 3451
}

L
Liu Jicong 已提交
3452
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
3453
                                           SSDataBlock* pResultBlock, SExprInfo* pScalarExprInfo,
wmmhello's avatar
wmmhello 已提交
3454
                                           int32_t numOfScalarExpr, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
3455
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
3456
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
3457 3458 3459
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
3460

3461
  int32_t numOfRows = 1024;
dengyihao's avatar
dengyihao 已提交
3462
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
3463 3464

  initResultSizeInfo(pOperator, numOfRows);
3465
  int32_t code = initAggInfo(&pOperator->exprSupp, &pInfo->aggSup, pExprInfo, numOfCols, keyBufSize, pTaskInfo->id.str);
L
Liu Jicong 已提交
3466
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3467 3468
    goto _error;
  }
H
Haojun Liao 已提交
3469

3470
  initBasicInfo(&pInfo->binfo, pResultBlock);
3471 3472 3473 3474
  code = initExprSupp(&pInfo->scalarExprSup, pScalarExprInfo, numOfScalarExpr);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
3475

L
Liu Jicong 已提交
3476
  pInfo->groupId = INT32_MIN;
dengyihao's avatar
dengyihao 已提交
3477
  pOperator->name = "TableAggregate";
3478
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_HASH_AGG;
3479
  pOperator->blocking = true;
dengyihao's avatar
dengyihao 已提交
3480 3481 3482
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
3483

3484 3485
  pOperator->fpSet = createOperatorFpSet(doOpenAggregateOptr, getAggregateResult, NULL, NULL, destroyAggOperatorInfo,
                                         aggEncodeResultRow, aggDecodeResultRow, NULL);
H
Haojun Liao 已提交
3486 3487 3488 3489 3490

  code = appendDownstream(pOperator, &downstream, 1);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
3491 3492

  return pOperator;
L
Liu Jicong 已提交
3493
_error:
H
Haojun Liao 已提交
3494
  destroyAggOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
3495 3496
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
3497 3498
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
3499 3500
}

3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519
static void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  if (pCtx == NULL) {
    return NULL;
  }

  for (int32_t i = 0; i < numOfOutput; ++i) {
    for (int32_t j = 0; j < pCtx[i].numOfParams; ++j) {
      taosVariantDestroy(&pCtx[i].param[j].param);
    }

    taosMemoryFreeClear(pCtx[i].subsidiaries.pCtx);
    taosMemoryFree(pCtx[i].input.pData);
    taosMemoryFree(pCtx[i].input.pColumnDataAgg);
  }

  taosMemoryFreeClear(pCtx);
  return NULL;
}

3520
void cleanupBasicInfo(SOptrBasicInfo* pInfo) {
3521 3522
  assert(pInfo != NULL);
  cleanupResultRowInfo(&pInfo->resultRowInfo);
H
Haojun Liao 已提交
3523
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
3524 3525
}

H
Haojun Liao 已提交
3526
void destroyBasicOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3527
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)param;
3528
  cleanupBasicInfo(pInfo);
3529
}
H
Haojun Liao 已提交
3530 3531

void destroyAggOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3532
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
3533
  cleanupBasicInfo(&pInfo->binfo);
3534
}
3535

H
Haojun Liao 已提交
3536
void destroySFillOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3537
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
3538
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
3539
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
wafwerar's avatar
wafwerar 已提交
3540
  taosMemoryFreeClear(pInfo->p);
3541 3542
}

H
Haojun Liao 已提交
3543
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput) {
D
fix bug  
dapan 已提交
3544 3545 3546
  if (NULL == param) {
    return;
  }
L
Liu Jicong 已提交
3547
  SProjectOperatorInfo* pInfo = (SProjectOperatorInfo*)param;
3548
  cleanupBasicInfo(&pInfo->binfo);
H
Haojun Liao 已提交
3549
  cleanupAggSup(&pInfo->aggSup);
H
Haojun Liao 已提交
3550
  taosArrayDestroy(pInfo->pPseudoColInfo);
3551 3552
}

3553
void cleanupExecSupp(SExprSupp* pSupp) {
3554 3555 3556 3557 3558 3559
  destroySqlFunctionCtx(pSupp->pCtx, pSupp->numOfExprs);
  destroyExprInfo(pSupp->pExprInfo, pSupp->numOfExprs);

  taosMemoryFree(pSupp->rowEntryInfoOffset);
}

H
Haojun Liao 已提交
3560
static void destroyIndefinitOperatorInfo(void* param, int32_t numOfOutput) {
3561
  SIndefOperatorInfo* pInfo = (SIndefOperatorInfo*)param;
3562
  cleanupBasicInfo(&pInfo->binfo);
H
Haojun Liao 已提交
3563 3564 3565

  taosArrayDestroy(pInfo->pPseudoColInfo);
  cleanupAggSup(&pInfo->aggSup);
3566
  cleanupExecSupp(&pInfo->scalarSup);
H
Haojun Liao 已提交
3567 3568
}

H
Haojun Liao 已提交
3569
void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3570
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
3571 3572 3573 3574
  taosRemoveRef(exchangeObjRefPool, pExInfo->self);
}

void doDestroyExchangeOperatorInfo(void* param) {
X
Xiaoyu Wang 已提交
3575
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
3576

H
Haojun Liao 已提交
3577 3578 3579 3580 3581 3582 3583 3584 3585
  taosArrayDestroy(pExInfo->pSources);
  taosArrayDestroy(pExInfo->pSourceDataInfo);
  if (pExInfo->pResult != NULL) {
    blockDataDestroy(pExInfo->pResult);
  }

  tsem_destroy(&pExInfo->ready);
}

H
Haojun Liao 已提交
3586 3587
static SArray* setRowTsColumnOutputInfo(SqlFunctionCtx* pCtx, int32_t numOfCols) {
  SArray* pList = taosArrayInit(4, sizeof(int32_t));
dengyihao's avatar
dengyihao 已提交
3588
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
3589 3590 3591 3592 3593 3594 3595 3596
    if (fmIsPseudoColumnFunc(pCtx[i].functionId)) {
      taosArrayPush(pList, &i);
    }
  }

  return pList;
}

L
Liu Jicong 已提交
3597
SOperatorInfo* createProjectOperatorInfo(SOperatorInfo* downstream, SProjectPhysiNode* pProjPhyNode,
dengyihao's avatar
dengyihao 已提交
3598
                                         SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
3599
  SProjectOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SProjectOperatorInfo));
L
Liu Jicong 已提交
3600
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
3601 3602 3603
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
3604

L
Liu Jicong 已提交
3605
  int32_t    numOfCols = 0;
3606 3607 3608 3609 3610 3611
  SExprInfo* pExprInfo = createExprInfo(pProjPhyNode->pProjections, NULL, &numOfCols);

  SSDataBlock* pResBlock = createResDataBlock(pProjPhyNode->node.pOutputDataBlockDesc);
  SLimit       limit = {.limit = pProjPhyNode->limit, .offset = pProjPhyNode->offset};
  SLimit       slimit = {.limit = pProjPhyNode->slimit, .offset = pProjPhyNode->soffset};

L
Liu Jicong 已提交
3612 3613 3614 3615
  pInfo->limit = limit;
  pInfo->slimit = slimit;
  pInfo->curOffset = limit.offset;
  pInfo->curSOffset = slimit.offset;
H
Haojun Liao 已提交
3616
  pInfo->binfo.pRes = pResBlock;
3617
  pInfo->pFilterNode = pProjPhyNode->node.pConditions;
H
Haojun Liao 已提交
3618 3619

  int32_t numOfRows = 4096;
dengyihao's avatar
dengyihao 已提交
3620
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
3621

3622 3623 3624 3625 3626
  // Make sure the size of SSDataBlock will never exceed the size of 2MB.
  int32_t TWOMB = 2 * 1024 * 1024;
  if (numOfRows * pResBlock->info.rowSize > TWOMB) {
    numOfRows = TWOMB / pResBlock->info.rowSize;
  }
3627
  initResultSizeInfo(pOperator, numOfRows);
3628

3629 3630
  initAggInfo(&pOperator->exprSupp, &pInfo->aggSup, pExprInfo, numOfCols, keyBufSize, pTaskInfo->id.str);
  initBasicInfo(&pInfo->binfo, pResBlock);
3631
  setFunctionResultOutput(pOperator, &pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, numOfCols);
3632

3633
  pInfo->pPseudoColInfo = setRowTsColumnOutputInfo(pOperator->exprSupp.pCtx, numOfCols);
X
Xiaoyu Wang 已提交
3634
  pOperator->name = "ProjectOperator";
H
Haojun Liao 已提交
3635
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
X
Xiaoyu Wang 已提交
3636 3637 3638 3639
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
3640

L
Liu Jicong 已提交
3641 3642
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doProjectOperation, NULL, NULL,
                                         destroyProjectOperatorInfo, NULL, NULL, NULL);
L
Liu Jicong 已提交
3643

3644
  int32_t code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
3645
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3646 3647
    goto _error;
  }
3648 3649

  return pOperator;
H
Haojun Liao 已提交
3650

L
Liu Jicong 已提交
3651
_error:
H
Haojun Liao 已提交
3652 3653
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
3654 3655
}

H
Haojun Liao 已提交
3656 3657
static SSDataBlock* doApplyIndefinitFunction(SOperatorInfo* pOperator) {
  SIndefOperatorInfo* pIndefInfo = pOperator->info;
3658
  SOptrBasicInfo*     pInfo = &pIndefInfo->binfo;
L
Liu Jicong 已提交
3659
  SExprSupp*          pSup = &pOperator->exprSupp;
H
Haojun Liao 已提交
3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693

  SSDataBlock* pRes = pInfo->pRes;
  blockDataCleanup(pRes);

  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  int64_t st = 0;
  int32_t order = 0;
  int32_t scanFlag = 0;

  if (pOperator->cost.openCost == 0) {
    st = taosGetTimestampUs();
  }

  SOperatorInfo* downstream = pOperator->pDownstream[0];

  while (1) {
    // The downstream exec may change the value of the newgroup, so use a local variable instead.
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
    if (pBlock == NULL) {
      doSetOperatorCompleted(pOperator);
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
    int32_t code = getTableScanInfo(pOperator->pDownstream[0], &order, &scanFlag);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }

    // there is an scalar expression that needs to be calculated before apply the group aggregation.
3694
    SExprSupp* pScalarSup = &pIndefInfo->scalarSup;
3695 3696
    if (pScalarSup->pExprInfo != NULL) {
      code = projectApplyFunctions(pScalarSup->pExprInfo, pBlock, pBlock, pScalarSup->pCtx, pScalarSup->numOfExprs,
L
Liu Jicong 已提交
3697
                                   pIndefInfo->pPseudoColInfo);
H
Haojun Liao 已提交
3698 3699 3700 3701 3702
      if (code != TSDB_CODE_SUCCESS) {
        longjmp(pTaskInfo->env, code);
      }
    }

3703
    setInputDataBlock(pOperator, pSup->pCtx, pBlock, order, scanFlag, false);
H
Haojun Liao 已提交
3704 3705
    blockDataEnsureCapacity(pInfo->pRes, pInfo->pRes->info.rows + pBlock->info.rows);

L
Liu Jicong 已提交
3706 3707
    code = projectApplyFunctions(pOperator->exprSupp.pExprInfo, pInfo->pRes, pBlock, pSup->pCtx,
                                 pOperator->exprSupp.numOfExprs, pIndefInfo->pPseudoColInfo);
H
Haojun Liao 已提交
3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
  }

  size_t rows = pInfo->pRes->info.rows;
  pOperator->resultInfo.totalRows += rows;

  if (pOperator->cost.openCost == 0) {
    pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
  }

  return (rows > 0) ? pInfo->pRes : NULL;
}

3723 3724
SOperatorInfo* createIndefinitOutputOperatorInfo(SOperatorInfo* downstream, SPhysiNode* pNode,
                                                 SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
3725
  SIndefOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SIndefOperatorInfo));
3726
  SOperatorInfo*      pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
3727 3728 3729 3730
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

3731 3732
  SExprSupp* pSup = &pOperator->exprSupp;

H
Haojun Liao 已提交
3733 3734 3735
  SIndefRowsFuncPhysiNode* pPhyNode = (SIndefRowsFuncPhysiNode*)pNode;

  int32_t    numOfExpr = 0;
X
Xiaoyu Wang 已提交
3736
  SExprInfo* pExprInfo = createExprInfo(pPhyNode->pFuncs, NULL, &numOfExpr);
H
Haojun Liao 已提交
3737 3738

  if (pPhyNode->pExprs != NULL) {
3739
    int32_t    num = 0;
3740
    SExprInfo* pSExpr = createExprInfo(pPhyNode->pExprs, NULL, &num);
3741
    int32_t    code = initExprSupp(&pInfo->scalarSup, pSExpr, num);
3742 3743 3744
    if (code != TSDB_CODE_SUCCESS) {
      goto _error;
    }
H
Haojun Liao 已提交
3745 3746
  }

3747
  SSDataBlock* pResBlock = createResDataBlock(pPhyNode->node.pOutputDataBlockDesc);
H
Haojun Liao 已提交
3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758

  int32_t numOfRows = 4096;
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;

  // Make sure the size of SSDataBlock will never exceed the size of 2MB.
  int32_t TWOMB = 2 * 1024 * 1024;
  if (numOfRows * pResBlock->info.rowSize > TWOMB) {
    numOfRows = TWOMB / pResBlock->info.rowSize;
  }
  initResultSizeInfo(pOperator, numOfRows);

3759 3760 3761
  initAggInfo(&pOperator->exprSupp, &pInfo->aggSup, pExprInfo, numOfExpr, keyBufSize, pTaskInfo->id.str);
  initBasicInfo(&pInfo->binfo, pResBlock);

3762
  setFunctionResultOutput(pOperator, &pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, numOfExpr);
H
Haojun Liao 已提交
3763

3764 3765
  pInfo->binfo.pRes = pResBlock;
  pInfo->pPseudoColInfo = setRowTsColumnOutputInfo(pSup->pCtx, numOfExpr);
H
Haojun Liao 已提交
3766

3767
  pOperator->name = "IndefinitOperator";
H
Haojun Liao 已提交
3768
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
3769 3770 3771
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
3772
  pOperator->exprSupp.numOfExprs = numOfExpr;
3773
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784

  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doApplyIndefinitFunction, NULL, NULL,
                                         destroyIndefinitOperatorInfo, NULL, NULL, NULL);

  int32_t code = appendDownstream(pOperator, &downstream, 1);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

  return pOperator;

3785
_error:
H
Haojun Liao 已提交
3786 3787 3788 3789 3790 3791
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
}

3792
static int32_t initFillInfo(SFillOperatorInfo* pInfo, SExprInfo* pExpr, int32_t numOfCols, SNodeListNode* pValNode,
L
Liu Jicong 已提交
3793
                            STimeWindow win, int32_t capacity, const char* id, SInterval* pInterval, int32_t fillType) {
3794
  SFillColInfo* pColInfo = createFillColInfo(pExpr, numOfCols, pValNode);
H
Haojun Liao 已提交
3795 3796

  STimeWindow w = TSWINDOW_INITIALIZER;
3797
  getAlignQueryTimeWindow(pInterval, pInterval->precision, win.skey, &w);
H
Haojun Liao 已提交
3798 3799

  int32_t order = TSDB_ORDER_ASC;
3800
  pInfo->pFillInfo = taosCreateFillInfo(order, w.skey, 0, capacity, numOfCols, pInterval, fillType, pColInfo, id);
H
Haojun Liao 已提交
3801

wafwerar's avatar
wafwerar 已提交
3802
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
H
Haojun Liao 已提交
3803
  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
H
Haojun Liao 已提交
3804 3805
    taosMemoryFree(pInfo->pFillInfo);
    taosMemoryFree(pInfo->p);
H
Haojun Liao 已提交
3806 3807 3808 3809 3810 3811
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

3812 3813 3814 3815 3816 3817 3818 3819
SOperatorInfo* createFillOperatorInfo(SOperatorInfo* downstream, SFillPhysiNode* pPhyFillNode, bool multigroupResult,
                                      SExecTaskInfo* pTaskInfo) {
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

L
Liu Jicong 已提交
3820 3821 3822 3823 3824
  int32_t      num = 0;
  SSDataBlock* pResBlock = createResDataBlock(pPhyFillNode->node.pOutputDataBlockDesc);
  SExprInfo*   pExprInfo = createExprInfo(pPhyFillNode->pTargets, NULL, &num);
  SInterval*   pInterval = &((SIntervalAggOperatorInfo*)downstream->info)->interval;
  int32_t      type = convertFillType(pPhyFillNode->mode);
3825

H
Haojun Liao 已提交
3826
  SResultInfo* pResultInfo = &pOperator->resultInfo;
3827 3828
  initResultSizeInfo(pOperator, 4096);

3829 3830
  int32_t code = initFillInfo(pInfo, pExprInfo, num, (SNodeListNode*)pPhyFillNode->pValues, pPhyFillNode->timeRange,
                              pResultInfo->capacity, pTaskInfo->id.str, pInterval, type);
3831 3832 3833
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
3834

L
Liu Jicong 已提交
3835
  pInfo->pRes = pResBlock;
3836
  pInfo->multigroupResult = multigroupResult;
dengyihao's avatar
dengyihao 已提交
3837
  pOperator->name = "FillOperator";
3838
  pOperator->blocking = false;
dengyihao's avatar
dengyihao 已提交
3839
  pOperator->status = OP_NOT_OPENED;
3840
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_FILL;
3841 3842 3843 3844
  pOperator->exprSupp.pExprInfo = pExprInfo;
  pOperator->exprSupp.numOfExprs = num;
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
3845

L
Liu Jicong 已提交
3846 3847
  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doFill, NULL, NULL, destroySFillOperatorInfo, NULL, NULL, NULL);
3848

3849
  code = appendDownstream(pOperator, &downstream, 1);
3850
  return pOperator;
H
Haojun Liao 已提交
3851

L
Liu Jicong 已提交
3852
_error:
wafwerar's avatar
wafwerar 已提交
3853 3854
  taosMemoryFreeClear(pOperator);
  taosMemoryFreeClear(pInfo);
H
Haojun Liao 已提交
3855
  return NULL;
3856 3857
}

D
dapan1121 已提交
3858
static SExecTaskInfo* createExecTaskInfo(uint64_t queryId, uint64_t taskId, EOPTR_EXEC_MODEL model, char* dbFName) {
wafwerar's avatar
wafwerar 已提交
3859
  SExecTaskInfo* pTaskInfo = taosMemoryCalloc(1, sizeof(SExecTaskInfo));
3860
  setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
3861

D
dapan1121 已提交
3862
  pTaskInfo->schemaVer.dbname = strdup(dbFName);
3863
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
3864
  pTaskInfo->id.queryId = queryId;
dengyihao's avatar
dengyihao 已提交
3865
  pTaskInfo->execModel = model;
H
Haojun Liao 已提交
3866

wafwerar's avatar
wafwerar 已提交
3867
  char* p = taosMemoryCalloc(1, 128);
L
Liu Jicong 已提交
3868
  snprintf(p, 128, "TID:0x%" PRIx64 " QID:0x%" PRIx64, taskId, queryId);
H
Haojun Liao 已提交
3869
  pTaskInfo->id.str = p;
H
Haojun Liao 已提交
3870

3871 3872
  return pTaskInfo;
}
H
Haojun Liao 已提交
3873

L
Liu Jicong 已提交
3874
static tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
wmmhello's avatar
wmmhello 已提交
3875
                                      STableListInfo* pTableListInfo, uint64_t queryId, uint64_t taskId);
H
Haojun Liao 已提交
3876

H
Haojun Liao 已提交
3877
static SArray* extractColumnInfo(SNodeList* pNodeList);
3878

D
dapan1121 已提交
3879
int32_t extractTableSchemaVersion(SReadHandle* pHandle, uint64_t uid, SExecTaskInfo* pTaskInfo) {
3880 3881
  SMetaReader mr = {0};
  metaReaderInit(&mr, pHandle->meta, 0);
D
dapan1121 已提交
3882 3883 3884 3885 3886
  int32_t code = metaGetTableEntryByUid(&mr, uid);
  if (code) {
    metaReaderClear(&mr);
    return code;
  }
3887 3888 3889 3890

  pTaskInfo->schemaVer.tablename = strdup(mr.me.name);

  if (mr.me.type == TSDB_SUPER_TABLE) {
3891 3892
    pTaskInfo->schemaVer.sversion = mr.me.stbEntry.schemaRow.version;
    pTaskInfo->schemaVer.tversion = mr.me.stbEntry.schemaTag.version;
3893 3894 3895
  } else if (mr.me.type == TSDB_CHILD_TABLE) {
    tb_uid_t suid = mr.me.ctbEntry.suid;
    metaGetTableEntryByUid(&mr, suid);
3896 3897
    pTaskInfo->schemaVer.sversion = mr.me.stbEntry.schemaRow.version;
    pTaskInfo->schemaVer.tversion = mr.me.stbEntry.schemaTag.version;
3898
  } else {
3899
    pTaskInfo->schemaVer.sversion = mr.me.ntbEntry.schemaRow.version;
3900
  }
3901 3902

  metaReaderClear(&mr);
D
dapan1121 已提交
3903 3904

  return TSDB_CODE_SUCCESS;
3905 3906
}

X
Xiaoyu Wang 已提交
3907 3908
int32_t generateGroupIdMap(STableListInfo* pTableListInfo, SReadHandle* pHandle, SArray* groupKey) {
  if (groupKey == NULL) {
wmmhello's avatar
wmmhello 已提交
3909 3910 3911 3912 3913 3914 3915 3916
    return TDB_CODE_SUCCESS;
  }

  pTableListInfo->map = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  if (pTableListInfo->map == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  int32_t keyLen = 0;
X
Xiaoyu Wang 已提交
3917
  void*   keyBuf = NULL;
wmmhello's avatar
wmmhello 已提交
3918 3919 3920
  int32_t numOfGroupCols = taosArrayGetSize(groupKey);
  for (int32_t j = 0; j < numOfGroupCols; ++j) {
    SColumn* pCol = taosArrayGet(groupKey, j);
X
Xiaoyu Wang 已提交
3921
    keyLen += pCol->bytes;  // actual data + null_flag
wmmhello's avatar
wmmhello 已提交
3922 3923 3924 3925 3926 3927 3928 3929 3930 3931
  }

  int32_t nullFlagSize = sizeof(int8_t) * numOfGroupCols;
  keyLen += nullFlagSize;

  keyBuf = taosMemoryCalloc(1, keyLen);
  if (keyBuf == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

X
Xiaoyu Wang 已提交
3932 3933 3934
  for (int32_t i = 0; i < taosArrayGetSize(pTableListInfo->pTableList); i++) {
    STableKeyInfo* info = taosArrayGet(pTableListInfo->pTableList, i);
    SMetaReader    mr = {0};
wmmhello's avatar
wmmhello 已提交
3935 3936 3937 3938 3939 3940 3941 3942
    metaReaderInit(&mr, pHandle->meta, 0);
    metaGetTableEntryByUid(&mr, info->uid);

    char* isNull = (char*)keyBuf;
    char* pStart = (char*)keyBuf + sizeof(int8_t) * numOfGroupCols;
    for (int32_t j = 0; j < numOfGroupCols; ++j) {
      SColumn* pCol = taosArrayGet(groupKey, j);

X
Xiaoyu Wang 已提交
3943
      if (strcmp(pCol->name, "tbname") == 0) {
wmmhello's avatar
wmmhello 已提交
3944 3945 3946
        isNull[i] = 0;
        memcpy(pStart, mr.me.name, strlen(mr.me.name));
        pStart += strlen(mr.me.name);
X
Xiaoyu Wang 已提交
3947
      } else {
wmmhello's avatar
wmmhello 已提交
3948 3949 3950
        STagVal tagVal = {0};
        tagVal.cid = pCol->colId;
        const char* p = metaGetTableTagVal(&mr.me, pCol->type, &tagVal);
X
Xiaoyu Wang 已提交
3951
        if (p == NULL) {
wmmhello's avatar
wmmhello 已提交
3952 3953 3954 3955 3956
          isNull[j] = 1;
          continue;
        }
        isNull[i] = 0;
        if (pCol->type == TSDB_DATA_TYPE_JSON) {
X
Xiaoyu Wang 已提交
3957 3958 3959
          //          int32_t dataLen = getJsonValueLen(pkey->pData);
          //          memcpy(pStart, (pkey->pData), dataLen);
          //          pStart += dataLen;
wmmhello's avatar
wmmhello 已提交
3960 3961 3962 3963 3964 3965 3966 3967 3968 3969
        } else if (IS_VAR_DATA_TYPE(pCol->type)) {
          memcpy(pStart, tagVal.pData, tagVal.nData);
          pStart += tagVal.nData;
          ASSERT(tagVal.nData <= pCol->bytes);
        } else {
          memcpy(pStart, &(tagVal.i64), pCol->bytes);
          pStart += pCol->bytes;
        }
      }
    }
X
Xiaoyu Wang 已提交
3970
    int32_t   len = (int32_t)(pStart - (char*)keyBuf);
3971 3972 3973 3974

    uint64_t* pGroupId = taosHashGet(pTableListInfo->map, keyBuf, len);

    if (!pGroupId) {
wmmhello's avatar
wmmhello 已提交
3975
      uint64_t tmpId = calcGroupId(keyBuf, len);
3976
      info->groupId = tmpId;
wmmhello's avatar
wmmhello 已提交
3977
      taosHashPut(pTableListInfo->map, &(info->uid), sizeof(uint64_t), &tmpId, sizeof(uint64_t));
3978 3979
    } else {
      info->groupId = *pGroupId;
wmmhello's avatar
wmmhello 已提交
3980 3981 3982 3983 3984 3985 3986 3987
    }

    metaReaderClear(&mr);
  }
  taosMemoryFree(keyBuf);
  return TDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
3988
SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle,
wmmhello's avatar
wmmhello 已提交
3989
                                  uint64_t queryId, uint64_t taskId, STableListInfo* pTableListInfo) {
3990 3991
  int32_t type = nodeType(pPhyNode);

X
Xiaoyu Wang 已提交
3992
  if (pPhyNode->pChildren == NULL || LIST_LENGTH(pPhyNode->pChildren) == 0) {
H
Haojun Liao 已提交
3993
    if (QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN == type) {
dengyihao's avatar
dengyihao 已提交
3994
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
3995

dengyihao's avatar
dengyihao 已提交
3996
      tsdbReaderT pDataReader =
wmmhello's avatar
wmmhello 已提交
3997
          doCreateDataReader(pTableScanNode, pHandle, pTableListInfo, (uint64_t)queryId, taskId);
3998
      if (pDataReader == NULL && terrno != 0) {
3999
        pTaskInfo->code = terrno;
4000 4001
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
4002

D
dapan1121 已提交
4003 4004 4005
      int32_t code = extractTableSchemaVersion(pHandle, pTableScanNode->scan.uid, pTaskInfo);
      if (code) {
        tsdbCleanupReadHandle(pDataReader);
4006
        pTaskInfo->code = terrno;
D
dapan1121 已提交
4007 4008
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
4009

X
Xiaoyu Wang 已提交
4010
      SArray* groupKeys = extractPartitionColInfo(pTableScanNode->pPartitionTags);
S
slzhou 已提交
4011
      code = generateGroupIdMap(pTableListInfo, pHandle, groupKeys);  // todo for json
4012
      taosArrayDestroy(groupKeys);
S
slzhou 已提交
4013
      if (code) {
wmmhello's avatar
wmmhello 已提交
4014
        tsdbCleanupReadHandle(pDataReader);
4015
        pTaskInfo->code = terrno;
wmmhello's avatar
wmmhello 已提交
4016 4017 4018
        return NULL;
      }

X
Xiaoyu Wang 已提交
4019
      SOperatorInfo*  pOperator = createTableScanOperatorInfo(pTableScanNode, pDataReader, pHandle, pTaskInfo);
4020 4021
      STableScanInfo* pScanInfo = pOperator->info;
      pTaskInfo->cost.pRecoder = &pScanInfo->readRecorder;
S
slzhou 已提交
4022 4023 4024
      return pOperator;
    } else if (QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN == type) {
      STableMergeScanPhysiNode* pTableScanNode = (STableMergeScanPhysiNode*)pPhyNode;
wmmhello's avatar
wmmhello 已提交
4025
      createScanTableListInfo(pTableScanNode, pHandle, pTableListInfo, queryId, taskId);
S
shenglian zhou 已提交
4026
      extractTableSchemaVersion(pHandle, pTableScanNode->scan.uid, pTaskInfo);
4027
      SOperatorInfo*  pOperator = createTableMergeScanOperatorInfo(pTableScanNode, pTableListInfo, pHandle, pTaskInfo, queryId, taskId);
4028 4029 4030
      STableScanInfo* pScanInfo = pOperator->info;
      pTaskInfo->cost.pRecoder = &pScanInfo->readRecorder;
      return pOperator;
H
Haojun Liao 已提交
4031
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == type) {
4032
      return createExchangeOperatorInfo(pHandle->pMsgCb->clientRpc, (SExchangePhysiNode*)pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
4033
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == type) {
X
Xiaoyu Wang 已提交
4034
      SScanPhysiNode*      pScanPhyNode = (SScanPhysiNode*)pPhyNode;  // simple child table.
5
54liuyao 已提交
4035
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
4036
      STimeWindowAggSupp   twSup = {
L
Liu Jicong 已提交
4037 4038 4039 4040
            .waterMark = pTableScanNode->watermark,
            .calTrigger = pTableScanNode->triggerType,
            .maxTs = INT64_MIN,
      };
5
54liuyao 已提交
4041
      tsdbReaderT pDataReader = NULL;
L
Liu Jicong 已提交
4042 4043

      if (pHandle) {
L
Liu Jicong 已提交
4044
        if (pHandle->vnode) {
L
Liu Jicong 已提交
4045
          // for stram
L
Liu Jicong 已提交
4046
          pDataReader =
wmmhello's avatar
wmmhello 已提交
4047
              doCreateDataReader(pTableScanNode, pHandle, pTableListInfo, (uint64_t)queryId, taskId);
L
Liu Jicong 已提交
4048
        } else {
L
Liu Jicong 已提交
4049
          // for tq
wmmhello's avatar
wmmhello 已提交
4050
          getTableList(pHandle->meta, pScanPhyNode, pTableListInfo);
L
Liu Jicong 已提交
4051
        }
5
54liuyao 已提交
4052
      }
4053

5
54liuyao 已提交
4054
      if (pDataReader == NULL && terrno != 0) {
4055
        qDebug("%s pDataReader is NULL", GET_TASKID(pTaskInfo));
5
54liuyao 已提交
4056 4057
        // return NULL;
      } else {
4058
        qDebug("%s pDataReader is not NULL", GET_TASKID(pTaskInfo));
5
54liuyao 已提交
4059
      }
4060

X
Xiaoyu Wang 已提交
4061 4062
      SArray* groupKeys = extractPartitionColInfo(pTableScanNode->pPartitionTags);
      int32_t code = generateGroupIdMap(pTableListInfo, pHandle, groupKeys);  // todo for json
4063
      taosArrayDestroy(groupKeys);
X
Xiaoyu Wang 已提交
4064
      if (code) {
4065 4066 4067
        tsdbCleanupReadHandle(pDataReader);
        return NULL;
      }
4068

X
Xiaoyu Wang 已提交
4069
      SOperatorInfo* pOperator = createStreamScanOperatorInfo(pDataReader, pHandle, pTableScanNode, pTaskInfo, &twSup);
4070

H
Haojun Liao 已提交
4071
      return pOperator;
H
Haojun Liao 已提交
4072
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == type) {
L
Liu Jicong 已提交
4073
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
4074
      return createSysTableScanOperatorInfo(pHandle, pSysScanPhyNode, pTaskInfo);
4075
    } else if (QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN == type) {
X
Xiaoyu Wang 已提交
4076
      STagScanPhysiNode* pScanPhyNode = (STagScanPhysiNode*)pPhyNode;
4077

wmmhello's avatar
wmmhello 已提交
4078
      int32_t code = getTableList(pHandle->meta, pScanPhyNode, pTableListInfo);
4079
      if (code != TSDB_CODE_SUCCESS) {
4080
        pTaskInfo->code = terrno;
4081 4082 4083
        return NULL;
      }

4084
      return createTagScanOperatorInfo(pHandle, pScanPhyNode, pTableListInfo, pTaskInfo);
4085
    } else if (QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN == type) {
4086
      SBlockDistScanPhysiNode* pBlockNode = (SBlockDistScanPhysiNode*)pPhyNode;
4087 4088 4089 4090 4091 4092 4093 4094 4095
      pTableListInfo->pTableList = taosArrayInit(4, sizeof(STableKeyInfo));

      if (pBlockNode->tableType == TSDB_SUPER_TABLE) {
        int32_t code = tsdbGetAllTableList(pHandle->meta, pBlockNode->uid, pTableListInfo->pTableList);
        if (code != TSDB_CODE_SUCCESS) {
          pTaskInfo->code = terrno;
          return NULL;
        }
      } else {  // Create one table group.
4096
        STableKeyInfo info = {.lastKey = 0, .uid = pBlockNode->uid, .groupId = 0};
4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123
        taosArrayPush(pTableListInfo->pTableList, &info);
      }

      SQueryTableDataCond cond = {0};

      {
        cond.order = TSDB_ORDER_ASC;
        cond.numOfCols = 1;
        cond.colList = taosMemoryCalloc(1, sizeof(SColumnInfo));
        if (cond.colList == NULL) {
          terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
          return NULL;
        }

        cond.colList->colId = 1;
        cond.colList->type = TSDB_DATA_TYPE_TIMESTAMP;
        cond.colList->bytes = sizeof(TSKEY);

        cond.numOfTWindows = 1;
        cond.twindows = taosMemoryCalloc(1, sizeof(STimeWindow));
        cond.twindows[0] = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
        cond.suid = pBlockNode->suid;
        cond.type = BLOCK_LOAD_OFFSET_SEQ_ORDER;
      }
      tsdbReaderT* pReader = tsdbReaderOpen(pHandle->vnode, &cond, pTableListInfo, queryId, taskId);
      cleanupQueryTableDataCond(&cond);

4124
      return createDataBlockInfoScanOperator(pReader, pHandle, cond.suid, pBlockNode, pTaskInfo);
H
Haojun Liao 已提交
4125 4126
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
4127 4128 4129
    }
  }

4130 4131
  int32_t num = 0;
  size_t  size = LIST_LENGTH(pPhyNode->pChildren);
H
Haojun Liao 已提交
4132

4133
  SOperatorInfo** ops = taosMemoryCalloc(size, POINTER_BYTES);
dengyihao's avatar
dengyihao 已提交
4134
  for (int32_t i = 0; i < size; ++i) {
4135
    SPhysiNode* pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
wmmhello's avatar
wmmhello 已提交
4136
    ops[i] = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableListInfo);
4137 4138 4139
    if (ops[i] == NULL) {
      return NULL;
    }
4140
  }
H
Haojun Liao 已提交
4141

4142
  SOperatorInfo* pOptr = NULL;
H
Haojun Liao 已提交
4143
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
4144
    pOptr = createProjectOperatorInfo(ops[0], (SProjectPhysiNode*)pPhyNode, pTaskInfo);
4145
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_AGG == type) {
H
Haojun Liao 已提交
4146 4147
    SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
    SExprInfo*     pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
4148
    SSDataBlock*   pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
4149

dengyihao's avatar
dengyihao 已提交
4150
    int32_t    numOfScalarExpr = 0;
4151 4152 4153 4154 4155
    SExprInfo* pScalarExprInfo = NULL;
    if (pAggNode->pExprs != NULL) {
      pScalarExprInfo = createExprInfo(pAggNode->pExprs, NULL, &numOfScalarExpr);
    }

H
Haojun Liao 已提交
4156 4157
    if (pAggNode->pGroupKeys != NULL) {
      SArray* pColList = extractColumnInfo(pAggNode->pGroupKeys);
dengyihao's avatar
dengyihao 已提交
4158
      pOptr = createGroupOperatorInfo(ops[0], pExprInfo, num, pResBlock, pColList, pAggNode->node.pConditions,
wmmhello's avatar
wmmhello 已提交
4159
                                      pScalarExprInfo, numOfScalarExpr, pTaskInfo);
H
Haojun Liao 已提交
4160
    } else {
dengyihao's avatar
dengyihao 已提交
4161 4162
      pOptr =
          createAggregateOperatorInfo(ops[0], pExprInfo, num, pResBlock, pScalarExprInfo, numOfScalarExpr, pTaskInfo);
H
Haojun Liao 已提交
4163
    }
X
Xiaoyu Wang 已提交
4164
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_INTERVAL == type || QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type) {
H
Haojun Liao 已提交
4165
    SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
4166

H
Haojun Liao 已提交
4167
    SExprInfo*   pExprInfo = createExprInfo(pIntervalPhyNode->window.pFuncs, NULL, &num);
4168
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
4169

dengyihao's avatar
dengyihao 已提交
4170 4171 4172 4173 4174 4175
    SInterval interval = {.interval = pIntervalPhyNode->interval,
                          .sliding = pIntervalPhyNode->sliding,
                          .intervalUnit = pIntervalPhyNode->intervalUnit,
                          .slidingUnit = pIntervalPhyNode->slidingUnit,
                          .offset = pIntervalPhyNode->offset,
                          .precision = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->node.resType.precision};
H
Haojun Liao 已提交
4176

X
Xiaoyu Wang 已提交
4177 4178 4179 4180 4181
    STimeWindowAggSupp as = {
        .waterMark = pIntervalPhyNode->window.watermark,
        .calTrigger = pIntervalPhyNode->window.triggerType,
        .maxTs = INT64_MIN,
    };
4182
    ASSERT(as.calTrigger != STREAM_TRIGGER_MAX_DELAY);
4183

4184
    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
L
Liu Jicong 已提交
4185 4186 4187
    bool    isStream = (QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type);
    pOptr =
        createIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId, &as, pTaskInfo, isStream);
4188

4189 4190
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_ALIGNED_INTERVAL == type) {
    SMergeAlignedIntervalPhysiNode* pIntervalPhyNode = (SMergeAlignedIntervalPhysiNode*)pPhyNode;
S
shenglian zhou 已提交
4191 4192 4193 4194 4195 4196 4197 4198 4199 4200

    SExprInfo*   pExprInfo = createExprInfo(pIntervalPhyNode->window.pFuncs, NULL, &num);
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);

    SInterval interval = {.interval = pIntervalPhyNode->interval,
                          .sliding = pIntervalPhyNode->sliding,
                          .intervalUnit = pIntervalPhyNode->intervalUnit,
                          .slidingUnit = pIntervalPhyNode->slidingUnit,
                          .offset = pIntervalPhyNode->offset,
                          .precision = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->node.resType.precision};
4201

S
shenglian zhou 已提交
4202
    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
4203
    pOptr = createMergeAlignedIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId, pTaskInfo);
4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_INTERVAL == type) {
    SMergeIntervalPhysiNode* pIntervalPhyNode = (SMergeIntervalPhysiNode*)pPhyNode;

    SExprInfo*   pExprInfo = createExprInfo(pIntervalPhyNode->window.pFuncs, NULL, &num);
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);

    SInterval interval = {.interval = pIntervalPhyNode->interval,
                          .sliding = pIntervalPhyNode->sliding,
                          .intervalUnit = pIntervalPhyNode->intervalUnit,
                          .slidingUnit = pIntervalPhyNode->slidingUnit,
                          .offset = pIntervalPhyNode->offset,
                          .precision = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->node.resType.precision};

    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
    pOptr = createMergeIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId, pTaskInfo);
5
54liuyao 已提交
4219
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SEMI_INTERVAL == type) {
4220
    int32_t children = 0;
5
54liuyao 已提交
4221 4222
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_FINAL_INTERVAL == type) {
4223
    int32_t children = 1;
5
54liuyao 已提交
4224
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
H
Haojun Liao 已提交
4225
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == type) {
4226
    pOptr = createSortOperatorInfo(ops[0], (SSortPhysiNode*)pPhyNode, pTaskInfo);
S
shenglian zhou 已提交
4227 4228
  } else if (QUERY_NODE_PHYSICAL_PLAN_GROUP_SORT == type) {
    pOptr = createGroupSortOperatorInfo(ops[0], (SGroupSortPhysiNode*)pPhyNode, pTaskInfo);
X
Xiaoyu Wang 已提交
4229
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE == type) {
4230 4231 4232
    SMergePhysiNode* pMergePhyNode = (SMergePhysiNode*)pPhyNode;

    SDataBlockDescNode* pDescNode = pPhyNode->pOutputDataBlockDesc;
X
Xiaoyu Wang 已提交
4233
    SSDataBlock*        pResBlock = createResDataBlock(pDescNode);
4234

X
Xiaoyu Wang 已提交
4235
    SArray* sortInfo = createSortInfo(pMergePhyNode->pMergeKeys);
4236
    int32_t numOfOutputCols = 0;
X
Xiaoyu Wang 已提交
4237
    SArray* pColList =
4238
        extractColMatchInfo(pMergePhyNode->pTargets, pDescNode, &numOfOutputCols, COL_MATCH_FROM_SLOT_ID);
S
shenglian zhou 已提交
4239
    SPhysiNode*  pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, 0);
4240 4241
    SSDataBlock* pInputDataBlock = createResDataBlock(pChildNode->pOutputDataBlockDesc);
    pOptr = createMultiwaySortMergeOperatorInfo(ops, size, pInputDataBlock, pResBlock, sortInfo, pColList, pTaskInfo);
4242
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_SESSION == type) {
H
Haojun Liao 已提交
4243 4244
    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;

X
Xiaoyu Wang 已提交
4245 4246
    STimeWindowAggSupp as = {.waterMark = pSessionNode->window.watermark,
                             .calTrigger = pSessionNode->window.triggerType};
4247

H
Haojun Liao 已提交
4248
    SExprInfo*   pExprInfo = createExprInfo(pSessionNode->window.pFuncs, NULL, &num);
4249
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
4250 4251
    int32_t      tsSlotId = ((SColumnNode*)pSessionNode->window.pTspk)->slotId;

X
Xiaoyu Wang 已提交
4252 4253
    pOptr =
        createSessionAggOperatorInfo(ops[0], pExprInfo, num, pResBlock, pSessionNode->gap, tsSlotId, &as, pTaskInfo);
4254
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION == type) {
4255 4256 4257 4258 4259 4260 4261
    pOptr = createStreamSessionAggOperatorInfo(ops[0], pPhyNode, pTaskInfo);
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SEMI_SESSION == type) {
    int32_t children = 0;
    pOptr = createStreamFinalSessionAggOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_FINAL_SESSION == type) {
    int32_t children = 1;
    pOptr = createStreamFinalSessionAggOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
H
Haojun Liao 已提交
4262
  } else if (QUERY_NODE_PHYSICAL_PLAN_PARTITION == type) {
4263
    pOptr = createPartitionOperatorInfo(ops[0], (SPartitionPhysiNode*)pPhyNode, pTaskInfo);
4264
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_STATE == type) {
dengyihao's avatar
dengyihao 已提交
4265
    SStateWinodwPhysiNode* pStateNode = (SStateWinodwPhysiNode*)pPhyNode;
4266

4267 4268
    STimeWindowAggSupp as = {.waterMark = pStateNode->window.watermark, .calTrigger = pStateNode->window.triggerType};

dengyihao's avatar
dengyihao 已提交
4269
    SExprInfo*   pExprInfo = createExprInfo(pStateNode->window.pFuncs, NULL, &num);
4270
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
4271 4272
    int32_t      tsSlotId = ((SColumnNode*)pStateNode->window.pTspk)->slotId;

4273
    SColumnNode* pColNode = (SColumnNode*)((STargetNode*)pStateNode->pStateKey)->pExpr;
X
Xiaoyu Wang 已提交
4274
    SColumn      col = extractColumnFromColumnNode(pColNode);
4275
    pOptr = createStatewindowOperatorInfo(ops[0], pExprInfo, num, pResBlock, &as, tsSlotId, &col, pTaskInfo);
4276
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_STATE == type) {
5
54liuyao 已提交
4277
    pOptr = createStreamStateAggOperatorInfo(ops[0], pPhyNode, pTaskInfo);
4278
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_JOIN == type) {
4279
    pOptr = createMergeJoinOperatorInfo(ops, size, (SJoinPhysiNode*)pPhyNode, pTaskInfo);
4280
  } else if (QUERY_NODE_PHYSICAL_PLAN_FILL == type) {
4281
    pOptr = createFillOperatorInfo(ops[0], (SFillPhysiNode*)pPhyNode, false, pTaskInfo);
H
Haojun Liao 已提交
4282 4283
  } else if (QUERY_NODE_PHYSICAL_PLAN_INDEF_ROWS_FUNC == type) {
    pOptr = createIndefinitOutputOperatorInfo(ops[0], pPhyNode, pTaskInfo);
4284 4285
  } else if (QUERY_NODE_PHYSICAL_PLAN_INTERP_FUNC == type) {
    pOptr = createTimeSliceOperatorInfo(ops[0], pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
4286 4287
  } else {
    ASSERT(0);
H
Haojun Liao 已提交
4288
  }
4289 4290 4291

  taosMemoryFree(ops);
  return pOptr;
4292
}
H
Haojun Liao 已提交
4293

4294
int32_t compareTimeWindow(const void* p1, const void* p2, const void* param) {
dengyihao's avatar
dengyihao 已提交
4295 4296 4297
  const SQueryTableDataCond* pCond = param;
  const STimeWindow*         pWin1 = p1;
  const STimeWindow*         pWin2 = p2;
4298 4299 4300 4301 4302 4303 4304 4305
  if (pCond->order == TSDB_ORDER_ASC) {
    return pWin1->skey - pWin2->skey;
  } else if (pCond->order == TSDB_ORDER_DESC) {
    return pWin2->skey - pWin1->skey;
  }
  return 0;
}

H
Haojun Liao 已提交
4306
SArray* extractColumnInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
4307
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4308 4309 4310 4311 4312 4313
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
4314 4315
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
H
Haojun Liao 已提交
4316

4317 4318 4319
    if (nodeType(pNode->pExpr) == QUERY_NODE_COLUMN) {
      SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

4320
      SColumn c = extractColumnFromColumnNode(pColNode);
4321 4322
      taosArrayPush(pList, &c);
    } else if (nodeType(pNode->pExpr) == QUERY_NODE_VALUE) {
L
Liu Jicong 已提交
4323 4324
      SValueNode* pValNode = (SValueNode*)pNode->pExpr;
      SColumn     c = {0};
4325
      c.slotId = pNode->slotId;
L
Liu Jicong 已提交
4326 4327 4328 4329
      c.colId = pNode->slotId;
      c.type = pValNode->node.type;
      c.bytes = pValNode->node.resType.bytes;
      c.scale = pValNode->node.resType.scale;
4330 4331 4332 4333
      c.precision = pValNode->node.resType.precision;

      taosArrayPush(pList, &c);
    }
H
Haojun Liao 已提交
4334 4335 4336 4337 4338
  }

  return pList;
}

L
Liu Jicong 已提交
4339
tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
wmmhello's avatar
wmmhello 已提交
4340 4341
                               STableListInfo* pTableListInfo, uint64_t queryId, uint64_t taskId) {
  int32_t code = getTableList(pHandle->meta, &pTableScanNode->scan, pTableListInfo);
wmmhello's avatar
wmmhello 已提交
4342 4343 4344 4345 4346 4347 4348 4349 4350 4351
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

  if (taosArrayGetSize(pTableListInfo->pTableList) == 0) {
    code = 0;
    qDebug("no table qualified for query, TID:0x%" PRIx64 ", QID:0x%" PRIx64, taskId, queryId);
    goto _error;
  }

4352
  SQueryTableDataCond cond = {0};
wmmhello's avatar
wmmhello 已提交
4353
  code = initQueryTableDataCond(&cond, pTableScanNode);
4354
  if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4355
    goto _error;
X
Xiaoyu Wang 已提交
4356
  }
4357

H
Haojun Liao 已提交
4358
  tsdbReaderT* pReader = tsdbReaderOpen(pHandle->vnode, &cond, pTableListInfo, queryId, taskId);
4359
  cleanupQueryTableDataCond(&cond);
H
Haojun Liao 已提交
4360 4361

  return pReader;
wmmhello's avatar
wmmhello 已提交
4362 4363 4364 4365

_error:
  terrno = code;
  return NULL;
H
Haojun Liao 已提交
4366 4367
}

4368
int32_t encodeOperator(SOperatorInfo* ops, char** result, int32_t* length) {
wmmhello's avatar
wmmhello 已提交
4369
  int32_t code = TDB_CODE_SUCCESS;
4370
  char*   pCurrent = NULL;
wmmhello's avatar
wmmhello 已提交
4371
  int32_t currLength = 0;
4372 4373
  if (ops->fpSet.encodeResultRow) {
    if (result == NULL || length == NULL) {
wmmhello's avatar
wmmhello 已提交
4374 4375 4376
      return TSDB_CODE_TSC_INVALID_INPUT;
    }
    code = ops->fpSet.encodeResultRow(ops, &pCurrent, &currLength);
wmmhello's avatar
wmmhello 已提交
4377

4378 4379
    if (code != TDB_CODE_SUCCESS) {
      if (*result != NULL) {
wmmhello's avatar
wmmhello 已提交
4380 4381 4382 4383 4384
        taosMemoryFree(*result);
        *result = NULL;
      }
      return code;
    }
wmmhello's avatar
wmmhello 已提交
4385

4386
    if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
4387
      *result = (char*)taosMemoryCalloc(1, currLength + sizeof(int32_t));
wmmhello's avatar
wmmhello 已提交
4388 4389 4390 4391 4392 4393
      if (*result == NULL) {
        taosMemoryFree(pCurrent);
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      memcpy(*result + sizeof(int32_t), pCurrent, currLength);
      *(int32_t*)(*result) = currLength + sizeof(int32_t);
4394
    } else {
wmmhello's avatar
wmmhello 已提交
4395
      int32_t sizePre = *(int32_t*)(*result);
4396
      char*   tmp = (char*)taosMemoryRealloc(*result, sizePre + currLength);
wmmhello's avatar
wmmhello 已提交
4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408
      if (tmp == NULL) {
        taosMemoryFree(pCurrent);
        taosMemoryFree(*result);
        *result = NULL;
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      *result = tmp;
      memcpy(*result + sizePre, pCurrent, currLength);
      *(int32_t*)(*result) += currLength;
    }
    taosMemoryFree(pCurrent);
    *length = *(int32_t*)(*result);
wmmhello's avatar
wmmhello 已提交
4409 4410
  }

wmmhello's avatar
wmmhello 已提交
4411 4412
  for (int32_t i = 0; i < ops->numOfDownstream; ++i) {
    code = encodeOperator(ops->pDownstream[i], result, length);
4413
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4414
      return code;
wmmhello's avatar
wmmhello 已提交
4415 4416
    }
  }
wmmhello's avatar
wmmhello 已提交
4417
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
4418 4419
}

H
Haojun Liao 已提交
4420
int32_t decodeOperator(SOperatorInfo* ops, const char* result, int32_t length) {
wmmhello's avatar
wmmhello 已提交
4421
  int32_t code = TDB_CODE_SUCCESS;
4422 4423
  if (ops->fpSet.decodeResultRow) {
    if (result == NULL) {
wmmhello's avatar
wmmhello 已提交
4424 4425
      return TSDB_CODE_TSC_INVALID_INPUT;
    }
H
Haojun Liao 已提交
4426

4427
    ASSERT(length == *(int32_t*)result);
H
Haojun Liao 已提交
4428 4429

    const char* data = result + sizeof(int32_t);
L
Liu Jicong 已提交
4430
    code = ops->fpSet.decodeResultRow(ops, (char*)data);
4431
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4432 4433
      return code;
    }
wmmhello's avatar
wmmhello 已提交
4434

wmmhello's avatar
wmmhello 已提交
4435
    int32_t totalLength = *(int32_t*)result;
4436 4437
    int32_t dataLength = *(int32_t*)data;

4438
    if (totalLength == dataLength + sizeof(int32_t)) {  // the last data
wmmhello's avatar
wmmhello 已提交
4439 4440
      result = NULL;
      length = 0;
4441
    } else {
wmmhello's avatar
wmmhello 已提交
4442 4443 4444 4445
      result += dataLength;
      *(int32_t*)(result) = totalLength - dataLength;
      length = totalLength - dataLength;
    }
wmmhello's avatar
wmmhello 已提交
4446 4447
  }

wmmhello's avatar
wmmhello 已提交
4448 4449
  for (int32_t i = 0; i < ops->numOfDownstream; ++i) {
    code = decodeOperator(ops->pDownstream[i], result, length);
4450
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4451
      return code;
wmmhello's avatar
wmmhello 已提交
4452 4453
    }
  }
wmmhello's avatar
wmmhello 已提交
4454
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
4455 4456
}

4457
int32_t createDataSinkParam(SDataSinkNode* pNode, void** pParam, qTaskInfo_t* pTaskInfo) {
D
dapan1121 已提交
4458
  SExecTaskInfo* pTask = *(SExecTaskInfo**)pTaskInfo;
4459

D
dapan1121 已提交
4460 4461
  switch (pNode->type) {
    case QUERY_NODE_PHYSICAL_PLAN_DELETE: {
4462
      SDeleterParam* pDeleterParam = taosMemoryCalloc(1, sizeof(SDeleterParam));
D
dapan1121 已提交
4463 4464 4465 4466 4467 4468 4469 4470 4471 4472
      if (NULL == pDeleterParam) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      int32_t tbNum = taosArrayGetSize(pTask->tableqinfoList.pTableList);
      pDeleterParam->pUidList = taosArrayInit(tbNum, sizeof(uint64_t));
      if (NULL == pDeleterParam->pUidList) {
        taosMemoryFree(pDeleterParam);
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      for (int32_t i = 0; i < tbNum; ++i) {
4473
        STableKeyInfo* pTable = taosArrayGet(pTask->tableqinfoList.pTableList, i);
D
dapan1121 已提交
4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486
        taosArrayPush(pDeleterParam->pUidList, &pTable->uid);
      }

      *pParam = pDeleterParam;
      break;
    }
    default:
      break;
  }

  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
4487
int32_t createExecTaskInfoImpl(SSubplan* pPlan, SExecTaskInfo** pTaskInfo, SReadHandle* pHandle, uint64_t taskId,
4488
                               const char* sql, EOPTR_EXEC_MODEL model) {
H
Haojun Liao 已提交
4489 4490
  uint64_t queryId = pPlan->id.queryId;

H
Haojun Liao 已提交
4491
  int32_t code = TSDB_CODE_SUCCESS;
D
dapan1121 已提交
4492
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model, pPlan->dbFName);
H
Haojun Liao 已提交
4493 4494 4495 4496
  if (*pTaskInfo == NULL) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _complete;
  }
H
Haojun Liao 已提交
4497

4498
  (*pTaskInfo)->sql = sql;
wmmhello's avatar
wmmhello 已提交
4499 4500
  (*pTaskInfo)->tableqinfoList.pTagCond = pPlan->pTagCond;
  (*pTaskInfo)->tableqinfoList.pTagIndexCond = pPlan->pTagIndexCond;
dengyihao's avatar
dengyihao 已提交
4501
  (*pTaskInfo)->pRoot = createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, queryId, taskId,
wmmhello's avatar
wmmhello 已提交
4502
                                           &(*pTaskInfo)->tableqinfoList);
D
dapan1121 已提交
4503
  if (NULL == (*pTaskInfo)->pRoot) {
4504
    code = (*pTaskInfo)->code;
D
dapan1121 已提交
4505 4506
    goto _complete;
  }
H
Haojun Liao 已提交
4507

4508
  if ((*pTaskInfo)->pRoot == NULL) {
H
Haojun Liao 已提交
4509
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
H
Haojun Liao 已提交
4510
    goto _complete;
4511 4512
  }

H
Haojun Liao 已提交
4513 4514
  return code;

H
Haojun Liao 已提交
4515
_complete:
wafwerar's avatar
wafwerar 已提交
4516
  taosMemoryFreeClear(*pTaskInfo);
H
Haojun Liao 已提交
4517 4518
  terrno = code;
  return code;
H
Haojun Liao 已提交
4519 4520
}

wmmhello's avatar
wmmhello 已提交
4521 4522 4523
static void doDestroyTableList(STableListInfo* pTableqinfoList) {
  taosArrayDestroy(pTableqinfoList->pTableList);
  taosHashCleanup(pTableqinfoList->map);
4524

wmmhello's avatar
wmmhello 已提交
4525 4526
  pTableqinfoList->pTableList = NULL;
  pTableqinfoList->map = NULL;
4527 4528
}

L
Liu Jicong 已提交
4529
void doDestroyTask(SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
4530 4531
  qDebug("%s execTask is freed", GET_TASKID(pTaskInfo));

wmmhello's avatar
wmmhello 已提交
4532
  doDestroyTableList(&pTaskInfo->tableqinfoList);
H
Haojun Liao 已提交
4533
  destroyOperatorInfo(pTaskInfo->pRoot);
L
Liu Jicong 已提交
4534 4535
  //  taosArrayDestroy(pTaskInfo->summary.queryProfEvents);
  //  taosHashCleanup(pTaskInfo->summary.operatorProfResults);
4536

4537 4538
  taosMemoryFree(pTaskInfo->schemaVer.dbname);
  taosMemoryFree(pTaskInfo->schemaVer.tablename);
wafwerar's avatar
wafwerar 已提交
4539 4540 4541
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553
}

static void doSetTagValueToResultBuf(char* output, const char* val, int16_t type, int16_t bytes) {
  if (val == NULL) {
    setNull(output, type, bytes);
    return;
  }

  if (IS_VAR_DATA_TYPE(type)) {
    // Binary data overflows for sort of unknown reasons. Let trim the overflow data
    if (varDataTLen(val) > bytes) {
      int32_t maxLen = bytes - VARSTR_HEADER_SIZE;
L
Liu Jicong 已提交
4554
      int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566
      memcpy(varDataVal(output), varDataVal(val), len);
      varDataSetLen(output, len);
    } else {
      varDataCopy(output, val);
    }
  } else {
    memcpy(output, val, bytes);
  }
}

static int64_t getQuerySupportBufSize(size_t numOfTables) {
  size_t s1 = sizeof(STableQueryInfo);
L
Liu Jicong 已提交
4567 4568
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
4569 4570 4571 4572 4573 4574 4575
}

int32_t checkForQueryBuf(size_t numOfTables) {
  int64_t t = getQuerySupportBufSize(numOfTables);
  if (tsQueryBufferSizeBytes < 0) {
    return TSDB_CODE_SUCCESS;
  } else if (tsQueryBufferSizeBytes > 0) {
L
Liu Jicong 已提交
4576
    while (1) {
4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602
      int64_t s = tsQueryBufferSizeBytes;
      int64_t remain = s - t;
      if (remain >= 0) {
        if (atomic_val_compare_exchange_64(&tsQueryBufferSizeBytes, s, remain) == s) {
          return TSDB_CODE_SUCCESS;
        }
      } else {
        return TSDB_CODE_QRY_NOT_ENOUGH_BUFFER;
      }
    }
  }

  // disable query processing if the value of tsQueryBufferSize is zero.
  return TSDB_CODE_QRY_NOT_ENOUGH_BUFFER;
}

void releaseQueryBuf(size_t numOfTables) {
  if (tsQueryBufferSizeBytes < 0) {
    return;
  }

  int64_t t = getQuerySupportBufSize(numOfTables);

  // restore value is not enough buffer available
  atomic_add_fetch_64(&tsQueryBufferSizeBytes, t);
}
D
dapan1121 已提交
4603

dengyihao's avatar
dengyihao 已提交
4604 4605
int32_t getOperatorExplainExecInfo(SOperatorInfo* operatorInfo, SExplainExecInfo** pRes, int32_t* capacity,
                                   int32_t* resNum) {
D
dapan1121 已提交
4606 4607
  if (*resNum >= *capacity) {
    *capacity += 10;
dengyihao's avatar
dengyihao 已提交
4608

D
dapan1121 已提交
4609 4610
    *pRes = taosMemoryRealloc(*pRes, (*capacity) * sizeof(SExplainExecInfo));
    if (NULL == *pRes) {
D
dapan1121 已提交
4611
      qError("malloc %d failed", (*capacity) * (int32_t)sizeof(SExplainExecInfo));
D
dapan1121 已提交
4612 4613 4614 4615
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

4616 4617 4618 4619 4620
  SExplainExecInfo* pInfo = &(*pRes)[*resNum];

  pInfo->numOfRows = operatorInfo->resultInfo.totalRows;
  pInfo->startupCost = operatorInfo->cost.openCost;
  pInfo->totalCost = operatorInfo->cost.totalCost;
D
dapan1121 已提交
4621

4622
  if (operatorInfo->fpSet.getExplainFn) {
4623
    int32_t code = operatorInfo->fpSet.getExplainFn(operatorInfo, &pInfo->verboseInfo, &pInfo->verboseLen);
D
dapan1121 已提交
4624
    if (code) {
4625
      qError("%s operator getExplainFn failed, code:%s", GET_TASKID(operatorInfo->pTaskInfo), tstrerror(code));
D
dapan1121 已提交
4626 4627
      return code;
    }
4628 4629 4630
  } else {
    pInfo->verboseLen = 0;
    pInfo->verboseInfo = NULL;
D
dapan1121 已提交
4631
  }
dengyihao's avatar
dengyihao 已提交
4632

D
dapan1121 已提交
4633
  ++(*resNum);
dengyihao's avatar
dengyihao 已提交
4634

D
dapan1121 已提交
4635
  int32_t code = 0;
D
dapan1121 已提交
4636 4637
  for (int32_t i = 0; i < operatorInfo->numOfDownstream; ++i) {
    code = getOperatorExplainExecInfo(operatorInfo->pDownstream[i], pRes, capacity, resNum);
D
dapan1121 已提交
4638 4639 4640 4641 4642 4643 4644
    if (code) {
      taosMemoryFreeClear(*pRes);
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
4645
}
5
54liuyao 已提交
4646

L
Liu Jicong 已提交
4647
int32_t initStreamAggSupporter(SStreamAggSupporter* pSup, const char* pKey, SqlFunctionCtx* pCtx, int32_t numOfOutput,
4648
                               int32_t size) {
4649
  pSup->resultRowSize = getResultRowSize(pCtx, numOfOutput);
5
54liuyao 已提交
4650 4651
  pSup->keySize = sizeof(int64_t) + sizeof(TSKEY);
  pSup->pKeyBuf = taosMemoryCalloc(1, pSup->keySize);
4652 4653
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);
  pSup->pResultRows = taosHashInit(1024, hashFn, false, HASH_NO_LOCK);
5
54liuyao 已提交
4654 4655 4656
  if (pSup->pKeyBuf == NULL || pSup->pResultRows == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
4657
  pSup->valueSize = size;
5
54liuyao 已提交
4658

5
54liuyao 已提交
4659 4660
  pSup->pScanWindow = taosArrayInit(4, sizeof(STimeWindow));

5
54liuyao 已提交
4661 4662 4663 4664 4665 4666 4667 4668 4669
  int32_t pageSize = 4096;
  while (pageSize < pSup->resultRowSize * 4) {
    pageSize <<= 1u;
  }
  // at least four pages need to be in buffer
  int32_t bufSize = 4096 * 256;
  if (bufSize <= pageSize) {
    bufSize = pageSize * 4;
  }
4670
  int32_t code = createDiskbasedBuf(&pSup->pResultBuf, pageSize, bufSize, pKey, TD_TMP_DIR_PATH);
L
Liu Jicong 已提交
4671
  for (int32_t i = 0; i < numOfOutput; ++i) {
4672 4673 4674
    pCtx[i].pBuf = pSup->pResultBuf;
  }
  return code;
5
54liuyao 已提交
4675
}