executorimpl.c 184.9 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
#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)

45 46 47 48 49
enum {
  PROJECT_RETRIEVE_CONTINUE = 0x1,
  PROJECT_RETRIEVE_DONE = 0x2,
};

50 51
#if 0
static UNUSED_FUNC void *u_malloc (size_t __size) {
wafwerar's avatar
wafwerar 已提交
52
  uint32_t v = taosRand();
53 54 55 56

  if (v % 1000 <= 0) {
    return NULL;
  } else {
wafwerar's avatar
wafwerar 已提交
57
    return taosMemoryMalloc(__size);
58 59 60 61
  }
}

static UNUSED_FUNC void* u_calloc(size_t num, size_t __size) {
wafwerar's avatar
wafwerar 已提交
62
  uint32_t v = taosRand();
63 64 65
  if (v % 1000 <= 0) {
    return NULL;
  } else {
wafwerar's avatar
wafwerar 已提交
66
    return taosMemoryCalloc(num, __size);
67 68 69 70
  }
}

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

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

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

L
Liu Jicong 已提交
87 88 89
int32_t getMaximumIdleDurationSec() { return tsShellActivityTimer * 2; }

static int32_t getExprFunctionId(SExprInfo* pExprInfo) {
90
  assert(pExprInfo != NULL && pExprInfo->pExpr != NULL && pExprInfo->pExpr->nodeType == TEXPR_UNARYEXPR_NODE);
91
  return 0;
92 93 94 95
}

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

96
static void setBlockStatisInfo(SqlFunctionCtx* pCtx, SExprInfo* pExpr, SSDataBlock* pSDataBlock);
97

X
Xiaoyu Wang 已提交
98
static void releaseQueryBuf(size_t numOfTables);
99 100 101 102 103

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

H
Haojun Liao 已提交
105
static void destroyIntervalOperatorInfo(void* param, int32_t numOfOutput);
H
Haojun Liao 已提交
106 107
static void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput);

108 109
static void destroyOperatorInfo(SOperatorInfo* pOperator);

110
void doSetOperatorCompleted(SOperatorInfo* pOperator) {
111
  pOperator->status = OP_EXEC_DONE;
112

113
  pOperator->cost.totalCost = (taosGetTimestampUs() - pOperator->pTaskInfo->cost.start * 1000) / 1000.0;
H
Haojun Liao 已提交
114
  if (pOperator->pTaskInfo != NULL) {
115
    setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
116 117
  }
}
118

H
Haojun Liao 已提交
119
int32_t operatorDummyOpenFn(SOperatorInfo* pOperator) {
120
  OPTR_SET_OPENED(pOperator);
121
  pOperator->cost.openCost = 0;
H
Haojun Liao 已提交
122
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
123 124
}

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

  return fpSet;
}

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

X
Xiaoyu Wang 已提交
144 145 146
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 已提交
147

148
static void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size);
L
Liu Jicong 已提交
149 150
static void doSetTableGroupOutputBuf(SOperatorInfo* pOperator, SAggOperatorInfo* pAggInfo, int32_t numOfOutput,
                                     uint64_t groupId);
151

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

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

  return true;
}

166
#if 0
L
Liu Jicong 已提交
167 168
static bool chkResultRowFromKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, char* pData,
                                int16_t bytes, bool masterscan, uint64_t uid) {
169 170 171
  bool existed = false;
  SET_RES_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid);

L
Liu Jicong 已提交
172 173
  SResultRow** p1 =
      (SResultRow**)taosHashGet(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
174 175 176 177 178 179 180 181 182 183 184

  // 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 已提交
185
        //        existed = (pResultRowInfo->pResult[0] == (*p1));
186 187
      } else {  // check if current pResultRowInfo contains the existed pResultRow
        SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid, pResultRowInfo);
L
Liu Jicong 已提交
188 189
        int64_t* index =
            taosHashGet(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
190 191 192 193 194 195 196 197 198 199 200 201 202
        if (index != NULL) {
          existed = true;
        } else {
          existed = false;
        }
      }
    }

    return existed;
  }

  return p1 != NULL;
}
203
#endif
204

205
SResultRow* getNewResultRow(SDiskbasedBuf* pResultBuf, int64_t tableGroupId, int32_t interBufSize) {
L
Liu Jicong 已提交
206
  SFilePage* pData = NULL;
207 208 209 210 211 212 213 214 215 216 217 218 219

  // 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 已提交
220
    if (pData->num + interBufSize > getBufPageSize(pResultBuf)) {
221 222 223 224 225 226 227 228 229 230 231 232 233 234
      // 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;
  }

235 236
  setBufPageDirty(pData, true);

237 238 239 240 241
  // 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 已提交
242
  pData->num += interBufSize;
243 244 245 246

  return pResultRow;
}

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

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

262 263
  SResultRow* pResult = NULL;

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

L
Liu Jicong 已提交
280
  // 1. close current opened time window
281
  if (pResultRowInfo->cur.pageId != -1 && ((pResult == NULL) || (pResult->pageId != pResultRowInfo->cur.pageId))) {
282
#ifdef BUF_PAGE_DEBUG
wmmhello's avatar
wmmhello 已提交
283
    qDebug("page_1");
284
#endif
285
    SResultRowPosition pos = pResultRowInfo->cur;
X
Xiaoyu Wang 已提交
286
    SFilePage*         pPage = getBufPage(pResultBuf, pos.pageId);
287 288 289 290 291
    releaseBufPage(pResultBuf, pPage);
  }

  // allocate a new buffer page
  if (pResult == NULL) {
292
#ifdef BUF_PAGE_DEBUG
wmmhello's avatar
wmmhello 已提交
293
    qDebug("page_2");
294
#endif
H
Haojun Liao 已提交
295
    ASSERT(pSup->resultRowSize > 0);
296 297
    pResult = getNewResultRow(pResultBuf, groupId, pSup->resultRowSize);

298
    initResultRow(pResult);
H
Haojun Liao 已提交
299

300 301
    // add a new result set for a new group
    SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
X
Xiaoyu Wang 已提交
302 303
    taosHashPut(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pos,
                sizeof(SResultRowPosition));
H
Haojun Liao 已提交
304 305
  }

306 307 308
  // 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 已提交
309
  // too many time window in query
310
  if (taosHashGetSize(pSup->pResultRowHashTable) > MAX_INTERVAL_TIME_WINDOW) {
H
Haojun Liao 已提交
311 312 313
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_TOO_MANY_TIMEWINDOW);
  }

H
Haojun Liao 已提交
314
  return pResult;
H
Haojun Liao 已提交
315 316
}

317
// a new buffer page for each table. Needs to opt this design
L
Liu Jicong 已提交
318
static int32_t addNewWindowResultBuf(SResultRow* pWindowRes, SDiskbasedBuf* pResultBuf, int32_t tid, uint32_t size) {
319 320 321 322
  if (pWindowRes->pageId != -1) {
    return 0;
  }

L
Liu Jicong 已提交
323
  SFilePage* pData = NULL;
324 325 326 327 328 329

  // 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 已提交
330
    pData = getNewBufPage(pResultBuf, tid, &pageId);
331
    pData->num = sizeof(SFilePage);
332 333
  } else {
    SPageInfo* pi = getLastPageInfo(list);
334
    pData = getBufPage(pResultBuf, getPageId(pi));
335
    pageId = getPageId(pi);
336

337
    if (pData->num + size > getBufPageSize(pResultBuf)) {
338
      // release current page first, and prepare the next one
339
      releaseBufPageInfo(pResultBuf, pi);
340

H
Haojun Liao 已提交
341
      pData = getNewBufPage(pResultBuf, tid, &pageId);
342
      if (pData != NULL) {
343
        pData->num = sizeof(SFilePage);
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
      }
    }
  }

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

364
//  query_range_start, query_range_end, window_duration, window_start, window_end
365
void initExecTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pQueryWindow) {
366 367 368
  pColData->info.type = TSDB_DATA_TYPE_TIMESTAMP;
  pColData->info.bytes = sizeof(int64_t);

369
  colInfoDataEnsureCapacity(pColData, 5);
370 371 372 373 374 375 376 377 378
  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);
}

L
Liu Jicong 已提交
379
void cleanupExecTimeWindowInfo(SColumnInfoData* pColData) { colDataDestroy(pColData); }
H
Haojun Liao 已提交
380

X
Xiaoyu Wang 已提交
381 382 383
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) {
384
  for (int32_t k = 0; k < numOfOutput; ++k) {
H
Haojun Liao 已提交
385
    // keep it temporarily
386
    // todo no need this??
dengyihao's avatar
dengyihao 已提交
387 388
    bool    hasAgg = pCtx[k].input.colDataAggIsSet;
    int32_t numOfRows = pCtx[k].input.numOfRows;
H
Haojun Liao 已提交
389
    int32_t startOffset = pCtx[k].input.startRowIndex;
390

391
    pCtx[k].input.startRowIndex = offset;
392
    pCtx[k].input.numOfRows = forwardStep;
393 394 395

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

400 401
    if (fmIsWindowPseudoColumnFunc(pCtx[k].functionId)) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
402 403

      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);
404

405
      SColumnInfoData idata = {0};
dengyihao's avatar
dengyihao 已提交
406
      idata.info.type = TSDB_DATA_TYPE_BIGINT;
407
      idata.info.bytes = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
dengyihao's avatar
dengyihao 已提交
408
      idata.pData = p;
409 410 411 412

      SScalarParam out = {.columnData = &idata};
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
      pCtx[k].sfp.process(&tw, 1, &out);
413
      pEntryInfo->numOfRes = 1;
414 415 416 417 418 419 420 421 422 423
    } 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);
        }
424
      }
425

426 427 428 429 430
      // restore it
      pCtx[k].input.colDataAggIsSet = hasAgg;
      pCtx[k].input.startRowIndex = startOffset;
      pCtx[k].input.numOfRows = numOfRows;
    }
431 432 433
  }
}

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

dengyihao's avatar
dengyihao 已提交
437 438
static void doSetInputDataBlockInfo(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock,
                                    int32_t order) {
439
  for (int32_t i = 0; i < pOperator->exprSupp.numOfExprs; ++i) {
440
    pCtx[i].order = order;
441
    pCtx[i].input.numOfRows = pBlock->info.rows;
442
    setBlockStatisInfo(&pCtx[i], &pOperator->exprSupp.pExprInfo[i], pBlock);
443 444 445
  }
}

X
Xiaoyu Wang 已提交
446 447
void setInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
                       int32_t scanFlag, bool createDummyCol) {
448
  if (pBlock->pBlockAgg != NULL) {
H
Haojun Liao 已提交
449
    doSetInputDataBlockInfo(pOperator, pCtx, pBlock, order);
450
  } else {
451
    doSetInputDataBlock(pOperator, pCtx, pBlock, order, scanFlag, createDummyCol);
H
Haojun Liao 已提交
452
  }
453 454
}

L
Liu Jicong 已提交
455 456
static int32_t doCreateConstantValColumnInfo(SInputColumnInfoData* pInput, SFunctParam* pFuncParam, int32_t paramIndex,
                                             int32_t numOfRows) {
457 458 459 460 461 462 463 464
  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)
465 466
    pColInfo->info.type = pFuncParam->param.nType;
    pColInfo->info.bytes = pFuncParam->param.nLen;
467 468

    pInput->pData[paramIndex] = pColInfo;
469 470
  } else {
    pColInfo = pInput->pData[paramIndex];
471 472
  }

473
  colInfoDataEnsureCapacity(pColInfo, numOfRows);
474

475
  int8_t type = pFuncParam->param.nType;
476 477
  if (type == TSDB_DATA_TYPE_BIGINT || type == TSDB_DATA_TYPE_UBIGINT) {
    int64_t v = pFuncParam->param.i;
dengyihao's avatar
dengyihao 已提交
478
    for (int32_t i = 0; i < numOfRows; ++i) {
479 480 481 482
      colDataAppendInt64(pColInfo, i, &v);
    }
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
dengyihao's avatar
dengyihao 已提交
483
    for (int32_t i = 0; i < numOfRows; ++i) {
484 485
      colDataAppendDouble(pColInfo, i, &v);
    }
486
  } else if (type == TSDB_DATA_TYPE_VARCHAR) {
L
Liu Jicong 已提交
487
    char* tmp = taosMemoryMalloc(pFuncParam->param.nLen + VARSTR_HEADER_SIZE);
488
    STR_WITH_SIZE_TO_VARSTR(tmp, pFuncParam->param.pz, pFuncParam->param.nLen);
L
Liu Jicong 已提交
489
    for (int32_t i = 0; i < numOfRows; ++i) {
490 491
      colDataAppend(pColInfo, i, tmp, false);
    }
492 493 494 495 496
  }

  return TSDB_CODE_SUCCESS;
}

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

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

L
Liu Jicong 已提交
505
    pCtx[i].pSrcBlock = pBlock;
X
Xiaoyu Wang 已提交
506
    pCtx[i].scanFlag = scanFlag;
H
Haojun Liao 已提交
507

508
    SInputColumnInfoData* pInput = &pCtx[i].input;
509
    pInput->uid = pBlock->info.uid;
C
Cary Xu 已提交
510
    pInput->colDataAggIsSet = false;
511

512
    SExprInfo* pOneExpr = &pOperator->exprSupp.pExprInfo[i];
513
    for (int32_t j = 0; j < pOneExpr->base.numOfParams; ++j) {
dengyihao's avatar
dengyihao 已提交
514
      SFunctParam* pFuncParam = &pOneExpr->base.pParam[j];
G
Ganlin Zhao 已提交
515 516
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
dengyihao's avatar
dengyihao 已提交
517
        pInput->pData[j] = taosArrayGet(pBlock->pDataBlock, slotId);
518 519 520
        pInput->totalRows = pBlock->info.rows;
        pInput->numOfRows = pBlock->info.rows;
        pInput->startRowIndex = 0;
521

522
        // NOTE: the last parameter is the primary timestamp column
H
Haojun Liao 已提交
523
        // todo: refactor this
524
        if (fmIsImplicitTsFunc(pCtx[i].functionId) && (j == pOneExpr->base.numOfParams - 1)) {
L
Liu Jicong 已提交
525 526
          pInput->pPTS = pInput->pData[j];  // in case of merge function, this is not always the ts column data.
                                            //          ASSERT(pInput->pPTS->info.type == TSDB_DATA_TYPE_TIMESTAMP);
527
        }
528 529
        ASSERT(pInput->pData[j] != NULL);
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
530 531 532
        // 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) {
533 534 535 536
          pInput->totalRows = pBlock->info.rows;
          pInput->numOfRows = pBlock->info.rows;
          pInput->startRowIndex = 0;

537
          code = doCreateConstantValColumnInfo(pInput, pFuncParam, j, pBlock->info.rows);
538 539 540
          if (code != TSDB_CODE_SUCCESS) {
            return code;
          }
541
        }
G
Ganlin Zhao 已提交
542 543
      }
    }
H
Haojun Liao 已提交
544
  }
545 546

  return code;
H
Haojun Liao 已提交
547 548
}

549
static int32_t doAggregateImpl(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx) {
550
  for (int32_t k = 0; k < pOperator->exprSupp.numOfExprs; ++k) {
H
Haojun Liao 已提交
551
    if (functionNeedToExecute(&pCtx[k])) {
552
      // todo add a dummy funtion to avoid process check
553 554 555
      if (pCtx[k].fpSet.process == NULL) {
        continue;
      }
H
Haojun Liao 已提交
556

557 558 559 560
      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;
561
      }
562 563
    }
  }
564 565

  return TSDB_CODE_SUCCESS;
566 567
}

H
Haojun Liao 已提交
568
static void setPseudoOutputColInfo(SSDataBlock* pResult, SqlFunctionCtx* pCtx, SArray* pPseudoList) {
dengyihao's avatar
dengyihao 已提交
569
  size_t num = (pPseudoList != NULL) ? taosArrayGetSize(pPseudoList) : 0;
H
Haojun Liao 已提交
570 571 572 573 574
  for (int32_t i = 0; i < num; ++i) {
    pCtx[i].pOutput = taosArrayGet(pResult->pDataBlock, i);
  }
}

575
int32_t projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBlock* pSrcBlock, SqlFunctionCtx* pCtx,
X
Xiaoyu Wang 已提交
576
                              int32_t numOfOutput, SArray* pPseudoList) {
H
Haojun Liao 已提交
577
  setPseudoOutputColInfo(pResult, pCtx, pPseudoList);
H
Haojun Liao 已提交
578
  pResult->info.groupId = pSrcBlock->info.groupId;
H
Haojun Liao 已提交
579

580 581
  // if the source equals to the destination, it is to create a new column as the result of scalar
  // function or some operators.
582 583
  bool createNewColModel = (pResult == pSrcBlock);

584 585
  int32_t numOfRows = 0;

586
  for (int32_t k = 0; k < numOfOutput; ++k) {
587 588
    int32_t               outputSlotId = pExpr[k].base.resSchema.slotId;
    SqlFunctionCtx*       pfCtx = &pCtx[k];
589
    SInputColumnInfoData* pInputData = &pfCtx->input;
590

L
Liu Jicong 已提交
591
    if (pExpr[k].pExpr->nodeType == QUERY_NODE_COLUMN) {  // it is a project query
592
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
593
      if (pResult->info.rows > 0 && !createNewColModel) {
594 595
        colDataMergeCol(pColInfoData, pResult->info.rows, &pResult->info.capacity, pInputData->pData[0],
                        pInputData->numOfRows);
596
      } else {
597
        colDataAssign(pColInfoData, pInputData->pData[0], pInputData->numOfRows, &pResult->info);
598
      }
599

600
      numOfRows = pInputData->numOfRows;
601
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_VALUE) {
602
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
603

dengyihao's avatar
dengyihao 已提交
604
      int32_t offset = createNewColModel ? 0 : pResult->info.rows;
605 606 607 608 609 610 611 612

      int32_t type = pExpr[k].base.pParam[0].param.nType;
      if (TSDB_DATA_TYPE_NULL == type) {
        colDataAppendNNULL(pColInfoData, offset, pSrcBlock->info.rows);
      } else {
        for (int32_t i = 0; i < pSrcBlock->info.rows; ++i) {
          colDataAppend(pColInfoData, i + offset, taosVariantGet(&pExpr[k].base.pParam[0].param, type), false);
        }
613
      }
614 615

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

620
      SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
621
      SColumnInfoData  idata = {.info = pResColData->info, .hasNull = true};
622

623
      SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
624
      int32_t      code = scalarCalculate(pExpr[k].pExpr->_optrRoot.pRootNode, pBlockList, &dest);
625 626 627 628
      if (code != TSDB_CODE_SUCCESS) {
        taosArrayDestroy(pBlockList);
        return code;
      }
629

dengyihao's avatar
dengyihao 已提交
630
      int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
631
      ASSERT(pResult->info.capacity > 0);
632
      colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
D
dapan1121 已提交
633
      colDataDestroy(&idata);
L
Liu Jicong 已提交
634

635
      numOfRows = dest.numOfRows;
636 637
      taosArrayDestroy(pBlockList);
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_FUNCTION) {
638 639
      // _rowts/_c0, not tbname column
      if (fmIsPseudoColumnFunc(pfCtx->functionId) && (!fmIsScanPseudoColumnFunc(pfCtx->functionId))) {
H
Haojun Liao 已提交
640
        // do nothing
641
      } else if (fmIsIndefiniteRowsFunc(pfCtx->functionId)) {
642 643
        SResultRowEntryInfo* pResInfo = GET_RES_INFO(pfCtx);
        pfCtx->fpSet.init(pfCtx, pResInfo);
644 645 646 647 648 649 650 651 652 653 654

        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 已提交
655
      } else if (fmIsAggFunc(pfCtx->functionId)) {
656 657
        // _group_key function for "partition by tbname" + csum(col_name) query
        SColumnInfoData* pOutput = taosArrayGet(pResult->pDataBlock, outputSlotId);
658
        int32_t          slotId = pfCtx->param[0].pCol->slotId;
659 660 661

        // todo handle the json tag
        SColumnInfoData* pInput = taosArrayGet(pSrcBlock->pDataBlock, slotId);
662
        for (int32_t f = 0; f < pSrcBlock->info.rows; ++f) {
663 664 665 666 667 668 669 670 671
          bool isNull = colDataIsNull_s(pInput, f);
          if (isNull) {
            colDataAppendNULL(pOutput, pResult->info.rows + f);
          } else {
            char* data = colDataGetData(pInput, f);
            colDataAppend(pOutput, pResult->info.rows + f, data, isNull);
          }
        }

H
Haojun Liao 已提交
672 673 674
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
675

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

679
        SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
680
        int32_t      code = scalarCalculate((SNode*)pExpr[k].pExpr->_function.pFunctNode, pBlockList, &dest);
681 682 683 684
        if (code != TSDB_CODE_SUCCESS) {
          taosArrayDestroy(pBlockList);
          return code;
        }
685

dengyihao's avatar
dengyihao 已提交
686
        int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
687
        ASSERT(pResult->info.capacity > 0);
688
        colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
D
dapan1121 已提交
689
        colDataDestroy(&idata);
690 691

        numOfRows = dest.numOfRows;
H
Haojun Liao 已提交
692 693
        taosArrayDestroy(pBlockList);
      }
694
    } else {
695
      ASSERT(0);
696 697
    }
  }
698

699 700 701
  if (!createNewColModel) {
    pResult->info.rows += numOfRows;
  }
702 703

  return TSDB_CODE_SUCCESS;
704 705
}

5
54liuyao 已提交
706
bool functionNeedToExecute(SqlFunctionCtx* pCtx) {
707
  struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
708

709 710 711 712 713
  // in case of timestamp column, always generated results.
  int32_t functionId = pCtx->functionId;
  if (functionId == -1) {
    return false;
  }
714

715 716
  if (pCtx->scanFlag == REPEAT_SCAN) {
    return fmIsRepeatScanFunc(pCtx->functionId);
717 718
  }

719 720
  if (isRowEntryCompleted(pResInfo)) {
    return false;
721 722
  }

723 724 725
  return true;
}

726 727 728 729 730 731 732
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;
    }
733

734 735 736
    // Set the correct column info (data type and bytes)
    pInput->pData[paramIndex]->info.type = type;
    pInput->pData[paramIndex]->info.bytes = tDataTypes[type].bytes;
737
  }
H
Haojun Liao 已提交
738

739 740 741 742 743 744
  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;
745 746
    }
  } else {
747
    da = pInput->pColumnDataAgg[paramIndex];
748 749
  }

750
  ASSERT(!IS_VAR_DATA_TYPE(type));
751

752 753
  if (type == TSDB_DATA_TYPE_BIGINT) {
    int64_t v = pFuncParam->param.i;
754
    *da = (SColumnDataAgg){.numOfNull = 0, .min = v, .max = v, .sum = v * numOfRows};
755 756
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
757
    *da = (SColumnDataAgg){.numOfNull = 0};
758

759 760 761 762 763 764
    *(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;

765
    *da = (SColumnDataAgg){.numOfNull = 0};
766 767 768 769 770
    *(bool*)&da->min = 0;
    *(bool*)&da->max = v;
    *(bool*)&da->sum = v * numOfRows;
  } else if (type == TSDB_DATA_TYPE_TIMESTAMP) {
    // do nothing
771
  } else {
772
    ASSERT(0);
773 774
  }

775 776
  return TSDB_CODE_SUCCESS;
}
777 778 779 780 781 782 783 784 785 786 787

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;

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

791 792
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
793 794 795 796
        pInput->pColumnDataAgg[j] = pBlock->pBlockAgg[slotId];
        if (pInput->pColumnDataAgg[j] == NULL) {
          pInput->colDataAggIsSet = false;
        }
797 798 799 800

        // 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);
801 802
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
        doCreateConstantValColumnAggInfo(pInput, pFuncParam, pFuncParam->param.nType, j, pBlock->info.rows);
803 804
      }
    }
805
  } else {
806
    pInput->colDataAggIsSet = false;
807 808 809
  }

  // set the statistics data for primary time stamp column
810 811 812 813 814
  //  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;
  //  }
815 816
}

L
Liu Jicong 已提交
817
bool isTaskKilled(SExecTaskInfo* pTaskInfo) {
818 819
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
L
Liu Jicong 已提交
820 821
  if (pTaskInfo->owner != 0 &&
      ((taosGetTimestampSec() - pTaskInfo->cost.start / 1000) > 10 * getMaximumIdleDurationSec())
822 823
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
    assert(pTaskInfo->cost.start != 0);
L
Liu Jicong 已提交
824 825 826
    //    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;
827 828 829 830 831
  }

  return false;
}

L
Liu Jicong 已提交
832
void setTaskKilled(SExecTaskInfo* pTaskInfo) { pTaskInfo->code = TSDB_CODE_TSC_QUERY_CANCELLED; }
833 834

/////////////////////////////////////////////////////////////////////////////////////////////
835
STimeWindow getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key) {
L
Liu Jicong 已提交
836
  STimeWindow win = {0};
837
  win.skey = taosTimeTruncate(key, pInterval, precision);
838 839

  /*
H
Haojun Liao 已提交
840
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
841 842
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
843 844 845
  win.ekey = taosTimeAdd(win.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
  if (win.ekey < win.skey) {
    win.ekey = INT64_MAX;
846
  }
847 848

  return win;
849 850
}

851
#if 0
L
Liu Jicong 已提交
852
static int32_t updateBlockLoadStatus(STaskAttr* pQuery, int32_t status) {
853

854 855 856
  bool hasFirstLastFunc = false;
  bool hasOtherFunc = false;

857
  if (status == BLK_DATA_DATA_LOAD || status == BLK_DATA_FILTEROUT) {
858 859 860 861 862
    return status;
  }

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

864 865 866 867 868 869 870 871 872 873
    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;
    }
874

875 876
  }

877
  if (hasFirstLastFunc && status == BLK_DATA_NOT_LOAD) {
L
Liu Jicong 已提交
878
    if (!hasOtherFunc) {
879
      return BLK_DATA_FILTEROUT;
880
    } else {
881
      return BLK_DATA_DATA_LOAD;
882 883 884 885 886 887
    }
  }

  return status;
}

888 889
#endif

L
Liu Jicong 已提交
890 891
// static void updateDataCheckOrder(SQInfo *pQInfo, SQueryTableReq* pQueryMsg, bool stableQuery) {
//   STaskAttr* pQueryAttr = pQInfo->runtimeEnv.pQueryAttr;
H
Haojun Liao 已提交
892
//
L
Liu Jicong 已提交
893 894 895 896
//   // 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 已提交
897
//
L
Liu Jicong 已提交
898 899 900 901 902
//   // 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 已提交
903
//
L
Liu Jicong 已提交
904 905
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
wafwerar's avatar
wafwerar 已提交
906
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
907
//     }
H
Haojun Liao 已提交
908
//
L
Liu Jicong 已提交
909 910 911
//     pQueryAttr->needReverseScan = false;
//     return;
//   }
H
Haojun Liao 已提交
912
//
L
Liu Jicong 已提交
913 914 915
//   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 已提交
916
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
917
//     }
H
Haojun Liao 已提交
918
//
L
Liu Jicong 已提交
919 920 921 922
//     pQueryAttr->needReverseScan = false;
//     doUpdateLastKey(pQueryAttr);
//     return;
//   }
H
Haojun Liao 已提交
923
//
L
Liu Jicong 已提交
924 925 926 927 928 929
//   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 已提交
930
//
L
Liu Jicong 已提交
931 932 933
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     return;
//   }
H
Haojun Liao 已提交
934
//
L
Liu Jicong 已提交
935 936 937 938
//   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 已提交
939 940
////               pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey);
//
wafwerar's avatar
wafwerar 已提交
941
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
942 943 944 945 946 947 948 949 950 951
//        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 已提交
952
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
953 954 955 956 957 958 959 960 961 962 963 964
//        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 已提交
965 966
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
967
//
wafwerar's avatar
wafwerar 已提交
968
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
969 970 971 972 973 974 975 976
//          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 已提交
977 978
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
979
//
wafwerar's avatar
wafwerar 已提交
980
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
981 982 983 984 985 986 987 988 989
//          doUpdateLastKey(pQueryAttr);
//        }
//
//        pQueryAttr->order.order = TSDB_ORDER_DESC;
//        pQueryAttr->needReverseScan = false;
//      }
//    }
//  }
//}
990

L
Liu Jicong 已提交
991 992 993
// static FORCE_INLINE bool doFilterByBlockStatistics(STaskRuntimeEnv* pRuntimeEnv, SDataStatis *pDataStatis,
// SqlFunctionCtx *pCtx, int32_t numOfRows) {
//   STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
994
//
L
Liu Jicong 已提交
995 996 997
//   if (pDataStatis == NULL || pQueryAttr->pFilters == NULL) {
//     return true;
//   }
998
//
L
Liu Jicong 已提交
999 1000
//   return filterRangeExecute(pQueryAttr->pFilters, pDataStatis, pQueryAttr->numOfCols, numOfRows);
// }
1001
#if 0
H
Haojun Liao 已提交
1002
static bool overlapWithTimeWindow(STaskAttr* pQueryAttr, SDataBlockInfo* pBlockInfo) {
1003 1004
  STimeWindow w = {0};

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

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

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

L
Liu Jicong 已提交
1016 1017
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
      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 已提交
1028
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
1029 1030 1031 1032 1033 1034
    assert(w.skey <= pBlockInfo->window.ekey);

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

L
Liu Jicong 已提交
1035 1036
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
      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;
}
1050
#endif
1051 1052

static uint32_t doFilterByBlockTimeWindow(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
1053
#if 0
H
Haojun Liao 已提交
1054
  SqlFunctionCtx* pCtx = pTableScanInfo->pCtx;
1055
  uint32_t        status = BLK_DATA_NOT_LOAD;
1056

L
Liu Jicong 已提交
1057
  int32_t numOfOutput = 0;  // pTableScanInfo->numOfOutput;
1058 1059
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;
H
Haojun Liao 已提交
1060
    int32_t colId = pTableScanInfo->pExpr[i].base.pParam[0].pCol->colId;
1061 1062 1063

    // group by + first/last should not apply the first/last block filter
    if (functionId < 0) {
1064
      status |= BLK_DATA_DATA_LOAD;
1065 1066
      return status;
    } else {
L
Liu Jicong 已提交
1067
      //      status |= aAggs[functionId].dataReqFunc(&pTableScanInfo->pCtx[i], &pBlock->info.window, colId);
1068
      //      if ((status & BLK_DATA_DATA_LOAD) == BLK_DATA_DATA_LOAD) {
L
Liu Jicong 已提交
1069 1070
      //        return status;
      //      }
1071 1072 1073 1074
    }
  }

  return status;
H
Haojun Liao 已提交
1075 1076
#endif
  return 0;
1077 1078
}

L
Liu Jicong 已提交
1079 1080
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
1081
  *status = BLK_DATA_NOT_LOAD;
1082

H
Haojun Liao 已提交
1083
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
1084
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
1085

L
Liu Jicong 已提交
1086 1087
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
1088

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

1091 1092
//  pCost->totalBlocks += 1;
//  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
1093
#if 0
1094 1095 1096
  // 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 已提交
1097
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
1098
    (*status) = BLK_DATA_DATA_LOAD;
1099 1100 1101
  }

  // check if this data block is required to load
1102
  if ((*status) != BLK_DATA_DATA_LOAD) {
1103 1104 1105 1106 1107 1108 1109
    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 已提交
1110
      bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1111 1112 1113 1114 1115 1116
      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,
1117
                                    pTableScanInfo->rowEntryInfoOffset);
1118 1119 1120
      } else {
        if (setResultOutputBufByKey(pRuntimeEnv, pTableScanInfo->pResultRowInfo, pBlock->info.uid, &win, masterScan, &pResult, groupId,
                                    pTableScanInfo->pCtx, pTableScanInfo->numOfOutput,
1121
                                    pTableScanInfo->rowEntryInfoOffset) != TSDB_CODE_SUCCESS) {
1122 1123 1124 1125 1126
          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,
1127
                               pTableScanInfo->rowEntryInfoOffset, pTableScanInfo->numOfOutput,
1128 1129 1130 1131 1132 1133
                               pRuntimeEnv->current->groupIndex);
    }

    if (needFilter) {
      (*status) = doFilterByBlockTimeWindow(pTableScanInfo, pBlock);
    } else {
1134
      (*status) = BLK_DATA_DATA_LOAD;
1135 1136 1137 1138
    }
  }

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

1141
  if ((*status) == BLK_DATA_NOT_LOAD || (*status) == BLK_DATA_FILTEROUT) {
1142 1143
    //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//           pBlockInfo->window.ekey, pBlockInfo->rows);
1144
    pCost->skipBlocks += 1;
1145
  } else if ((*status) == BLK_DATA_SMA_LOAD) {
1146 1147
    // this function never returns error?
    pCost->loadBlockStatis += 1;
1148
//    tsdbRetrieveDatablockSMA(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1149 1150

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
1151
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1152 1153 1154
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
1155
    assert((*status) == BLK_DATA_DATA_LOAD);
1156 1157 1158

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
1159
//    tsdbRetrieveDatablockSMA(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1160 1161 1162 1163 1164 1165

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

H
Haojun Liao 已提交
1166
          bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1167 1168 1169 1170 1171
          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,
1172
                                      pTableScanInfo->rowEntryInfoOffset) != TSDB_CODE_SUCCESS) {
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
            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
1184
            pCost->skipBlocks += 1;
1185 1186
            //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId,
//                   pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
1187
            (*status) = BLK_DATA_FILTEROUT;
1188 1189 1190 1191 1192 1193 1194 1195
            return TSDB_CODE_SUCCESS;
          }
        }
      }
    }

    // current block has been discard due to filter applied
//    if (!doFilterByBlockStatistics(pRuntimeEnv, pBlock->pBlockAgg, pTableScanInfo->pCtx, pBlockInfo->rows)) {
1196
//      pCost->skipBlocks += 1;
1197 1198
//      qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//             pBlockInfo->window.ekey, pBlockInfo->rows);
1199
//      (*status) = BLK_DATA_FILTEROUT;
1200 1201 1202 1203 1204
//      return TSDB_CODE_SUCCESS;
//    }

    pCost->totalCheckedRows += pBlockInfo->rows;
    pCost->loadBlocks += 1;
1205
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1206 1207 1208 1209 1210
//    if (pBlock->pDataBlock == NULL) {
//      return terrno;
//    }

//    if (pQueryAttr->pFilters != NULL) {
1211
//      filterSetColFieldData(pQueryAttr->pFilters, taosArrayGetSize(pBlock->pDataBlock), pBlock->pDataBlock);
1212
//    }
1213

1214 1215 1216 1217
//    if (pQueryAttr->pFilters != NULL || pRuntimeEnv->pTsBuf != NULL) {
//      filterColRowsInDataBlock(pRuntimeEnv, pBlock, ascQuery);
//    }
  }
H
Haojun Liao 已提交
1218
#endif
1219 1220 1221
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1222
static void updateTableQueryInfoForReverseScan(STableQueryInfo* pTableQueryInfo) {
1223 1224 1225 1226
  if (pTableQueryInfo == NULL) {
    return;
  }

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

L
Liu Jicong 已提交
1230 1231
  //  SWITCH_ORDER(pTableQueryInfo->cur.order);
  //  pTableQueryInfo->cur.vgroupIndex = -1;
1232 1233

  // set the index to be the end slot of result rows array
dengyihao's avatar
dengyihao 已提交
1234 1235 1236 1237 1238 1239
  //  SResultRowInfo* pResultRowInfo = &pTableQueryInfo->resInfo;
  //  if (pResultRowInfo->size > 0) {
  //    pResultRowInfo->curPos = pResultRowInfo->size - 1;
  //  } else {
  //    pResultRowInfo->curPos = -1;
  //  }
1240 1241
}

H
Haojun Liao 已提交
1242
void initResultRow(SResultRow* pResultRow) {
X
Xiaoyu Wang 已提交
1243
  //  pResultRow->pEntryInfo = (struct SResultRowEntryInfo*)((char*)pResultRow + sizeof(SResultRow));
1244 1245 1246 1247 1248
}

/*
 * 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 已提交
1249 1250 1251
 * +------------+-----------------result column 1------------+------------------result column 2-----------+
 * | SResultRow | SResultRowEntryInfo | intermediate buffer1 | SResultRowEntryInfo | intermediate buffer 2|
 * +------------+--------------------------------------------+--------------------------------------------+
1252 1253
 *           offset[0]                                  offset[1]                                   offset[2]
 */
1254
// TODO refactor: some function move away
L
Liu Jicong 已提交
1255 1256 1257
void setFunctionResultOutput(SOperatorInfo* pOperator, SOptrBasicInfo* pInfo, SAggSupporter* pSup, int32_t stage,
                             int32_t numOfExprs) {
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
1258 1259
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
  int32_t*        rowEntryInfoOffset = pOperator->exprSupp.rowEntryInfoOffset;
H
Haojun Liao 已提交
1260

H
Haojun Liao 已提交
1261
  SResultRowInfo* pResultRowInfo = &pInfo->resultRowInfo;
1262
  initResultRowInfo(pResultRowInfo);
H
Haojun Liao 已提交
1263

L
Liu Jicong 已提交
1264 1265
  int64_t     tid = 0;
  int64_t     groupId = 0;
1266 1267
  SResultRow* pRow = doSetResultOutBufByKey(pSup->pResultBuf, pResultRowInfo, (char*)&tid, sizeof(tid), true, groupId,
                                            pTaskInfo, false, pSup);
H
Haojun Liao 已提交
1268

1269
  for (int32_t i = 0; i < numOfExprs; ++i) {
1270
    struct SResultRowEntryInfo* pEntry = getResultEntryInfo(pRow, i, rowEntryInfoOffset);
H
Haojun Liao 已提交
1271 1272
    cleanupResultRowEntry(pEntry);

L
Liu Jicong 已提交
1273
    pCtx[i].resultInfo = pEntry;
1274
    pCtx[i].scanFlag = stage;
H
Haojun Liao 已提交
1275 1276
  }

1277
  initCtxOutputBuffer(pCtx, numOfExprs);
H
Haojun Liao 已提交
1278 1279
}

H
Haojun Liao 已提交
1280
void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size) {
1281 1282
  for (int32_t j = 0; j < size; ++j) {
    struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[j]);
dengyihao's avatar
dengyihao 已提交
1283 1284
    if (isRowEntryInitialized(pResInfo) || fmIsPseudoColumnFunc(pCtx[j].functionId) || pCtx[j].functionId == -1 ||
        fmIsScalarFunc(pCtx[j].functionId)) {
1285 1286 1287
      continue;
    }

H
Haojun Liao 已提交
1288
    pCtx[j].fpSet.init(&pCtx[j], pCtx[j].resultInfo);
1289 1290 1291
  }
}

L
Liu Jicong 已提交
1292
void setTaskStatus(SExecTaskInfo* pTaskInfo, int8_t status) {
1293
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
1294
    pTaskInfo->status = status;
1295 1296
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
1297
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
1298
    pTaskInfo->status |= status;
1299 1300 1301
  }
}

L
Liu Jicong 已提交
1302
void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo) {
1303 1304 1305 1306
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
1307
  //  taosVariantDestroy(&pTableQueryInfo->tag);
dengyihao's avatar
dengyihao 已提交
1308
  //  cleanupResultRowInfo(&pTableQueryInfo->resInfo);
1309 1310
}

1311
void setResultRowInitCtx(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowEntryInfoOffset) {
1312
  for (int32_t i = 0; i < numOfOutput; ++i) {
1313
    pCtx[i].resultInfo = getResultEntryInfo(pResult, i, rowEntryInfoOffset);
1314 1315 1316 1317 1318

    struct SResultRowEntryInfo* pResInfo = pCtx[i].resultInfo;
    if (isRowEntryCompleted(pResInfo) && isRowEntryInitialized(pResInfo)) {
      continue;
    }
1319 1320 1321 1322 1323

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

1324 1325 1326 1327 1328 1329
    if (!pResInfo->initialized) {
      if (pCtx[i].functionId != -1) {
        pCtx[i].fpSet.init(&pCtx[i], pResInfo);
      } else {
        pResInfo->initialized = true;
      }
1330 1331 1332 1333
    }
  }
}

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

1336
void doFilter(const SNode* pFilterNode, SSDataBlock* pBlock, const SArray* pColMatchInfo) {
1337
  if (pFilterNode == NULL || pBlock->info.rows == 0) {
S
shenglian zhou 已提交
1338 1339
    return;
  }
1340

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

H
Haojun Liao 已提交
1343
  // todo move to the initialization function
H
Haojun Liao 已提交
1344
  int32_t code = filterInitFromNode((SNode*)pFilterNode, &filter, 0);
1345

1346
  size_t             numOfCols = taosArrayGetSize(pBlock->pDataBlock);
1347
  SFilterColumnParam param1 = {.numOfCols = numOfCols, .pDataBlock = pBlock->pDataBlock};
1348 1349 1350
  code = filterSetDataFromSlotId(filter, &param1);

  int8_t* rowRes = NULL;
1351

1352
  // todo the keep seems never to be True??
1353
  bool keep = filterExecute(filter, pBlock, &rowRes, NULL, param1.numOfCols);
D
dapan1121 已提交
1354
  filterFreeInfo(filter);
1355

H
Haojun Liao 已提交
1356
  extractQualifiedTupleByFilterResult(pBlock, rowRes, keep);
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370

  if (pColMatchInfo != NULL) {
    for(int32_t i = 0; i < taosArrayGetSize(pColMatchInfo); ++i) {
      SColMatchInfo* pInfo = taosArrayGet(pColMatchInfo, i);
      if (pInfo->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
        SColumnInfoData* pColData = taosArrayGet(pBlock->pDataBlock, pInfo->targetSlotId);
        if (pColData->info.type == TSDB_DATA_TYPE_TIMESTAMP) {
          blockDataUpdateTsWindow(pBlock, pInfo->targetSlotId);
          break;
        }
      }
    }
  }

H
Haojun Liao 已提交
1371
  taosMemoryFree(rowRes);
1372 1373
}

H
Haojun Liao 已提交
1374
void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const int8_t* rowRes, bool keep) {
1375 1376 1377 1378 1379
  if (keep) {
    return;
  }

  if (rowRes != NULL) {
L
Liu Jicong 已提交
1380
    int32_t      totalRows = pBlock->info.rows;
1381
    SSDataBlock* px = createOneDataBlock(pBlock, true);
1382

1383 1384
    size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
    for (int32_t i = 0; i < numOfCols; ++i) {
1385 1386
      SColumnInfoData* pSrc = taosArrayGet(px->pDataBlock, i);
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, i);
1387
      // it is a reserved column for scalar function, and no data in this column yet.
1388
      if (pDst->pData == NULL || pSrc->pData == NULL) {
1389 1390 1391
        continue;
      }

1392 1393
      colInfoDataCleanup(pDst, pBlock->info.rows);

1394
      int32_t numOfRows = 0;
1395
      for (int32_t j = 0; j < totalRows; ++j) {
D
dapan1121 已提交
1396 1397 1398
        if (rowRes[j] == 0) {
          continue;
        }
1399

D
dapan1121 已提交
1400
        if (colDataIsNull_s(pSrc, j)) {
1401
          colDataAppendNULL(pDst, numOfRows);
D
dapan1121 已提交
1402
        } else {
1403
          colDataAppend(pDst, numOfRows, colDataGetData(pSrc, j), false);
D
dapan1121 已提交
1404
        }
1405
        numOfRows += 1;
H
Haojun Liao 已提交
1406
      }
1407

1408 1409 1410 1411 1412
      if (pBlock->info.rows == totalRows) {
        pBlock->info.rows = numOfRows;
      } else {
        ASSERT(pBlock->info.rows == numOfRows);
      }
1413
    }
1414

dengyihao's avatar
dengyihao 已提交
1415
    blockDataDestroy(px);  // fix memory leak
1416 1417 1418
  } else {
    // do nothing
    pBlock->info.rows = 0;
1419 1420 1421
  }
}

L
Liu Jicong 已提交
1422 1423
void doSetTableGroupOutputBuf(SOperatorInfo* pOperator, SAggOperatorInfo* pAggInfo, int32_t numOfOutput,
                              uint64_t groupId) {
1424
  // for simple group by query without interval, all the tables belong to one group result.
L
Liu Jicong 已提交
1425
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
1426
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
1427 1428
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
  int32_t*        rowEntryInfoOffset = pOperator->exprSupp.rowEntryInfoOffset;
1429

1430
  SResultRow* pResultRow = doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, (char*)&groupId,
L
Liu Jicong 已提交
1431
                                                  sizeof(groupId), true, groupId, pTaskInfo, false, &pAggInfo->aggSup);
L
Liu Jicong 已提交
1432
  assert(pResultRow != NULL);
1433 1434 1435 1436 1437 1438

  /*
   * 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 已提交
1439 1440
    int32_t ret =
        addNewWindowResultBuf(pResultRow, pAggInfo->aggSup.pResultBuf, groupId, pAggInfo->binfo.pRes->info.rowSize);
1441 1442 1443 1444 1445
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

1446
  setResultRowInitCtx(pResultRow, pCtx, numOfOutput, rowEntryInfoOffset);
1447 1448
}

1449
void setExecutionContext(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId, SAggOperatorInfo* pAggInfo) {
H
Haojun Liao 已提交
1450
  if (pAggInfo->groupId != INT32_MIN && pAggInfo->groupId == groupId) {
1451 1452
    return;
  }
1453
#ifdef BUF_PAGE_DEBUG
L
Liu Jicong 已提交
1454
  qDebug("page_setbuf, groupId:%" PRIu64, groupId);
1455
#endif
1456
  doSetTableGroupOutputBuf(pOperator, pAggInfo, numOfOutput, groupId);
1457 1458

  // record the current active group id
H
Haojun Liao 已提交
1459
  pAggInfo->groupId = groupId;
1460 1461
}

1462 1463
static void doUpdateNumOfRows(SResultRow* pRow, int32_t numOfExprs, const int32_t* rowCellOffset) {
  for (int32_t j = 0; j < numOfExprs; ++j) {
1464
    struct SResultRowEntryInfo* pResInfo = getResultEntryInfo(pRow, j, rowCellOffset);
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
    if (!isRowEntryInitialized(pResInfo)) {
      continue;
    }

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

1475
int32_t finalizeResultRowIntoResultDataBlock(SDiskbasedBuf* pBuf, SResultRowPosition* resultRowPosition,
S
shenglian zhou 已提交
1476 1477 1478
                                             SqlFunctionCtx* pCtx, SExprInfo* pExprInfo, int32_t numOfExprs,
                                             const int32_t* rowCellOffset, SSDataBlock* pBlock,
                                             SExecTaskInfo* pTaskInfo) {
1479 1480 1481 1482 1483 1484 1485 1486 1487
  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;
  }

1488 1489 1490 1491 1492 1493 1494
  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);
    }
1495 1496 1497 1498 1499
  }

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

1500
    pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowCellOffset);
1501 1502 1503 1504 1505 1506 1507 1508 1509
    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 {
1510 1511
      // expand the result into multiple rows. E.g., _wstart, top(k, 20)
      // the _wstart needs to copy to 20 following rows, since the results of top-k expands to 20 different rows.
1512 1513 1514 1515 1516 1517 1518 1519 1520
      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);
1521
  pBlock->info.rows += pRow->numOfRows;
1522 1523 1524 1525

  return 0;
}

X
Xiaoyu Wang 已提交
1526 1527 1528
int32_t doCopyToSDataBlock(SExecTaskInfo* pTaskInfo, SSDataBlock* pBlock, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf,
                           SGroupResInfo* pGroupResInfo, const int32_t* rowCellOffset, SqlFunctionCtx* pCtx,
                           int32_t numOfExprs) {
1529
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
1530
  int32_t start = pGroupResInfo->index;
1531

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

1536
    SResultRow* pRow = (SResultRow*)((char*)page + pPos->pos.offset);
1537 1538

    doUpdateNumOfRows(pRow, numOfExprs, rowCellOffset);
1539 1540
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
1541
      releaseBufPage(pBuf, page);
1542 1543 1544
      continue;
    }

1545 1546 1547 1548 1549
    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) {
1550
        releaseBufPage(pBuf, page);
1551 1552 1553 1554
        break;
      }
    }

1555
    if (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
1556
      releaseBufPage(pBuf, page);
1557 1558 1559 1560 1561
      break;
    }

    pGroupResInfo->index += 1;

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

1565
      pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowCellOffset);
1566
      if (pCtx[j].fpSet.finalize) {
1567
#ifdef BUF_PAGE_DEBUG
wmmhello's avatar
wmmhello 已提交
1568
        qDebug("\npage_finalize %d", numOfExprs);
1569
#endif
1570
        int32_t code = pCtx[j].fpSet.finalize(&pCtx[j], pBlock);
1571
        if (TAOS_FAILED(code)) {
1572 1573
          qError("%s build result data block error, code %s", GET_TASKID(pTaskInfo), tstrerror(code));
          longjmp(pTaskInfo->env, code);
1574
        }
1575 1576
      } else if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
        // do nothing, todo refactor
1577
      } else {
1578 1579
        // expand the result into multiple rows. E.g., _wstart, top(k, 20)
        // the _wstart needs to copy to 20 following rows, since the results of top-k expands to 20 different rows.
X
Xiaoyu Wang 已提交
1580 1581
        SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId);
        char*            in = GET_ROWCELL_INTERBUF(pCtx[j].resultInfo);
1582
        if (pCtx[j].increase) {
L
Liu Jicong 已提交
1583
          int64_t ts = *(int64_t*)in;
1584
          for (int32_t k = 0; k < pRow->numOfRows; ++k) {
L
Liu Jicong 已提交
1585
            colDataAppend(pColInfoData, pBlock->info.rows + k, (const char*)&ts, pCtx[j].resultInfo->isNullRes);
1586 1587 1588 1589 1590 1591
            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 已提交
1592
        }
1593
      }
1594 1595
    }

1596
    releaseBufPage(pBuf, page);
1597
    pBlock->info.rows += pRow->numOfRows;
L
Liu Jicong 已提交
1598 1599 1600
    //    if (pBlock->info.rows >= pBlock->info.capacity) {  // output buffer is full
    //      break;
    //    }
1601 1602
  }

X
Xiaoyu Wang 已提交
1603 1604
  qDebug("%s result generated, rows:%d, groupId:%" PRIu64, GET_TASKID(pTaskInfo), pBlock->info.rows,
         pBlock->info.groupId);
1605
  blockDataUpdateTsWindow(pBlock, 0);
1606 1607 1608
  return 0;
}

X
Xiaoyu Wang 已提交
1609 1610
void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SGroupResInfo* pGroupResInfo,
                            SDiskbasedBuf* pBuf) {
1611 1612
  SExprInfo*     pExprInfo = pOperator->exprSupp.pExprInfo;
  int32_t        numOfExprs = pOperator->exprSupp.numOfExprs;
1613 1614
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

1615
  int32_t*        rowCellOffset = pOperator->exprSupp.rowEntryInfoOffset;
X
Xiaoyu Wang 已提交
1616
  SSDataBlock*    pBlock = pbInfo->pRes;
1617
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
1618

1619 1620 1621
  // set output datablock version
  pBlock->info.version = pTaskInfo->version;

1622
  blockDataCleanup(pBlock);
1623
  if (!hasDataInGroupInfo(pGroupResInfo)) {
1624 1625 1626
    return;
  }

1627 1628
  // clear the existed group id
  pBlock->info.groupId = 0;
1629
  doCopyToSDataBlock(pTaskInfo, pBlock, pExprInfo, pBuf, pGroupResInfo, rowCellOffset, pCtx, numOfExprs);
1630 1631
}

L
Liu Jicong 已提交
1632
static void updateNumOfRowsInResultRows(SqlFunctionCtx* pCtx, int32_t numOfOutput, SResultRowInfo* pResultRowInfo,
1633
                                        int32_t* rowEntryInfoOffset) {
1634
  // update the number of result for each, only update the number of rows for the corresponding window result.
L
Liu Jicong 已提交
1635 1636 1637
  //  if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
  //    return;
  //  }
H
Haojun Liao 已提交
1638
#if 0
1639
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
L
Liu Jicong 已提交
1640
    SResultRow* pResult = pResultRowInfo->pResult[i];
1641 1642 1643 1644 1645 1646 1647

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

1648
      SResultRowEntryInfo* pCell = getResultEntryInfo(pResult, j, rowEntryInfoOffset);
1649
      pResult->numOfRows = (uint16_t)(TMAX(pResult->numOfRows, pCell->numOfRes));
1650 1651
    }
  }
H
Haojun Liao 已提交
1652
#endif
1653 1654
}

L
Liu Jicong 已提交
1655
static int32_t compressQueryColData(SColumnInfoData* pColRes, int32_t numOfRows, char* data, int8_t compressed) {
1656 1657
  int32_t colSize = pColRes->info.bytes * numOfRows;
  return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data,
L
Liu Jicong 已提交
1658
                                                      colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0);
1659 1660
}

L
Liu Jicong 已提交
1661 1662
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
1663

L
Liu Jicong 已提交
1664 1665 1666
  //  uint64_t hashSize = taosHashGetMemSize(pQInfo->runtimeEnv.pResultRowHashTable);
  //  hashSize += taosHashGetMemSize(pRuntimeEnv->tableqinfoGroupInfo.map);
  //  pSummary->hashSize = hashSize;
1667 1668 1669 1670

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

L
Liu Jicong 已提交
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
  //  SResultRowPool* p = pTaskInfo->pool;
  //  if (p != NULL) {
  //    pSummary->winInfoSize = getResultRowPoolMemSize(p);
  //    pSummary->numOfTimeWindows = getNumOfAllocatedResultRows(p);
  //  } else {
  //    pSummary->winInfoSize = 0;
  //    pSummary->numOfTimeWindows = 0;
  //  }
  //
  //  calculateOperatorProfResults(pQInfo);

1682 1683
  SFileBlockLoadRecorder* pRecorder = pSummary->pRecoder;
  if (pSummary->pRecoder != NULL) {
X
Xiaoyu Wang 已提交
1684 1685
    qDebug("%s :cost summary: elapsed time:%" PRId64 " us, first merge:%" PRId64
           " us, total blocks:%d, "
1686 1687 1688 1689
           "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 已提交
1690 1691 1692
  // 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);
1693 1694
}

L
Liu Jicong 已提交
1695 1696 1697
// static void updateOffsetVal(STaskRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
1698
//
L
Liu Jicong 已提交
1699
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
1700
//
L
Liu Jicong 已提交
1701 1702 1703 1704
//   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;
//   }
1705
//
L
Liu Jicong 已提交
1706 1707 1708 1709 1710
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     pQueryAttr->pos = (int32_t)pQueryAttr->limit.offset;
//   } else {
//     pQueryAttr->pos = pBlockInfo->rows - (int32_t)pQueryAttr->limit.offset - 1;
//   }
1711
//
L
Liu Jicong 已提交
1712
//   assert(pQueryAttr->pos >= 0 && pQueryAttr->pos <= pBlockInfo->rows - 1);
1713
//
L
Liu Jicong 已提交
1714 1715
//   SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//   SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
1716
//
L
Liu Jicong 已提交
1717 1718
//   // update the pQueryAttr->limit.offset value, and pQueryAttr->pos value
//   TSKEY *keys = (TSKEY *) pColInfoData->pData;
1719
//
L
Liu Jicong 已提交
1720 1721 1722
//   // update the offset value
//   pTableQueryInfo->lastKey = keys[pQueryAttr->pos];
//   pQueryAttr->limit.offset = 0;
1723
//
L
Liu Jicong 已提交
1724
//   int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
1725
//
L
Liu Jicong 已提交
1726 1727 1728 1729
//   //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);
// }
1730

L
Liu Jicong 已提交
1731 1732
// void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
1733
//
L
Liu Jicong 已提交
1734 1735 1736
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//     return;
//   }
1737
//
L
Liu Jicong 已提交
1738 1739
//   pQueryAttr->pos = 0;
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
1740
//
L
Liu Jicong 已提交
1741 1742
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//   TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
1743
//
L
Liu Jicong 已提交
1744 1745 1746 1747 1748
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pTsdbReadHandle)) {
//     if (isTaskKilled(pRuntimeEnv->qinfo)) {
//       longjmp(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
//     }
1749
//
L
Liu Jicong 已提交
1750
//     tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
1751
//
L
Liu Jicong 已提交
1752 1753 1754 1755
//     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;
1756
//
L
Liu Jicong 已提交
1757 1758 1759 1760 1761 1762 1763
//       //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;
//     }
//   }
1764
//
L
Liu Jicong 已提交
1765 1766 1767 1768 1769 1770 1771 1772 1773
//   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;
1774
//
L
Liu Jicong 已提交
1775 1776 1777
//   assert(pQueryAttr->limit.offset == 0);
//   STimeWindow tw = *win;
//   getNextTimeWindow(pQueryAttr, &tw);
1778
//
L
Liu Jicong 已提交
1779 1780
//   if ((tw.skey <= pBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) ||
//       (tw.ekey >= pBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
1781
//
L
Liu Jicong 已提交
1782 1783 1784 1785
//     // 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);
1786
//
L
Liu Jicong 已提交
1787 1788 1789 1790
//     tw = *win;
//     int32_t startPos =
//         getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1);
//     assert(startPos >= 0);
1791
//
L
Liu Jicong 已提交
1792 1793
//     // set the abort info
//     pQueryAttr->pos = startPos;
1794
//
L
Liu Jicong 已提交
1795 1796 1797 1798
//     // reset the query start timestamp
//     pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
//     pQueryAttr->window.skey = pTableQueryInfo->win.skey;
//     TSKEY key = pTableQueryInfo->win.skey;
1799
//
L
Liu Jicong 已提交
1800 1801
//     pWindowResInfo->prevSKey = tw.skey;
//     int32_t index = pRuntimeEnv->resultRowInfo.curIndex;
1802
//
L
Liu Jicong 已提交
1803 1804
//     int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//     pRuntimeEnv->resultRowInfo.curIndex = index;  // restore the window index
1805
//
L
Liu Jicong 已提交
1806 1807 1808 1809
//     //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);
1810
//
L
Liu Jicong 已提交
1811 1812 1813 1814 1815
//     return key;
//   } else {  // do nothing
//     pQueryAttr->window.skey      = tw.skey;
//     pWindowResInfo->prevSKey = tw.skey;
//     pTableQueryInfo->lastKey = tw.skey;
1816
//
L
Liu Jicong 已提交
1817 1818
//     return tw.skey;
//   }
1819
//
L
Liu Jicong 已提交
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
//   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);
//   }
1830
//
L
Liu Jicong 已提交
1831 1832 1833 1834 1835
//   // 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;
//   }
1836
//
L
Liu Jicong 已提交
1837 1838 1839 1840 1841 1842 1843
//   /*
//    * 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);
1844
//
L
Liu Jicong 已提交
1845 1846
//   STimeWindow w = TSWINDOW_INITIALIZER;
//   bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
1847
//
L
Liu Jicong 已提交
1848 1849
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//   STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
1850
//
L
Liu Jicong 已提交
1851 1852 1853
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pRuntimeEnv->pTsdbReadHandle)) {
//     tsdbRetrieveDataBlockInfo(pRuntimeEnv->pTsdbReadHandle, &blockInfo);
1854
//
L
Liu Jicong 已提交
1855 1856 1857 1858 1859 1860 1861 1862 1863
//     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;
//     }
1864
//
L
Liu Jicong 已提交
1865 1866
//     // the first time window
//     STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQueryAttr);
1867
//
L
Liu Jicong 已提交
1868 1869
//     while (pQueryAttr->limit.offset > 0) {
//       STimeWindow tw = win;
1870
//
L
Liu Jicong 已提交
1871 1872 1873
//       if ((win.ekey <= blockInfo.window.ekey && ascQuery) || (win.ekey >= blockInfo.window.skey && !ascQuery)) {
//         pQueryAttr->limit.offset -= 1;
//         pWindowResInfo->prevSKey = win.skey;
1874
//
L
Liu Jicong 已提交
1875 1876 1877 1878 1879 1880
//         // 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;
//         }
//       }
1881
//
L
Liu Jicong 已提交
1882 1883 1884 1885
//       if (pQueryAttr->limit.offset == 0) {
//         *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//         return true;
//       }
1886
//
L
Liu Jicong 已提交
1887 1888
//       // current window does not ended in current data block, try next data block
//       getNextTimeWindow(pQueryAttr, &tw);
1889
//
L
Liu Jicong 已提交
1890 1891 1892 1893 1894 1895 1896 1897 1898
//       /*
//        * 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)) {
1899
//
L
Liu Jicong 已提交
1900 1901
//         SArray *pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//         SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
1902
//
L
Liu Jicong 已提交
1903 1904 1905
//         if ((win.ekey > blockInfo.window.ekey && ascQuery) || (win.ekey < blockInfo.window.skey && !ascQuery)) {
//           pQueryAttr->limit.offset -= 1;
//         }
1906
//
L
Liu Jicong 已提交
1907 1908 1909 1910 1911 1912 1913 1914
//         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);
1915
//
L
Liu Jicong 已提交
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
//           // 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.
//       }
//     }
//   }
1927
//
L
Liu Jicong 已提交
1928 1929 1930 1931
//   // check for error
//   if (terrno != TSDB_CODE_SUCCESS) {
//     longjmp(pRuntimeEnv->env, terrno);
//   }
1932
//
L
Liu Jicong 已提交
1933 1934
//   return true;
// }
1935

1936
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
1937
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
1938
    assert(p->numOfDownstream == 0);
1939 1940
  }

wafwerar's avatar
wafwerar 已提交
1941
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
1942 1943 1944 1945 1946 1947 1948
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

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

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

1953
static void doTableQueryInfoTimeWindowCheck(SExecTaskInfo* pTaskInfo, STableQueryInfo* pTableQueryInfo, int32_t order) {
H
Haojun Liao 已提交
1954 1955
#if 0
    if (order == TSDB_ORDER_ASC) {
1956 1957
    assert(
        (pTableQueryInfo->win.skey <= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
1958 1959
        (pTableQueryInfo->lastKey >= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey >= pTaskInfo->window.skey && pTableQueryInfo->win.ekey <= pTaskInfo->window.ekey));
1960 1961 1962
  } else {
    assert(
        (pTableQueryInfo->win.skey >= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
1963 1964
        (pTableQueryInfo->lastKey <= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey <= pTaskInfo->window.skey && pTableQueryInfo->win.ekey >= pTaskInfo->window.ekey));
1965
  }
H
Haojun Liao 已提交
1966
#endif
1967 1968
}

1969 1970 1971 1972
typedef struct SFetchRspHandleWrapper {
  uint32_t exchangeId;
  int32_t  sourceIndex;
} SFetchRspHandleWrapper;
1973

D
dapan1121 已提交
1974
int32_t loadRemoteDataCallback(void* param, SDataBuf* pMsg, int32_t code) {
X
Xiaoyu Wang 已提交
1975
  SFetchRspHandleWrapper* pWrapper = (SFetchRspHandleWrapper*)param;
1976 1977 1978 1979 1980 1981 1982

  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 已提交
1983
  int32_t          index = pWrapper->sourceIndex;
1984
  SSourceDataInfo* pSourceDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, index);
1985

H
Haojun Liao 已提交
1986 1987
  if (code == TSDB_CODE_SUCCESS) {
    pSourceDataInfo->pRsp = pMsg->pData;
1988

H
Haojun Liao 已提交
1989 1990
    SRetrieveTableRsp* pRsp = pSourceDataInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
dengyihao's avatar
dengyihao 已提交
1991
    pRsp->compLen = htonl(pRsp->compLen);
1992
    pRsp->numOfCols = htonl(pRsp->numOfCols);
dengyihao's avatar
dengyihao 已提交
1993
    pRsp->useconds = htobe64(pRsp->useconds);
1994

1995
    ASSERT(pRsp != NULL);
1996
    qDebug("%s fetch rsp received, index:%d, rows:%d", pSourceDataInfo->taskId, index, pRsp->numOfRows);
H
Haojun Liao 已提交
1997 1998
  } else {
    pSourceDataInfo->code = code;
D
dapan1121 已提交
1999
    qDebug("%s fetch rsp received, index:%d, error:%d", pSourceDataInfo->taskId, index, tstrerror(code));
H
Haojun Liao 已提交
2000
  }
H
Haojun Liao 已提交
2001

H
Haojun Liao 已提交
2002
  pSourceDataInfo->status = EX_SOURCE_DATA_READY;
2003 2004 2005 2006

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

wmmhello's avatar
wmmhello 已提交
2007
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2008 2009
}

D
dapan1121 已提交
2010
void qProcessRspMsg(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
S
Shengliang Guan 已提交
2011 2012
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
  assert(pMsg->info.ahandle != NULL);
H
Haojun Liao 已提交
2013 2014 2015 2016

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

  if (pMsg->contLen > 0) {
wafwerar's avatar
wafwerar 已提交
2017
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
H
Haojun Liao 已提交
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
    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);
2029 2030
}

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

wafwerar's avatar
wafwerar 已提交
2034
  SResFetchReq* pMsg = taosMemoryCalloc(1, sizeof(SResFetchReq));
2035 2036 2037 2038
  if (NULL == pMsg) {
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
  }
2039

L
Liu Jicong 已提交
2040 2041
  SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, sourceIndex);
  SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, sourceIndex);
2042

2043 2044
  ASSERT(pDataInfo->status == EX_SOURCE_DATA_NOT_READY);

2045 2046 2047
  qDebug("%s build fetch msg and send to vgId:%d, ep:%s, taskId:0x%" PRIx64 ", execId:%d, %d/%" PRIzu,
         GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->addr.epSet.eps[0].fqdn, pSource->taskId, pSource->execId,
         sourceIndex, totalSources);
2048 2049 2050 2051 2052

  pMsg->header.vgId = htonl(pSource->addr.nodeId);
  pMsg->sId = htobe64(pSource->schedId);
  pMsg->taskId = htobe64(pSource->taskId);
  pMsg->queryId = htobe64(pTaskInfo->id.queryId);
D
dapan1121 已提交
2053
  pMsg->execId = htonl(pSource->execId);
2054 2055

  // send the fetch remote task result reques
wafwerar's avatar
wafwerar 已提交
2056
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
2057
  if (NULL == pMsgSendInfo) {
wafwerar's avatar
wafwerar 已提交
2058
    taosMemoryFreeClear(pMsg);
2059 2060 2061
    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 已提交
2062 2063
  }

2064
  SFetchRspHandleWrapper* pWrapper = taosMemoryCalloc(1, sizeof(SFetchRspHandleWrapper));
X
Xiaoyu Wang 已提交
2065
  pWrapper->exchangeId = pExchangeInfo->self;
2066 2067 2068
  pWrapper->sourceIndex = sourceIndex;

  pMsgSendInfo->param = pWrapper;
D
dapan1121 已提交
2069
  pMsgSendInfo->paramFreeFp = taosMemoryFree;
2070 2071
  pMsgSendInfo->msgInfo.pData = pMsg;
  pMsgSendInfo->msgInfo.len = sizeof(SResFetchReq);
L
Liu Jicong 已提交
2072
  pMsgSendInfo->msgType = pSource->fetchMsgType;
2073
  pMsgSendInfo->fp = loadRemoteDataCallback;
2074

2075
  int64_t transporterId = 0;
L
Liu Jicong 已提交
2076
  int32_t code = asyncSendMsgToServer(pExchangeInfo->pTransporter, &pSource->addr.epSet, &transporterId, pMsgSendInfo);
2077 2078 2079
  return TSDB_CODE_SUCCESS;
}

2080
int32_t extractDataBlockFromFetchRsp(SSDataBlock* pRes, SLoadRemoteDataInfo* pLoadInfo, int32_t numOfRows, char* pData,
L
Liu Jicong 已提交
2081 2082
                                     int32_t compLen, int32_t numOfOutput, int64_t startTs, uint64_t* total,
                                     SArray* pColList) {
H
Haojun Liao 已提交
2083
  if (pColList == NULL) {  // data from other sources
2084
    blockDataCleanup(pRes);
2085
    //    blockDataEnsureCapacity(pRes, numOfRows);
2086
    blockDecode(pRes, numOfOutput, numOfRows, pData);
H
Haojun Liao 已提交
2087
  } else {  // extract data according to pColList
2088
    ASSERT(numOfOutput == taosArrayGetSize(pColList));
2089 2090 2091 2092 2093
    char* pStart = pData;

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

2094
    // todo refactor:extract method
2095
    SSysTableSchema* pSchema = (SSysTableSchema*)pStart;
dengyihao's avatar
dengyihao 已提交
2096
    for (int32_t i = 0; i < numOfCols; ++i) {
2097 2098 2099 2100 2101 2102 2103
      SSysTableSchema* p = (SSysTableSchema*)pStart;

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

2104
    SSDataBlock* pBlock = createDataBlock();
dengyihao's avatar
dengyihao 已提交
2105
    for (int32_t i = 0; i < numOfCols; ++i) {
2106 2107
      SColumnInfoData idata = createColumnInfoData(pSchema[i].type, pSchema[i].bytes, pSchema[i].colId);
      blockDataAppendColInfo(pBlock, &idata);
2108 2109
    }

2110
    blockDecode(pBlock, numOfCols, numOfRows, pStart);
2111 2112
    blockDataEnsureCapacity(pRes, numOfRows);

H
Haojun Liao 已提交
2113
    // data from mnode
2114
    pRes->info.rows = numOfRows;
2115 2116
    relocateColumnData(pRes, pColList, pBlock->pDataBlock, false);
    blockDataDestroy(pBlock);
2117
  }
2118

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

2122
  int64_t el = taosGetTimestampUs() - startTs;
2123

H
Haojun Liao 已提交
2124 2125
  pLoadInfo->totalRows += numOfRows;
  pLoadInfo->totalSize += compLen;
2126

H
Haojun Liao 已提交
2127 2128 2129
  if (total != NULL) {
    *total += numOfRows;
  }
2130

H
Haojun Liao 已提交
2131
  pLoadInfo->totalElapsed += el;
2132 2133
  return TSDB_CODE_SUCCESS;
}
2134

L
Liu Jicong 已提交
2135 2136
static void* setAllSourcesCompleted(SOperatorInfo* pOperator, int64_t startTs) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
2137
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
2138

2139
  int64_t              el = taosGetTimestampUs() - startTs;
H
Haojun Liao 已提交
2140
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2141

H
Haojun Liao 已提交
2142
  pLoadInfo->totalElapsed += el;
H
Haojun Liao 已提交
2143

2144
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
L
Liu Jicong 已提交
2145 2146 2147
  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);
2148 2149 2150 2151 2152

  doSetOperatorCompleted(pOperator);
  return NULL;
}

L
Liu Jicong 已提交
2153 2154
static SSDataBlock* concurrentlyLoadRemoteDataImpl(SOperatorInfo* pOperator, SExchangeInfo* pExchangeInfo,
                                                   SExecTaskInfo* pTaskInfo) {
2155 2156 2157 2158 2159 2160 2161 2162
  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);
2163
      if (pDataInfo->status == EX_SOURCE_DATA_EXHAUSTED) {
2164
        completed += 1;
H
Haojun Liao 已提交
2165 2166
        continue;
      }
2167

2168
      if (pDataInfo->status != EX_SOURCE_DATA_READY) {
2169 2170 2171
        continue;
      }

2172 2173 2174 2175 2176
      if (pDataInfo->code != TSDB_CODE_SUCCESS) {
        code = pDataInfo->code;
        goto _error;
      }

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

L
Liu Jicong 已提交
2180
      SSDataBlock*         pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
2181
      SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2182
      if (pRsp->numOfRows == 0) {
2183 2184
        qDebug("%s vgId:%d, taskId:0x%" PRIx64 " execId:%d index:%d completed, rowsOfSource:%" PRIu64
               ", totalRows:%" PRIu64 ", completed:%d try next %d/%" PRIzu,
D
dapan1121 已提交
2185
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pSource->execId, i, pDataInfo->totalRows,
2186
               pExchangeInfo->loadInfo.totalRows, completed + 1, i + 1, totalSources);
2187
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2188
        completed += 1;
D
dapan1121 已提交
2189
        taosMemoryFreeClear(pDataInfo->pRsp);
2190 2191
        continue;
      }
H
Haojun Liao 已提交
2192

H
Haojun Liao 已提交
2193
      SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
2194 2195 2196
      code =
          extractDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
                                       pTableRsp->compLen, pTableRsp->numOfCols, startTs, &pDataInfo->totalRows, NULL);
2197
      if (code != 0) {
2198
        taosMemoryFreeClear(pDataInfo->pRsp);
2199 2200 2201
        goto _error;
      }

2202
      if (pRsp->completed == 1) {
2203 2204
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64
               " execId:%d"
X
Xiaoyu Wang 已提交
2205 2206
               " index:%d completed, numOfRows:%d, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64 ", totalBytes:%" PRIu64
               ", completed:%d try next %d/%" PRIzu,
2207 2208
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pSource->execId, i, pRes->info.rows,
               pDataInfo->totalRows, pLoadInfo->totalRows, pLoadInfo->totalSize, completed + 1, i + 1, totalSources);
2209
        completed += 1;
2210
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2211
      } else {
D
dapan1121 已提交
2212
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " execId:%d numOfRows:%d, totalRows:%" PRIu64
dengyihao's avatar
dengyihao 已提交
2213
               ", totalBytes:%" PRIu64,
2214 2215
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pSource->execId, pRes->info.rows,
               pLoadInfo->totalRows, pLoadInfo->totalSize);
2216 2217
      }

2218 2219
      taosMemoryFreeClear(pDataInfo->pRsp);

2220 2221
      if (pDataInfo->status != EX_SOURCE_DATA_EXHAUSTED) {
        pDataInfo->status = EX_SOURCE_DATA_NOT_READY;
2222 2223
        code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
        if (code != TSDB_CODE_SUCCESS) {
2224
          taosMemoryFreeClear(pDataInfo->pRsp);
2225 2226 2227 2228 2229 2230 2231
          goto _error;
        }
      }

      return pExchangeInfo->pResult;
    }

2232
    if (completed == totalSources) {
2233 2234
      return setAllSourcesCompleted(pOperator, startTs);
    }
H
Haojun Liao 已提交
2235 2236

    sched_yield();
2237 2238 2239 2240 2241 2242 2243
  }

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

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

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

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
2252
  for (int32_t i = 0; i < totalSources; ++i) {
2253 2254
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2255 2256
      pTaskInfo->code = code;
      return code;
2257 2258 2259 2260
    }
  }

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

2264
  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
2265
  pOperator->cost.openCost = taosGetTimestampUs() - startTs;
2266

2267
  tsem_wait(&pExchangeInfo->ready);
H
Haojun Liao 已提交
2268
  return TSDB_CODE_SUCCESS;
2269 2270
}

L
Liu Jicong 已提交
2271 2272 2273
static SSDataBlock* seqLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2274

L
Liu Jicong 已提交
2275
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
2276
  int64_t startTs = taosGetTimestampUs();
2277

L
Liu Jicong 已提交
2278
  while (1) {
2279 2280
    if (pExchangeInfo->current >= totalSources) {
      return setAllSourcesCompleted(pOperator, startTs);
2281
    }
2282

2283 2284 2285
    doSendFetchDataRequest(pExchangeInfo, pTaskInfo, pExchangeInfo->current);
    tsem_wait(&pExchangeInfo->ready);

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

H
Haojun Liao 已提交
2289
    if (pDataInfo->code != TSDB_CODE_SUCCESS) {
2290 2291
      qError("%s vgId:%d, taskID:0x%" PRIx64 " execId:%d error happens, code:%s", GET_TASKID(pTaskInfo),
             pSource->addr.nodeId, pSource->taskId, pSource->execId, tstrerror(pDataInfo->code));
H
Haojun Liao 已提交
2292 2293 2294 2295
      pOperator->pTaskInfo->code = pDataInfo->code;
      return NULL;
    }

L
Liu Jicong 已提交
2296
    SRetrieveTableRsp*   pRsp = pDataInfo->pRsp;
H
Haojun Liao 已提交
2297
    SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2298
    if (pRsp->numOfRows == 0) {
2299 2300
      qDebug("%s vgId:%d, taskID:0x%" PRIx64 " execId:%d %d of total completed, rowsOfSource:%" PRIu64
             ", totalRows:%" PRIu64 " try next",
D
dapan1121 已提交
2301
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pSource->execId, pExchangeInfo->current + 1,
H
Haojun Liao 已提交
2302
             pDataInfo->totalRows, pLoadInfo->totalRows);
H
Haojun Liao 已提交
2303

2304
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2305
      pExchangeInfo->current += 1;
D
dapan1121 已提交
2306
      taosMemoryFreeClear(pDataInfo->pRsp);
2307 2308
      continue;
    }
H
Haojun Liao 已提交
2309

L
Liu Jicong 已提交
2310
    SSDataBlock*       pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
2311
    SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
2312
    int32_t            code =
2313
        extractDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
L
Liu Jicong 已提交
2314
                                     pTableRsp->compLen, pTableRsp->numOfCols, startTs, &pDataInfo->totalRows, NULL);
2315 2316

    if (pRsp->completed == 1) {
D
dapan1121 已提交
2317
      qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " execId:%d numOfRows:%d, rowsOfSource:%" PRIu64
L
Liu Jicong 已提交
2318
             ", totalRows:%" PRIu64 ", totalBytes:%" PRIu64 " try next %d/%" PRIzu,
2319 2320 2321
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pSource->execId, pRes->info.rows,
             pDataInfo->totalRows, pLoadInfo->totalRows, pLoadInfo->totalSize, pExchangeInfo->current + 1,
             totalSources);
2322

2323
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2324 2325
      pExchangeInfo->current += 1;
    } else {
D
dapan1121 已提交
2326
      qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " execId:%d numOfRows:%d, totalRows:%" PRIu64
L
Liu Jicong 已提交
2327
             ", totalBytes:%" PRIu64,
2328 2329
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pSource->execId, pRes->info.rows,
             pLoadInfo->totalRows, pLoadInfo->totalSize);
2330 2331
    }

2332
    pOperator->resultInfo.totalRows += pRes->info.rows;
2333
    taosMemoryFreeClear(pDataInfo->pRsp);
2334 2335
    return pExchangeInfo->pResult;
  }
2336 2337
}

L
Liu Jicong 已提交
2338
static int32_t prepareLoadRemoteData(SOperatorInfo* pOperator) {
2339
  if (OPTR_IS_OPENED(pOperator)) {
H
Haojun Liao 已提交
2340 2341 2342
    return TSDB_CODE_SUCCESS;
  }

2343 2344
  int64_t st = taosGetTimestampUs();

L
Liu Jicong 已提交
2345
  SExchangeInfo* pExchangeInfo = pOperator->info;
2346
  if (!pExchangeInfo->seqLoadData) {
H
Haojun Liao 已提交
2347 2348 2349 2350 2351 2352
    int32_t code = prepareConcurrentlyLoad(pOperator);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

2353
  OPTR_SET_OPENED(pOperator);
2354
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
2355 2356 2357
  return TSDB_CODE_SUCCESS;
}

2358
static SSDataBlock* doLoadRemoteDataImpl(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2359 2360
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2361

2362
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
2363
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2364 2365
    return NULL;
  }
2366

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

2370
  if (pOperator->status == OP_EXEC_DONE) {
L
Liu Jicong 已提交
2371 2372 2373
    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);
2374 2375 2376 2377 2378 2379
    return NULL;
  }

  if (pExchangeInfo->seqLoadData) {
    return seqLoadRemoteData(pOperator);
  } else {
2380
    return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
2381
  }
H
Haojun Liao 已提交
2382
}
2383

2384 2385 2386 2387 2388 2389 2390 2391
static SSDataBlock* doLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

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

L
Liu Jicong 已提交
2392
  while (1) {
2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
    SSDataBlock* pBlock = doLoadRemoteDataImpl(pOperator);
    if (pBlock == NULL) {
      return NULL;
    }

    ASSERT(pBlock == pExchangeInfo->pResult);

    SLimitInfo* pLimitInfo = &pExchangeInfo->limitInfo;
    if (hasLimitOffsetInfo(pLimitInfo)) {
      int32_t status = handleLimitOffset(pOperator, pLimitInfo, pExchangeInfo->pResult, false);
      if (status == PROJECT_RETRIEVE_CONTINUE) {
        continue;
      } else if (status == PROJECT_RETRIEVE_DONE) {
        size_t rows = pExchangeInfo->pResult->info.rows;
        pExchangeInfo->limitInfo.numOfOutputRows += rows;

        if (rows == 0) {
          doSetOperatorCompleted(pOperator);
          return NULL;
        } else {
          return pExchangeInfo->pResult;
        }
      }
    } else {
      return pExchangeInfo->pResult;
    }
  }
}

2422
static int32_t initDataSource(int32_t numOfSources, SExchangeInfo* pInfo, const char* id) {
2423
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
H
Haojun Liao 已提交
2424 2425
  if (pInfo->pSourceDataInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
2426 2427
  }

L
Liu Jicong 已提交
2428
  for (int32_t i = 0; i < numOfSources; ++i) {
2429
    SSourceDataInfo dataInfo = {0};
H
Haojun Liao 已提交
2430
    dataInfo.status = EX_SOURCE_DATA_NOT_READY;
2431
    dataInfo.taskId = id;
L
Liu Jicong 已提交
2432
    dataInfo.index = i;
X
Xiaoyu Wang 已提交
2433
    SSourceDataInfo* pDs = taosArrayPush(pInfo->pSourceDataInfo, &dataInfo);
2434
    if (pDs == NULL) {
H
Haojun Liao 已提交
2435 2436 2437 2438 2439 2440 2441 2442
      taosArrayDestroy(pInfo->pSourceDataInfo);
      return TSDB_CODE_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
}

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

2446
  if (numOfSources == 0) {
X
Xiaoyu Wang 已提交
2447
    qError("%s invalid number: %d of sources in exchange operator", id, (int32_t)numOfSources);
2448 2449 2450
    return TSDB_CODE_INVALID_PARA;
  }

H
Haojun Liao 已提交
2451
  pInfo->pSources = taosArrayInit(numOfSources, sizeof(SDownstreamSourceNode));
wmmhello's avatar
wmmhello 已提交
2452
  if (pInfo->pSources == NULL) {
2453
    return TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
2454 2455
  }

L
Liu Jicong 已提交
2456
  for (int32_t i = 0; i < numOfSources; ++i) {
D
dapan1121 已提交
2457
    SDownstreamSourceNode* pNode = (SDownstreamSourceNode*)nodesListGetNode((SNodeList*)pExNode->pSrcEndPoints, i);
H
Haojun Liao 已提交
2458 2459
    taosArrayPush(pInfo->pSources, pNode);
  }
2460

2461
  initLimitInfo(pExNode->node.pLimit, pExNode->node.pSlimit, &pInfo->limitInfo);
2462 2463
  pInfo->self = taosAddRef(exchangeObjRefPool, pInfo);

2464
  return initDataSource(numOfSources, pInfo, id);
2465 2466 2467 2468 2469 2470
}

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 已提交
2471
    goto _error;
2472
  }
H
Haojun Liao 已提交
2473

2474
  int32_t code = initExchangeOperator(pExNode, pInfo, GET_TASKID(pTaskInfo));
2475 2476 2477
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2478 2479

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

2481
  pInfo->seqLoadData = false;
2482
  pInfo->pTransporter = pTransporter;
2483 2484
  pInfo->pResult = createResDataBlock(pExNode->node.pOutputDataBlockDesc);
  pOperator->name = "ExchangeOperator";
X
Xiaoyu Wang 已提交
2485
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_EXCHANGE;
X
Xiaoyu Wang 已提交
2486
  pOperator->blocking = false;
2487 2488
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
2489
  pOperator->exprSupp.numOfExprs = taosArrayGetSize(pInfo->pResult->pDataBlock);
X
Xiaoyu Wang 已提交
2490
  pOperator->pTaskInfo = pTaskInfo;
2491

L
Liu Jicong 已提交
2492 2493
  pOperator->fpSet = createOperatorFpSet(prepareLoadRemoteData, doLoadRemoteData, NULL, NULL,
                                         destroyExchangeOperatorInfo, NULL, NULL, NULL);
2494
  return pOperator;
H
Haojun Liao 已提交
2495

L
Liu Jicong 已提交
2496
_error:
H
Haojun Liao 已提交
2497
  if (pInfo != NULL) {
2498
    doDestroyExchangeOperatorInfo(pInfo);
H
Haojun Liao 已提交
2499 2500
  }

wafwerar's avatar
wafwerar 已提交
2501
  taosMemoryFreeClear(pOperator);
2502
  pTaskInfo->code = code;
H
Haojun Liao 已提交
2503
  return NULL;
2504 2505
}

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

2509
static void destroySortedMergeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
2510
  SSortedMergeOperatorInfo* pInfo = (SSortedMergeOperatorInfo*)param;
H
Haojun Liao 已提交
2511
  taosArrayDestroy(pInfo->pSortInfo);
2512 2513 2514
  taosArrayDestroy(pInfo->groupInfo);

  if (pInfo->pSortHandle != NULL) {
H
Haojun Liao 已提交
2515
    tsortDestroySortHandle(pInfo->pSortHandle);
2516 2517
  }

H
Haojun Liao 已提交
2518
  blockDataDestroy(pInfo->binfo.pRes);
H
Haojun Liao 已提交
2519
  cleanupAggSup(&pInfo->aggSup);
L
Liu Jicong 已提交
2520

D
dapan1121 已提交
2521
  taosMemoryFreeClear(param);
2522
}
H
Haojun Liao 已提交
2523

L
Liu Jicong 已提交
2524
static bool needToMerge(SSDataBlock* pBlock, SArray* groupInfo, char** buf, int32_t rowIndex) {
2525 2526 2527 2528
  size_t size = taosArrayGetSize(groupInfo);
  if (size == 0) {
    return true;
  }
2529

2530 2531
  for (int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(groupInfo, i);
2532

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

2536 2537 2538
    if ((isNull && buf[i] != NULL) || (!isNull && buf[i] == NULL)) {
      return false;
    }
2539

2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
    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;
      }
2553 2554 2555
    }
  }

2556
  return 0;
2557 2558
}

L
Liu Jicong 已提交
2559 2560 2561
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 已提交
2562
                                             //    pCtx[j].startRow = rowIndex;
2563 2564
  }

2565 2566
  for (int32_t j = 0; j < numOfExpr; ++j) {
    int32_t functionId = pCtx[j].functionId;
L
Liu Jicong 已提交
2567 2568 2569 2570 2571 2572 2573 2574 2575
    //    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]);
    //    }
2576
  }
2577
}
2578

L
Liu Jicong 已提交
2579 2580
static void doFinalizeResultImpl(SqlFunctionCtx* pCtx, int32_t numOfExpr) {
  for (int32_t j = 0; j < numOfExpr; ++j) {
2581 2582 2583 2584
    int32_t functionId = pCtx[j].functionId;
    //    if (functionId == FUNC_TAG_DUMMY || functionId == FUNC_TS_DUMMY) {
    //      continue;
    //    }
2585

2586 2587 2588 2589
    //    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 已提交
2590
    //    pCtx[j].fpSet.finalize(&pCtx[j]);
2591 2592
  }
}
2593

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

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

2601 2602 2603
    char* data = colDataGetData(pColInfo, rowIndex);
    memcpy(rowColData[i], data, colDataGetLength(pColInfo, rowIndex));
  }
2604

2605 2606
  return true;
}
2607

2608 2609
static void doMergeImpl(SOperatorInfo* pOperator, int32_t numOfExpr, SSDataBlock* pBlock) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
2610

2611
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
2612

L
Liu Jicong 已提交
2613
  for (int32_t i = 0; i < pBlock->info.rows; ++i) {
2614 2615 2616 2617 2618 2619 2620 2621 2622
    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);
2623 2624
        int32_t numOfRows = getNumOfResult(pOperator->exprSupp.pCtx, pOperator->exprSupp.numOfExprs, NULL);
        //        setTagValueForMultipleRows(pCtx, pOperator->exprSupp.numOfExprs, numOfRows);
2625

2626
        // TODO check for available buffer;
H
Haojun Liao 已提交
2627

2628 2629 2630 2631 2632
        // next group info data
        pInfo->binfo.pRes->info.rows += numOfRows;
        for (int32_t j = 0; j < numOfExpr; ++j) {
          if (pCtx[j].functionId < 0) {
            continue;
2633
          }
2634

H
Haojun Liao 已提交
2635
          pCtx[j].fpSet.process(&pCtx[j]);
2636
        }
2637 2638 2639

        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
        pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
H
Haojun Liao 已提交
2640
      }
2641 2642 2643 2644
    }
  }
}

2645 2646
static SSDataBlock* doMerge(SOperatorInfo* pOperator) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
2647
  SSortHandle*              pHandle = pInfo->pSortHandle;
2648

2649
  SSDataBlock* pDataBlock = createOneDataBlock(pInfo->binfo.pRes, false);
2650
  blockDataEnsureCapacity(pDataBlock, pOperator->resultInfo.capacity);
2651

L
Liu Jicong 已提交
2652
  while (1) {
2653
    blockDataCleanup(pDataBlock);
2654
    while (1) {
H
Haojun Liao 已提交
2655
      STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
2656 2657
      if (pTupleHandle == NULL) {
        break;
2658
      }
2659

2660 2661
      // build datablock for merge for one group
      appendOneRowToDataBlock(pDataBlock, pTupleHandle);
2662
      if (pDataBlock->info.rows >= pOperator->resultInfo.capacity) {
2663 2664
        break;
      }
2665
    }
2666

2667 2668 2669
    if (pDataBlock->info.rows == 0) {
      break;
    }
2670

2671
    setInputDataBlock(pOperator, pOperator->exprSupp.pCtx, pDataBlock, TSDB_ORDER_ASC, MAIN_SCAN, true);
L
Liu Jicong 已提交
2672 2673
    //  updateOutputBuf(&pInfo->binfo, &pAggInfo->bufCapacity, pBlock->info.rows * pAggInfo->resultRowFactor,
    //  pOperator->pRuntimeEnv, true);
2674
    doMergeImpl(pOperator, pOperator->exprSupp.numOfExprs, pDataBlock);
2675 2676
    // flush to tuple store, and after all data have been handled, return to upstream node or sink node
  }
2677

2678 2679 2680
  doFinalizeResultImpl(pOperator->exprSupp.pCtx, pOperator->exprSupp.numOfExprs);
  int32_t numOfRows = getNumOfResult(pOperator->exprSupp.pCtx, pOperator->exprSupp.numOfExprs, NULL);
  //        setTagValueForMultipleRows(pCtx, pOperator->exprSupp.numOfExprs, numOfRows);
2681

2682
  // TODO check for available buffer;
2683

2684 2685
  // next group info data
  pInfo->binfo.pRes->info.rows += numOfRows;
L
Liu Jicong 已提交
2686
  return (pInfo->binfo.pRes->info.rows > 0) ? pInfo->binfo.pRes : NULL;
2687
}
2688

L
Liu Jicong 已提交
2689 2690
SSDataBlock* getSortedMergeBlockData(SSortHandle* pHandle, SSDataBlock* pDataBlock, int32_t capacity,
                                     SArray* pColMatchInfo, SSortedMergeOperatorInfo* pInfo) {
2691 2692 2693 2694 2695 2696 2697 2698 2699 2700
  blockDataCleanup(pDataBlock);

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

  blockDataEnsureCapacity(p, capacity);

  while (1) {
2701
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
2702 2703 2704 2705
    if (pTupleHandle == NULL) {
      break;
    }

2706
    appendOneRowToDataBlock(p, pTupleHandle);
2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719
    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);
2720
      colDataAssign(pDst, pSrc, p->info.rows, &pDataBlock->info);
2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
    }

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

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

2731
static SSDataBlock* doSortedMerge(SOperatorInfo* pOperator) {
2732 2733
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
2734 2735
  }

L
Liu Jicong 已提交
2736
  SExecTaskInfo*            pTaskInfo = pOperator->pTaskInfo;
2737
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
2738
  if (pOperator->status == OP_RES_TO_RETURN) {
2739
    return getSortedMergeBlockData(pInfo->pSortHandle, pInfo->binfo.pRes, pOperator->resultInfo.capacity, NULL, pInfo);
2740 2741
  }

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

2746
  tsortSetFetchRawDataFp(pInfo->pSortHandle, loadNextDataBlock, NULL, NULL);
2747

L
Liu Jicong 已提交
2748
  for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
wmmhello's avatar
wmmhello 已提交
2749
    SSortSource* ps = taosMemoryCalloc(1, sizeof(SSortSource));
H
Haojun Liao 已提交
2750
    ps->param = pOperator->pDownstream[i];
H
Haojun Liao 已提交
2751
    tsortAddSource(pInfo->pSortHandle, ps);
2752 2753
  }

H
Haojun Liao 已提交
2754
  int32_t code = tsortOpen(pInfo->pSortHandle);
2755
  if (code != TSDB_CODE_SUCCESS) {
2756
    longjmp(pTaskInfo->env, terrno);
2757 2758
  }

H
Haojun Liao 已提交
2759
  pOperator->status = OP_RES_TO_RETURN;
2760
  return doMerge(pOperator);
2761
}
2762

L
Liu Jicong 已提交
2763 2764
static int32_t initGroupCol(SExprInfo* pExprInfo, int32_t numOfCols, SArray* pGroupInfo,
                            SSortedMergeOperatorInfo* pInfo) {
2765 2766
  if (pGroupInfo == NULL || taosArrayGetSize(pGroupInfo) == 0) {
    return 0;
H
Haojun Liao 已提交
2767 2768
  }

2769 2770 2771 2772 2773 2774 2775 2776
  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 已提交
2777 2778
  size_t numOfGroupCol = taosArrayGetSize(pInfo->groupInfo);
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
2779
    SColumn* pCol = taosArrayGet(pGroupInfo, i);
L
Liu Jicong 已提交
2780
    for (int32_t j = 0; j < numOfCols; ++j) {
H
Haojun Liao 已提交
2781
      SExprInfo* pe = &pExprInfo[j];
2782
      if (pe->base.resSchema.slotId == pCol->colId) {
2783 2784
        taosArrayPush(plist, pCol);
        taosArrayPush(pInfo->groupInfo, &j);
H
Haojun Liao 已提交
2785
        len += pCol->bytes;
2786 2787
        break;
      }
H
Haojun Liao 已提交
2788 2789 2790
    }
  }

2791
  ASSERT(taosArrayGetSize(pGroupInfo) == taosArrayGetSize(plist));
H
Haojun Liao 已提交
2792

wafwerar's avatar
wafwerar 已提交
2793
  pInfo->groupVal = taosMemoryCalloc(1, (POINTER_BYTES * numOfGroupCol + len));
2794 2795 2796 2797
  if (pInfo->groupVal == NULL) {
    taosArrayDestroy(plist);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
2798

2799
  int32_t offset = 0;
L
Liu Jicong 已提交
2800 2801
  char*   start = (char*)(pInfo->groupVal + (POINTER_BYTES * numOfGroupCol));
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
2802 2803
    pInfo->groupVal[i] = start + offset;
    SColumn* pCol = taosArrayGet(plist, i);
H
Haojun Liao 已提交
2804
    offset += pCol->bytes;
2805
  }
H
Haojun Liao 已提交
2806

2807
  taosArrayDestroy(plist);
H
Haojun Liao 已提交
2808

2809 2810
  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
2811

L
Liu Jicong 已提交
2812 2813 2814
SOperatorInfo* createSortedMergeOperatorInfo(SOperatorInfo** downstream, int32_t numOfDownstream, SExprInfo* pExprInfo,
                                             int32_t num, SArray* pSortInfo, SArray* pGroupInfo,
                                             SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
2815
  SSortedMergeOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortedMergeOperatorInfo));
L
Liu Jicong 已提交
2816
  SOperatorInfo*            pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2817
  if (pInfo == NULL || pOperator == NULL) {
2818
    goto _error;
2819
  }
H
Haojun Liao 已提交
2820

2821 2822 2823 2824 2825
  int32_t code = initExprSupp(&pOperator->exprSupp, pExprInfo, num);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

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

2828
  if (pOperator->exprSupp.pCtx == NULL || pInfo->binfo.pRes == NULL) {
2829 2830
    goto _error;
  }
H
Haojun Liao 已提交
2831

2832
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
2833
  code = doInitAggInfoSup(&pInfo->aggSup, pOperator->exprSupp.pCtx, num, keyBufSize, pTaskInfo->id.str);
2834 2835 2836
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
2837

2838
  setFunctionResultOutput(pOperator, &pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, num);
H
Haojun Liao 已提交
2839
  code = initGroupCol(pExprInfo, num, pGroupInfo, pInfo);
2840 2841 2842
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
2843

L
Liu Jicong 已提交
2844 2845 2846 2847 2848
  //  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 已提交
2849

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

L
Liu Jicong 已提交
2852
  pOperator->name = "SortedMerge";
X
Xiaoyu Wang 已提交
2853
  // pOperator->operatorType = OP_SortedMerge;
2854 2855 2856
  pOperator->blocking = true;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
L
Liu Jicong 已提交
2857
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
2858

2859 2860
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doSortedMerge, NULL, NULL, destroySortedMergeOperatorInfo,
                                         NULL, NULL, NULL);
2861 2862 2863
  code = appendDownstream(pOperator, downstream, numOfDownstream);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
2864
  }
H
Haojun Liao 已提交
2865

2866
  return pOperator;
H
Haojun Liao 已提交
2867

L
Liu Jicong 已提交
2868
_error:
2869
  if (pInfo != NULL) {
H
Haojun Liao 已提交
2870
    destroySortedMergeOperatorInfo(pInfo, num);
H
Haojun Liao 已提交
2871 2872
  }

wafwerar's avatar
wafwerar 已提交
2873 2874
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
2875 2876
  terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
2877 2878
}

X
Xiaoyu Wang 已提交
2879
int32_t getTableScanInfo(SOperatorInfo* pOperator, int32_t* order, int32_t* scanFlag) {
2880
  // todo add more information about exchange operation
2881
  int32_t type = pOperator->operatorType;
X
Xiaoyu Wang 已提交
2882
  if (type == QUERY_NODE_PHYSICAL_PLAN_EXCHANGE || type == QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN ||
2883
      type == QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN || type == QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN ||
2884
      type == QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN || type == QUERY_NODE_PHYSICAL_PLAN_LAST_ROW_SCAN) {
2885 2886 2887
    *order = TSDB_ORDER_ASC;
    *scanFlag = MAIN_SCAN;
    return TSDB_CODE_SUCCESS;
2888
  } else if (type == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN || type == QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN) {
2889 2890 2891 2892 2893
    STableScanInfo* pTableScanInfo = pOperator->info;
    *order = pTableScanInfo->cond.order;
    *scanFlag = pTableScanInfo->scanFlag;
    return TSDB_CODE_SUCCESS;
  } else {
H
Haojun Liao 已提交
2894
    if (pOperator->pDownstream == NULL || pOperator->pDownstream[0] == NULL) {
2895
      return TSDB_CODE_INVALID_PARA;
H
Haojun Liao 已提交
2896
    } else {
2897
      return getTableScanInfo(pOperator->pDownstream[0], order, scanFlag);
2898 2899 2900
    }
  }
}
L
Liu Jicong 已提交
2901
#if 0
L
Liu Jicong 已提交
2902
int32_t doPrepareScan(SOperatorInfo* pOperator, uint64_t uid, int64_t ts) {
L
Liu Jicong 已提交
2903
  uint8_t type = pOperator->operatorType;
2904 2905 2906

  pOperator->status = OP_OPENED;

L
Liu Jicong 已提交
2907
  if (type == QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN) {
2908
    SStreamScanInfo* pScanInfo = pOperator->info;
L
Liu Jicong 已提交
2909
    pScanInfo->blockType = STREAM_INPUT__TABLE_SCAN;
2910

2911
    pScanInfo->pTableScanOp->status = OP_OPENED;
2912

2913
    STableScanInfo* pInfo = pScanInfo->pTableScanOp->info;
2914 2915
    ASSERT(pInfo->scanMode == TABLE_SCAN__TABLE_ORDER);

L
Liu Jicong 已提交
2916 2917 2918 2919
    if (uid == 0) {
      pInfo->noTable = 1;
      return TSDB_CODE_SUCCESS;
    }
2920 2921 2922 2923 2924 2925

    /*if (pSnapShotScanInfo->dataReader == NULL) {*/
    /*pSnapShotScanInfo->dataReader = tsdbReaderOpen(pHandle->vnode, &pSTInfo->cond, tableList, 0, 0);*/
    /*pSnapShotScanInfo->scanMode = TABLE_SCAN__TABLE_ORDER;*/
    /*}*/

L
Liu Jicong 已提交
2926 2927
    pInfo->noTable = 0;

2928
    if (pInfo->lastStatus.uid != uid || pInfo->lastStatus.ts != ts) {
L
Liu Jicong 已提交
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939
      SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

      int32_t tableSz = taosArrayGetSize(pTaskInfo->tableqinfoList.pTableList);
      bool    found = false;
      for (int32_t i = 0; i < tableSz; i++) {
        STableKeyInfo* pTableInfo = taosArrayGet(pTaskInfo->tableqinfoList.pTableList, i);
        if (pTableInfo->uid == uid) {
          found = true;
          pInfo->currentTable = i;
        }
      }
2940
      // TODO after processing drop, found can be false
L
Liu Jicong 已提交
2941
      ASSERT(found);
2942 2943

      tsdbSetTableId(pInfo->dataReader, uid);
H
Haojun Liao 已提交
2944 2945 2946 2947
      int64_t oldSkey = pInfo->cond.twindows.skey;
      pInfo->cond.twindows.skey = ts + 1;
      tsdbReaderReset(pInfo->dataReader, &pInfo->cond);
      pInfo->cond.twindows.skey = oldSkey;
2948 2949
      pInfo->scanTimes = 0;

S
Shengliang Guan 已提交
2950
      qDebug("tsdb reader offset seek to uid %" PRId64 " ts %" PRId64 ", table cur set to %d , all table num %d", uid, ts,
L
Liu Jicong 已提交
2951
             pInfo->currentTable, tableSz);
L
Liu Jicong 已提交
2952
    }
L
Liu Jicong 已提交
2953

L
Liu Jicong 已提交
2954
    return TSDB_CODE_SUCCESS;
2955

L
Liu Jicong 已提交
2956
  } else {
2957 2958 2959 2960 2961
    if (pOperator->numOfDownstream == 1) {
      return doPrepareScan(pOperator->pDownstream[0], uid, ts);
    } else if (pOperator->numOfDownstream == 0) {
      qError("failed to find stream scan operator to set the input data block");
      return TSDB_CODE_QRY_APP_ERROR;
L
Liu Jicong 已提交
2962
    } else {
2963 2964
      qError("join not supported for stream block scan");
      return TSDB_CODE_QRY_APP_ERROR;
L
Liu Jicong 已提交
2965 2966 2967 2968
    }
  }
}

2969 2970 2971
int32_t doGetScanStatus(SOperatorInfo* pOperator, uint64_t* uid, int64_t* ts) {
  int32_t type = pOperator->operatorType;
  if (type == QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN) {
2972 2973
    SStreamScanInfo* pScanInfo = pOperator->info;
    STableScanInfo*  pSnapShotScanInfo = pScanInfo->pTableScanOp->info;
L
Liu Jicong 已提交
2974 2975
    *uid = pSnapShotScanInfo->lastStatus.uid;
    *ts = pSnapShotScanInfo->lastStatus.ts;
2976 2977 2978 2979 2980 2981 2982 2983 2984 2985
  } else {
    if (pOperator->pDownstream[0] == NULL) {
      return TSDB_CODE_INVALID_PARA;
    } else {
      doGetScanStatus(pOperator->pDownstream[0], uid, ts);
    }
  }

  return TSDB_CODE_SUCCESS;
}
L
Liu Jicong 已提交
2986
#endif
2987

2988
// this is a blocking operator
L
Liu Jicong 已提交
2989
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
2990 2991
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
2992 2993
  }

H
Haojun Liao 已提交
2994
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
2995
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
2996

2997 2998
  SExprSupp*     pSup = &pOperator->exprSupp;
  SOperatorInfo* downstream = pOperator->pDownstream[0];
2999

3000 3001
  int64_t st = taosGetTimestampUs();

3002 3003 3004
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;

H
Haojun Liao 已提交
3005
  while (1) {
3006
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
3007 3008 3009 3010
    if (pBlock == NULL) {
      break;
    }

3011 3012 3013 3014
    int32_t code = getTableScanInfo(pOperator, &order, &scanFlag);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
3015

3016
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
3017 3018 3019
    if (pAggInfo->scalarExprSup.pExprInfo != NULL) {
      SExprSupp* pSup1 = &pAggInfo->scalarExprSup;
      code = projectApplyFunctions(pSup1->pExprInfo, pBlock, pBlock, pSup1->pCtx, pSup1->numOfExprs, NULL);
3020
      if (code != TSDB_CODE_SUCCESS) {
3021
        longjmp(pTaskInfo->env, code);
3022
      }
3023 3024
    }

3025
    // the pDataBlock are always the same one, no need to call this again
3026 3027
    setExecutionContext(pOperator, pOperator->exprSupp.numOfExprs, pBlock->info.groupId, pAggInfo);
    setInputDataBlock(pOperator, pSup->pCtx, pBlock, order, scanFlag, true);
3028
    code = doAggregateImpl(pOperator, pSup->pCtx);
3029 3030 3031
    if (code != 0) {
      longjmp(pTaskInfo->env, code);
    }
3032 3033
  }

H
Haojun Liao 已提交
3034
  closeAllResultRows(&pAggInfo->binfo.resultRowInfo);
3035
  initGroupedResultInfo(&pAggInfo->groupResInfo, pAggInfo->aggSup.pResultRowHashTable, 0);
H
Haojun Liao 已提交
3036
  OPTR_SET_OPENED(pOperator);
3037

3038
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
3039 3040 3041
  return TSDB_CODE_SUCCESS;
}

3042
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
3043
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
3044 3045 3046 3047 3048 3049
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

L
Liu Jicong 已提交
3050
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3051
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
H
Haojun Liao 已提交
3052
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
3053
    doSetOperatorCompleted(pOperator);
H
Haojun Liao 已提交
3054 3055 3056
    return NULL;
  }

H
Haojun Liao 已提交
3057
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
S
slzhou 已提交
3058 3059
  while (1) {
    doBuildResultDatablock(pOperator, pInfo, &pAggInfo->groupResInfo, pAggInfo->aggSup.pResultBuf);
3060
    doFilter(pAggInfo->pCondition, pInfo->pRes, NULL);
S
slzhou 已提交
3061 3062 3063 3064 3065

    if (!hasDataInGroupInfo(&pAggInfo->groupResInfo)) {
      doSetOperatorCompleted(pOperator);
      break;
    }
3066

S
slzhou 已提交
3067 3068 3069 3070
    if (pInfo->pRes->info.rows > 0) {
      break;
    }
  }
3071
  size_t rows = blockDataGetNumOfRows(pInfo->pRes);
3072 3073
  pOperator->resultInfo.totalRows += rows;

3074
  return (rows == 0) ? NULL : pInfo->pRes;
3075 3076
}

wmmhello's avatar
wmmhello 已提交
3077
int32_t aggEncodeResultRow(SOperatorInfo* pOperator, char** result, int32_t* length) {
3078
  if (result == NULL || length == NULL) {
wmmhello's avatar
wmmhello 已提交
3079 3080 3081
    return TSDB_CODE_TSC_INVALID_INPUT;
  }
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)(pOperator->info);
3082 3083 3084 3085 3086
  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 已提交
3087

C
Cary Xu 已提交
3088 3089 3090 3091 3092 3093
  // no result
  if (getTotalBufSize(pSup->pResultBuf) == 0) {
    *result = NULL;
    *length = 0;
    return TSDB_CODE_SUCCESS;
  }
3094

wmmhello's avatar
wmmhello 已提交
3095
  *result = (char*)taosMemoryCalloc(1, totalSize);
L
Liu Jicong 已提交
3096
  if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
3097
    return TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
3098
  }
wmmhello's avatar
wmmhello 已提交
3099

wmmhello's avatar
wmmhello 已提交
3100
  int32_t offset = sizeof(int32_t);
wmmhello's avatar
wmmhello 已提交
3101 3102
  *(int32_t*)(*result + offset) = size;
  offset += sizeof(int32_t);
3103 3104

  // prepare memory
3105
  SResultRowPosition* pos = &pInfo->resultRowInfo.cur;
dengyihao's avatar
dengyihao 已提交
3106 3107
  void*               pPage = getBufPage(pSup->pResultBuf, pos->pageId);
  SResultRow*         pRow = (SResultRow*)((char*)pPage + pos->offset);
3108 3109 3110
  setBufPageDirty(pPage, true);
  releaseBufPage(pSup->pResultBuf, pPage);

dengyihao's avatar
dengyihao 已提交
3111
  void* pIter = taosHashIterate(pSup->pResultRowHashTable, NULL);
wmmhello's avatar
wmmhello 已提交
3112
  while (pIter) {
dengyihao's avatar
dengyihao 已提交
3113
    void*               key = taosHashGetKey(pIter, &keyLen);
3114
    SResultRowPosition* p1 = (SResultRowPosition*)pIter;
3115

dengyihao's avatar
dengyihao 已提交
3116
    pPage = (SFilePage*)getBufPage(pSup->pResultBuf, p1->pageId);
3117
    pRow = (SResultRow*)((char*)pPage + p1->offset);
3118 3119
    setBufPageDirty(pPage, true);
    releaseBufPage(pSup->pResultBuf, pPage);
wmmhello's avatar
wmmhello 已提交
3120 3121 3122

    // recalculate the result size
    int32_t realTotalSize = offset + sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize;
L
Liu Jicong 已提交
3123
    if (realTotalSize > totalSize) {
wmmhello's avatar
wmmhello 已提交
3124
      char* tmp = (char*)taosMemoryRealloc(*result, realTotalSize);
L
Liu Jicong 已提交
3125
      if (tmp == NULL) {
wafwerar's avatar
wafwerar 已提交
3126
        taosMemoryFree(*result);
wmmhello's avatar
wmmhello 已提交
3127
        *result = NULL;
wmmhello's avatar
wmmhello 已提交
3128
        return TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
3129
      } else {
wmmhello's avatar
wmmhello 已提交
3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141
        *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);
3142
    memcpy(*result + offset, pRow, pSup->resultRowSize);
wmmhello's avatar
wmmhello 已提交
3143 3144 3145 3146 3147
    offset += pSup->resultRowSize;

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

wmmhello's avatar
wmmhello 已提交
3148 3149 3150 3151
  *(int32_t*)(*result) = offset;
  *length = offset;

  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
3152 3153
}

3154
int32_t aggDecodeResultRow(SOperatorInfo* pOperator, char* result) {
3155
  if (result == NULL) {
wmmhello's avatar
wmmhello 已提交
3156
    return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3157
  }
wmmhello's avatar
wmmhello 已提交
3158
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)(pOperator->info);
3159
  SAggSupporter*  pSup = (SAggSupporter*)POINTER_SHIFT(pOperator->info, sizeof(SOptrBasicInfo));
wmmhello's avatar
wmmhello 已提交
3160 3161

  //  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
3162
  int32_t length = *(int32_t*)(result);
wmmhello's avatar
wmmhello 已提交
3163
  int32_t offset = sizeof(int32_t);
3164 3165 3166 3167

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

L
Liu Jicong 已提交
3168
  while (count-- > 0 && length > offset) {
wmmhello's avatar
wmmhello 已提交
3169 3170 3171
    int32_t keyLen = *(int32_t*)(result + offset);
    offset += sizeof(int32_t);

L
Liu Jicong 已提交
3172
    uint64_t    tableGroupId = *(uint64_t*)(result + offset);
3173
    SResultRow* resultRow = getNewResultRow(pSup->pResultBuf, tableGroupId, pSup->resultRowSize);
L
Liu Jicong 已提交
3174
    if (!resultRow) {
wmmhello's avatar
wmmhello 已提交
3175
      return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3176
    }
3177

wmmhello's avatar
wmmhello 已提交
3178
    // add a new result set for a new group
3179 3180
    SResultRowPosition pos = {.pageId = resultRow->pageId, .offset = resultRow->offset};
    taosHashPut(pSup->pResultRowHashTable, result + offset, keyLen, &pos, sizeof(SResultRowPosition));
wmmhello's avatar
wmmhello 已提交
3181 3182 3183

    offset += keyLen;
    int32_t valueLen = *(int32_t*)(result + offset);
L
Liu Jicong 已提交
3184
    if (valueLen != pSup->resultRowSize) {
wmmhello's avatar
wmmhello 已提交
3185
      return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3186 3187 3188 3189 3190 3191 3192 3193 3194 3195
    }
    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 已提交
3196
    pInfo->resultRowInfo.cur = (SResultRowPosition){.pageId = resultRow->pageId, .offset = resultRow->offset};
wmmhello's avatar
wmmhello 已提交
3197 3198
  }

L
Liu Jicong 已提交
3199
  if (offset != length) {
wmmhello's avatar
wmmhello 已提交
3200
    return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3201
  }
wmmhello's avatar
wmmhello 已提交
3202
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
3203 3204
}

3205 3206 3207 3208 3209
int32_t handleLimitOffset(SOperatorInfo* pOperator, SLimitInfo* pLimitInfo, SSDataBlock* pBlock, bool holdDataInBuf) {
  if (pLimitInfo->remainGroupOffset > 0) {
    if (pLimitInfo->currentGroupId == 0) {  // it is the first group
      pLimitInfo->currentGroupId = pBlock->info.groupId;
      blockDataCleanup(pBlock);
3210
      return PROJECT_RETRIEVE_CONTINUE;
3211 3212 3213
    } else if (pLimitInfo->currentGroupId != pBlock->info.groupId) {
      // now it is the data from a new group
      pLimitInfo->remainGroupOffset -= 1;
3214 3215

      // ignore data block in current group
3216 3217
      if (pLimitInfo->remainGroupOffset > 0) {
        blockDataCleanup(pBlock);
3218 3219 3220 3221 3222
        return PROJECT_RETRIEVE_CONTINUE;
      }
    }

    // set current group id of the project operator
3223
    pLimitInfo->currentGroupId = pBlock->info.groupId;
3224 3225
  }

3226
  // here check for a new group data, we need to handle the data of the previous group.
3227 3228 3229
  if (pLimitInfo->currentGroupId != 0 && pLimitInfo->currentGroupId != pBlock->info.groupId) {
    pLimitInfo->numOfOutputGroups += 1;
    if ((pLimitInfo->slimit.limit > 0) && (pLimitInfo->slimit.limit <= pLimitInfo->numOfOutputGroups)) {
3230
      pOperator->status = OP_EXEC_DONE;
3231
      blockDataCleanup(pBlock);
3232 3233 3234 3235 3236

      return PROJECT_RETRIEVE_DONE;
    }

    // reset the value for a new group data
3237 3238
    pLimitInfo->numOfOutputRows = 0;
    pLimitInfo->remainOffset = pLimitInfo->limit.offset;
3239 3240 3241 3242 3243

    // existing rows that belongs to previous group.
    if (pBlock->info.rows > 0) {
      return PROJECT_RETRIEVE_DONE;
    }
3244 3245 3246 3247 3248
  }

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

  // set current group id
3249
  pLimitInfo->currentGroupId = pBlock->info.groupId;
3250

3251 3252 3253
  if (pLimitInfo->remainOffset >= pBlock->info.rows) {
    pLimitInfo->remainOffset -= pBlock->info.rows;
    blockDataCleanup(pBlock);
3254
    return PROJECT_RETRIEVE_CONTINUE;
3255 3256 3257
  } else if (pLimitInfo->remainOffset < pBlock->info.rows && pLimitInfo->remainOffset > 0) {
    blockDataTrimFirstNRows(pBlock, pLimitInfo->remainOffset);
    pLimitInfo->remainOffset = 0;
3258 3259
  }

3260
  // check for the limitation in each group
3261 3262 3263 3264
  if (pLimitInfo->limit.limit >= 0 && pLimitInfo->numOfOutputRows + pBlock->info.rows >= pLimitInfo->limit.limit) {
    int32_t keepRows = (int32_t)(pLimitInfo->limit.limit - pLimitInfo->numOfOutputRows);
    blockDataKeepFirstNRows(pBlock, keepRows);
    if (pLimitInfo->slimit.limit > 0 && pLimitInfo->slimit.limit <= pLimitInfo->numOfOutputGroups) {
3265 3266 3267
      pOperator->status = OP_EXEC_DONE;
    }

3268
    return PROJECT_RETRIEVE_DONE;
3269
  }
3270

3271
  // todo optimize performance
3272 3273
  // 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.
3274 3275
  if ((!holdDataInBuf) || (pBlock->info.rows >= pOperator->resultInfo.threshold) || pLimitInfo->slimit.offset != -1 ||
      pLimitInfo->slimit.limit != -1) {
3276
    return PROJECT_RETRIEVE_DONE;
L
Liu Jicong 已提交
3277
  } else {  // not full enough, continue to accumulate the output data in the buffer.
3278 3279 3280 3281
    return PROJECT_RETRIEVE_CONTINUE;
  }
}

3282
static SSDataBlock* doProjectOperation(SOperatorInfo* pOperator) {
3283
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
L
Liu Jicong 已提交
3284
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
3285

L
Liu Jicong 已提交
3286
  SExprSupp*   pSup = &pOperator->exprSupp;
3287
  SSDataBlock* pRes = pInfo->pRes;
H
Haojun Liao 已提交
3288 3289 3290
  SSDataBlock* pFinalRes = pProjectInfo->pFinalRes;

  blockDataCleanup(pFinalRes);
3291

3292
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3293
  if (pOperator->status == OP_EXEC_DONE) {
L
Liu Jicong 已提交
3294 3295 3296 3297
    if (pTaskInfo->execModel == OPTR_EXEC_MODEL_QUEUE) {
      pOperator->status = OP_OPENED;
      return NULL;
    }
3298 3299
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
3300

3301
  int64_t st = 0;
3302 3303 3304
  int32_t order = 0;
  int32_t scanFlag = 0;

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

H
Haojun Liao 已提交
3309
  SOperatorInfo* downstream = pOperator->pDownstream[0];
H
Haojun Liao 已提交
3310
  SLimitInfo* pLimitInfo = &pProjectInfo->limitInfo;
H
Haojun Liao 已提交
3311

H
Haojun Liao 已提交
3312 3313 3314
  while(1) {
    while (1) {
      blockDataCleanup(pRes);
3315

H
Haojun Liao 已提交
3316 3317 3318 3319 3320 3321
      // 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;
      }
3322

H
Haojun Liao 已提交
3323 3324 3325 3326
      if (pBlock->info.type == STREAM_RETRIEVE) {
        // for stream interval
        return pBlock;
      }
3327

H
Haojun Liao 已提交
3328 3329 3330
      if (pLimitInfo->remainGroupOffset > 0) {
        if (pLimitInfo->currentGroupId == 0 || pLimitInfo->currentGroupId == pBlock->info.groupId) {  // it is the first group
          pLimitInfo->currentGroupId = pBlock->info.groupId;
3331
          ASSERT(pTaskInfo->execModel != OPTR_EXEC_MODEL_STREAM);
H
Haojun Liao 已提交
3332 3333 3334 3335 3336
          continue;
        } else if (pLimitInfo->currentGroupId != pBlock->info.groupId) {
          // now it is the data from a new group
          pLimitInfo->remainGroupOffset -= 1;
          pLimitInfo->currentGroupId = pBlock->info.groupId;
3337

H
Haojun Liao 已提交
3338 3339
          // ignore data block in current group
          if (pLimitInfo->remainGroupOffset > 0) {
3340
            ASSERT(pTaskInfo->execModel != OPTR_EXEC_MODEL_STREAM);
H
Haojun Liao 已提交
3341 3342 3343
            continue;
          }
        }
3344

H
Haojun Liao 已提交
3345 3346 3347
        // set current group id of the project operator
        pLimitInfo->currentGroupId = pBlock->info.groupId;
      }
3348

H
Haojun Liao 已提交
3349 3350 3351 3352 3353 3354 3355 3356
      // remainGroupOffset == 0
      // here check for a new group data, we need to handle the data of the previous group.
      if (pLimitInfo->currentGroupId != 0 && pLimitInfo->currentGroupId != pBlock->info.groupId) {
        pLimitInfo->numOfOutputGroups += 1;
        if ((pLimitInfo->slimit.limit > 0) && (pLimitInfo->slimit.limit <= pLimitInfo->numOfOutputGroups)) {
          doSetOperatorCompleted(pOperator);
          break;
        }
3357

H
Haojun Liao 已提交
3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368
        // reset the value for a new group data
        // existing rows that belongs to previous group.
        pLimitInfo->numOfOutputRows = 0;
        pLimitInfo->remainOffset = pLimitInfo->limit.offset;
      }

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

H
Haojun Liao 已提交
3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384
      setInputDataBlock(pOperator, pSup->pCtx, pBlock, order, scanFlag, false);
      blockDataEnsureCapacity(pInfo->pRes, pInfo->pRes->info.rows + pBlock->info.rows);

      code = projectApplyFunctions(pSup->pExprInfo, pInfo->pRes, pBlock, pSup->pCtx, pSup->numOfExprs,
                                   pProjectInfo->pPseudoColInfo);
      if (code != TSDB_CODE_SUCCESS) {
        longjmp(pTaskInfo->env, code);
      }

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

      if (pLimitInfo->remainOffset >= pInfo->pRes->info.rows) {
        pLimitInfo->remainOffset -= pInfo->pRes->info.rows;
        blockDataCleanup(pInfo->pRes);
3385
        ASSERT(pTaskInfo->execModel != OPTR_EXEC_MODEL_STREAM);
H
Haojun Liao 已提交
3386 3387 3388 3389
        continue;
      } else if (pLimitInfo->remainOffset < pInfo->pRes->info.rows && pLimitInfo->remainOffset > 0) {
        blockDataTrimFirstNRows(pInfo->pRes, pLimitInfo->remainOffset);
        pLimitInfo->remainOffset = 0;
3390
        ASSERT(pTaskInfo->execModel != OPTR_EXEC_MODEL_STREAM);
H
Haojun Liao 已提交
3391 3392 3393 3394 3395 3396 3397
      }

      // check for the limitation in each group
      if (pLimitInfo->limit.limit >= 0 &&
          pLimitInfo->numOfOutputRows + pInfo->pRes->info.rows >= pLimitInfo->limit.limit) {
        int32_t keepRows = (int32_t)(pLimitInfo->limit.limit - pLimitInfo->numOfOutputRows);
        blockDataKeepFirstNRows(pInfo->pRes, keepRows);
3398
        ASSERT(pTaskInfo->execModel != OPTR_EXEC_MODEL_STREAM);
H
Haojun Liao 已提交
3399 3400 3401 3402
        if (pLimitInfo->slimit.limit > 0 && pLimitInfo->slimit.limit <= pLimitInfo->numOfOutputGroups) {
          pOperator->status = OP_EXEC_DONE;
        }
      }
3403

H
Haojun Liao 已提交
3404
      pLimitInfo->numOfOutputRows += pInfo->pRes->info.rows;
5
54liuyao 已提交
3405 3406 3407
      break;
    }

H
Haojun Liao 已提交
3408 3409
    // no results generated
    if (pInfo->pRes->info.rows == 0 || (!pProjectInfo->mergeDataBlocks)) {
3410 3411
      break;
    }
dengyihao's avatar
dengyihao 已提交
3412

H
Haojun Liao 已提交
3413
    if (pProjectInfo->mergeDataBlocks) {
3414 3415 3416 3417 3418
      pFinalRes->info.groupId = pInfo->pRes->info.groupId;
      pFinalRes->info.version = pInfo->pRes->info.version;

      // continue merge data, ignore the group id
      blockDataMerge(pFinalRes, pInfo->pRes);
3419

3420 3421
      if (pFinalRes->info.rows + pInfo->pRes->info.rows <= pOperator->resultInfo.threshold &&
          pTaskInfo->execModel != OPTR_EXEC_MODEL_STREAM) {
H
Haojun Liao 已提交
3422 3423 3424 3425 3426 3427
        continue;
      }
    }

    // do apply filter
    SSDataBlock* p = pProjectInfo->mergeDataBlocks ? pFinalRes : pRes;
3428
    doFilter(pProjectInfo->pFilterNode, p, NULL);
H
Haojun Liao 已提交
3429 3430 3431 3432 3433 3434 3435
    if (p->info.rows > 0) {
      break;
    }
  }

  SSDataBlock* p = pProjectInfo->mergeDataBlocks ? pFinalRes : pRes;
  pOperator->resultInfo.totalRows += p->info.rows;
3436 3437

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

H
Haojun Liao 已提交
3441
  return (p->info.rows > 0) ? p : NULL;
3442 3443
}

H
Haojun Liao 已提交
3444
static void doHandleRemainBlockForNewGroupImpl(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo,
L
Liu Jicong 已提交
3445
                                               SExecTaskInfo* pTaskInfo) {
3446
  pInfo->totalInputRows = pInfo->existNewGroupBlock->info.rows;
H
Haojun Liao 已提交
3447

L
Liu Jicong 已提交
3448 3449
  int64_t ekey =
      Q_STATUS_EQUAL(pTaskInfo->status, TASK_COMPLETED) ? pInfo->win.ekey : pInfo->existNewGroupBlock->info.window.ekey;
3450 3451
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

3452
  taosFillSetStartInfo(pInfo->pFillInfo, pInfo->existNewGroupBlock->info.rows, ekey);
3453 3454
  taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->existNewGroupBlock);

H
Haojun Liao 已提交
3455 3456 3457
  int32_t numOfResultRows = pResultInfo->capacity - pInfo->pRes->info.rows;
  taosFillResultDataBlock(pInfo->pFillInfo, pInfo->pRes, numOfResultRows);

3458
  pInfo->curGroupId = pInfo->existNewGroupBlock->info.groupId;
3459 3460 3461
  pInfo->existNewGroupBlock = NULL;
}

H
Haojun Liao 已提交
3462
static void doHandleRemainBlockFromNewGroup(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo,
L
Liu Jicong 已提交
3463
                                            SExecTaskInfo* pTaskInfo) {
3464
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
H
Haojun Liao 已提交
3465 3466 3467
    int32_t numOfResultRows = pResultInfo->capacity - pInfo->pRes->info.rows;
    taosFillResultDataBlock(pInfo->pFillInfo, pInfo->pRes, numOfResultRows);
    if (pInfo->pRes->info.rows > pResultInfo->threshold) {
3468 3469 3470 3471 3472 3473
      return;
    }
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
H
Haojun Liao 已提交
3474
    doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, pTaskInfo);
3475 3476 3477
  }
}

S
slzhou 已提交
3478
static SSDataBlock* doFillImpl(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
3479 3480
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
3481

H
Haojun Liao 已提交
3482
  SResultInfo* pResultInfo = &pOperator->resultInfo;
3483 3484 3485
  SSDataBlock* pResBlock = pInfo->pRes;

  blockDataCleanup(pResBlock);
3486

H
Haojun Liao 已提交
3487 3488
  doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, pTaskInfo);
  if (pResBlock->info.rows > pResultInfo->threshold || pResBlock->info.rows > 0) {
3489
    pResBlock->info.groupId = pInfo->curGroupId;
3490
    return pResBlock;
H
Haojun Liao 已提交
3491
  }
3492

H
Haojun Liao 已提交
3493
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
3494
  while (1) {
3495
    SSDataBlock* pBlock = pDownstream->fpSet.getNextFn(pDownstream);
3496 3497 3498 3499 3500
    if (pBlock == NULL) {
      if (pInfo->totalInputRows == 0) {
        pOperator->status = OP_EXEC_DONE;
        return NULL;
      }
3501

3502
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pInfo->win.ekey);
3503
    } else {
3504 3505 3506
      blockDataUpdateTsWindow(pBlock, pInfo->primaryTsCol);

      if (pInfo->curGroupId == 0 || pInfo->curGroupId == pBlock->info.groupId) {
L
Liu Jicong 已提交
3507
        pInfo->curGroupId = pBlock->info.groupId;  // the first data block
3508 3509

        pInfo->totalInputRows += pBlock->info.rows;
3510

3511 3512
        taosFillSetStartInfo(pInfo->pFillInfo, pBlock->info.rows, pBlock->info.window.ekey);
        taosFillSetInputDataBlock(pInfo->pFillInfo, pBlock);
L
Liu Jicong 已提交
3513
      } else if (pInfo->curGroupId != pBlock->info.groupId) {  // the new group data block
3514 3515 3516 3517 3518
        pInfo->existNewGroupBlock = pBlock;

        // Fill the previous group data block, before handle the data block of new group.
        // Close the fill operation for previous group data block
        taosFillSetStartInfo(pInfo->pFillInfo, 0, pInfo->win.ekey);
3519 3520 3521
      }
    }

3522
    blockDataEnsureCapacity(pResBlock, pOperator->resultInfo.capacity);
H
Haojun Liao 已提交
3523

3524 3525
    int32_t numOfResultRows = pOperator->resultInfo.capacity - pResBlock->info.rows;
    taosFillResultDataBlock(pInfo->pFillInfo, pResBlock, numOfResultRows);
3526 3527

    // current group has no more result to return
3528
    if (pResBlock->info.rows > 0) {
3529 3530
      // 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
3531
      if (pResBlock->info.rows > pResultInfo->threshold || pBlock == NULL || pInfo->existNewGroupBlock != NULL) {
3532
        pResBlock->info.groupId = pInfo->curGroupId;
3533
        return pResBlock;
3534 3535
      }

H
Haojun Liao 已提交
3536
      doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, pTaskInfo);
3537
      if (pResBlock->info.rows >= pOperator->resultInfo.threshold || pBlock == NULL) {
3538
        pResBlock->info.groupId = pInfo->curGroupId;
3539
        return pResBlock;
3540 3541 3542
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
H
Haojun Liao 已提交
3543
      doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, pTaskInfo);
3544
      if (pResBlock->info.rows > pResultInfo->threshold) {
3545
        pResBlock->info.groupId = pInfo->curGroupId;
3546
        return pResBlock;
3547 3548 3549 3550 3551 3552 3553
      }
    } else {
      return NULL;
    }
  }
}

S
slzhou 已提交
3554 3555 3556 3557 3558 3559 3560 3561
static SSDataBlock* doFill(SOperatorInfo* pOperator) {
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;

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

S
slzhou 已提交
3562
  SSDataBlock* fillResult = NULL;
S
slzhou 已提交
3563
  while (true) {
S
slzhou 已提交
3564
    fillResult = doFillImpl(pOperator);
S
slzhou 已提交
3565 3566 3567 3568 3569
    if (fillResult == NULL) {
      doSetOperatorCompleted(pOperator);
      break;
    }

3570
    doFilter(pInfo->pCondition, fillResult, pInfo->pColMatchColInfo);
S
slzhou 已提交
3571 3572 3573 3574 3575
    if (fillResult->info.rows > 0) {
      break;
    }
  }

S
slzhou 已提交
3576
  if (fillResult != NULL) {
3577
    pOperator->resultInfo.totalRows += fillResult->info.rows;
S
slzhou 已提交
3578
  }
S
slzhou 已提交
3579

S
slzhou 已提交
3580
  return fillResult;
S
slzhou 已提交
3581 3582
}

H
Haojun Liao 已提交
3583 3584 3585
static void destroyExprInfo(SExprInfo* pExpr, int32_t numOfExprs) {
  for (int32_t i = 0; i < numOfExprs; ++i) {
    SExprInfo* pExprInfo = &pExpr[i];
L
Liu Jicong 已提交
3586
    for (int32_t j = 0; j < pExprInfo->base.numOfParams; ++j) {
H
Haojun Liao 已提交
3587 3588 3589
      if (pExprInfo->base.pParam[j].type == FUNC_PARAM_TYPE_COLUMN) {
        taosMemoryFreeClear(pExprInfo->base.pParam[j].pCol);
      }
H
Haojun Liao 已提交
3590
    }
H
Haojun Liao 已提交
3591

H
Haojun Liao 已提交
3592
    taosMemoryFree(pExprInfo->base.pParam);
H
Haojun Liao 已提交
3593 3594 3595 3596
    taosMemoryFree(pExprInfo->pExpr);
  }
}

3597 3598 3599 3600 3601
static void destroyOperatorInfo(SOperatorInfo* pOperator) {
  if (pOperator == NULL) {
    return;
  }

3602
  if (pOperator->fpSet.closeFn != NULL) {
3603
    pOperator->fpSet.closeFn(pOperator->info, pOperator->exprSupp.numOfExprs);
3604 3605
  }

H
Haojun Liao 已提交
3606
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
3607
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
3608
      destroyOperatorInfo(pOperator->pDownstream[i]);
3609 3610
    }

wafwerar's avatar
wafwerar 已提交
3611
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
3612
    pOperator->numOfDownstream = 0;
3613 3614
  }

3615
  cleanupExprSupp(&pOperator->exprSupp);
wafwerar's avatar
wafwerar 已提交
3616
  taosMemoryFreeClear(pOperator);
3617 3618
}

3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633
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 已提交
3634 3635
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                         const char* pKey) {
3636 3637
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

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

H
Haojun Liao 已提交
3642
  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowHashTable == NULL) {
3643 3644 3645
    return TSDB_CODE_OUT_OF_MEMORY;
  }

dengyihao's avatar
dengyihao 已提交
3646
  uint32_t defaultPgsz = 0;
3647 3648
  uint32_t defaultBufsz = 0;
  getBufferPgSize(pAggSup->resultRowSize, &defaultPgsz, &defaultBufsz);
H
Haojun Liao 已提交
3649

3650
  int32_t code = createDiskbasedBuf(&pAggSup->pResultBuf, defaultPgsz, defaultBufsz, pKey, TD_TMP_DIR_PATH);
H
Haojun Liao 已提交
3651 3652 3653 3654
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

3655 3656 3657
  return TSDB_CODE_SUCCESS;
}

3658
void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
3659
  taosMemoryFreeClear(pAggSup->keyBuf);
3660
  taosHashCleanup(pAggSup->pResultRowHashTable);
H
Haojun Liao 已提交
3661
  destroyDiskbasedBuf(pAggSup->pResultBuf);
3662 3663
}

L
Liu Jicong 已提交
3664 3665
int32_t initAggInfo(SExprSupp* pSup, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols, size_t keyBufSize,
                    const char* pkey) {
3666 3667 3668 3669 3670
  int32_t code = initExprSupp(pSup, pExprInfo, numOfCols);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

3671
  doInitAggInfoSup(pAggSup, pSup->pCtx, numOfCols, keyBufSize, pkey);
L
Liu Jicong 已提交
3672
  for (int32_t i = 0; i < numOfCols; ++i) {
3673
    pSup->pCtx[i].pBuf = pAggSup->pResultBuf;
3674 3675
  }

3676
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
3677 3678
}

L
Liu Jicong 已提交
3679
void initResultSizeInfo(SResultInfo* pResultInfo, int32_t numOfRows) {
wmmhello's avatar
wmmhello 已提交
3680
  ASSERT(numOfRows != 0);
3681 3682
  pResultInfo->capacity = numOfRows;
  pResultInfo->threshold = numOfRows * 0.75;
3683

3684 3685
  if (pResultInfo->threshold == 0) {
    pResultInfo->threshold = numOfRows;
3686 3687 3688
  }
}

3689 3690 3691 3692 3693
void initBasicInfo(SOptrBasicInfo* pInfo, SSDataBlock* pBlock) {
  pInfo->pRes = pBlock;
  initResultRowInfo(&pInfo->resultRowInfo);
}

3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712
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;
}

3713
int32_t initExprSupp(SExprSupp* pSup, SExprInfo* pExprInfo, int32_t numOfExpr) {
3714 3715 3716 3717
  pSup->pExprInfo = pExprInfo;
  pSup->numOfExprs = numOfExpr;
  if (pSup->pExprInfo != NULL) {
    pSup->pCtx = createSqlFunctionCtx(pExprInfo, numOfExpr, &pSup->rowEntryInfoOffset);
3718 3719 3720
    if (pSup->pCtx == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
3721
  }
3722 3723

  return TSDB_CODE_SUCCESS;
3724 3725
}

3726 3727 3728 3729 3730 3731 3732 3733 3734 3735
void cleanupExprSupp(SExprSupp* pSupp) {
  destroySqlFunctionCtx(pSupp->pCtx, pSupp->numOfExprs);
  if (pSupp->pExprInfo != NULL) {
    destroyExprInfo(pSupp->pExprInfo, pSupp->numOfExprs);
  }

  taosMemoryFreeClear(pSupp->pExprInfo);
  taosMemoryFree(pSupp->rowEntryInfoOffset);
}

L
Liu Jicong 已提交
3736
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
S
slzhou 已提交
3737
                                           SSDataBlock* pResultBlock, SNode* pCondition, SExprInfo* pScalarExprInfo,
wmmhello's avatar
wmmhello 已提交
3738
                                           int32_t numOfScalarExpr, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
3739
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
3740
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
3741 3742 3743
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
3744

3745
  int32_t numOfRows = 1024;
dengyihao's avatar
dengyihao 已提交
3746
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
3747

3748
  initResultSizeInfo(&pOperator->resultInfo, numOfRows);
3749
  int32_t code = initAggInfo(&pOperator->exprSupp, &pInfo->aggSup, pExprInfo, numOfCols, keyBufSize, pTaskInfo->id.str);
L
Liu Jicong 已提交
3750
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3751 3752
    goto _error;
  }
H
Haojun Liao 已提交
3753

3754
  initBasicInfo(&pInfo->binfo, pResultBlock);
3755 3756 3757 3758
  code = initExprSupp(&pInfo->scalarExprSup, pScalarExprInfo, numOfScalarExpr);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
3759

L
Liu Jicong 已提交
3760
  pInfo->groupId = INT32_MIN;
S
slzhou 已提交
3761
  pInfo->pCondition = pCondition;
dengyihao's avatar
dengyihao 已提交
3762
  pOperator->name = "TableAggregate";
3763
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_HASH_AGG;
3764
  pOperator->blocking = true;
dengyihao's avatar
dengyihao 已提交
3765 3766 3767
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
3768

3769 3770
  pOperator->fpSet = createOperatorFpSet(doOpenAggregateOptr, getAggregateResult, NULL, NULL, destroyAggOperatorInfo,
                                         aggEncodeResultRow, aggDecodeResultRow, NULL);
H
Haojun Liao 已提交
3771 3772 3773 3774 3775

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

  return pOperator;
L
Liu Jicong 已提交
3778
_error:
H
Haojun Liao 已提交
3779
  destroyAggOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
3780 3781
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
3782 3783
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
3784 3785
}

3786
void cleanupBasicInfo(SOptrBasicInfo* pInfo) {
3787 3788
  assert(pInfo != NULL);
  cleanupResultRowInfo(&pInfo->resultRowInfo);
H
Haojun Liao 已提交
3789
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
3790 3791
}

H
Haojun Liao 已提交
3792
void destroyBasicOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3793
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)param;
3794
  cleanupBasicInfo(pInfo);
L
Liu Jicong 已提交
3795

D
dapan1121 已提交
3796
  taosMemoryFreeClear(param);
3797
}
H
Haojun Liao 已提交
3798

H
Haojun Liao 已提交
3799 3800 3801 3802 3803 3804 3805
static void freeItem(void* pItem) {
  void** p = pItem;
  if (*p != NULL) {
    taosMemoryFreeClear(*p);
  }
}

H
Haojun Liao 已提交
3806
void destroyAggOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3807
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
L
Liu Jicong 已提交
3808 3809
  cleanupBasicInfo(&pInfo->binfo);

H
Haojun Liao 已提交
3810
  cleanupAggSup(&pInfo->aggSup);
H
Haojun Liao 已提交
3811
  cleanupGroupResInfo(&pInfo->groupResInfo);
D
dapan1121 已提交
3812
  taosMemoryFreeClear(param);
3813
}
3814

H
Haojun Liao 已提交
3815
void destroySFillOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3816
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
3817
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
3818
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
wafwerar's avatar
wafwerar 已提交
3819
  taosMemoryFreeClear(pInfo->p);
L
Liu Jicong 已提交
3820

D
dapan1121 已提交
3821
  taosMemoryFreeClear(param);
3822 3823
}

H
Haojun Liao 已提交
3824
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput) {
D
fix bug  
dapan 已提交
3825 3826 3827
  if (NULL == param) {
    return;
  }
L
Liu Jicong 已提交
3828
  SProjectOperatorInfo* pInfo = (SProjectOperatorInfo*)param;
3829
  cleanupBasicInfo(&pInfo->binfo);
H
Haojun Liao 已提交
3830
  cleanupAggSup(&pInfo->aggSup);
H
Haojun Liao 已提交
3831
  taosArrayDestroy(pInfo->pPseudoColInfo);
L
Liu Jicong 已提交
3832

H
Haojun Liao 已提交
3833
  blockDataDestroy(pInfo->pFinalRes);
D
dapan1121 已提交
3834
  taosMemoryFreeClear(param);
3835 3836
}

H
Haojun Liao 已提交
3837
static void destroyIndefinitOperatorInfo(void* param, int32_t numOfOutput) {
3838
  SIndefOperatorInfo* pInfo = (SIndefOperatorInfo*)param;
3839
  cleanupBasicInfo(&pInfo->binfo);
H
Haojun Liao 已提交
3840 3841 3842

  taosArrayDestroy(pInfo->pPseudoColInfo);
  cleanupAggSup(&pInfo->aggSup);
3843
  cleanupExprSupp(&pInfo->scalarSup);
L
Liu Jicong 已提交
3844

D
dapan1121 已提交
3845
  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
3846 3847
}

H
Haojun Liao 已提交
3848
void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3849
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
3850 3851 3852 3853
  taosRemoveRef(exchangeObjRefPool, pExInfo->self);
}

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

H
Haojun Liao 已提交
3856 3857 3858
  taosArrayDestroy(pExInfo->pSources);
  taosArrayDestroy(pExInfo->pSourceDataInfo);
  if (pExInfo->pResult != NULL) {
H
Haojun Liao 已提交
3859
    pExInfo->pResult = blockDataDestroy(pExInfo->pResult);
H
Haojun Liao 已提交
3860 3861 3862
  }

  tsem_destroy(&pExInfo->ready);
L
Liu Jicong 已提交
3863

D
dapan1121 已提交
3864
  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
3865 3866
}

H
Haojun Liao 已提交
3867 3868
static SArray* setRowTsColumnOutputInfo(SqlFunctionCtx* pCtx, int32_t numOfCols) {
  SArray* pList = taosArrayInit(4, sizeof(int32_t));
dengyihao's avatar
dengyihao 已提交
3869
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
3870 3871 3872 3873 3874 3875 3876 3877
    if (fmIsPseudoColumnFunc(pCtx[i].functionId)) {
      taosArrayPush(pList, &i);
    }
  }

  return pList;
}

L
Liu Jicong 已提交
3878
SOperatorInfo* createProjectOperatorInfo(SOperatorInfo* downstream, SProjectPhysiNode* pProjPhyNode,
dengyihao's avatar
dengyihao 已提交
3879
                                         SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
3880
  SProjectOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SProjectOperatorInfo));
L
Liu Jicong 已提交
3881
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
3882 3883 3884
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
3885

L
Liu Jicong 已提交
3886
  int32_t    numOfCols = 0;
3887 3888 3889
  SExprInfo* pExprInfo = createExprInfo(pProjPhyNode->pProjections, NULL, &numOfCols);

  SSDataBlock* pResBlock = createResDataBlock(pProjPhyNode->node.pOutputDataBlockDesc);
3890
  initLimitInfo(pProjPhyNode->node.pLimit, pProjPhyNode->node.pSlimit, &pInfo->limitInfo);
3891

H
Haojun Liao 已提交
3892
  pInfo->binfo.pRes = pResBlock;
H
Haojun Liao 已提交
3893 3894
  pInfo->pFinalRes = createOneDataBlock(pResBlock, false);

3895
  pInfo->pFilterNode = pProjPhyNode->node.pConditions;
H
Haojun Liao 已提交
3896
  pInfo->mergeDataBlocks = pProjPhyNode->mergeDataBlock;
H
Haojun Liao 已提交
3897 3898

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

3901 3902 3903 3904 3905
  // 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;
  }
3906
  initResultSizeInfo(&pOperator->resultInfo, numOfRows);
3907

3908 3909
  initAggInfo(&pOperator->exprSupp, &pInfo->aggSup, pExprInfo, numOfCols, keyBufSize, pTaskInfo->id.str);
  initBasicInfo(&pInfo->binfo, pResBlock);
3910
  setFunctionResultOutput(pOperator, &pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, numOfCols);
3911

3912
  pInfo->pPseudoColInfo = setRowTsColumnOutputInfo(pOperator->exprSupp.pCtx, numOfCols);
X
Xiaoyu Wang 已提交
3913
  pOperator->name = "ProjectOperator";
H
Haojun Liao 已提交
3914
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
X
Xiaoyu Wang 已提交
3915 3916 3917 3918
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
3919

L
Liu Jicong 已提交
3920 3921
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doProjectOperation, NULL, NULL,
                                         destroyProjectOperatorInfo, NULL, NULL, NULL);
L
Liu Jicong 已提交
3922

3923
  int32_t code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
3924
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3925 3926
    goto _error;
  }
3927 3928

  return pOperator;
H
Haojun Liao 已提交
3929

L
Liu Jicong 已提交
3930
_error:
H
Haojun Liao 已提交
3931 3932
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
3933 3934
}

3935 3936
static void doHandleDataBlock(SOperatorInfo* pOperator, SSDataBlock* pBlock, SOperatorInfo* downstream,
                              SExecTaskInfo* pTaskInfo) {
3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969
  int32_t order = 0;
  int32_t scanFlag = 0;

  SIndefOperatorInfo* pIndefInfo = pOperator->info;
  SOptrBasicInfo*     pInfo = &pIndefInfo->binfo;
  SExprSupp*          pSup = &pOperator->exprSupp;

  // the pDataBlock are always the same one, no need to call this again
  int32_t code = getTableScanInfo(downstream, &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.
  SExprSupp* pScalarSup = &pIndefInfo->scalarSup;
  if (pScalarSup->pExprInfo != NULL) {
    code = projectApplyFunctions(pScalarSup->pExprInfo, pBlock, pBlock, pScalarSup->pCtx, pScalarSup->numOfExprs,
                                 pIndefInfo->pPseudoColInfo);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
  }

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

  code = projectApplyFunctions(pSup->pExprInfo, pInfo->pRes, pBlock, pSup->pCtx, pSup->numOfExprs,
                               pIndefInfo->pPseudoColInfo);
  if (code != TSDB_CODE_SUCCESS) {
    longjmp(pTaskInfo->env, code);
  }
}

H
Haojun Liao 已提交
3970 3971
static SSDataBlock* doApplyIndefinitFunction(SOperatorInfo* pOperator) {
  SIndefOperatorInfo* pIndefInfo = pOperator->info;
3972
  SOptrBasicInfo*     pInfo = &pIndefInfo->binfo;
L
Liu Jicong 已提交
3973
  SExprSupp*          pSup = &pOperator->exprSupp;
H
Haojun Liao 已提交
3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990

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

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

  int64_t st = 0;

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

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

3991
  while (1) {
3992
    // here we need to handle the existsed group results
3993
    if (pIndefInfo->pNextGroupRes != NULL) {  // todo extract method
3994 3995
      for (int32_t k = 0; k < pSup->numOfExprs; ++k) {
        SqlFunctionCtx* pCtx = &pSup->pCtx[k];
H
Haojun Liao 已提交
3996

3997 3998 3999 4000 4001 4002 4003
        SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
        pResInfo->initialized = false;
        pCtx->pOutput = NULL;
      }

      doHandleDataBlock(pOperator, pIndefInfo->pNextGroupRes, downstream, pTaskInfo);
      pIndefInfo->pNextGroupRes = NULL;
H
Haojun Liao 已提交
4004 4005
    }

4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028
    if (pInfo->pRes->info.rows < pOperator->resultInfo.threshold) {
      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;
        }

        if (pIndefInfo->groupId == 0 && pBlock->info.groupId != 0) {
          pIndefInfo->groupId = pBlock->info.groupId;  // this is the initial group result
        } else {
          if (pIndefInfo->groupId != pBlock->info.groupId) {  // reset output buffer and computing status
            pIndefInfo->groupId = pBlock->info.groupId;
            pIndefInfo->pNextGroupRes = pBlock;
            break;
          }
        }

        doHandleDataBlock(pOperator, pBlock, downstream, pTaskInfo);
        if (pInfo->pRes->info.rows >= pOperator->resultInfo.threshold) {
          break;
        }
H
Haojun Liao 已提交
4029 4030 4031
      }
    }

4032
    doFilter(pIndefInfo->pCondition, pInfo->pRes, NULL);
4033
    size_t rows = pInfo->pRes->info.rows;
4034
    if (rows > 0 || pOperator->status == OP_EXEC_DONE) {
4035
      break;
4036 4037
    } else {
      blockDataCleanup(pInfo->pRes);
H
Haojun Liao 已提交
4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050
    }
  }

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

4051 4052
SOperatorInfo* createIndefinitOutputOperatorInfo(SOperatorInfo* downstream, SPhysiNode* pNode,
                                                 SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
4053
  SIndefOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SIndefOperatorInfo));
4054
  SOperatorInfo*      pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4055 4056 4057 4058
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

4059 4060
  SExprSupp* pSup = &pOperator->exprSupp;

H
Haojun Liao 已提交
4061 4062 4063
  SIndefRowsFuncPhysiNode* pPhyNode = (SIndefRowsFuncPhysiNode*)pNode;

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

  if (pPhyNode->pExprs != NULL) {
4067
    int32_t    num = 0;
4068
    SExprInfo* pSExpr = createExprInfo(pPhyNode->pExprs, NULL, &num);
4069
    int32_t    code = initExprSupp(&pInfo->scalarSup, pSExpr, num);
4070 4071 4072
    if (code != TSDB_CODE_SUCCESS) {
      goto _error;
    }
H
Haojun Liao 已提交
4073 4074
  }

4075
  SSDataBlock* pResBlock = createResDataBlock(pPhyNode->node.pOutputDataBlockDesc);
H
Haojun Liao 已提交
4076 4077 4078 4079 4080 4081 4082 4083 4084

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

4086
  initResultSizeInfo(&pOperator->resultInfo, numOfRows);
H
Haojun Liao 已提交
4087

4088
  initAggInfo(pSup, &pInfo->aggSup, pExprInfo, numOfExpr, keyBufSize, pTaskInfo->id.str);
4089 4090
  initBasicInfo(&pInfo->binfo, pResBlock);

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

4093 4094 4095
  pInfo->binfo.pRes = pResBlock;
  pInfo->pCondition = pPhyNode->node.pConditions;
  pInfo->pPseudoColInfo = setRowTsColumnOutputInfo(pSup->pCtx, numOfExpr);
H
Haojun Liao 已提交
4096

4097
  pOperator->name = "IndefinitOperator";
4098
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_INDEF_ROWS_FUNC;
4099 4100 4101
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
4102
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113

  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;

4114
_error:
H
Haojun Liao 已提交
4115 4116 4117 4118 4119 4120
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
}

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

4125
  STimeWindow w = getAlignQueryTimeWindow(pInterval, pInterval->precision, win.skey);
4126
  w = getFirstQualifiedTimeWindow(win.skey, &w, pInterval, TSDB_ORDER_ASC);
H
Haojun Liao 已提交
4127 4128

  int32_t order = TSDB_ORDER_ASC;
L
Liu Jicong 已提交
4129 4130
  pInfo->pFillInfo =
      taosCreateFillInfo(order, w.skey, 0, capacity, numOfCols, pInterval, fillType, pColInfo, pInfo->primaryTsCol, id);
H
Haojun Liao 已提交
4131

4132
  pInfo->win = win;
L
Liu Jicong 已提交
4133
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
4134

H
Haojun Liao 已提交
4135
  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
H
Haojun Liao 已提交
4136 4137
    taosMemoryFree(pInfo->pFillInfo);
    taosMemoryFree(pInfo->p);
H
Haojun Liao 已提交
4138 4139 4140 4141 4142 4143
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

L
Liu Jicong 已提交
4144 4145
SOperatorInfo* createFillOperatorInfo(SOperatorInfo* downstream, SFillPhysiNode* pPhyFillNode,
                                      SExecTaskInfo* pTaskInfo) {
4146 4147 4148 4149 4150 4151
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

L
Liu Jicong 已提交
4152 4153 4154
  int32_t      num = 0;
  SSDataBlock* pResBlock = createResDataBlock(pPhyFillNode->node.pOutputDataBlockDesc);
  SExprInfo*   pExprInfo = createExprInfo(pPhyFillNode->pTargets, NULL, &num);
4155 4156 4157 4158
  SInterval*   pInterval =
      QUERY_NODE_PHYSICAL_PLAN_MERGE_ALIGNED_INTERVAL == downstream->operatorType
            ? &((SMergeAlignedIntervalAggOperatorInfo*)downstream->info)->intervalAggOperatorInfo->interval
            : &((SIntervalAggOperatorInfo*)downstream->info)->interval;
4159

4160
  int32_t type = convertFillType(pPhyFillNode->mode);
4161

H
Haojun Liao 已提交
4162
  SResultInfo* pResultInfo = &pOperator->resultInfo;
4163
  initResultSizeInfo(&pOperator->resultInfo, 4096);
H
Haojun Liao 已提交
4164
  pInfo->primaryTsCol = ((SColumnNode*)pPhyFillNode->pWStartTs)->slotId;
4165

4166
  int32_t numOfOutputCols = 0;
4167 4168
  SArray* pColMatchColInfo = extractColMatchInfo(pPhyFillNode->pTargets, pPhyFillNode->node.pOutputDataBlockDesc,
                                                 &numOfOutputCols, COL_MATCH_FROM_SLOT_ID);
4169

4170 4171
  int32_t code = initFillInfo(pInfo, pExprInfo, num, (SNodeListNode*)pPhyFillNode->pValues, pPhyFillNode->timeRange,
                              pResultInfo->capacity, pTaskInfo->id.str, pInterval, type);
4172 4173 4174
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4175

4176 4177 4178 4179 4180 4181 4182 4183
  pInfo->pRes = pResBlock;
  pInfo->pCondition = pPhyFillNode->node.pConditions;
  pInfo->pColMatchColInfo = pColMatchColInfo;
  pOperator->name = "FillOperator";
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_FILL;
  pOperator->exprSupp.pExprInfo = pExprInfo;
4184
  pOperator->exprSupp.numOfExprs = num;
4185 4186
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
4187

L
Liu Jicong 已提交
4188 4189
  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doFill, NULL, NULL, destroySFillOperatorInfo, NULL, NULL, NULL);
4190

4191
  code = appendDownstream(pOperator, &downstream, 1);
4192
  return pOperator;
H
Haojun Liao 已提交
4193

L
Liu Jicong 已提交
4194
_error:
wafwerar's avatar
wafwerar 已提交
4195 4196
  taosMemoryFreeClear(pOperator);
  taosMemoryFreeClear(pInfo);
H
Haojun Liao 已提交
4197
  return NULL;
4198 4199
}

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

4204
  pTaskInfo->schemaInfo.dbname = strdup(dbFName);
4205
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
4206
  pTaskInfo->id.queryId = queryId;
dengyihao's avatar
dengyihao 已提交
4207
  pTaskInfo->execModel = model;
H
Haojun Liao 已提交
4208

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

4213 4214
  return pTaskInfo;
}
H
Haojun Liao 已提交
4215

H
Haojun Liao 已提交
4216
static SArray* extractColumnInfo(SNodeList* pNodeList);
4217

H
Haojun Liao 已提交
4218 4219
SSchemaWrapper* extractQueriedColumnSchema(SScanPhysiNode* pScanNode);

4220
int32_t extractTableSchemaInfo(SReadHandle* pHandle, SScanPhysiNode* pScanNode, SExecTaskInfo* pTaskInfo) {
4221 4222
  SMetaReader mr = {0};
  metaReaderInit(&mr, pHandle->meta, 0);
4223
  int32_t code = metaGetTableEntryByUid(&mr, pScanNode->uid);
4224
  if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
4225 4226
    qError("failed to get the table meta, uid:0x%" PRIx64 ", suid:0x%" PRIx64 ", %s", pScanNode->uid, pScanNode->suid,
           GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
4227

D
dapan1121 已提交
4228
    metaReaderClear(&mr);
4229
    return terrno;
D
dapan1121 已提交
4230
  }
4231

4232 4233
  SSchemaInfo* pSchemaInfo = &pTaskInfo->schemaInfo;
  pSchemaInfo->tablename = strdup(mr.me.name);
4234 4235

  if (mr.me.type == TSDB_SUPER_TABLE) {
4236 4237
    pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.stbEntry.schemaRow);
    pSchemaInfo->tversion = mr.me.stbEntry.schemaTag.version;
4238
  } else if (mr.me.type == TSDB_CHILD_TABLE) {
4239 4240
    tDecoderClear(&mr.coder);

4241 4242
    tb_uid_t suid = mr.me.ctbEntry.suid;
    metaGetTableEntryByUid(&mr, suid);
4243 4244
    pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.stbEntry.schemaRow);
    pSchemaInfo->tversion = mr.me.stbEntry.schemaTag.version;
4245
  } else {
4246
    pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.ntbEntry.schemaRow);
4247
  }
4248 4249

  metaReaderClear(&mr);
4250

H
Haojun Liao 已提交
4251 4252 4253 4254 4255
  pSchemaInfo->qsw = extractQueriedColumnSchema(pScanNode);
  return TSDB_CODE_SUCCESS;
}

SSchemaWrapper* extractQueriedColumnSchema(SScanPhysiNode* pScanNode) {
4256 4257 4258
  int32_t numOfCols = LIST_LENGTH(pScanNode->pScanCols);
  int32_t numOfTags = LIST_LENGTH(pScanNode->pScanPseudoCols);

4259
  SSchemaWrapper* pqSw = taosMemoryCalloc(1, sizeof(SSchemaWrapper));
4260
  pqSw->pSchema = taosMemoryCalloc(numOfCols + numOfTags, sizeof(SSchema));
4261

L
Liu Jicong 已提交
4262
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
4263
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pScanNode->pScanCols, i);
4264 4265
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

H
Haojun Liao 已提交
4266 4267 4268 4269 4270
    SSchema* pSchema = &pqSw->pSchema[pqSw->nCols++];
    pSchema->colId = pColNode->colId;
    pSchema->type = pColNode->node.resType.type;
    pSchema->type = pColNode->node.resType.bytes;
    strncpy(pSchema->name, pColNode->colName, tListLen(pSchema->name));
4271 4272
  }

4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288
  // this the tags and pseudo function columns, we only keep the tag columns
  for(int32_t i = 0; i < numOfTags; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pScanNode->pScanPseudoCols, i);

    int32_t type = nodeType(pNode->pExpr);
    if (type == QUERY_NODE_COLUMN) {
      SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

      SSchema* pSchema = &pqSw->pSchema[pqSw->nCols++];
      pSchema->colId = pColNode->colId;
      pSchema->type = pColNode->node.resType.type;
      pSchema->type = pColNode->node.resType.bytes;
      strncpy(pSchema->name, pColNode->colName, tListLen(pSchema->name));
    }
  }

H
Haojun Liao 已提交
4289
  return pqSw;
4290 4291
}

4292 4293 4294
static void cleanupTableSchemaInfo(SSchemaInfo* pSchemaInfo) {
  taosMemoryFreeClear(pSchemaInfo->dbname);
  if (pSchemaInfo->sw == NULL) {
4295 4296 4297
    return;
  }

4298
  taosMemoryFree(pSchemaInfo->tablename);
4299 4300
  tDeleteSSchemaWrapper(pSchemaInfo->sw);
  tDeleteSSchemaWrapper(pSchemaInfo->qsw);
4301 4302
}

4303
static int32_t sortTableGroup(STableListInfo* pTableListInfo, int32_t groupNum) {
wmmhello's avatar
wmmhello 已提交
4304
  taosArrayClear(pTableListInfo->pGroupList);
4305 4306
  SArray* sortSupport = taosArrayInit(groupNum, sizeof(uint64_t));
  if (sortSupport == NULL) return TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
4307 4308
  for (int32_t i = 0; i < taosArrayGetSize(pTableListInfo->pTableList); i++) {
    STableKeyInfo* info = taosArrayGet(pTableListInfo->pTableList, i);
4309
    uint64_t*      groupId = taosHashGet(pTableListInfo->map, &info->uid, sizeof(uint64_t));
wmmhello's avatar
wmmhello 已提交
4310 4311

    int32_t index = taosArraySearchIdx(sortSupport, groupId, compareUint64Val, TD_EQ);
4312 4313 4314 4315
    if (index == -1) {
      void*   p = taosArraySearch(sortSupport, groupId, compareUint64Val, TD_GT);
      SArray* tGroup = taosArrayInit(8, sizeof(STableKeyInfo));
      if (tGroup == NULL) {
wmmhello's avatar
wmmhello 已提交
4316 4317 4318
        taosArrayDestroy(sortSupport);
        return TSDB_CODE_OUT_OF_MEMORY;
      }
4319
      if (taosArrayPush(tGroup, info) == NULL) {
wmmhello's avatar
wmmhello 已提交
4320 4321 4322 4323
        qError("taos push info array error");
        taosArrayDestroy(sortSupport);
        return TSDB_CODE_QRY_APP_ERROR;
      }
4324
      if (p == NULL) {
wmmhello's avatar
wmmhello 已提交
4325
        if (taosArrayPush(sortSupport, groupId) == NULL) {
wmmhello's avatar
wmmhello 已提交
4326 4327 4328 4329
          qError("taos push support array error");
          taosArrayDestroy(sortSupport);
          return TSDB_CODE_QRY_APP_ERROR;
        }
wmmhello's avatar
wmmhello 已提交
4330
        if (taosArrayPush(pTableListInfo->pGroupList, &tGroup) == NULL) {
wmmhello's avatar
wmmhello 已提交
4331 4332 4333 4334
          qError("taos push group array error");
          taosArrayDestroy(sortSupport);
          return TSDB_CODE_QRY_APP_ERROR;
        }
4335
      } else {
wmmhello's avatar
wmmhello 已提交
4336
        int32_t pos = TARRAY_ELEM_IDX(sortSupport, p);
4337
        if (taosArrayInsert(sortSupport, pos, groupId) == NULL) {
wmmhello's avatar
wmmhello 已提交
4338 4339 4340 4341
          qError("taos insert support array error");
          taosArrayDestroy(sortSupport);
          return TSDB_CODE_QRY_APP_ERROR;
        }
4342
        if (taosArrayInsert(pTableListInfo->pGroupList, pos, &tGroup) == NULL) {
wmmhello's avatar
wmmhello 已提交
4343 4344 4345 4346 4347
          qError("taos insert group array error");
          taosArrayDestroy(sortSupport);
          return TSDB_CODE_QRY_APP_ERROR;
        }
      }
4348
    } else {
wmmhello's avatar
wmmhello 已提交
4349
      SArray* tGroup = (SArray*)taosArrayGetP(pTableListInfo->pGroupList, index);
4350
      if (taosArrayPush(tGroup, info) == NULL) {
wmmhello's avatar
wmmhello 已提交
4351 4352 4353 4354 4355 4356 4357 4358 4359 4360
        qError("taos push uid array error");
        taosArrayDestroy(sortSupport);
        return TSDB_CODE_QRY_APP_ERROR;
      }
    }
  }
  taosArrayDestroy(sortSupport);
  return TDB_CODE_SUCCESS;
}

wmmhello's avatar
wmmhello 已提交
4361 4362
int32_t generateGroupIdMap(STableListInfo* pTableListInfo, SReadHandle* pHandle, SNodeList* group) {
  if (group == NULL) {
wmmhello's avatar
wmmhello 已提交
4363 4364 4365 4366 4367 4368 4369 4370
    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 已提交
4371
  void*   keyBuf = NULL;
wmmhello's avatar
wmmhello 已提交
4372

4373
  SNode* node;
wmmhello's avatar
wmmhello 已提交
4374
  FOREACH(node, group) {
4375
    SExprNode* pExpr = (SExprNode*)node;
wmmhello's avatar
wmmhello 已提交
4376
    keyLen += pExpr->resType.bytes;
wmmhello's avatar
wmmhello 已提交
4377 4378
  }

wmmhello's avatar
wmmhello 已提交
4379
  int32_t nullFlagSize = sizeof(int8_t) * LIST_LENGTH(group);
wmmhello's avatar
wmmhello 已提交
4380 4381 4382 4383 4384 4385 4386
  keyLen += nullFlagSize;

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

4387
  int32_t groupNum = 0;
X
Xiaoyu Wang 已提交
4388 4389
  for (int32_t i = 0; i < taosArrayGetSize(pTableListInfo->pTableList); i++) {
    STableKeyInfo* info = taosArrayGet(pTableListInfo->pTableList, i);
H
Haojun Liao 已提交
4390
    int32_t code = getGroupIdFromTagsVal(pHandle->meta, info->uid, group, keyBuf, &info->groupId);
4391 4392
    if (code != TSDB_CODE_SUCCESS) {
      return code;
wmmhello's avatar
wmmhello 已提交
4393
    }
4394

4395
    taosHashPut(pTableListInfo->map, &(info->uid), sizeof(uint64_t), &info->groupId, sizeof(uint64_t));
4396
    groupNum++;
wmmhello's avatar
wmmhello 已提交
4397
  }
4398

wmmhello's avatar
wmmhello 已提交
4399
  taosMemoryFree(keyBuf);
4400

4401
  if (pTableListInfo->needSortTableByGroupId) {
wmmhello's avatar
wmmhello 已提交
4402
    return sortTableGroup(pTableListInfo, groupNum);
4403 4404
  }

wmmhello's avatar
wmmhello 已提交
4405 4406 4407
  return TDB_CODE_SUCCESS;
}

4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426
static int32_t initTableblockDistQueryCond(uint64_t uid, SQueryTableDataCond* pCond) {
  memset(pCond, 0, sizeof(SQueryTableDataCond));

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

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

  pCond->twindows = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
  pCond->suid = uid;
  pCond->type = BLOCK_LOAD_OFFSET_ORDER;
  pCond->startVersion = -1;
L
Liu Jicong 已提交
4427
  pCond->endVersion = -1;
4428 4429 4430 4431

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
4432
SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle,
L
Liu Jicong 已提交
4433 4434
                                  STableListInfo* pTableListInfo, SNode* pTagCond, SNode* pTagIndexCond,
                                  const char* pUser) {
4435 4436
  int32_t type = nodeType(pPhyNode);

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

L
Liu Jicong 已提交
4441 4442 4443
      int32_t code =
          createScanTableListInfo(&pTableScanNode->scan, pTableScanNode->pGroupTags, pTableScanNode->groupSort, pHandle,
                                  pTableListInfo, pTagCond, pTagIndexCond, GET_TASKID(pTaskInfo));
4444
      if (code) {
wmmhello's avatar
wmmhello 已提交
4445
        pTaskInfo->code = code;
D
dapan1121 已提交
4446 4447
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
4448

4449
      code = extractTableSchemaInfo(pHandle, &pTableScanNode->scan, pTaskInfo);
S
slzhou 已提交
4450
      if (code) {
4451
        pTaskInfo->code = terrno;
wmmhello's avatar
wmmhello 已提交
4452 4453 4454
        return NULL;
      }

H
Haojun Liao 已提交
4455
      SOperatorInfo*  pOperator = createTableScanOperatorInfo(pTableScanNode, pHandle, pTaskInfo);
4456 4457
      STableScanInfo* pScanInfo = pOperator->info;
      pTaskInfo->cost.pRecoder = &pScanInfo->readRecorder;
S
slzhou 已提交
4458
      return pOperator;
L
Liu Jicong 已提交
4459

S
slzhou 已提交
4460 4461
    } else if (QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN == type) {
      STableMergeScanPhysiNode* pTableScanNode = (STableMergeScanPhysiNode*)pPhyNode;
L
Liu Jicong 已提交
4462 4463 4464
      int32_t                   code =
          createScanTableListInfo(&pTableScanNode->scan, pTableScanNode->pGroupTags, pTableScanNode->groupSort, pHandle,
                                  pTableListInfo, pTagCond, pTagIndexCond, GET_TASKID(pTaskInfo));
L
Liu Jicong 已提交
4465
      if (code) {
wmmhello's avatar
wmmhello 已提交
4466
        pTaskInfo->code = code;
wmmhello's avatar
wmmhello 已提交
4467 4468
        return NULL;
      }
4469

4470
      code = extractTableSchemaInfo(pHandle, &pTableScanNode->scan, pTaskInfo);
wmmhello's avatar
wmmhello 已提交
4471 4472 4473 4474
      if (code) {
        pTaskInfo->code = terrno;
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
4475

L
Liu Jicong 已提交
4476
      SOperatorInfo* pOperator = createTableMergeScanOperatorInfo(pTableScanNode, pTableListInfo, pHandle, pTaskInfo);
wmmhello's avatar
wmmhello 已提交
4477

4478 4479 4480
      STableScanInfo* pScanInfo = pOperator->info;
      pTaskInfo->cost.pRecoder = &pScanInfo->readRecorder;
      return pOperator;
L
Liu Jicong 已提交
4481

H
Haojun Liao 已提交
4482
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == type) {
4483
      return createExchangeOperatorInfo(pHandle->pMsgCb->clientRpc, (SExchangePhysiNode*)pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
4484
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == type) {
5
54liuyao 已提交
4485
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
5
54liuyao 已提交
4486
      if (pHandle->vnode) {
L
Liu Jicong 已提交
4487 4488 4489
        int32_t code =
            createScanTableListInfo(&pTableScanNode->scan, pTableScanNode->pGroupTags, pTableScanNode->groupSort,
                                    pHandle, pTableListInfo, pTagCond, pTagIndexCond, GET_TASKID(pTaskInfo));
L
Liu Jicong 已提交
4490
        if (code) {
wmmhello's avatar
wmmhello 已提交
4491 4492 4493
          pTaskInfo->code = code;
          return NULL;
        }
L
Liu Jicong 已提交
4494 4495 4496 4497 4498 4499 4500

#ifndef NDEBUG
        int32_t sz = taosArrayGetSize(pTableListInfo->pTableList);
        for (int32_t i = 0; i < sz; i++) {
          STableKeyInfo* pKeyInfo = taosArrayGet(pTableListInfo->pTableList, i);
          qDebug("creating stream task: add table %ld", pKeyInfo->uid);
        }
5
54liuyao 已提交
4501
      }
L
Liu Jicong 已提交
4502
#endif
4503

H
Haojun Liao 已提交
4504
      pTaskInfo->schemaInfo.qsw = extractQueriedColumnSchema(&pTableScanNode->scan);
4505
      SOperatorInfo* pOperator = createStreamScanOperatorInfo(pHandle, pTableScanNode, pTagCond, pTaskInfo);
H
Haojun Liao 已提交
4506
      return pOperator;
L
Liu Jicong 已提交
4507

H
Haojun Liao 已提交
4508
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == type) {
L
Liu Jicong 已提交
4509
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
4510
      return createSysTableScanOperatorInfo(pHandle, pSysScanPhyNode, pUser, pTaskInfo);
4511
    } else if (QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN == type) {
X
Xiaoyu Wang 已提交
4512
      STagScanPhysiNode* pScanPhyNode = (STagScanPhysiNode*)pPhyNode;
4513

4514
      int32_t code = getTableList(pHandle->meta, pHandle->vnode, pScanPhyNode, pTagCond, pTagIndexCond, pTableListInfo);
4515
      if (code != TSDB_CODE_SUCCESS) {
4516
        pTaskInfo->code = terrno;
4517 4518 4519
        return NULL;
      }

4520
      return createTagScanOperatorInfo(pHandle, pScanPhyNode, pTableListInfo, pTaskInfo);
4521
    } else if (QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN == type) {
4522
      SBlockDistScanPhysiNode* pBlockNode = (SBlockDistScanPhysiNode*)pPhyNode;
4523 4524 4525
      pTableListInfo->pTableList = taosArrayInit(4, sizeof(STableKeyInfo));

      if (pBlockNode->tableType == TSDB_SUPER_TABLE) {
4526
        int32_t code = vnodeGetAllTableList(pHandle->vnode, pBlockNode->uid, pTableListInfo->pTableList);
4527 4528 4529 4530 4531
        if (code != TSDB_CODE_SUCCESS) {
          pTaskInfo->code = terrno;
          return NULL;
        }
      } else {  // Create one table group.
4532
        STableKeyInfo info = {.uid = pBlockNode->uid, .groupId = 0};
4533 4534 4535 4536
        taosArrayPush(pTableListInfo->pTableList, &info);
      }

      SQueryTableDataCond cond = {0};
L
Liu Jicong 已提交
4537
      int32_t             code = initTableblockDistQueryCond(pBlockNode->suid, &cond);
4538 4539
      if (code != TSDB_CODE_SUCCESS) {
        return NULL;
4540
      }
H
Haojun Liao 已提交
4541 4542 4543

      STsdbReader* pReader = NULL;
      tsdbReaderOpen(pHandle->vnode, &cond, pTableListInfo->pTableList, &pReader, "");
4544 4545
      cleanupQueryTableDataCond(&cond);

4546
      return createDataBlockInfoScanOperator(pReader, pHandle, cond.suid, pBlockNode, pTaskInfo);
H
Haojun Liao 已提交
4547 4548 4549
    } else if (QUERY_NODE_PHYSICAL_PLAN_LAST_ROW_SCAN == type) {
      SLastRowScanPhysiNode* pScanNode = (SLastRowScanPhysiNode*)pPhyNode;

L
Liu Jicong 已提交
4550 4551
      int32_t code = createScanTableListInfo(&pScanNode->scan, pScanNode->pGroupTags, true, pHandle, pTableListInfo,
                                             pTagCond, pTagIndexCond, GET_TASKID(pTaskInfo));
4552 4553 4554 4555
      if (code != TSDB_CODE_SUCCESS) {
        pTaskInfo->code = code;
        return NULL;
      }
4556

4557
      code = extractTableSchemaInfo(pHandle, &pScanNode->scan, pTaskInfo);
4558 4559 4560
      if (code != TSDB_CODE_SUCCESS) {
        pTaskInfo->code = code;
        return NULL;
H
Haojun Liao 已提交
4561 4562
      }

4563
      return createLastrowScanOperator(pScanNode, pHandle, pTaskInfo);
H
Haojun Liao 已提交
4564 4565
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
4566 4567 4568
    }
  }

4569 4570
  int32_t num = 0;
  size_t  size = LIST_LENGTH(pPhyNode->pChildren);
H
Haojun Liao 已提交
4571

4572
  SOperatorInfo** ops = taosMemoryCalloc(size, POINTER_BYTES);
dengyihao's avatar
dengyihao 已提交
4573
  for (int32_t i = 0; i < size; ++i) {
4574
    SPhysiNode* pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
4575
    ops[i] = createOperatorTree(pChildNode, pTaskInfo, pHandle, pTableListInfo, pTagCond, pTagIndexCond, pUser);
4576 4577 4578
    if (ops[i] == NULL) {
      return NULL;
    }
4579
  }
H
Haojun Liao 已提交
4580

4581
  SOperatorInfo* pOptr = NULL;
H
Haojun Liao 已提交
4582
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
4583
    pOptr = createProjectOperatorInfo(ops[0], (SProjectPhysiNode*)pPhyNode, pTaskInfo);
4584
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_AGG == type) {
H
Haojun Liao 已提交
4585 4586
    SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
    SExprInfo*     pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
4587
    SSDataBlock*   pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
4588

dengyihao's avatar
dengyihao 已提交
4589
    int32_t    numOfScalarExpr = 0;
4590 4591 4592 4593 4594
    SExprInfo* pScalarExprInfo = NULL;
    if (pAggNode->pExprs != NULL) {
      pScalarExprInfo = createExprInfo(pAggNode->pExprs, NULL, &numOfScalarExpr);
    }

H
Haojun Liao 已提交
4595 4596
    if (pAggNode->pGroupKeys != NULL) {
      SArray* pColList = extractColumnInfo(pAggNode->pGroupKeys);
dengyihao's avatar
dengyihao 已提交
4597
      pOptr = createGroupOperatorInfo(ops[0], pExprInfo, num, pResBlock, pColList, pAggNode->node.pConditions,
wmmhello's avatar
wmmhello 已提交
4598
                                      pScalarExprInfo, numOfScalarExpr, pTaskInfo);
H
Haojun Liao 已提交
4599
    } else {
L
Liu Jicong 已提交
4600 4601
      pOptr = createAggregateOperatorInfo(ops[0], pExprInfo, num, pResBlock, pAggNode->node.pConditions,
                                          pScalarExprInfo, numOfScalarExpr, pTaskInfo);
H
Haojun Liao 已提交
4602
    }
X
Xiaoyu Wang 已提交
4603
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_INTERVAL == type || QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type) {
H
Haojun Liao 已提交
4604
    SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
4605

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

dengyihao's avatar
dengyihao 已提交
4609 4610 4611 4612 4613 4614
    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 已提交
4615

X
Xiaoyu Wang 已提交
4616 4617 4618 4619 4620
    STimeWindowAggSupp as = {
        .waterMark = pIntervalPhyNode->window.watermark,
        .calTrigger = pIntervalPhyNode->window.triggerType,
        .maxTs = INT64_MIN,
    };
4621
    ASSERT(as.calTrigger != STREAM_TRIGGER_MAX_DELAY);
4622

4623
    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
L
Liu Jicong 已提交
4624
    bool    isStream = (QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type);
4625 4626
    pOptr = createIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId, &as, pIntervalPhyNode,
                                       pTaskInfo, isStream);
4627

4628 4629
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_ALIGNED_INTERVAL == type) {
    SMergeAlignedIntervalPhysiNode* pIntervalPhyNode = (SMergeAlignedIntervalPhysiNode*)pPhyNode;
S
shenglian zhou 已提交
4630 4631 4632 4633 4634 4635 4636 4637 4638 4639

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

S
shenglian zhou 已提交
4641
    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
L
Liu Jicong 已提交
4642 4643
    pOptr = createMergeAlignedIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId,
                                                   pPhyNode->pConditions, pTaskInfo);
S
shenglian zhou 已提交
4644
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_INTERVAL == type) {
X
Xiaoyu Wang 已提交
4645
    SMergeIntervalPhysiNode* pIntervalPhyNode = (SMergeIntervalPhysiNode*)pPhyNode;
S
shenglian zhou 已提交
4646 4647 4648 4649 4650 4651 4652 4653 4654 4655

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

S
shenglian zhou 已提交
4657 4658
    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
    pOptr = createMergeIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId, pTaskInfo);
5
54liuyao 已提交
4659
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SEMI_INTERVAL == type) {
4660
    int32_t children = 0;
5
54liuyao 已提交
4661 4662
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_FINAL_INTERVAL == type) {
5
54liuyao 已提交
4663
    int32_t children = pHandle->numOfVgroups;
5
54liuyao 已提交
4664
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
H
Haojun Liao 已提交
4665
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == type) {
4666
    pOptr = createSortOperatorInfo(ops[0], (SSortPhysiNode*)pPhyNode, pTaskInfo);
S
shenglian zhou 已提交
4667 4668
  } else if (QUERY_NODE_PHYSICAL_PLAN_GROUP_SORT == type) {
    pOptr = createGroupSortOperatorInfo(ops[0], (SGroupSortPhysiNode*)pPhyNode, pTaskInfo);
X
Xiaoyu Wang 已提交
4669
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE == type) {
4670
    SMergePhysiNode* pMergePhyNode = (SMergePhysiNode*)pPhyNode;
4671
    pOptr = createMultiwayMergeOperatorInfo(ops, size, pMergePhyNode, pTaskInfo);
4672
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_SESSION == type) {
H
Haojun Liao 已提交
4673 4674
    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;

X
Xiaoyu Wang 已提交
4675 4676
    STimeWindowAggSupp as = {.waterMark = pSessionNode->window.watermark,
                             .calTrigger = pSessionNode->window.triggerType};
4677

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

L
Liu Jicong 已提交
4682 4683
    pOptr = createSessionAggOperatorInfo(ops[0], pExprInfo, num, pResBlock, pSessionNode->gap, tsSlotId, &as,
                                         pPhyNode->pConditions, pTaskInfo);
4684
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION == type) {
4685 4686 4687 4688 4689 4690 4691
    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 已提交
4692
  } else if (QUERY_NODE_PHYSICAL_PLAN_PARTITION == type) {
4693
    pOptr = createPartitionOperatorInfo(ops[0], (SPartitionPhysiNode*)pPhyNode, pTaskInfo);
4694
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_STATE == type) {
dengyihao's avatar
dengyihao 已提交
4695
    SStateWinodwPhysiNode* pStateNode = (SStateWinodwPhysiNode*)pPhyNode;
4696

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

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

4703
    SColumnNode* pColNode = (SColumnNode*)((STargetNode*)pStateNode->pStateKey)->pExpr;
X
Xiaoyu Wang 已提交
4704
    SColumn      col = extractColumnFromColumnNode(pColNode);
L
Liu Jicong 已提交
4705 4706
    pOptr = createStatewindowOperatorInfo(ops[0], pExprInfo, num, pResBlock, &as, tsSlotId, &col, pPhyNode->pConditions,
                                          pTaskInfo);
4707
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_STATE == type) {
5
54liuyao 已提交
4708
    pOptr = createStreamStateAggOperatorInfo(ops[0], pPhyNode, pTaskInfo);
4709
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_JOIN == type) {
4710
    pOptr = createMergeJoinOperatorInfo(ops, size, (SJoinPhysiNode*)pPhyNode, pTaskInfo);
4711
  } else if (QUERY_NODE_PHYSICAL_PLAN_FILL == type) {
H
Haojun Liao 已提交
4712
    pOptr = createFillOperatorInfo(ops[0], (SFillPhysiNode*)pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
4713 4714
  } else if (QUERY_NODE_PHYSICAL_PLAN_INDEF_ROWS_FUNC == type) {
    pOptr = createIndefinitOutputOperatorInfo(ops[0], pPhyNode, pTaskInfo);
4715 4716
  } else if (QUERY_NODE_PHYSICAL_PLAN_INTERP_FUNC == type) {
    pOptr = createTimeSliceOperatorInfo(ops[0], pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
4717 4718
  } else {
    ASSERT(0);
H
Haojun Liao 已提交
4719
  }
4720 4721 4722

  taosMemoryFree(ops);
  return pOptr;
4723
}
H
Haojun Liao 已提交
4724

H
Haojun Liao 已提交
4725
SArray* extractColumnInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
4726
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4727 4728 4729 4730 4731 4732
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

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

4736 4737 4738
    if (nodeType(pNode->pExpr) == QUERY_NODE_COLUMN) {
      SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

4739
      SColumn c = extractColumnFromColumnNode(pColNode);
4740 4741
      taosArrayPush(pList, &c);
    } else if (nodeType(pNode->pExpr) == QUERY_NODE_VALUE) {
L
Liu Jicong 已提交
4742 4743
      SValueNode* pValNode = (SValueNode*)pNode->pExpr;
      SColumn     c = {0};
4744
      c.slotId = pNode->slotId;
L
Liu Jicong 已提交
4745 4746 4747 4748
      c.colId = pNode->slotId;
      c.type = pValNode->node.type;
      c.bytes = pValNode->node.resType.bytes;
      c.scale = pValNode->node.resType.scale;
4749 4750 4751 4752
      c.precision = pValNode->node.resType.precision;

      taosArrayPush(pList, &c);
    }
H
Haojun Liao 已提交
4753 4754 4755 4756 4757
  }

  return pList;
}

4758
#if 0
L
Liu Jicong 已提交
4759 4760
STsdbReader* doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
                                STableListInfo* pTableListInfo, const char* idstr) {
4761
  int32_t code = getTableList(pHandle->meta, pHandle->vnode, &pTableScanNode->scan, pTableListInfo);
wmmhello's avatar
wmmhello 已提交
4762 4763 4764 4765 4766 4767
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

  if (taosArrayGetSize(pTableListInfo->pTableList) == 0) {
    code = 0;
H
Haojun Liao 已提交
4768
    qDebug("no table qualified for query, %s", idstr);
wmmhello's avatar
wmmhello 已提交
4769 4770 4771
    goto _error;
  }

4772
  SQueryTableDataCond cond = {0};
wmmhello's avatar
wmmhello 已提交
4773
  code = initQueryTableDataCond(&cond, pTableScanNode);
4774
  if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4775
    goto _error;
X
Xiaoyu Wang 已提交
4776
  }
4777

H
Hongze Cheng 已提交
4778
  STsdbReader* pReader;
H
Haojun Liao 已提交
4779
  code = tsdbReaderOpen(pHandle->vnode, &cond, pTableListInfo->pTableList, &pReader, idstr);
H
Haojun Liao 已提交
4780 4781 4782 4783
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

4784
  cleanupQueryTableDataCond(&cond);
H
Haojun Liao 已提交
4785 4786

  return pReader;
wmmhello's avatar
wmmhello 已提交
4787 4788 4789 4790

_error:
  terrno = code;
  return NULL;
H
Haojun Liao 已提交
4791
}
4792
#endif
H
Haojun Liao 已提交
4793

L
Liu Jicong 已提交
4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806
static int32_t extractTbscanInStreamOpTree(SOperatorInfo* pOperator, STableScanInfo** ppInfo) {
  if (pOperator->operatorType != QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN) {
    if (pOperator->numOfDownstream == 0) {
      qError("failed to find stream scan operator");
      return TSDB_CODE_QRY_APP_ERROR;
    }

    if (pOperator->numOfDownstream > 1) {
      qError("join not supported for stream block scan");
      return TSDB_CODE_QRY_APP_ERROR;
    }
    return extractTbscanInStreamOpTree(pOperator->pDownstream[0], ppInfo);
  } else {
4807 4808 4809
    SStreamScanInfo* pInfo = pOperator->info;
    ASSERT(pInfo->pTableScanOp->operatorType == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN);
    *ppInfo = pInfo->pTableScanOp->info;
L
Liu Jicong 已提交
4810 4811 4812 4813
    return 0;
  }
}

4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835
int32_t extractTableScanNode(SPhysiNode* pNode, STableScanPhysiNode** ppNode) {
  if (pNode->pChildren == NULL || LIST_LENGTH(pNode->pChildren) == 0) {
    if (QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN == pNode->type) {
      *ppNode = (STableScanPhysiNode*)pNode;
      return 0;
    } else {
      ASSERT(0);
      terrno = TSDB_CODE_QRY_APP_ERROR;
      return -1;
    }
  } else {
    if (LIST_LENGTH(pNode->pChildren) != 1) {
      ASSERT(0);
      terrno = TSDB_CODE_QRY_APP_ERROR;
      return -1;
    }
    SPhysiNode* pChildNode = (SPhysiNode*)nodesListGetNode(pNode->pChildren, 0);
    return extractTableScanNode(pChildNode, ppNode);
  }
  return -1;
}

4836
#if 0
L
Liu Jicong 已提交
4837 4838 4839 4840 4841
int32_t rebuildReader(SOperatorInfo* pOperator, SSubplan* plan, SReadHandle* pHandle, int64_t uid, int64_t ts) {
  STableScanInfo* pTableScanInfo = NULL;
  if (extractTbscanInStreamOpTree(pOperator, &pTableScanInfo) < 0) {
    return -1;
  }
4842

L
Liu Jicong 已提交
4843 4844 4845 4846
  STableScanPhysiNode* pNode = NULL;
  if (extractTableScanNode(plan->pNode, &pNode) < 0) {
    ASSERT(0);
  }
4847

H
Haojun Liao 已提交
4848
  tsdbReaderClose(pTableScanInfo->dataReader);
4849

L
Liu Jicong 已提交
4850
  STableListInfo info = {0};
H
Haojun Liao 已提交
4851
  pTableScanInfo->dataReader = doCreateDataReader(pNode, pHandle, &info, NULL);
L
Liu Jicong 已提交
4852 4853 4854 4855
  if (pTableScanInfo->dataReader == NULL) {
    ASSERT(0);
    qError("failed to create data reader");
    return TSDB_CODE_QRY_APP_ERROR;
4856
  }
L
Liu Jicong 已提交
4857
  // TODO: set uid and ts to data reader
4858 4859
  return 0;
}
4860
#endif
4861

C
Cary Xu 已提交
4862
int32_t encodeOperator(SOperatorInfo* ops, char** result, int32_t* length, int32_t* nOptrWithVal) {
wmmhello's avatar
wmmhello 已提交
4863
  int32_t code = TDB_CODE_SUCCESS;
4864
  char*   pCurrent = NULL;
wmmhello's avatar
wmmhello 已提交
4865
  int32_t currLength = 0;
4866
  if (ops->fpSet.encodeResultRow) {
C
Cary Xu 已提交
4867
    if (result == NULL || length == NULL || nOptrWithVal == NULL) {
wmmhello's avatar
wmmhello 已提交
4868 4869 4870
      return TSDB_CODE_TSC_INVALID_INPUT;
    }
    code = ops->fpSet.encodeResultRow(ops, &pCurrent, &currLength);
wmmhello's avatar
wmmhello 已提交
4871

4872 4873
    if (code != TDB_CODE_SUCCESS) {
      if (*result != NULL) {
wmmhello's avatar
wmmhello 已提交
4874 4875 4876 4877
        taosMemoryFree(*result);
        *result = NULL;
      }
      return code;
C
Cary Xu 已提交
4878 4879 4880
    } else if (currLength == 0) {
      ASSERT(!pCurrent);
      goto _downstream;
wmmhello's avatar
wmmhello 已提交
4881
    }
wmmhello's avatar
wmmhello 已提交
4882

C
Cary Xu 已提交
4883 4884
    ++(*nOptrWithVal);

C
Cary Xu 已提交
4885
    ASSERT(currLength >= 0);
wmmhello's avatar
wmmhello 已提交
4886

4887
    if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
4888
      *result = (char*)taosMemoryCalloc(1, currLength + sizeof(int32_t));
wmmhello's avatar
wmmhello 已提交
4889 4890 4891 4892 4893 4894
      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);
4895
    } else {
wmmhello's avatar
wmmhello 已提交
4896
      int32_t sizePre = *(int32_t*)(*result);
4897
      char*   tmp = (char*)taosMemoryRealloc(*result, sizePre + currLength);
wmmhello's avatar
wmmhello 已提交
4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909
      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 已提交
4910 4911
  }

C
Cary Xu 已提交
4912
_downstream:
wmmhello's avatar
wmmhello 已提交
4913
  for (int32_t i = 0; i < ops->numOfDownstream; ++i) {
C
Cary Xu 已提交
4914
    code = encodeOperator(ops->pDownstream[i], result, length, nOptrWithVal);
4915
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4916
      return code;
wmmhello's avatar
wmmhello 已提交
4917 4918
    }
  }
wmmhello's avatar
wmmhello 已提交
4919
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
4920 4921
}

H
Haojun Liao 已提交
4922
int32_t decodeOperator(SOperatorInfo* ops, const char* result, int32_t length) {
wmmhello's avatar
wmmhello 已提交
4923
  int32_t code = TDB_CODE_SUCCESS;
4924 4925
  if (ops->fpSet.decodeResultRow) {
    if (result == NULL) {
wmmhello's avatar
wmmhello 已提交
4926 4927
      return TSDB_CODE_TSC_INVALID_INPUT;
    }
H
Haojun Liao 已提交
4928

4929
    ASSERT(length == *(int32_t*)result);
H
Haojun Liao 已提交
4930 4931

    const char* data = result + sizeof(int32_t);
L
Liu Jicong 已提交
4932
    code = ops->fpSet.decodeResultRow(ops, (char*)data);
4933
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4934 4935
      return code;
    }
wmmhello's avatar
wmmhello 已提交
4936

wmmhello's avatar
wmmhello 已提交
4937
    int32_t totalLength = *(int32_t*)result;
4938 4939
    int32_t dataLength = *(int32_t*)data;

4940
    if (totalLength == dataLength + sizeof(int32_t)) {  // the last data
wmmhello's avatar
wmmhello 已提交
4941 4942
      result = NULL;
      length = 0;
4943
    } else {
wmmhello's avatar
wmmhello 已提交
4944 4945 4946 4947
      result += dataLength;
      *(int32_t*)(result) = totalLength - dataLength;
      length = totalLength - dataLength;
    }
wmmhello's avatar
wmmhello 已提交
4948 4949
  }

wmmhello's avatar
wmmhello 已提交
4950 4951
  for (int32_t i = 0; i < ops->numOfDownstream; ++i) {
    code = decodeOperator(ops->pDownstream[i], result, length);
4952
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4953
      return code;
wmmhello's avatar
wmmhello 已提交
4954 4955
    }
  }
wmmhello's avatar
wmmhello 已提交
4956
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
4957 4958
}

D
dapan1121 已提交
4959
int32_t createDataSinkParam(SDataSinkNode* pNode, void** pParam, qTaskInfo_t* pTaskInfo, SReadHandle* readHandle) {
D
dapan1121 已提交
4960
  SExecTaskInfo* pTask = *(SExecTaskInfo**)pTaskInfo;
4961

D
dapan1121 已提交
4962
  switch (pNode->type) {
D
dapan1121 已提交
4963 4964 4965 4966 4967 4968
    case QUERY_NODE_PHYSICAL_PLAN_QUERY_INSERT: {
      SInserterParam* pInserterParam = taosMemoryCalloc(1, sizeof(SInserterParam));
      if (NULL == pInserterParam) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      pInserterParam->readHandle = readHandle;
L
Liu Jicong 已提交
4969

D
dapan1121 已提交
4970 4971 4972
      *pParam = pInserterParam;
      break;
    }
D
dapan1121 已提交
4973
    case QUERY_NODE_PHYSICAL_PLAN_DELETE: {
4974
      SDeleterParam* pDeleterParam = taosMemoryCalloc(1, sizeof(SDeleterParam));
D
dapan1121 已提交
4975 4976 4977 4978
      if (NULL == pDeleterParam) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      int32_t tbNum = taosArrayGetSize(pTask->tableqinfoList.pTableList);
D
dapan1121 已提交
4979
      pDeleterParam->suid = pTask->tableqinfoList.suid;
D
dapan1121 已提交
4980 4981 4982 4983 4984 4985
      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) {
4986
        STableKeyInfo* pTable = taosArrayGet(pTask->tableqinfoList.pTableList, i);
D
dapan1121 已提交
4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999
        taosArrayPush(pDeleterParam->pUidList, &pTable->uid);
      }

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

  return TSDB_CODE_SUCCESS;
}

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

H
Haojun Liao 已提交
5004
  int32_t code = TSDB_CODE_SUCCESS;
D
dapan1121 已提交
5005
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model, pPlan->dbFName);
H
Haojun Liao 已提交
5006 5007 5008 5009
  if (*pTaskInfo == NULL) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _complete;
  }
H
Haojun Liao 已提交
5010

5011
  (*pTaskInfo)->sql = sql;
5012
  (*pTaskInfo)->pSubplan = pPlan;
L
Liu Jicong 已提交
5013 5014
  (*pTaskInfo)->pRoot = createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, &(*pTaskInfo)->tableqinfoList,
                                           pPlan->pTagCond, pPlan->pTagIndexCond, pPlan->user);
L
Liu Jicong 已提交
5015

D
dapan1121 已提交
5016
  if (NULL == (*pTaskInfo)->pRoot) {
5017
    code = (*pTaskInfo)->code;
D
dapan1121 已提交
5018
    goto _complete;
5019 5020
  }

H
Haojun Liao 已提交
5021 5022
  return code;

H
Haojun Liao 已提交
5023
_complete:
wafwerar's avatar
wafwerar 已提交
5024
  taosMemoryFreeClear(*pTaskInfo);
H
Haojun Liao 已提交
5025 5026
  terrno = code;
  return code;
H
Haojun Liao 已提交
5027 5028
}

wmmhello's avatar
wmmhello 已提交
5029 5030 5031
static void doDestroyTableList(STableListInfo* pTableqinfoList) {
  taosArrayDestroy(pTableqinfoList->pTableList);
  taosHashCleanup(pTableqinfoList->map);
5032 5033
  if (pTableqinfoList->needSortTableByGroupId) {
    for (int32_t i = 0; i < taosArrayGetSize(pTableqinfoList->pGroupList); i++) {
wmmhello's avatar
wmmhello 已提交
5034
      SArray* tmp = taosArrayGetP(pTableqinfoList->pGroupList, i);
5035 5036 5037
      if (tmp == pTableqinfoList->pTableList) {
        continue;
      }
wmmhello's avatar
wmmhello 已提交
5038 5039 5040 5041
      taosArrayDestroy(tmp);
    }
  }
  taosArrayDestroy(pTableqinfoList->pGroupList);
5042

wmmhello's avatar
wmmhello 已提交
5043 5044
  pTableqinfoList->pTableList = NULL;
  pTableqinfoList->map = NULL;
5045 5046
}

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

wmmhello's avatar
wmmhello 已提交
5050
  doDestroyTableList(&pTaskInfo->tableqinfoList);
H
Haojun Liao 已提交
5051
  destroyOperatorInfo(pTaskInfo->pRoot);
5052 5053 5054
  cleanupTableSchemaInfo(&pTaskInfo->schemaInfo);

  nodesDestroyNode((SNode*)pTaskInfo->pSubplan);
5055

wafwerar's avatar
wafwerar 已提交
5056 5057 5058
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070
}

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 已提交
5071
      int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083
      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 已提交
5084 5085
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
5086 5087 5088 5089 5090 5091 5092
}

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 已提交
5093
    while (1) {
5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119
      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 已提交
5120

dengyihao's avatar
dengyihao 已提交
5121 5122
int32_t getOperatorExplainExecInfo(SOperatorInfo* operatorInfo, SExplainExecInfo** pRes, int32_t* capacity,
                                   int32_t* resNum) {
D
dapan1121 已提交
5123 5124
  if (*resNum >= *capacity) {
    *capacity += 10;
dengyihao's avatar
dengyihao 已提交
5125

D
dapan1121 已提交
5126 5127
    *pRes = taosMemoryRealloc(*pRes, (*capacity) * sizeof(SExplainExecInfo));
    if (NULL == *pRes) {
D
dapan1121 已提交
5128
      qError("malloc %d failed", (*capacity) * (int32_t)sizeof(SExplainExecInfo));
D
dapan1121 已提交
5129 5130 5131 5132
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

5133 5134 5135 5136 5137
  SExplainExecInfo* pInfo = &(*pRes)[*resNum];

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

5139
  if (operatorInfo->fpSet.getExplainFn) {
5140
    int32_t code = operatorInfo->fpSet.getExplainFn(operatorInfo, &pInfo->verboseInfo, &pInfo->verboseLen);
D
dapan1121 已提交
5141
    if (code) {
5142
      qError("%s operator getExplainFn failed, code:%s", GET_TASKID(operatorInfo->pTaskInfo), tstrerror(code));
D
dapan1121 已提交
5143 5144
      return code;
    }
5145 5146 5147
  } else {
    pInfo->verboseLen = 0;
    pInfo->verboseInfo = NULL;
D
dapan1121 已提交
5148
  }
dengyihao's avatar
dengyihao 已提交
5149

D
dapan1121 已提交
5150
  ++(*resNum);
dengyihao's avatar
dengyihao 已提交
5151

D
dapan1121 已提交
5152
  int32_t code = 0;
D
dapan1121 已提交
5153 5154
  for (int32_t i = 0; i < operatorInfo->numOfDownstream; ++i) {
    code = getOperatorExplainExecInfo(operatorInfo->pDownstream[i], pRes, capacity, resNum);
D
dapan1121 已提交
5155 5156 5157 5158 5159 5160 5161
    if (code) {
      taosMemoryFreeClear(*pRes);
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
5162
}
5
54liuyao 已提交
5163

L
Liu Jicong 已提交
5164
int32_t initStreamAggSupporter(SStreamAggSupporter* pSup, const char* pKey, SqlFunctionCtx* pCtx, int32_t numOfOutput,
5165
                               int32_t size) {
5166
  pSup->resultRowSize = getResultRowSize(pCtx, numOfOutput);
5
54liuyao 已提交
5167 5168
  pSup->keySize = sizeof(int64_t) + sizeof(TSKEY);
  pSup->pKeyBuf = taosMemoryCalloc(1, pSup->keySize);
5169 5170
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);
  pSup->pResultRows = taosHashInit(1024, hashFn, false, HASH_NO_LOCK);
5
54liuyao 已提交
5171 5172 5173
  if (pSup->pKeyBuf == NULL || pSup->pResultRows == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
5174
  pSup->valueSize = size;
5
54liuyao 已提交
5175

5176
  pSup->pScanBlock = createSpecialDataBlock(STREAM_CLEAR);
5
54liuyao 已提交
5177 5178 5179 5180 5181 5182 5183 5184 5185
  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;
  }
5186
  int32_t code = createDiskbasedBuf(&pSup->pResultBuf, pageSize, bufSize, pKey, TD_TMP_DIR_PATH);
L
Liu Jicong 已提交
5187
  for (int32_t i = 0; i < numOfOutput; ++i) {
5188 5189 5190
    pCtx[i].pBuf = pSup->pResultBuf;
  }
  return code;
5
54liuyao 已提交
5191
}