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

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

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

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

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

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

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

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

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

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

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

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

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

84
static void setBlockSMAInfo(SqlFunctionCtx* pCtx, SExprInfo* pExpr, SSDataBlock* pBlock);
85

X
Xiaoyu Wang 已提交
86
static void releaseQueryBuf(size_t numOfTables);
87

88 89 90 91
static void destroyFillOperatorInfo(void* param);
static void destroyProjectOperatorInfo(void* param);
static void destroyOrderOperatorInfo(void* param);
static void destroyAggOperatorInfo(void* param);
X
Xiaoyu Wang 已提交
92

93 94
static void destroyIntervalOperatorInfo(void* param);
static void destroyExchangeOperatorInfo(void* param);
H
Haojun Liao 已提交
95

96 97
static void destroyOperatorInfo(SOperatorInfo* pOperator);

98
void doSetOperatorCompleted(SOperatorInfo* pOperator) {
99
  pOperator->status = OP_EXEC_DONE;
100

101
  pOperator->cost.totalCost = (taosGetTimestampUs() - pOperator->pTaskInfo->cost.start * 1000) / 1000.0;
H
Haojun Liao 已提交
102
  if (pOperator->pTaskInfo != NULL) {
103
    setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
104 105
  }
}
106

H
Haojun Liao 已提交
107
int32_t operatorDummyOpenFn(SOperatorInfo* pOperator) {
108
  OPTR_SET_OPENED(pOperator);
109
  pOperator->cost.openCost = 0;
H
Haojun Liao 已提交
110
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
111 112
}

113
SOperatorFpSet createOperatorFpSet(__optr_open_fn_t openFn, __optr_fn_t nextFn, __optr_fn_t streamFn,
L
Liu Jicong 已提交
114
                                   __optr_fn_t cleanup, __optr_close_fn_t closeFn, __optr_encode_fn_t encode,
115
                                   __optr_decode_fn_t decode, __optr_explain_fn_t explain) {
116 117 118 119 120 121 122 123 124 125 126 127 128 129
  SOperatorFpSet fpSet = {
      ._openFn = openFn,
      .getNextFn = nextFn,
      .getStreamResFn = streamFn,
      .cleanupFn = cleanup,
      .closeFn = closeFn,
      .encodeResultRow = encode,
      .decodeResultRow = decode,
      .getExplainFn = explain,
  };

  return fpSet;
}

130 131
static int32_t doCopyToSDataBlock(SExecTaskInfo* pTaskInfo, SSDataBlock* pBlock, SExprSupp* pSup, SDiskbasedBuf* pBuf,
                                  SGroupResInfo* pGroupResInfo);
H
Haojun Liao 已提交
132

133
static void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size);
134
static void doSetTableGroupOutputBuf(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId);
135

136
#if 0
L
Liu Jicong 已提交
137 138
static bool chkResultRowFromKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, char* pData,
                                int16_t bytes, bool masterscan, uint64_t uid) {
139 140 141
  bool existed = false;
  SET_RES_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid);

L
Liu Jicong 已提交
142 143
  SResultRow** p1 =
      (SResultRow**)taosHashGet(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
144 145 146 147 148 149 150 151 152 153 154

  // 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 已提交
155
        //        existed = (pResultRowInfo->pResult[0] == (*p1));
156 157
      } else {  // check if current pResultRowInfo contains the existed pResultRow
        SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid, pResultRowInfo);
L
Liu Jicong 已提交
158 159
        int64_t* index =
            taosHashGet(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
160 161 162 163 164 165 166 167 168 169 170 171 172
        if (index != NULL) {
          existed = true;
        } else {
          existed = false;
        }
      }
    }

    return existed;
  }

  return p1 != NULL;
}
173
#endif
174

175
SResultRow* getNewResultRow(SDiskbasedBuf* pResultBuf, int32_t* currentPageId, int32_t interBufSize) {
L
Liu Jicong 已提交
176
  SFilePage* pData = NULL;
177 178 179

  // in the first scan, new space needed for results
  int32_t pageId = -1;
180
  if (*currentPageId == -1) {
181
    pData = getNewBufPage(pResultBuf, &pageId);
182 183
    pData->num = sizeof(SFilePage);
  } else {
184 185
    pData = getBufPage(pResultBuf, *currentPageId);
    pageId = *currentPageId;
186

wmmhello's avatar
wmmhello 已提交
187
    if (pData->num + interBufSize > getBufPageSize(pResultBuf)) {
188
      // release current page first, and prepare the next one
189
      releaseBufPage(pResultBuf, pData);
190

191
      pData = getNewBufPage(pResultBuf, &pageId);
192 193 194 195 196 197 198 199 200 201
      if (pData != NULL) {
        pData->num = sizeof(SFilePage);
      }
    }
  }

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

202 203
  setBufPageDirty(pData, true);

204 205 206 207
  // 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;
208
  *currentPageId = pageId;
209

wmmhello's avatar
wmmhello 已提交
210
  pData->num += interBufSize;
211 212 213
  return pResultRow;
}

214 215 216 217 218 219 220
/**
 * the struct of key in hash table
 * +----------+---------------+
 * | group id |   key data    |
 * | 8 bytes  | actual length |
 * +----------+---------------+
 */
221 222 223
SResultRow* doSetResultOutBufByKey(SDiskbasedBuf* pResultBuf, SResultRowInfo* pResultRowInfo, char* pData,
                                   int16_t bytes, bool masterscan, uint64_t groupId, SExecTaskInfo* pTaskInfo,
                                   bool isIntervalQuery, SAggSupporter* pSup) {
224
  SET_RES_WINDOW_KEY(pSup->keyBuf, pData, bytes, groupId);
H
Haojun Liao 已提交
225

dengyihao's avatar
dengyihao 已提交
226
  SResultRowPosition* p1 =
227
      (SResultRowPosition*)tSimpleHashGet(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
H
Haojun Liao 已提交
228

229 230
  SResultRow* pResult = NULL;

H
Haojun Liao 已提交
231 232
  // in case of repeat scan/reverse scan, no new time window added.
  if (isIntervalQuery) {
233
    if (masterscan && p1 != NULL) {  // the *p1 may be NULL in case of sliding+offset exists.
234
      pResult = getResultRowByPos(pResultBuf, p1, true);
235
      ASSERT(pResult->pageId == p1->pageId && pResult->offset == p1->offset);
H
Haojun Liao 已提交
236 237
    }
  } else {
dengyihao's avatar
dengyihao 已提交
238 239
    // In case of group by column query, the required SResultRow object must be existInCurrentResusltRowInfo in the
    // pResultRowInfo object.
H
Haojun Liao 已提交
240
    if (p1 != NULL) {
241
      // todo
242
      pResult = getResultRowByPos(pResultBuf, p1, true);
243
      ASSERT(pResult->pageId == p1->pageId && pResult->offset == p1->offset);
H
Haojun Liao 已提交
244 245 246
    }
  }

L
Liu Jicong 已提交
247
  // 1. close current opened time window
248
  if (pResultRowInfo->cur.pageId != -1 && ((pResult == NULL) || (pResult->pageId != pResultRowInfo->cur.pageId))) {
249
    SResultRowPosition pos = pResultRowInfo->cur;
X
Xiaoyu Wang 已提交
250
    SFilePage*         pPage = getBufPage(pResultBuf, pos.pageId);
251 252 253 254 255
    releaseBufPage(pResultBuf, pPage);
  }

  // allocate a new buffer page
  if (pResult == NULL) {
H
Haojun Liao 已提交
256
    ASSERT(pSup->resultRowSize > 0);
257
    pResult = getNewResultRow(pResultBuf, &pSup->currentPageId, pSup->resultRowSize);
258

259 260
    // add a new result set for a new group
    SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
261
    tSimpleHashPut(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pos,
L
Liu Jicong 已提交
262
                   sizeof(SResultRowPosition));
H
Haojun Liao 已提交
263 264
  }

265 266 267
  // 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 已提交
268
  // too many time window in query
269
  if (pTaskInfo->execModel == OPTR_EXEC_MODEL_BATCH &&
270
      tSimpleHashGetSize(pSup->pResultRowHashTable) > MAX_INTERVAL_TIME_WINDOW) {
271
    T_LONG_JMP(pTaskInfo->env, TSDB_CODE_QRY_TOO_MANY_TIMEWINDOW);
H
Haojun Liao 已提交
272 273
  }

H
Haojun Liao 已提交
274
  return pResult;
H
Haojun Liao 已提交
275 276
}

277
// a new buffer page for each table. Needs to opt this design
L
Liu Jicong 已提交
278
static int32_t addNewWindowResultBuf(SResultRow* pWindowRes, SDiskbasedBuf* pResultBuf, int32_t tid, uint32_t size) {
279 280 281 282
  if (pWindowRes->pageId != -1) {
    return 0;
  }

L
Liu Jicong 已提交
283
  SFilePage* pData = NULL;
284 285 286

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

  if (taosArrayGetSize(list) == 0) {
290
    pData = getNewBufPage(pResultBuf, &pageId);
291
    pData->num = sizeof(SFilePage);
292 293
  } else {
    SPageInfo* pi = getLastPageInfo(list);
294
    pData = getBufPage(pResultBuf, getPageId(pi));
295
    pageId = getPageId(pi);
296

297
    if (pData->num + size > getBufPageSize(pResultBuf)) {
298
      // release current page first, and prepare the next one
299
      releaseBufPageInfo(pResultBuf, pi);
300

301
      pData = getNewBufPage(pResultBuf, &pageId);
302
      if (pData != NULL) {
303
        pData->num = sizeof(SFilePage);
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
      }
    }
  }

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

324
//  query_range_start, query_range_end, window_duration, window_start, window_end
325
void initExecTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pQueryWindow) {
326 327 328
  pColData->info.type = TSDB_DATA_TYPE_TIMESTAMP;
  pColData->info.bytes = sizeof(int64_t);

329
  colInfoDataEnsureCapacity(pColData, 5);
330 331 332 333 334 335 336 337 338
  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 已提交
339
void cleanupExecTimeWindowInfo(SColumnInfoData* pColData) { colDataDestroy(pColData); }
H
Haojun Liao 已提交
340

341 342 343 344 345 346 347 348 349 350 351 352 353 354
typedef struct {
  bool    hasAgg;
  int32_t numOfRows;
  int32_t startOffset;
} SFunctionCtxStatus;

static void functionCtxSave(SqlFunctionCtx* pCtx, SFunctionCtxStatus* pStatus) {
  pStatus->hasAgg = pCtx->input.colDataAggIsSet;
  pStatus->numOfRows = pCtx->input.numOfRows;
  pStatus->startOffset = pCtx->input.startRowIndex;
}

static void functionCtxRestore(SqlFunctionCtx* pCtx, SFunctionCtxStatus* pStatus) {
  pCtx->input.colDataAggIsSet = pStatus->hasAgg;
H
Haojun Liao 已提交
355
  pCtx->input.numOfRows = pStatus->numOfRows;
356 357 358 359 360
  pCtx->input.startRowIndex = pStatus->startOffset;
}

void doApplyFunctions(SExecTaskInfo* taskInfo, SqlFunctionCtx* pCtx, SColumnInfoData* pTimeWindowData, int32_t offset,
                      int32_t forwardStep, int32_t numOfTotal, int32_t numOfOutput) {
361
  for (int32_t k = 0; k < numOfOutput; ++k) {
H
Haojun Liao 已提交
362
    // keep it temporarily
363 364
    SFunctionCtxStatus status = {0};
    functionCtxSave(&pCtx[k], &status);
365

366
    pCtx[k].input.startRowIndex = offset;
367
    pCtx[k].input.numOfRows = forwardStep;
368 369 370

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

375 376
    if (fmIsWindowPseudoColumnFunc(pCtx[k].functionId)) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
377 378

      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);
379

380
      SColumnInfoData idata = {0};
dengyihao's avatar
dengyihao 已提交
381
      idata.info.type = TSDB_DATA_TYPE_BIGINT;
382
      idata.info.bytes = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
dengyihao's avatar
dengyihao 已提交
383
      idata.pData = p;
384 385 386 387

      SScalarParam out = {.columnData = &idata};
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
      pCtx[k].sfp.process(&tw, 1, &out);
388
      pEntryInfo->numOfRes = 1;
389 390 391 392 393 394 395 396
    } 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;
397
          T_LONG_JMP(taskInfo->env, code);
398
        }
399
      }
400

401
      // restore it
402
      functionCtxRestore(&pCtx[k], &status);
403
    }
404 405 406
  }
}

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

dengyihao's avatar
dengyihao 已提交
410 411
static void doSetInputDataBlockInfo(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock,
                                    int32_t order) {
412
  for (int32_t i = 0; i < pOperator->exprSupp.numOfExprs; ++i) {
413
    pCtx[i].order = order;
414
    pCtx[i].input.numOfRows = pBlock->info.rows;
415
    setBlockSMAInfo(&pCtx[i], &pOperator->exprSupp.pExprInfo[i], pBlock);
416
    pCtx[i].pSrcBlock = pBlock;
417 418 419
  }
}

X
Xiaoyu Wang 已提交
420 421
void setInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
                       int32_t scanFlag, bool createDummyCol) {
422
  if (pBlock->pBlockAgg != NULL) {
H
Haojun Liao 已提交
423
    doSetInputDataBlockInfo(pOperator, pCtx, pBlock, order);
424
  } else {
425
    doSetInputDataBlock(pOperator, pCtx, pBlock, order, scanFlag, createDummyCol);
H
Haojun Liao 已提交
426
  }
427 428
}

L
Liu Jicong 已提交
429 430
static int32_t doCreateConstantValColumnInfo(SInputColumnInfoData* pInput, SFunctParam* pFuncParam, int32_t paramIndex,
                                             int32_t numOfRows) {
431 432 433 434 435 436 437 438
  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)
439 440
    pColInfo->info.type = pFuncParam->param.nType;
    pColInfo->info.bytes = pFuncParam->param.nLen;
441 442

    pInput->pData[paramIndex] = pColInfo;
443 444
  } else {
    pColInfo = pInput->pData[paramIndex];
445 446
  }

447
  colInfoDataEnsureCapacity(pColInfo, numOfRows);
448

449
  int8_t type = pFuncParam->param.nType;
450 451
  if (type == TSDB_DATA_TYPE_BIGINT || type == TSDB_DATA_TYPE_UBIGINT) {
    int64_t v = pFuncParam->param.i;
dengyihao's avatar
dengyihao 已提交
452
    for (int32_t i = 0; i < numOfRows; ++i) {
453 454 455 456
      colDataAppendInt64(pColInfo, i, &v);
    }
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
dengyihao's avatar
dengyihao 已提交
457
    for (int32_t i = 0; i < numOfRows; ++i) {
458 459
      colDataAppendDouble(pColInfo, i, &v);
    }
460
  } else if (type == TSDB_DATA_TYPE_VARCHAR) {
L
Liu Jicong 已提交
461
    char* tmp = taosMemoryMalloc(pFuncParam->param.nLen + VARSTR_HEADER_SIZE);
462
    STR_WITH_SIZE_TO_VARSTR(tmp, pFuncParam->param.pz, pFuncParam->param.nLen);
L
Liu Jicong 已提交
463
    for (int32_t i = 0; i < numOfRows; ++i) {
464 465
      colDataAppend(pColInfo, i, tmp, false);
    }
466 467 468 469 470
  }

  return TSDB_CODE_SUCCESS;
}

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

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

L
Liu Jicong 已提交
479
    pCtx[i].pSrcBlock = pBlock;
X
Xiaoyu Wang 已提交
480
    pCtx[i].scanFlag = scanFlag;
H
Haojun Liao 已提交
481

482
    SInputColumnInfoData* pInput = &pCtx[i].input;
483
    pInput->uid = pBlock->info.uid;
C
Cary Xu 已提交
484
    pInput->colDataAggIsSet = false;
485

486
    SExprInfo* pOneExpr = &pOperator->exprSupp.pExprInfo[i];
487
    for (int32_t j = 0; j < pOneExpr->base.numOfParams; ++j) {
dengyihao's avatar
dengyihao 已提交
488
      SFunctParam* pFuncParam = &pOneExpr->base.pParam[j];
G
Ganlin Zhao 已提交
489 490
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
dengyihao's avatar
dengyihao 已提交
491
        pInput->pData[j] = taosArrayGet(pBlock->pDataBlock, slotId);
492 493 494
        pInput->totalRows = pBlock->info.rows;
        pInput->numOfRows = pBlock->info.rows;
        pInput->startRowIndex = 0;
495

496
        // NOTE: the last parameter is the primary timestamp column
H
Haojun Liao 已提交
497
        // todo: refactor this
498
        if (fmIsImplicitTsFunc(pCtx[i].functionId) && (j == pOneExpr->base.numOfParams - 1)) {
L
Liu Jicong 已提交
499 500
          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);
501
        }
502 503
        ASSERT(pInput->pData[j] != NULL);
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
504 505 506
        // 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) {
507 508 509 510
          pInput->totalRows = pBlock->info.rows;
          pInput->numOfRows = pBlock->info.rows;
          pInput->startRowIndex = 0;

511
          code = doCreateConstantValColumnInfo(pInput, pFuncParam, j, pBlock->info.rows);
512 513 514
          if (code != TSDB_CODE_SUCCESS) {
            return code;
          }
515
        }
G
Ganlin Zhao 已提交
516 517
      }
    }
H
Haojun Liao 已提交
518
  }
519 520

  return code;
H
Haojun Liao 已提交
521 522
}

523
static int32_t doAggregateImpl(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx) {
524
  for (int32_t k = 0; k < pOperator->exprSupp.numOfExprs; ++k) {
H
Haojun Liao 已提交
525
    if (functionNeedToExecute(&pCtx[k])) {
526
      // todo add a dummy funtion to avoid process check
527 528 529
      if (pCtx[k].fpSet.process == NULL) {
        continue;
      }
H
Haojun Liao 已提交
530

531 532 533 534
      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;
535
      }
536 537
    }
  }
538 539

  return TSDB_CODE_SUCCESS;
540 541
}

H
Haojun Liao 已提交
542
static void setPseudoOutputColInfo(SSDataBlock* pResult, SqlFunctionCtx* pCtx, SArray* pPseudoList) {
dengyihao's avatar
dengyihao 已提交
543
  size_t num = (pPseudoList != NULL) ? taosArrayGetSize(pPseudoList) : 0;
H
Haojun Liao 已提交
544 545 546 547 548
  for (int32_t i = 0; i < num; ++i) {
    pCtx[i].pOutput = taosArrayGet(pResult->pDataBlock, i);
  }
}

549
int32_t projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBlock* pSrcBlock, SqlFunctionCtx* pCtx,
X
Xiaoyu Wang 已提交
550
                              int32_t numOfOutput, SArray* pPseudoList) {
H
Haojun Liao 已提交
551
  setPseudoOutputColInfo(pResult, pCtx, pPseudoList);
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571

  if (pSrcBlock == NULL) {
    for (int32_t k = 0; k < numOfOutput; ++k) {
      int32_t outputSlotId = pExpr[k].base.resSchema.slotId;

      ASSERT(pExpr[k].pExpr->nodeType == QUERY_NODE_VALUE);
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);

      int32_t type = pExpr[k].base.pParam[0].param.nType;
      if (TSDB_DATA_TYPE_NULL == type) {
        colDataAppendNNULL(pColInfoData, 0, 1);
      } else {
        colDataAppend(pColInfoData, 0, taosVariantGet(&pExpr[k].base.pParam[0].param, type), false);
      }
    }

    pResult->info.rows = 1;
    return TSDB_CODE_SUCCESS;
  }

H
Haojun Liao 已提交
572
  pResult->info.groupId = pSrcBlock->info.groupId;
H
Haojun Liao 已提交
573

574 575
  // if the source equals to the destination, it is to create a new column as the result of scalar
  // function or some operators.
576 577
  bool createNewColModel = (pResult == pSrcBlock);

578 579
  int32_t numOfRows = 0;

580
  for (int32_t k = 0; k < numOfOutput; ++k) {
581 582
    int32_t               outputSlotId = pExpr[k].base.resSchema.slotId;
    SqlFunctionCtx*       pfCtx = &pCtx[k];
583
    SInputColumnInfoData* pInputData = &pfCtx->input;
584

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

594
      numOfRows = pInputData->numOfRows;
595
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_VALUE) {
596
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
597

dengyihao's avatar
dengyihao 已提交
598
      int32_t offset = createNewColModel ? 0 : pResult->info.rows;
599 600 601 602 603 604 605 606

      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);
        }
607
      }
608 609

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

614
      SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
615
      SColumnInfoData  idata = {.info = pResColData->info, .hasNull = true};
616

617
      SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
618
      int32_t      code = scalarCalculate(pExpr[k].pExpr->_optrRoot.pRootNode, pBlockList, &dest);
619 620 621 622
      if (code != TSDB_CODE_SUCCESS) {
        taosArrayDestroy(pBlockList);
        return code;
      }
623

dengyihao's avatar
dengyihao 已提交
624
      int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
625
      ASSERT(pResult->info.capacity > 0);
626
      colDataMergeCol(pResColData, startOffset, (int32_t*)&pResult->info.capacity, &idata, dest.numOfRows);
D
dapan1121 已提交
627
      colDataDestroy(&idata);
L
Liu Jicong 已提交
628

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

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

648 649 650 651 652
        // link pDstBlock to set selectivity value
        if (pfCtx->subsidiaries.num > 0) {
          pfCtx->pDstBlock = pResult;
        }

653
        numOfRows = pfCtx->fpSet.process(pfCtx);
H
Haojun Liao 已提交
654
      } else if (fmIsAggFunc(pfCtx->functionId)) {
G
Ganlin Zhao 已提交
655
        // selective value output should be set during corresponding function execution
656 657 658
        if (fmIsSelectValueFunc(pfCtx->functionId)) {
          continue;
        }
659 660
        // _group_key function for "partition by tbname" + csum(col_name) query
        SColumnInfoData* pOutput = taosArrayGet(pResult->pDataBlock, outputSlotId);
661
        int32_t          slotId = pfCtx->param[0].pCol->slotId;
662 663 664

        // todo handle the json tag
        SColumnInfoData* pInput = taosArrayGet(pSrcBlock->pDataBlock, slotId);
665
        for (int32_t f = 0; f < pSrcBlock->info.rows; ++f) {
666 667 668 669 670 671 672 673 674
          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 已提交
675 676 677
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
678

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

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

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

        numOfRows = dest.numOfRows;
H
Haojun Liao 已提交
695 696
        taosArrayDestroy(pBlockList);
      }
697
    } else {
698
      return TSDB_CODE_OPS_NOT_SUPPORT;
699 700
    }
  }
701

702 703 704
  if (!createNewColModel) {
    pResult->info.rows += numOfRows;
  }
705 706

  return TSDB_CODE_SUCCESS;
707 708
}

5
54liuyao 已提交
709
bool functionNeedToExecute(SqlFunctionCtx* pCtx) {
710
  struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
711

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

718 719
  if (pCtx->scanFlag == REPEAT_SCAN) {
    return fmIsRepeatScanFunc(pCtx->functionId);
720 721
  }

722 723
  if (isRowEntryCompleted(pResInfo)) {
    return false;
724 725
  }

726 727 728
  return true;
}

729 730 731 732 733 734 735
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;
    }
736

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

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

753
  ASSERT(!IS_VAR_DATA_TYPE(type));
754

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

762 763 764 765 766 767
    *(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;

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

778 779
  return TSDB_CODE_SUCCESS;
}
780

781
void setBlockSMAInfo(SqlFunctionCtx* pCtx, SExprInfo* pExprInfo, SSDataBlock* pBlock) {
782 783 784 785 786 787 788 789 790
  int32_t numOfRows = pBlock->info.rows;

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

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

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

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

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

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

  return false;
}

L
Liu Jicong 已提交
828
void setTaskKilled(SExecTaskInfo* pTaskInfo) { pTaskInfo->code = TSDB_CODE_TSC_QUERY_CANCELLED; }
829 830

/////////////////////////////////////////////////////////////////////////////////////////////
831
STimeWindow getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key) {
L
Liu Jicong 已提交
832
  STimeWindow win = {0};
833
  win.skey = taosTimeTruncate(key, pInterval, precision);
834 835

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

  return win;
845 846
}

847
#if 0
H
Haojun Liao 已提交
848
static bool overlapWithTimeWindow(STaskAttr* pQueryAttr, SDataBlockInfo* pBlockInfo) {
849 850
  STimeWindow w = {0};

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

854
  if (true) {
L
Liu Jicong 已提交
855
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.skey, sk, ek, &w);
856 857 858 859 860 861
    assert(w.ekey >= pBlockInfo->window.skey);

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

L
Liu Jicong 已提交
862 863
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
864 865 866 867 868 869 870 871 872 873
      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 已提交
874
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
875 876 877 878 879 880
    assert(w.skey <= pBlockInfo->window.ekey);

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

L
Liu Jicong 已提交
881 882
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
883 884 885 886 887 888 889 890 891 892 893 894 895
      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;
}
896
#endif
897 898

static uint32_t doFilterByBlockTimeWindow(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
899
#if 0
H
Haojun Liao 已提交
900
  SqlFunctionCtx* pCtx = pTableScanInfo->pCtx;
901
  uint32_t        status = BLK_DATA_NOT_LOAD;
902

L
Liu Jicong 已提交
903
  int32_t numOfOutput = 0;  // pTableScanInfo->numOfOutput;
904 905
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;
H
Haojun Liao 已提交
906
    int32_t colId = pTableScanInfo->pExpr[i].base.pParam[0].pCol->colId;
907 908 909

    // group by + first/last should not apply the first/last block filter
    if (functionId < 0) {
910
      status |= BLK_DATA_DATA_LOAD;
911 912
      return status;
    } else {
L
Liu Jicong 已提交
913
      //      status |= aAggs[functionId].dataReqFunc(&pTableScanInfo->pCtx[i], &pBlock->info.window, colId);
914
      //      if ((status & BLK_DATA_DATA_LOAD) == BLK_DATA_DATA_LOAD) {
L
Liu Jicong 已提交
915 916
      //        return status;
      //      }
917 918 919 920
    }
  }

  return status;
H
Haojun Liao 已提交
921 922
#endif
  return 0;
923 924
}

L
Liu Jicong 已提交
925 926
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
927
  *status = BLK_DATA_NOT_LOAD;
928

H
Haojun Liao 已提交
929
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
930
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
931

L
Liu Jicong 已提交
932 933
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
934

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

937 938
//  pCost->totalBlocks += 1;
//  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
939
#if 0
940 941 942
  // 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 已提交
943
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
944
    (*status) = BLK_DATA_DATA_LOAD;
945 946 947
  }

  // check if this data block is required to load
948
  if ((*status) != BLK_DATA_DATA_LOAD) {
949 950 951 952 953 954 955
    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 已提交
956
      bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
957 958 959 960 961 962
      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,
963
                                    pTableScanInfo->rowEntryInfoOffset);
964 965 966
      } else {
        if (setResultOutputBufByKey(pRuntimeEnv, pTableScanInfo->pResultRowInfo, pBlock->info.uid, &win, masterScan, &pResult, groupId,
                                    pTableScanInfo->pCtx, pTableScanInfo->numOfOutput,
967
                                    pTableScanInfo->rowEntryInfoOffset) != TSDB_CODE_SUCCESS) {
968
          T_LONG_JMP(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
969 970 971 972
        }
      }
    } else if (pQueryAttr->stableQuery && (!pQueryAttr->tsCompQuery) && (!pQueryAttr->diffQuery)) { // stable aggregate, not interval aggregate or normal column aggregate
      doSetTableGroupOutputBuf(pRuntimeEnv, pTableScanInfo->pResultRowInfo, pTableScanInfo->pCtx,
973
                               pTableScanInfo->rowEntryInfoOffset, pTableScanInfo->numOfOutput,
974 975 976 977 978 979
                               pRuntimeEnv->current->groupIndex);
    }

    if (needFilter) {
      (*status) = doFilterByBlockTimeWindow(pTableScanInfo, pBlock);
    } else {
980
      (*status) = BLK_DATA_DATA_LOAD;
981 982 983 984
    }
  }

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

987
  if ((*status) == BLK_DATA_NOT_LOAD || (*status) == BLK_DATA_FILTEROUT) {
988 989
    //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//           pBlockInfo->window.ekey, pBlockInfo->rows);
990
    pCost->skipBlocks += 1;
991
  } else if ((*status) == BLK_DATA_SMA_LOAD) {
992 993
    // this function never returns error?
    pCost->loadBlockStatis += 1;
994
//    tsdbRetrieveDatablockSMA(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
995 996

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
997
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
998 999 1000
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
1001
    assert((*status) == BLK_DATA_DATA_LOAD);
1002 1003 1004

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
1005
//    tsdbRetrieveDatablockSMA(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1006 1007 1008 1009 1010 1011

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

H
Haojun Liao 已提交
1012
          bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1013 1014 1015 1016 1017
          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,
1018
                                      pTableScanInfo->rowEntryInfoOffset) != TSDB_CODE_SUCCESS) {
1019
            T_LONG_JMP(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
          }
        }
      }
      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
1030
            pCost->skipBlocks += 1;
1031 1032
            //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId,
//                   pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
1033
            (*status) = BLK_DATA_FILTEROUT;
1034 1035 1036 1037 1038 1039 1040
            return TSDB_CODE_SUCCESS;
          }
        }
      }
    }

    // current block has been discard due to filter applied
H
Haojun Liao 已提交
1041
//    if (!doFilterByBlockSMA(pRuntimeEnv, pBlock->pBlockAgg, pTableScanInfo->pCtx, pBlockInfo->rows)) {
1042
//      pCost->skipBlocks += 1;
1043 1044
//      qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//             pBlockInfo->window.ekey, pBlockInfo->rows);
1045
//      (*status) = BLK_DATA_FILTEROUT;
1046 1047 1048 1049 1050
//      return TSDB_CODE_SUCCESS;
//    }

    pCost->totalCheckedRows += pBlockInfo->rows;
    pCost->loadBlocks += 1;
1051
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1052 1053 1054 1055 1056
//    if (pBlock->pDataBlock == NULL) {
//      return terrno;
//    }

//    if (pQueryAttr->pFilters != NULL) {
1057
//      filterSetColFieldData(pQueryAttr->pFilters, taosArrayGetSize(pBlock->pDataBlock), pBlock->pDataBlock);
1058
//    }
1059

1060 1061 1062 1063
//    if (pQueryAttr->pFilters != NULL || pRuntimeEnv->pTsBuf != NULL) {
//      filterColRowsInDataBlock(pRuntimeEnv, pBlock, ascQuery);
//    }
  }
H
Haojun Liao 已提交
1064
#endif
1065 1066 1067
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1068
static void updateTableQueryInfoForReverseScan(STableQueryInfo* pTableQueryInfo) {
1069 1070 1071 1072 1073
  if (pTableQueryInfo == NULL) {
    return;
  }
}

L
Liu Jicong 已提交
1074
void setTaskStatus(SExecTaskInfo* pTaskInfo, int8_t status) {
1075
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
1076
    pTaskInfo->status = status;
1077 1078
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
1079
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
1080
    pTaskInfo->status |= status;
1081 1082 1083
  }
}

1084
void setResultRowInitCtx(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowEntryInfoOffset) {
5
54liuyao 已提交
1085
  bool init = false;
1086
  for (int32_t i = 0; i < numOfOutput; ++i) {
1087
    pCtx[i].resultInfo = getResultEntryInfo(pResult, i, rowEntryInfoOffset);
5
54liuyao 已提交
1088 1089 1090
    if (init) {
      continue;
    }
1091 1092 1093 1094 1095

    struct SResultRowEntryInfo* pResInfo = pCtx[i].resultInfo;
    if (isRowEntryCompleted(pResInfo) && isRowEntryInitialized(pResInfo)) {
      continue;
    }
1096 1097 1098 1099 1100

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

1101 1102 1103 1104 1105 1106
    if (!pResInfo->initialized) {
      if (pCtx[i].functionId != -1) {
        pCtx[i].fpSet.init(&pCtx[i], pResInfo);
      } else {
        pResInfo->initialized = true;
      }
5
54liuyao 已提交
1107 1108
    } else {
      init = true;
1109 1110 1111 1112
    }
  }
}

1113
static void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const SColumnInfoData* p, bool keep, int32_t status);
1114

1115
void doFilter(const SNode* pFilterNode, SSDataBlock* pBlock, const SArray* pColMatchInfo) {
1116
  if (pFilterNode == NULL || pBlock->info.rows == 0) {
S
shenglian zhou 已提交
1117 1118
    return;
  }
1119

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

H
Haojun Liao 已提交
1122
  // todo move to the initialization function
H
Haojun Liao 已提交
1123
  int32_t code = filterInitFromNode((SNode*)pFilterNode, &filter, 0);
1124
  SFilterColumnParam param1 = {.numOfCols = taosArrayGetSize(pBlock->pDataBlock), .pDataBlock = pBlock->pDataBlock};
1125 1126
  code = filterSetDataFromSlotId(filter, &param1);

1127 1128
  SColumnInfoData* p = NULL;
  int32_t status = 0;
1129

1130
  // todo the keep seems never to be True??
1131
  bool keep = filterExecute(filter, pBlock, &p, NULL, param1.numOfCols, &status);
D
dapan1121 已提交
1132
  filterFreeInfo(filter);
1133

1134
  extractQualifiedTupleByFilterResult(pBlock, p, keep, status);
1135 1136

  if (pColMatchInfo != NULL) {
1137
    for (int32_t i = 0; i < taosArrayGetSize(pColMatchInfo); ++i) {
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
      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;
        }
      }
    }
  }

1149 1150
  colDataDestroy(p);
  taosMemoryFree(p);
1151 1152
}

1153
void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const SColumnInfoData* p, bool keep, int32_t status) {
1154 1155 1156 1157
  if (keep) {
    return;
  }

1158 1159 1160 1161 1162 1163 1164
  int32_t totalRows = pBlock->info.rows;

  if (status == FILTER_RESULT_ALL_QUALIFIED) {
    // here nothing needs to be done
  } else if (status == FILTER_RESULT_NONE_QUALIFIED) {
    pBlock->info.rows = 0;
  } else {
1165
    SSDataBlock* px = createOneDataBlock(pBlock, true);
1166

1167 1168
    size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
    for (int32_t i = 0; i < numOfCols; ++i) {
1169 1170
      SColumnInfoData* pSrc = taosArrayGet(px->pDataBlock, i);
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, i);
1171
      // it is a reserved column for scalar function, and no data in this column yet.
1172
      if (pDst->pData == NULL || pSrc->pData == NULL) {
1173 1174 1175
        continue;
      }

1176 1177
      colInfoDataCleanup(pDst, pBlock->info.rows);

1178
      int32_t numOfRows = 0;
1179
      for (int32_t j = 0; j < totalRows; ++j) {
1180
        if (((int8_t*)p->pData)[j] == 0) {
D
dapan1121 已提交
1181 1182
          continue;
        }
1183

D
dapan1121 已提交
1184
        if (colDataIsNull_s(pSrc, j)) {
1185
          colDataAppendNULL(pDst, numOfRows);
D
dapan1121 已提交
1186
        } else {
1187
          colDataAppend(pDst, numOfRows, colDataGetData(pSrc, j), false);
D
dapan1121 已提交
1188
        }
1189
        numOfRows += 1;
H
Haojun Liao 已提交
1190
      }
1191

1192
      // todo this value can be assigned directly
1193 1194 1195 1196 1197
      if (pBlock->info.rows == totalRows) {
        pBlock->info.rows = numOfRows;
      } else {
        ASSERT(pBlock->info.rows == numOfRows);
      }
1198
    }
1199

dengyihao's avatar
dengyihao 已提交
1200
    blockDataDestroy(px);  // fix memory leak
1201 1202 1203
  }
}

1204
  void doSetTableGroupOutputBuf(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId) {
1205
  // for simple group by query without interval, all the tables belong to one group result.
1206 1207 1208
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
  SAggOperatorInfo* pAggInfo = pOperator->info;

1209
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
1210 1211
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
  int32_t*        rowEntryInfoOffset = pOperator->exprSupp.rowEntryInfoOffset;
1212

1213
  SResultRow* pResultRow = doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, (char*)&groupId,
L
Liu Jicong 已提交
1214
                                                  sizeof(groupId), true, groupId, pTaskInfo, false, &pAggInfo->aggSup);
L
Liu Jicong 已提交
1215
  assert(pResultRow != NULL);
1216 1217 1218 1219 1220 1221

  /*
   * 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 已提交
1222 1223
    int32_t ret =
        addNewWindowResultBuf(pResultRow, pAggInfo->aggSup.pResultBuf, groupId, pAggInfo->binfo.pRes->info.rowSize);
1224 1225 1226 1227 1228
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

1229
  setResultRowInitCtx(pResultRow, pCtx, numOfOutput, rowEntryInfoOffset);
1230 1231
}

1232 1233 1234
static void setExecutionContext(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId) {
  SAggOperatorInfo* pAggInfo = pOperator->info;
  if (pAggInfo->groupId != UINT64_MAX && pAggInfo->groupId == groupId) {
1235 1236
    return;
  }
1237 1238

  doSetTableGroupOutputBuf(pOperator, numOfOutput, groupId);
1239 1240

  // record the current active group id
H
Haojun Liao 已提交
1241
  pAggInfo->groupId = groupId;
1242 1243
}

dengyihao's avatar
dengyihao 已提交
1244 1245
static void doUpdateNumOfRows(SqlFunctionCtx* pCtx, SResultRow* pRow, int32_t numOfExprs,
                              const int32_t* rowCellOffset) {
1246
  bool returnNotNull = false;
1247
  for (int32_t j = 0; j < numOfExprs; ++j) {
1248
    struct SResultRowEntryInfo* pResInfo = getResultEntryInfo(pRow, j, rowCellOffset);
1249 1250 1251 1252 1253 1254 1255
    if (!isRowEntryInitialized(pResInfo)) {
      continue;
    }

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

1257
    if (fmIsNotNullOutputFunc(pCtx[j].functionId)) {
1258 1259
      returnNotNull = true;
    }
1260
  }
S
shenglian zhou 已提交
1261 1262
  // if all expr skips all blocks, e.g. all null inputs for max function, output one row in final result.
  //  except for first/last, which require not null output, output no rows
1263
  if (pRow->numOfRows == 0 && !returnNotNull) {
1264
    pRow->numOfRows = 1;
1265 1266 1267
  }
}

1268 1269
static void doCopyResultToDataBlock(SExprInfo* pExprInfo, int32_t numOfExprs, SResultRow* pRow, SqlFunctionCtx* pCtx,
                                    SSDataBlock* pBlock, const int32_t* rowEntryOffset, SExecTaskInfo* pTaskInfo) {
1270 1271 1272
  for (int32_t j = 0; j < numOfExprs; ++j) {
    int32_t slotId = pExprInfo[j].base.resSchema.slotId;

1273
    pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowEntryOffset);
1274 1275 1276 1277
    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));
1278
        T_LONG_JMP(pTaskInfo->env, code);
1279 1280
      }
    } else if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
1281
      // do nothing
1282
    } else {
1283 1284
      // 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.
1285 1286 1287 1288 1289 1290 1291
      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);
      }
    }
  }
1292 1293
}

1294 1295 1296
// todo refactor. SResultRow has direct pointer in miainfo
int32_t finalizeResultRows(SDiskbasedBuf* pBuf, SResultRowPosition* resultRowPosition, SExprSupp* pSup,
                           SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo) {
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
  SFilePage*  page = getBufPage(pBuf, resultRowPosition->pageId);
  SResultRow* pRow = (SResultRow*)((char*)page + resultRowPosition->offset);

  SqlFunctionCtx* pCtx = pSup->pCtx;
  SExprInfo*      pExprInfo = pSup->pExprInfo;
  const int32_t*  rowEntryOffset = pSup->rowEntryInfoOffset;

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

  int32_t size = pBlock->info.capacity;
  while (pBlock->info.rows + pRow->numOfRows > size) {
    size = size * 1.25;
  }

  int32_t code = blockDataEnsureCapacity(pBlock, size);
  if (TAOS_FAILED(code)) {
    releaseBufPage(pBuf, page);
    qError("%s ensure result data capacity failed, code %s", GET_TASKID(pTaskInfo), tstrerror(code));
    T_LONG_JMP(pTaskInfo->env, code);
  }

  doCopyResultToDataBlock(pExprInfo, pSup->numOfExprs, pRow, pCtx, pBlock, rowEntryOffset, pTaskInfo);
1323 1324

  releaseBufPage(pBuf, page);
1325
  pBlock->info.rows += pRow->numOfRows;
1326 1327 1328
  return 0;
}

1329 1330 1331 1332 1333 1334 1335
int32_t doCopyToSDataBlock(SExecTaskInfo* pTaskInfo, SSDataBlock* pBlock, SExprSupp* pSup, SDiskbasedBuf* pBuf,
                           SGroupResInfo* pGroupResInfo) {
  SExprInfo*      pExprInfo = pSup->pExprInfo;
  int32_t         numOfExprs = pSup->numOfExprs;
  int32_t*        rowEntryOffset = pSup->rowEntryInfoOffset;
  SqlFunctionCtx* pCtx = pSup->pCtx;

1336
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
1337

1338
  for (int32_t i = pGroupResInfo->index; i < numOfRows; i += 1) {
L
Liu Jicong 已提交
1339 1340
    SResKeyPos* pPos = taosArrayGetP(pGroupResInfo->pRows, i);
    SFilePage*  page = getBufPage(pBuf, pPos->pos.pageId);
1341

1342
    SResultRow* pRow = (SResultRow*)((char*)page + pPos->pos.offset);
1343

H
Haojun Liao 已提交
1344
    doUpdateNumOfRows(pCtx, pRow, numOfExprs, rowEntryOffset);
1345 1346

    // no results, continue to check the next one
1347 1348
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
1349
      releaseBufPage(pBuf, page);
1350 1351 1352
      continue;
    }

1353 1354 1355 1356 1357
    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) {
1358
        releaseBufPage(pBuf, page);
1359 1360 1361 1362
        break;
      }
    }

1363
    if (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
1364
      ASSERT(pBlock->info.rows > 0);
1365
      releaseBufPage(pBuf, page);
1366 1367 1368 1369
      break;
    }

    pGroupResInfo->index += 1;
1370
    doCopyResultToDataBlock(pExprInfo, numOfExprs, pRow, pCtx, pBlock, rowEntryOffset, pTaskInfo);
1371

1372
    releaseBufPage(pBuf, page);
1373
    pBlock->info.rows += pRow->numOfRows;
1374 1375
  }

X
Xiaoyu Wang 已提交
1376 1377
  qDebug("%s result generated, rows:%d, groupId:%" PRIu64, GET_TASKID(pTaskInfo), pBlock->info.rows,
         pBlock->info.groupId);
1378

1379
  blockDataUpdateTsWindow(pBlock, 0);
1380 1381 1382
  return 0;
}

X
Xiaoyu Wang 已提交
1383 1384
void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SGroupResInfo* pGroupResInfo,
                            SDiskbasedBuf* pBuf) {
1385
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
1386
  SSDataBlock*   pBlock = pbInfo->pRes;
1387

1388 1389 1390
  // set output datablock version
  pBlock->info.version = pTaskInfo->version;

1391
  blockDataCleanup(pBlock);
1392
  if (!hasRemainResults(pGroupResInfo)) {
1393 1394 1395
    return;
  }

1396 1397
  // clear the existed group id
  pBlock->info.groupId = 0;
1398 1399 1400
  if (!pbInfo->mergeResultBlock) {
    doCopyToSDataBlock(pTaskInfo, pBlock, &pOperator->exprSupp, pBuf, pGroupResInfo);
  } else {
dengyihao's avatar
dengyihao 已提交
1401
    while (hasRemainResults(pGroupResInfo)) {
1402 1403 1404
      doCopyToSDataBlock(pTaskInfo, pBlock, &pOperator->exprSupp, pBuf, pGroupResInfo);
      if (pBlock->info.rows >= pOperator->resultInfo.threshold) {
        break;
1405 1406
      }

1407 1408
      // clearing group id to continue to merge data that belong to different groups
      pBlock->info.groupId = 0;
1409
    }
1410 1411 1412

    // clear the group id info in SSDataBlock, since the client does not need it
    pBlock->info.groupId = 0;
1413 1414 1415
  }
}

L
Liu Jicong 已提交
1416
static int32_t compressQueryColData(SColumnInfoData* pColRes, int32_t numOfRows, char* data, int8_t compressed) {
1417 1418
  int32_t colSize = pColRes->info.bytes * numOfRows;
  return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data,
L
Liu Jicong 已提交
1419
                                                      colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0);
1420 1421
}

L
Liu Jicong 已提交
1422 1423
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
1424

L
Liu Jicong 已提交
1425 1426 1427
  //  uint64_t hashSize = taosHashGetMemSize(pQInfo->runtimeEnv.pResultRowHashTable);
  //  hashSize += taosHashGetMemSize(pRuntimeEnv->tableqinfoGroupInfo.map);
  //  pSummary->hashSize = hashSize;
1428

L
Liu Jicong 已提交
1429 1430 1431 1432 1433 1434 1435 1436 1437
  //  SResultRowPool* p = pTaskInfo->pool;
  //  if (p != NULL) {
  //    pSummary->winInfoSize = getResultRowPoolMemSize(p);
  //    pSummary->numOfTimeWindows = getNumOfAllocatedResultRows(p);
  //  } else {
  //    pSummary->winInfoSize = 0;
  //    pSummary->numOfTimeWindows = 0;
  //  }

1438 1439
  SFileBlockLoadRecorder* pRecorder = pSummary->pRecoder;
  if (pSummary->pRecoder != NULL) {
1440
    qDebug(
X
Xiaoyu Wang 已提交
1441 1442 1443 1444
        "%s :cost summary: elapsed time:%.2f ms, total blocks:%d, load block SMA:%d, load data block:%d, total "
        "rows:%" PRId64 ", check rows:%" PRId64,
        GET_TASKID(pTaskInfo), pSummary->elapsedTime / 1000.0, pRecorder->totalBlocks, pRecorder->loadBlockStatis,
        pRecorder->loadBlocks, pRecorder->totalRows, pRecorder->totalCheckedRows);
1445
  }
1446

L
Liu Jicong 已提交
1447 1448 1449
  // 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);
1450 1451
}

L
Liu Jicong 已提交
1452 1453 1454
// static void updateOffsetVal(STaskRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
1455
//
L
Liu Jicong 已提交
1456
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
1457
//
L
Liu Jicong 已提交
1458 1459 1460 1461
//   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;
//   }
1462
//
L
Liu Jicong 已提交
1463 1464 1465 1466 1467
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     pQueryAttr->pos = (int32_t)pQueryAttr->limit.offset;
//   } else {
//     pQueryAttr->pos = pBlockInfo->rows - (int32_t)pQueryAttr->limit.offset - 1;
//   }
1468
//
L
Liu Jicong 已提交
1469
//   assert(pQueryAttr->pos >= 0 && pQueryAttr->pos <= pBlockInfo->rows - 1);
1470
//
L
Liu Jicong 已提交
1471 1472
//   SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//   SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
1473
//
L
Liu Jicong 已提交
1474 1475
//   // update the pQueryAttr->limit.offset value, and pQueryAttr->pos value
//   TSKEY *keys = (TSKEY *) pColInfoData->pData;
1476
//
L
Liu Jicong 已提交
1477 1478 1479
//   // update the offset value
//   pTableQueryInfo->lastKey = keys[pQueryAttr->pos];
//   pQueryAttr->limit.offset = 0;
1480
//
L
Liu Jicong 已提交
1481
//   int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
1482
//
L
Liu Jicong 已提交
1483 1484 1485 1486
//   //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);
// }
1487

L
Liu Jicong 已提交
1488 1489
// void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
1490
//
L
Liu Jicong 已提交
1491 1492 1493
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//     return;
//   }
1494
//
L
Liu Jicong 已提交
1495 1496
//   pQueryAttr->pos = 0;
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
1497
//
L
Liu Jicong 已提交
1498 1499
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//   TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
1500
//
L
Liu Jicong 已提交
1501 1502 1503
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pTsdbReadHandle)) {
//     if (isTaskKilled(pRuntimeEnv->qinfo)) {
1504
//       T_LONG_JMP(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
L
Liu Jicong 已提交
1505
//     }
1506
//
L
Liu Jicong 已提交
1507
//     tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
1508
//
L
Liu Jicong 已提交
1509 1510 1511 1512
//     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;
1513
//
L
Liu Jicong 已提交
1514 1515 1516 1517 1518 1519 1520
//       //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;
//     }
//   }
1521
//
L
Liu Jicong 已提交
1522
//   if (terrno != TSDB_CODE_SUCCESS) {
1523
//     T_LONG_JMP(pRuntimeEnv->env, terrno);
L
Liu Jicong 已提交
1524 1525 1526 1527 1528 1529 1530
//   }
// }

// static TSKEY doSkipIntervalProcess(STaskRuntimeEnv* pRuntimeEnv, STimeWindow* win, SDataBlockInfo* pBlockInfo,
// STableQueryInfo* pTableQueryInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
1531
//
L
Liu Jicong 已提交
1532 1533 1534
//   assert(pQueryAttr->limit.offset == 0);
//   STimeWindow tw = *win;
//   getNextTimeWindow(pQueryAttr, &tw);
1535
//
L
Liu Jicong 已提交
1536 1537
//   if ((tw.skey <= pBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) ||
//       (tw.ekey >= pBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
1538
//
L
Liu Jicong 已提交
1539 1540 1541 1542
//     // 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);
1543
//
L
Liu Jicong 已提交
1544 1545 1546 1547
//     tw = *win;
//     int32_t startPos =
//         getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1);
//     assert(startPos >= 0);
1548
//
L
Liu Jicong 已提交
1549 1550
//     // set the abort info
//     pQueryAttr->pos = startPos;
1551
//
L
Liu Jicong 已提交
1552 1553 1554 1555
//     // reset the query start timestamp
//     pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
//     pQueryAttr->window.skey = pTableQueryInfo->win.skey;
//     TSKEY key = pTableQueryInfo->win.skey;
1556
//
L
Liu Jicong 已提交
1557 1558
//     pWindowResInfo->prevSKey = tw.skey;
//     int32_t index = pRuntimeEnv->resultRowInfo.curIndex;
1559
//
L
Liu Jicong 已提交
1560 1561
//     int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//     pRuntimeEnv->resultRowInfo.curIndex = index;  // restore the window index
1562
//
L
Liu Jicong 已提交
1563 1564 1565 1566
//     //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);
1567
//
L
Liu Jicong 已提交
1568 1569 1570 1571 1572
//     return key;
//   } else {  // do nothing
//     pQueryAttr->window.skey      = tw.skey;
//     pWindowResInfo->prevSKey = tw.skey;
//     pTableQueryInfo->lastKey = tw.skey;
1573
//
L
Liu Jicong 已提交
1574 1575
//     return tw.skey;
//   }
1576
//
L
Liu Jicong 已提交
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
//   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);
//   }
1587
//
L
Liu Jicong 已提交
1588 1589 1590 1591 1592
//   // 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;
//   }
1593
//
L
Liu Jicong 已提交
1594 1595 1596 1597 1598 1599 1600
//   /*
//    * 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);
1601
//
L
Liu Jicong 已提交
1602 1603
//   STimeWindow w = TSWINDOW_INITIALIZER;
//   bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
1604
//
L
Liu Jicong 已提交
1605 1606
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//   STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
1607
//
L
Liu Jicong 已提交
1608 1609 1610
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pRuntimeEnv->pTsdbReadHandle)) {
//     tsdbRetrieveDataBlockInfo(pRuntimeEnv->pTsdbReadHandle, &blockInfo);
1611
//
L
Liu Jicong 已提交
1612 1613 1614 1615 1616 1617 1618 1619 1620
//     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;
//     }
1621
//
L
Liu Jicong 已提交
1622 1623
//     // the first time window
//     STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQueryAttr);
1624
//
L
Liu Jicong 已提交
1625 1626
//     while (pQueryAttr->limit.offset > 0) {
//       STimeWindow tw = win;
1627
//
L
Liu Jicong 已提交
1628 1629 1630
//       if ((win.ekey <= blockInfo.window.ekey && ascQuery) || (win.ekey >= blockInfo.window.skey && !ascQuery)) {
//         pQueryAttr->limit.offset -= 1;
//         pWindowResInfo->prevSKey = win.skey;
1631
//
L
Liu Jicong 已提交
1632 1633 1634 1635 1636 1637
//         // 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;
//         }
//       }
1638
//
L
Liu Jicong 已提交
1639 1640 1641 1642
//       if (pQueryAttr->limit.offset == 0) {
//         *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//         return true;
//       }
1643
//
L
Liu Jicong 已提交
1644 1645
//       // current window does not ended in current data block, try next data block
//       getNextTimeWindow(pQueryAttr, &tw);
1646
//
L
Liu Jicong 已提交
1647 1648 1649 1650 1651 1652 1653 1654 1655
//       /*
//        * 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)) {
1656
//
L
Liu Jicong 已提交
1657 1658
//         SArray *pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//         SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
1659
//
L
Liu Jicong 已提交
1660 1661 1662
//         if ((win.ekey > blockInfo.window.ekey && ascQuery) || (win.ekey < blockInfo.window.skey && !ascQuery)) {
//           pQueryAttr->limit.offset -= 1;
//         }
1663
//
L
Liu Jicong 已提交
1664 1665 1666 1667 1668 1669 1670 1671
//         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);
1672
//
L
Liu Jicong 已提交
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
//           // 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.
//       }
//     }
//   }
1684
//
L
Liu Jicong 已提交
1685 1686
//   // check for error
//   if (terrno != TSDB_CODE_SUCCESS) {
1687
//     T_LONG_JMP(pRuntimeEnv->env, terrno);
L
Liu Jicong 已提交
1688
//   }
1689
//
L
Liu Jicong 已提交
1690 1691
//   return true;
// }
1692

1693
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
1694
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
1695
    assert(p->numOfDownstream == 0);
1696 1697
  }

wafwerar's avatar
wafwerar 已提交
1698
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
1699 1700 1701 1702 1703 1704 1705
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

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

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

1710 1711 1712 1713
typedef struct SFetchRspHandleWrapper {
  uint32_t exchangeId;
  int32_t  sourceIndex;
} SFetchRspHandleWrapper;
1714

D
dapan1121 已提交
1715
int32_t loadRemoteDataCallback(void* param, SDataBuf* pMsg, int32_t code) {
X
Xiaoyu Wang 已提交
1716
  SFetchRspHandleWrapper* pWrapper = (SFetchRspHandleWrapper*)param;
1717 1718 1719 1720

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

X
Xiaoyu Wang 已提交
1725
  int32_t          index = pWrapper->sourceIndex;
1726
  SSourceDataInfo* pSourceDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, index);
1727

H
Haojun Liao 已提交
1728 1729
  if (code == TSDB_CODE_SUCCESS) {
    pSourceDataInfo->pRsp = pMsg->pData;
1730

H
Haojun Liao 已提交
1731 1732
    SRetrieveTableRsp* pRsp = pSourceDataInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
dengyihao's avatar
dengyihao 已提交
1733
    pRsp->compLen = htonl(pRsp->compLen);
1734
    pRsp->numOfCols = htonl(pRsp->numOfCols);
dengyihao's avatar
dengyihao 已提交
1735
    pRsp->useconds = htobe64(pRsp->useconds);
1736
    pRsp->numOfBlocks = htonl(pRsp->numOfBlocks);
1737

1738
    ASSERT(pRsp != NULL);
H
Haojun Liao 已提交
1739 1740
    qDebug("%s fetch rsp received, index:%d, blocks:%d, rows:%d", pSourceDataInfo->taskId, index, pRsp->numOfBlocks,
           pRsp->numOfRows);
H
Haojun Liao 已提交
1741
  } else {
1742
    taosMemoryFree(pMsg->pData);
H
Haojun Liao 已提交
1743
    pSourceDataInfo->code = code;
D
dapan1121 已提交
1744
    qDebug("%s fetch rsp received, index:%d, error:%d", pSourceDataInfo->taskId, index, tstrerror(code));
H
Haojun Liao 已提交
1745
  }
H
Haojun Liao 已提交
1746

H
Haojun Liao 已提交
1747
  pSourceDataInfo->status = EX_SOURCE_DATA_READY;
1748 1749 1750 1751

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

wmmhello's avatar
wmmhello 已提交
1752
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1753 1754
}

D
dapan1121 已提交
1755
void qProcessRspMsg(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
S
Shengliang Guan 已提交
1756 1757
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
  assert(pMsg->info.ahandle != NULL);
H
Haojun Liao 已提交
1758 1759 1760 1761

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

  if (pMsg->contLen > 0) {
wafwerar's avatar
wafwerar 已提交
1762
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
H
Haojun Liao 已提交
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
    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);
1774 1775
}

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

L
Liu Jicong 已提交
1779 1780
  SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, sourceIndex);
  SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, sourceIndex);
1781

1782 1783
  ASSERT(pDataInfo->status == EX_SOURCE_DATA_NOT_READY);

1784
  SFetchRspHandleWrapper* pWrapper = taosMemoryCalloc(1, sizeof(SFetchRspHandleWrapper));
X
Xiaoyu Wang 已提交
1785
  pWrapper->exchangeId = pExchangeInfo->self;
1786 1787
  pWrapper->sourceIndex = sourceIndex;

D
dapan1121 已提交
1788 1789
  if (pSource->localExec) {
    SDataBuf pBuf = {0};
1790
    int32_t code = (*pTaskInfo->localFetch.fp)(pTaskInfo->localFetch.handle, pSource->schedId, pTaskInfo->id.queryId, pSource->taskId, 0, pSource->execId, &pBuf.pData, pTaskInfo->localFetch.explainRes);
D
dapan1121 已提交
1791
    loadRemoteDataCallback(pWrapper, &pBuf, code);
D
dapan1121 已提交
1792
    taosMemoryFree(pWrapper);
D
dapan1121 已提交
1793
  } else {
D
dapan1121 已提交
1794 1795 1796 1797 1798 1799
    SResFetchReq* pMsg = taosMemoryCalloc(1, sizeof(SResFetchReq));
    if (NULL == pMsg) {
      pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
      return pTaskInfo->code;
    }

D
dapan1121 已提交
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
    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);

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

    // send the fetch remote task result reques
    SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
    if (NULL == pMsgSendInfo) {
      taosMemoryFreeClear(pMsg);
      qError("%s prepare message %d failed", GET_TASKID(pTaskInfo), (int32_t)sizeof(SMsgSendInfo));
      pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
      return pTaskInfo->code;
    }

    pMsgSendInfo->param = pWrapper;
    pMsgSendInfo->paramFreeFp = taosMemoryFree;
    pMsgSendInfo->msgInfo.pData = pMsg;
    pMsgSendInfo->msgInfo.len = sizeof(SResFetchReq);
    pMsgSendInfo->msgType = pSource->fetchMsgType;
    pMsgSendInfo->fp = loadRemoteDataCallback;
1825

D
dapan1121 已提交
1826 1827 1828 1829
    int64_t transporterId = 0;
    int32_t code = asyncSendMsgToServer(pExchangeInfo->pTransporter, &pSource->addr.epSet, &transporterId, pMsgSendInfo);
  }
  
1830 1831 1832
  return TSDB_CODE_SUCCESS;
}

1833 1834 1835 1836 1837 1838 1839 1840
void updateLoadRemoteInfo(SLoadRemoteDataInfo* pInfo, int32_t numOfRows, int32_t dataLen, int64_t startTs,
                          SOperatorInfo* pOperator) {
  pInfo->totalRows += numOfRows;
  pInfo->totalSize += dataLen;
  pInfo->totalElapsed += (taosGetTimestampUs() - startTs);
  pOperator->resultInfo.totalRows += numOfRows;
}

H
Haojun Liao 已提交
1841
int32_t extractDataBlockFromFetchRsp(SSDataBlock* pRes, char* pData, SArray* pColList, char** pNextStart) {
H
Haojun Liao 已提交
1842
  if (pColList == NULL) {  // data from other sources
1843
    blockDataCleanup(pRes);
dengyihao's avatar
dengyihao 已提交
1844
    *pNextStart = (char*)blockDecode(pRes, pData);
H
Haojun Liao 已提交
1845
  } else {  // extract data according to pColList
1846 1847 1848 1849 1850
    char* pStart = pData;

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

1851
    // todo refactor:extract method
1852
    SSysTableSchema* pSchema = (SSysTableSchema*)pStart;
dengyihao's avatar
dengyihao 已提交
1853
    for (int32_t i = 0; i < numOfCols; ++i) {
1854 1855 1856 1857 1858 1859 1860
      SSysTableSchema* p = (SSysTableSchema*)pStart;

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

1861
    SSDataBlock* pBlock = createDataBlock();
dengyihao's avatar
dengyihao 已提交
1862
    for (int32_t i = 0; i < numOfCols; ++i) {
1863 1864
      SColumnInfoData idata = createColumnInfoData(pSchema[i].type, pSchema[i].bytes, pSchema[i].colId);
      blockDataAppendColInfo(pBlock, &idata);
1865 1866
    }

1867
    blockDecode(pBlock, pStart);
1868
    blockDataEnsureCapacity(pRes, pBlock->info.rows);
1869

H
Haojun Liao 已提交
1870
    // data from mnode
1871
    pRes->info.rows = pBlock->info.rows;
1872 1873
    relocateColumnData(pRes, pColList, pBlock->pDataBlock, false);
    blockDataDestroy(pBlock);
1874
  }
1875

1876 1877
  // todo move this to time window aggregator, since the primary timestamp may not be known by exchange operator.
  blockDataUpdateTsWindow(pRes, 0);
1878 1879
  return TSDB_CODE_SUCCESS;
}
1880

L
Liu Jicong 已提交
1881 1882
static void* setAllSourcesCompleted(SOperatorInfo* pOperator, int64_t startTs) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
1883
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
1884

1885
  int64_t              el = taosGetTimestampUs() - startTs;
H
Haojun Liao 已提交
1886
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
1887

H
Haojun Liao 已提交
1888
  pLoadInfo->totalElapsed += el;
H
Haojun Liao 已提交
1889

1890
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
L
Liu Jicong 已提交
1891 1892 1893
  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);
1894 1895 1896 1897 1898

  doSetOperatorCompleted(pOperator);
  return NULL;
}

1899 1900
static void concurrentlyLoadRemoteDataImpl(SOperatorInfo* pOperator, SExchangeInfo* pExchangeInfo,
                                           SExecTaskInfo* pTaskInfo) {
1901 1902 1903 1904 1905 1906 1907 1908
  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);
1909
      if (pDataInfo->status == EX_SOURCE_DATA_EXHAUSTED) {
1910
        completed += 1;
H
Haojun Liao 已提交
1911 1912
        continue;
      }
1913

1914
      if (pDataInfo->status != EX_SOURCE_DATA_READY) {
1915 1916 1917
        continue;
      }

1918 1919 1920 1921 1922
      if (pDataInfo->code != TSDB_CODE_SUCCESS) {
        code = pDataInfo->code;
        goto _error;
      }

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

H
Haojun Liao 已提交
1926
      SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
1927
      if (pRsp->numOfRows == 0) {
1928 1929
        qDebug("%s vgId:%d, taskId:0x%" PRIx64 " execId:%d index:%d completed, rowsOfSource:%" PRIu64
               ", totalRows:%" PRIu64 ", completed:%d try next %d/%" PRIzu,
D
dapan1121 已提交
1930
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pSource->execId, i, pDataInfo->totalRows,
1931
               pExchangeInfo->loadInfo.totalRows, completed + 1, i + 1, totalSources);
1932
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
1933
        completed += 1;
D
dapan1121 已提交
1934
        taosMemoryFreeClear(pDataInfo->pRsp);
1935 1936
        continue;
      }
H
Haojun Liao 已提交
1937

1938
      SRetrieveTableRsp* pRetrieveRsp = pDataInfo->pRsp;
dengyihao's avatar
dengyihao 已提交
1939 1940 1941
      int32_t            index = 0;
      char*              pStart = pRetrieveRsp->data;
      while (index++ < pRetrieveRsp->numOfBlocks) {
1942
        SSDataBlock* pb = createOneDataBlock(pExchangeInfo->pDummyBlock, false);
H
Haojun Liao 已提交
1943
        code = extractDataBlockFromFetchRsp(pb, pStart, NULL, &pStart);
1944 1945 1946 1947 1948 1949
        if (code != 0) {
          taosMemoryFreeClear(pDataInfo->pRsp);
          goto _error;
        }

        taosArrayPush(pExchangeInfo->pResultBlockList, &pb);
1950 1951
      }

1952
      updateLoadRemoteInfo(pLoadInfo, pRetrieveRsp->numOfRows, pRetrieveRsp->compLen, startTs, pOperator);
1953

1954
      if (pRsp->completed == 1) {
dengyihao's avatar
dengyihao 已提交
1955 1956 1957 1958
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64
               " execId:%d"
               " index:%d completed, blocks:%d, numOfRows:%d, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
               ", total:%.2f Kb,"
1959
               " completed:%d try next %d/%" PRIzu,
H
Haojun Liao 已提交
1960 1961 1962
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pSource->execId, i, pRsp->numOfBlocks,
               pRsp->numOfRows, pDataInfo->totalRows, pLoadInfo->totalRows, pLoadInfo->totalSize / 1024.0,
               completed + 1, i + 1, totalSources);
1963
        completed += 1;
1964
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
1965
      } else {
dengyihao's avatar
dengyihao 已提交
1966 1967 1968 1969
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64
               " execId:%d blocks:%d, numOfRows:%d, totalRows:%" PRIu64 ", total:%.2f Kb",
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pSource->execId, pRsp->numOfBlocks,
               pRsp->numOfRows, pLoadInfo->totalRows, pLoadInfo->totalSize / 1024.0);
1970 1971
      }

1972 1973
      taosMemoryFreeClear(pDataInfo->pRsp);

1974 1975
      if (pDataInfo->status != EX_SOURCE_DATA_EXHAUSTED) {
        pDataInfo->status = EX_SOURCE_DATA_NOT_READY;
1976 1977
        code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
        if (code != TSDB_CODE_SUCCESS) {
1978
          taosMemoryFreeClear(pDataInfo->pRsp);
1979 1980 1981 1982
          goto _error;
        }
      }

1983
      return;
1984 1985
    }

1986
    if (completed == totalSources) {
1987 1988
      setAllSourcesCompleted(pOperator, startTs);
      return;
1989
    }
H
Haojun Liao 已提交
1990 1991

    sched_yield();
1992 1993 1994 1995 1996 1997
  }

_error:
  pTaskInfo->code = code;
}

L
Liu Jicong 已提交
1998 1999 2000
static int32_t prepareConcurrentlyLoad(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2001

L
Liu Jicong 已提交
2002
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
2003 2004 2005
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
2006
  for (int32_t i = 0; i < totalSources; ++i) {
2007 2008
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2009 2010
      pTaskInfo->code = code;
      return code;
2011 2012 2013 2014
    }
  }

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

2018
  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
2019
  pOperator->cost.openCost = taosGetTimestampUs() - startTs;
2020

2021
  tsem_wait(&pExchangeInfo->ready);
H
Haojun Liao 已提交
2022
  return TSDB_CODE_SUCCESS;
2023 2024
}

2025
static int32_t seqLoadRemoteData(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2026 2027
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2028

L
Liu Jicong 已提交
2029
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
2030
  int64_t startTs = taosGetTimestampUs();
2031

L
Liu Jicong 已提交
2032
  while (1) {
2033
    if (pExchangeInfo->current >= totalSources) {
2034 2035
      setAllSourcesCompleted(pOperator, startTs);
      return TSDB_CODE_SUCCESS;
2036
    }
2037

2038 2039 2040
    doSendFetchDataRequest(pExchangeInfo, pTaskInfo, pExchangeInfo->current);
    tsem_wait(&pExchangeInfo->ready);

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

H
Haojun Liao 已提交
2044
    if (pDataInfo->code != TSDB_CODE_SUCCESS) {
2045 2046
      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 已提交
2047
      pOperator->pTaskInfo->code = pDataInfo->code;
2048
      return pOperator->pTaskInfo->code;
H
Haojun Liao 已提交
2049 2050
    }

L
Liu Jicong 已提交
2051
    SRetrieveTableRsp*   pRsp = pDataInfo->pRsp;
H
Haojun Liao 已提交
2052
    SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2053
    if (pRsp->numOfRows == 0) {
2054 2055
      qDebug("%s vgId:%d, taskID:0x%" PRIx64 " execId:%d %d of total completed, rowsOfSource:%" PRIu64
             ", totalRows:%" PRIu64 " try next",
D
dapan1121 已提交
2056
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pSource->execId, pExchangeInfo->current + 1,
H
Haojun Liao 已提交
2057
             pDataInfo->totalRows, pLoadInfo->totalRows);
H
Haojun Liao 已提交
2058

2059
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2060
      pExchangeInfo->current += 1;
D
dapan1121 已提交
2061
      taosMemoryFreeClear(pDataInfo->pRsp);
2062 2063
      continue;
    }
H
Haojun Liao 已提交
2064

2065 2066 2067
    SRetrieveTableRsp* pRetrieveRsp = pDataInfo->pRsp;

    char*   pStart = pRetrieveRsp->data;
H
Haojun Liao 已提交
2068
    int32_t code = extractDataBlockFromFetchRsp(NULL, pStart, NULL, &pStart);
2069 2070

    if (pRsp->completed == 1) {
D
dapan1121 已提交
2071
      qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " execId:%d numOfRows:%d, rowsOfSource:%" PRIu64
L
Liu Jicong 已提交
2072
             ", totalRows:%" PRIu64 ", totalBytes:%" PRIu64 " try next %d/%" PRIzu,
2073
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pSource->execId, pRetrieveRsp->numOfRows,
2074 2075
             pDataInfo->totalRows, pLoadInfo->totalRows, pLoadInfo->totalSize, pExchangeInfo->current + 1,
             totalSources);
2076

2077
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2078 2079
      pExchangeInfo->current += 1;
    } else {
D
dapan1121 已提交
2080
      qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " execId:%d numOfRows:%d, totalRows:%" PRIu64
L
Liu Jicong 已提交
2081
             ", totalBytes:%" PRIu64,
2082
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pSource->execId, pRetrieveRsp->numOfRows,
2083
             pLoadInfo->totalRows, pLoadInfo->totalSize);
2084 2085
    }

2086 2087 2088
    updateLoadRemoteInfo(pLoadInfo, pRetrieveRsp->numOfRows, pRetrieveRsp->compLen, startTs, pOperator);
    pDataInfo->totalRows += pRetrieveRsp->numOfRows;

2089
    taosMemoryFreeClear(pDataInfo->pRsp);
2090
    return TSDB_CODE_SUCCESS;
2091
  }
2092 2093
}

L
Liu Jicong 已提交
2094
static int32_t prepareLoadRemoteData(SOperatorInfo* pOperator) {
2095
  if (OPTR_IS_OPENED(pOperator)) {
H
Haojun Liao 已提交
2096 2097 2098
    return TSDB_CODE_SUCCESS;
  }

2099 2100
  int64_t st = taosGetTimestampUs();

L
Liu Jicong 已提交
2101
  SExchangeInfo* pExchangeInfo = pOperator->info;
2102
  if (!pExchangeInfo->seqLoadData) {
H
Haojun Liao 已提交
2103 2104 2105 2106 2107 2108
    int32_t code = prepareConcurrentlyLoad(pOperator);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

2109
  OPTR_SET_OPENED(pOperator);
2110
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
2111 2112 2113
  return TSDB_CODE_SUCCESS;
}

2114 2115 2116 2117 2118
static void freeBlock(void* pParam) {
  SSDataBlock* pBlock = *(SSDataBlock**)pParam;
  blockDataDestroy(pBlock);
}

2119
static SSDataBlock* doLoadRemoteDataImpl(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2120 2121
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2122

2123
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
2124
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2125 2126
    return NULL;
  }
2127

2128
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
H
Haojun Liao 已提交
2129

2130
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2131
  if (pOperator->status == OP_EXEC_DONE) {
L
Liu Jicong 已提交
2132 2133 2134
    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);
2135 2136 2137
    return NULL;
  }

2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
  size_t size = taosArrayGetSize(pExchangeInfo->pResultBlockList);
  if (size == 0 || pExchangeInfo->rspBlockIndex >= size) {
    pExchangeInfo->rspBlockIndex = 0;
    taosArrayClearEx(pExchangeInfo->pResultBlockList, freeBlock);
    if (pExchangeInfo->seqLoadData) {
      seqLoadRemoteData(pOperator);
    } else {
      concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
    }

    if (taosArrayGetSize(pExchangeInfo->pResultBlockList) == 0) {
      return NULL;
    }
2151
  }
2152 2153 2154

  // we have buffered retrieved datablock, return it directly
  return taosArrayGetP(pExchangeInfo->pResultBlockList, pExchangeInfo->rspBlockIndex++);
H
Haojun Liao 已提交
2155
}
2156

2157 2158 2159 2160 2161 2162 2163 2164
static SSDataBlock* doLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

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

L
Liu Jicong 已提交
2165
  while (1) {
2166 2167 2168 2169 2170 2171 2172
    SSDataBlock* pBlock = doLoadRemoteDataImpl(pOperator);
    if (pBlock == NULL) {
      return NULL;
    }

    SLimitInfo* pLimitInfo = &pExchangeInfo->limitInfo;
    if (hasLimitOffsetInfo(pLimitInfo)) {
2173
      int32_t status = handleLimitOffset(pOperator, pLimitInfo, pBlock, false);
2174 2175 2176
      if (status == PROJECT_RETRIEVE_CONTINUE) {
        continue;
      } else if (status == PROJECT_RETRIEVE_DONE) {
2177
        size_t rows = pBlock->info.rows;
2178 2179 2180 2181 2182 2183
        pExchangeInfo->limitInfo.numOfOutputRows += rows;

        if (rows == 0) {
          doSetOperatorCompleted(pOperator);
          return NULL;
        } else {
2184
          return pBlock;
2185 2186 2187
        }
      }
    } else {
2188
      return pBlock;
2189 2190 2191 2192
    }
  }
}

2193
static int32_t initDataSource(int32_t numOfSources, SExchangeInfo* pInfo, const char* id) {
2194
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
H
Haojun Liao 已提交
2195 2196
  if (pInfo->pSourceDataInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
2197 2198
  }

L
Liu Jicong 已提交
2199
  for (int32_t i = 0; i < numOfSources; ++i) {
2200
    SSourceDataInfo dataInfo = {0};
H
Haojun Liao 已提交
2201
    dataInfo.status = EX_SOURCE_DATA_NOT_READY;
2202
    dataInfo.taskId = id;
L
Liu Jicong 已提交
2203
    dataInfo.index = i;
X
Xiaoyu Wang 已提交
2204
    SSourceDataInfo* pDs = taosArrayPush(pInfo->pSourceDataInfo, &dataInfo);
2205
    if (pDs == NULL) {
H
Haojun Liao 已提交
2206 2207 2208 2209 2210 2211 2212 2213
      taosArrayDestroy(pInfo->pSourceDataInfo);
      return TSDB_CODE_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
}

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

2217
  if (numOfSources == 0) {
X
Xiaoyu Wang 已提交
2218
    qError("%s invalid number: %d of sources in exchange operator", id, (int32_t)numOfSources);
2219 2220 2221
    return TSDB_CODE_INVALID_PARA;
  }

H
Haojun Liao 已提交
2222
  pInfo->pSources = taosArrayInit(numOfSources, sizeof(SDownstreamSourceNode));
wmmhello's avatar
wmmhello 已提交
2223
  if (pInfo->pSources == NULL) {
2224
    return TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
2225 2226
  }

L
Liu Jicong 已提交
2227
  for (int32_t i = 0; i < numOfSources; ++i) {
D
dapan1121 已提交
2228
    SDownstreamSourceNode* pNode = (SDownstreamSourceNode*)nodesListGetNode((SNodeList*)pExNode->pSrcEndPoints, i);
H
Haojun Liao 已提交
2229 2230
    taosArrayPush(pInfo->pSources, pNode);
  }
2231

2232
  initLimitInfo(pExNode->node.pLimit, pExNode->node.pSlimit, &pInfo->limitInfo);
2233 2234
  pInfo->self = taosAddRef(exchangeObjRefPool, pInfo);

2235
  return initDataSource(numOfSources, pInfo, id);
2236 2237 2238 2239 2240 2241
}

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 已提交
2242
    goto _error;
2243
  }
H
Haojun Liao 已提交
2244

2245
  int32_t code = initExchangeOperator(pExNode, pInfo, GET_TASKID(pTaskInfo));
2246 2247 2248
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2249 2250

  tsem_init(&pInfo->ready, 0, 0);
2251 2252
  pInfo->pDummyBlock = createResDataBlock(pExNode->node.pOutputDataBlockDesc);
  pInfo->pResultBlockList = taosArrayInit(1, POINTER_BYTES);
2253

2254
  pInfo->seqLoadData = false;
2255
  pInfo->pTransporter = pTransporter;
2256

2257
  pOperator->name = "ExchangeOperator";
X
Xiaoyu Wang 已提交
2258
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_EXCHANGE;
X
Xiaoyu Wang 已提交
2259
  pOperator->blocking = false;
2260 2261
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
2262
  pOperator->exprSupp.numOfExprs = taosArrayGetSize(pInfo->pDummyBlock->pDataBlock);
X
Xiaoyu Wang 已提交
2263
  pOperator->pTaskInfo = pTaskInfo;
2264

L
Liu Jicong 已提交
2265 2266
  pOperator->fpSet = createOperatorFpSet(prepareLoadRemoteData, doLoadRemoteData, NULL, NULL,
                                         destroyExchangeOperatorInfo, NULL, NULL, NULL);
2267
  return pOperator;
H
Haojun Liao 已提交
2268

L
Liu Jicong 已提交
2269
_error:
H
Haojun Liao 已提交
2270
  if (pInfo != NULL) {
2271
    doDestroyExchangeOperatorInfo(pInfo);
H
Haojun Liao 已提交
2272 2273
  }

wafwerar's avatar
wafwerar 已提交
2274
  taosMemoryFreeClear(pOperator);
2275
  pTaskInfo->code = code;
H
Haojun Liao 已提交
2276
  return NULL;
2277 2278
}

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

L
Liu Jicong 已提交
2282
static bool needToMerge(SSDataBlock* pBlock, SArray* groupInfo, char** buf, int32_t rowIndex) {
2283 2284 2285 2286
  size_t size = taosArrayGetSize(groupInfo);
  if (size == 0) {
    return true;
  }
2287

2288 2289
  for (int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(groupInfo, i);
2290

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

2294 2295 2296
    if ((isNull && buf[i] != NULL) || (!isNull && buf[i] == NULL)) {
      return false;
    }
2297

2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310
    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;
      }
2311 2312 2313
    }
  }

2314
  return 0;
2315 2316
}

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

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

2324 2325 2326
    char* data = colDataGetData(pColInfo, rowIndex);
    memcpy(rowColData[i], data, colDataGetLength(pColInfo, rowIndex));
  }
2327

2328 2329
  return true;
}
2330

X
Xiaoyu Wang 已提交
2331
int32_t getTableScanInfo(SOperatorInfo* pOperator, int32_t* order, int32_t* scanFlag) {
2332
  // todo add more information about exchange operation
2333
  int32_t type = pOperator->operatorType;
X
Xiaoyu Wang 已提交
2334
  if (type == QUERY_NODE_PHYSICAL_PLAN_EXCHANGE || type == QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN ||
2335
      type == QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN || type == QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN ||
2336
      type == QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN || type == QUERY_NODE_PHYSICAL_PLAN_LAST_ROW_SCAN) {
2337 2338 2339
    *order = TSDB_ORDER_ASC;
    *scanFlag = MAIN_SCAN;
    return TSDB_CODE_SUCCESS;
2340
  } else if (type == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
2341 2342 2343 2344
    STableScanInfo* pTableScanInfo = pOperator->info;
    *order = pTableScanInfo->cond.order;
    *scanFlag = pTableScanInfo->scanFlag;
    return TSDB_CODE_SUCCESS;
2345 2346 2347 2348 2349
  } else if (type == QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN) {
    STableMergeScanInfo* pTableScanInfo = pOperator->info;
    *order = pTableScanInfo->cond.order;
    *scanFlag = pTableScanInfo->scanFlag;
    return TSDB_CODE_SUCCESS;
2350
  } else {
H
Haojun Liao 已提交
2351
    if (pOperator->pDownstream == NULL || pOperator->pDownstream[0] == NULL) {
2352
      return TSDB_CODE_INVALID_PARA;
H
Haojun Liao 已提交
2353
    } else {
2354
      return getTableScanInfo(pOperator->pDownstream[0], order, scanFlag);
2355 2356 2357
    }
  }
}
2358

2359
// this is a blocking operator
L
Liu Jicong 已提交
2360
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
2361 2362
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
2363 2364
  }

H
Haojun Liao 已提交
2365
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
2366
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
2367

2368 2369
  SExprSupp*     pSup = &pOperator->exprSupp;
  SOperatorInfo* downstream = pOperator->pDownstream[0];
2370

2371 2372
  int64_t st = taosGetTimestampUs();

2373 2374 2375
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;

H
Haojun Liao 已提交
2376
  while (1) {
2377
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
2378 2379 2380 2381
    if (pBlock == NULL) {
      break;
    }

2382 2383
    int32_t code = getTableScanInfo(pOperator, &order, &scanFlag);
    if (code != TSDB_CODE_SUCCESS) {
2384
      T_LONG_JMP(pTaskInfo->env, code);
2385
    }
2386

2387
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
2388 2389 2390
    if (pAggInfo->scalarExprSup.pExprInfo != NULL) {
      SExprSupp* pSup1 = &pAggInfo->scalarExprSup;
      code = projectApplyFunctions(pSup1->pExprInfo, pBlock, pBlock, pSup1->pCtx, pSup1->numOfExprs, NULL);
2391
      if (code != TSDB_CODE_SUCCESS) {
2392
        T_LONG_JMP(pTaskInfo->env, code);
2393
      }
2394 2395
    }

2396
    // the pDataBlock are always the same one, no need to call this again
2397
    setExecutionContext(pOperator, pOperator->exprSupp.numOfExprs, pBlock->info.groupId);
2398
    setInputDataBlock(pOperator, pSup->pCtx, pBlock, order, scanFlag, true);
2399
    code = doAggregateImpl(pOperator, pSup->pCtx);
2400
    if (code != 0) {
2401
      T_LONG_JMP(pTaskInfo->env, code);
2402
    }
2403 2404
  }

2405
  initGroupedResultInfo(&pAggInfo->groupResInfo, pAggInfo->aggSup.pResultRowHashTable, 0);
H
Haojun Liao 已提交
2406
  OPTR_SET_OPENED(pOperator);
2407

2408
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
2409 2410 2411
  return TSDB_CODE_SUCCESS;
}

2412
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2413
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
2414 2415 2416 2417 2418 2419
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

L
Liu Jicong 已提交
2420
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2421
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
H
Haojun Liao 已提交
2422
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
2423
    doSetOperatorCompleted(pOperator);
H
Haojun Liao 已提交
2424 2425 2426
    return NULL;
  }

H
Haojun Liao 已提交
2427
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
S
slzhou 已提交
2428 2429
  while (1) {
    doBuildResultDatablock(pOperator, pInfo, &pAggInfo->groupResInfo, pAggInfo->aggSup.pResultBuf);
2430
    doFilter(pAggInfo->pCondition, pInfo->pRes, NULL);
S
slzhou 已提交
2431

2432
    if (!hasRemainResults(&pAggInfo->groupResInfo)) {
S
slzhou 已提交
2433 2434 2435
      doSetOperatorCompleted(pOperator);
      break;
    }
2436

S
slzhou 已提交
2437 2438 2439 2440
    if (pInfo->pRes->info.rows > 0) {
      break;
    }
  }
2441

2442
  size_t rows = blockDataGetNumOfRows(pInfo->pRes);
2443 2444
  pOperator->resultInfo.totalRows += rows;

2445
  return (rows == 0) ? NULL : pInfo->pRes;
2446 2447
}

wmmhello's avatar
wmmhello 已提交
2448
int32_t aggEncodeResultRow(SOperatorInfo* pOperator, char** result, int32_t* length) {
2449
  if (result == NULL || length == NULL) {
wmmhello's avatar
wmmhello 已提交
2450 2451 2452
    return TSDB_CODE_TSC_INVALID_INPUT;
  }
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)(pOperator->info);
2453
  SAggSupporter*  pSup = (SAggSupporter*)POINTER_SHIFT(pOperator->info, sizeof(SOptrBasicInfo));
2454
  int32_t         size = tSimpleHashGetSize(pSup->pResultRowHashTable);
2455 2456 2457
  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 已提交
2458

C
Cary Xu 已提交
2459 2460 2461 2462 2463 2464
  // no result
  if (getTotalBufSize(pSup->pResultBuf) == 0) {
    *result = NULL;
    *length = 0;
    return TSDB_CODE_SUCCESS;
  }
2465

wmmhello's avatar
wmmhello 已提交
2466
  *result = (char*)taosMemoryCalloc(1, totalSize);
L
Liu Jicong 已提交
2467
  if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
2468
    return TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
2469
  }
wmmhello's avatar
wmmhello 已提交
2470

wmmhello's avatar
wmmhello 已提交
2471
  int32_t offset = sizeof(int32_t);
wmmhello's avatar
wmmhello 已提交
2472 2473
  *(int32_t*)(*result + offset) = size;
  offset += sizeof(int32_t);
2474 2475

  // prepare memory
2476
  SResultRowPosition* pos = &pInfo->resultRowInfo.cur;
dengyihao's avatar
dengyihao 已提交
2477 2478
  void*               pPage = getBufPage(pSup->pResultBuf, pos->pageId);
  SResultRow*         pRow = (SResultRow*)((char*)pPage + pos->offset);
2479 2480
  setBufPageDirty(pPage, true);
  releaseBufPage(pSup->pResultBuf, pPage);
L
Liu Jicong 已提交
2481

2482 2483 2484 2485
  int32_t iter = 0;
  void*   pIter = NULL;
  while ((pIter = tSimpleHashIterate(pSup->pResultRowHashTable, pIter, &iter))) {
    void*               key = tSimpleHashGetKey(pIter, &keyLen);
2486
    SResultRowPosition* p1 = (SResultRowPosition*)pIter;
2487

dengyihao's avatar
dengyihao 已提交
2488
    pPage = (SFilePage*)getBufPage(pSup->pResultBuf, p1->pageId);
2489
    pRow = (SResultRow*)((char*)pPage + p1->offset);
2490 2491
    setBufPageDirty(pPage, true);
    releaseBufPage(pSup->pResultBuf, pPage);
wmmhello's avatar
wmmhello 已提交
2492 2493 2494

    // recalculate the result size
    int32_t realTotalSize = offset + sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize;
L
Liu Jicong 已提交
2495
    if (realTotalSize > totalSize) {
wmmhello's avatar
wmmhello 已提交
2496
      char* tmp = (char*)taosMemoryRealloc(*result, realTotalSize);
L
Liu Jicong 已提交
2497
      if (tmp == NULL) {
wafwerar's avatar
wafwerar 已提交
2498
        taosMemoryFree(*result);
wmmhello's avatar
wmmhello 已提交
2499
        *result = NULL;
wmmhello's avatar
wmmhello 已提交
2500
        return TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
2501
      } else {
wmmhello's avatar
wmmhello 已提交
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513
        *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);
2514
    memcpy(*result + offset, pRow, pSup->resultRowSize);
wmmhello's avatar
wmmhello 已提交
2515 2516 2517
    offset += pSup->resultRowSize;
  }

wmmhello's avatar
wmmhello 已提交
2518 2519 2520 2521
  *(int32_t*)(*result) = offset;
  *length = offset;

  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
2522 2523
}

2524
int32_t aggDecodeResultRow(SOperatorInfo* pOperator, char* result) {
2525
  if (result == NULL) {
wmmhello's avatar
wmmhello 已提交
2526
    return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
2527
  }
wmmhello's avatar
wmmhello 已提交
2528
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)(pOperator->info);
2529
  SAggSupporter*  pSup = (SAggSupporter*)POINTER_SHIFT(pOperator->info, sizeof(SOptrBasicInfo));
wmmhello's avatar
wmmhello 已提交
2530 2531

  //  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
2532
  int32_t length = *(int32_t*)(result);
wmmhello's avatar
wmmhello 已提交
2533
  int32_t offset = sizeof(int32_t);
2534 2535 2536 2537

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

L
Liu Jicong 已提交
2538
  while (count-- > 0 && length > offset) {
wmmhello's avatar
wmmhello 已提交
2539 2540 2541
    int32_t keyLen = *(int32_t*)(result + offset);
    offset += sizeof(int32_t);

L
Liu Jicong 已提交
2542
    uint64_t    tableGroupId = *(uint64_t*)(result + offset);
2543
    SResultRow* resultRow = getNewResultRow(pSup->pResultBuf, &pSup->currentPageId, pSup->resultRowSize);
L
Liu Jicong 已提交
2544
    if (!resultRow) {
wmmhello's avatar
wmmhello 已提交
2545
      return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
2546
    }
2547

wmmhello's avatar
wmmhello 已提交
2548
    // add a new result set for a new group
2549
    SResultRowPosition pos = {.pageId = resultRow->pageId, .offset = resultRow->offset};
2550
    tSimpleHashPut(pSup->pResultRowHashTable, result + offset, keyLen, &pos, sizeof(SResultRowPosition));
wmmhello's avatar
wmmhello 已提交
2551 2552 2553

    offset += keyLen;
    int32_t valueLen = *(int32_t*)(result + offset);
L
Liu Jicong 已提交
2554
    if (valueLen != pSup->resultRowSize) {
wmmhello's avatar
wmmhello 已提交
2555
      return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
2556 2557 2558 2559 2560 2561 2562 2563 2564
    }
    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;

dengyihao's avatar
dengyihao 已提交
2565
    pInfo->resultRowInfo.cur = (SResultRowPosition){.pageId = resultRow->pageId, .offset = resultRow->offset};
H
Haojun Liao 已提交
2566
    // releaseBufPage(pSup->pResultBuf, getBufPage(pSup->pResultBuf, pageId));
wmmhello's avatar
wmmhello 已提交
2567 2568
  }

L
Liu Jicong 已提交
2569
  if (offset != length) {
wmmhello's avatar
wmmhello 已提交
2570
    return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
2571
  }
wmmhello's avatar
wmmhello 已提交
2572
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
2573 2574
}

2575 2576 2577 2578 2579
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);
2580
      return PROJECT_RETRIEVE_CONTINUE;
2581 2582 2583
    } else if (pLimitInfo->currentGroupId != pBlock->info.groupId) {
      // now it is the data from a new group
      pLimitInfo->remainGroupOffset -= 1;
2584 2585

      // ignore data block in current group
2586 2587
      if (pLimitInfo->remainGroupOffset > 0) {
        blockDataCleanup(pBlock);
2588 2589 2590 2591 2592
        return PROJECT_RETRIEVE_CONTINUE;
      }
    }

    // set current group id of the project operator
2593
    pLimitInfo->currentGroupId = pBlock->info.groupId;
2594 2595
  }

2596
  // here check for a new group data, we need to handle the data of the previous group.
2597 2598 2599
  if (pLimitInfo->currentGroupId != 0 && pLimitInfo->currentGroupId != pBlock->info.groupId) {
    pLimitInfo->numOfOutputGroups += 1;
    if ((pLimitInfo->slimit.limit > 0) && (pLimitInfo->slimit.limit <= pLimitInfo->numOfOutputGroups)) {
2600
      pOperator->status = OP_EXEC_DONE;
2601
      blockDataCleanup(pBlock);
2602 2603 2604 2605 2606

      return PROJECT_RETRIEVE_DONE;
    }

    // reset the value for a new group data
2607 2608
    pLimitInfo->numOfOutputRows = 0;
    pLimitInfo->remainOffset = pLimitInfo->limit.offset;
2609 2610 2611 2612 2613

    // existing rows that belongs to previous group.
    if (pBlock->info.rows > 0) {
      return PROJECT_RETRIEVE_DONE;
    }
2614 2615 2616 2617 2618
  }

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

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

2621 2622 2623
  if (pLimitInfo->remainOffset >= pBlock->info.rows) {
    pLimitInfo->remainOffset -= pBlock->info.rows;
    blockDataCleanup(pBlock);
2624
    return PROJECT_RETRIEVE_CONTINUE;
2625 2626 2627
  } else if (pLimitInfo->remainOffset < pBlock->info.rows && pLimitInfo->remainOffset > 0) {
    blockDataTrimFirstNRows(pBlock, pLimitInfo->remainOffset);
    pLimitInfo->remainOffset = 0;
2628 2629
  }

2630
  // check for the limitation in each group
2631 2632 2633 2634
  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) {
2635 2636 2637
      pOperator->status = OP_EXEC_DONE;
    }

2638
    return PROJECT_RETRIEVE_DONE;
2639
  }
2640

2641
  // todo optimize performance
2642 2643
  // 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.
2644 2645
  if ((!holdDataInBuf) || (pBlock->info.rows >= pOperator->resultInfo.threshold) || pLimitInfo->slimit.offset != -1 ||
      pLimitInfo->slimit.limit != -1) {
2646
    return PROJECT_RETRIEVE_DONE;
L
Liu Jicong 已提交
2647
  } else {  // not full enough, continue to accumulate the output data in the buffer.
2648 2649 2650 2651
    return PROJECT_RETRIEVE_CONTINUE;
  }
}

2652
static void doApplyScalarCalculation(SOperatorInfo* pOperator, SSDataBlock* pBlock, int32_t order, int32_t scanFlag);
L
Liu Jicong 已提交
2653 2654
static void doHandleRemainBlockForNewGroupImpl(SOperatorInfo* pOperator, SFillOperatorInfo* pInfo,
                                               SResultInfo* pResultInfo, SExecTaskInfo* pTaskInfo) {
2655
  pInfo->totalInputRows = pInfo->existNewGroupBlock->info.rows;
2656 2657 2658 2659 2660
  SSDataBlock* pResBlock = pInfo->pFinalRes;

  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;
  getTableScanInfo(pOperator, &order, &scanFlag);
H
Haojun Liao 已提交
2661

L
Liu Jicong 已提交
2662 2663
  int64_t ekey =
      Q_STATUS_EQUAL(pTaskInfo->status, TASK_COMPLETED) ? pInfo->win.ekey : pInfo->existNewGroupBlock->info.window.ekey;
2664 2665
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

2666
  blockDataCleanup(pInfo->pRes);
2667 2668 2669 2670
  doApplyScalarCalculation(pOperator, pInfo->existNewGroupBlock, order, scanFlag);

  taosFillSetStartInfo(pInfo->pFillInfo, pInfo->pRes->info.rows, ekey);
  taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->pRes);
2671

2672 2673
  int32_t numOfResultRows = pResultInfo->capacity - pResBlock->info.rows;
  taosFillResultDataBlock(pInfo->pFillInfo, pResBlock, numOfResultRows);
H
Haojun Liao 已提交
2674

2675
  pInfo->curGroupId = pInfo->existNewGroupBlock->info.groupId;
2676 2677 2678
  pInfo->existNewGroupBlock = NULL;
}

L
Liu Jicong 已提交
2679 2680
static void doHandleRemainBlockFromNewGroup(SOperatorInfo* pOperator, SFillOperatorInfo* pInfo,
                                            SResultInfo* pResultInfo, SExecTaskInfo* pTaskInfo) {
2681
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
H
Haojun Liao 已提交
2682 2683
    int32_t numOfResultRows = pResultInfo->capacity - pInfo->pFinalRes->info.rows;
    taosFillResultDataBlock(pInfo->pFillInfo, pInfo->pFinalRes, numOfResultRows);
2684 2685
    pInfo->pRes->info.groupId = pInfo->curGroupId;
    return;
2686 2687 2688 2689
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
2690 2691 2692 2693 2694 2695
    doHandleRemainBlockForNewGroupImpl(pOperator, pInfo, pResultInfo, pTaskInfo);
  }
}

static void doApplyScalarCalculation(SOperatorInfo* pOperator, SSDataBlock* pBlock, int32_t order, int32_t scanFlag) {
  SFillOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
2696 2697
  SExprSupp*         pSup = &pOperator->exprSupp;
  SSDataBlock*       pResBlock = pInfo->pFinalRes;
2698 2699 2700 2701 2702 2703 2704 2705 2706

  setInputDataBlock(pOperator, pSup->pCtx, pBlock, order, scanFlag, false);
  projectApplyFunctions(pSup->pExprInfo, pInfo->pRes, pBlock, pSup->pCtx, pSup->numOfExprs, NULL);
  pInfo->pRes->info.groupId = pBlock->info.groupId;

  SColumnInfoData* pDst = taosArrayGet(pInfo->pRes->pDataBlock, pInfo->primaryTsCol);
  SColumnInfoData* pSrc = taosArrayGet(pBlock->pDataBlock, pInfo->primarySrcSlotId);
  colDataAssign(pDst, pSrc, pInfo->pRes->info.rows, &pResBlock->info);

L
Liu Jicong 已提交
2707
  for (int32_t i = 0; i < pInfo->numOfNotFillExpr; ++i) {
2708 2709 2710 2711
    SFillColInfo* pCol = &pInfo->pFillInfo->pFillCol[i + pInfo->numOfExpr];
    ASSERT(pCol->notFillCol);

    SExprInfo* pExpr = pCol->pExpr;
L
Liu Jicong 已提交
2712 2713
    int32_t    srcSlotId = pExpr->base.pParam[0].pCol->slotId;
    int32_t    dstSlotId = pExpr->base.resSchema.slotId;
2714 2715 2716 2717

    SColumnInfoData* pDst1 = taosArrayGet(pInfo->pRes->pDataBlock, dstSlotId);
    SColumnInfoData* pSrc1 = taosArrayGet(pBlock->pDataBlock, srcSlotId);
    colDataAssign(pDst1, pSrc1, pInfo->pRes->info.rows, &pResBlock->info);
2718 2719 2720
  }
}

S
slzhou 已提交
2721
static SSDataBlock* doFillImpl(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2722 2723
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
2724

H
Haojun Liao 已提交
2725
  SResultInfo* pResultInfo = &pOperator->resultInfo;
H
Haojun Liao 已提交
2726
  SSDataBlock* pResBlock = pInfo->pFinalRes;
2727 2728

  blockDataCleanup(pResBlock);
2729

H
Haojun Liao 已提交
2730 2731
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;
2732
  getTableScanInfo(pOperator, &order, &scanFlag);
2733

2734
  doHandleRemainBlockFromNewGroup(pOperator, pInfo, pResultInfo, pTaskInfo);
2735
  if (pResBlock->info.rows > 0) {
2736
    pResBlock->info.groupId = pInfo->curGroupId;
2737
    return pResBlock;
H
Haojun Liao 已提交
2738
  }
2739

H
Haojun Liao 已提交
2740
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
2741
  while (1) {
2742
    SSDataBlock* pBlock = pDownstream->fpSet.getNextFn(pDownstream);
2743 2744
    if (pBlock == NULL) {
      if (pInfo->totalInputRows == 0) {
2745
        doSetOperatorCompleted(pOperator);
2746 2747
        return NULL;
      }
2748

2749
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pInfo->win.ekey);
2750
    } else {
2751
      blockDataUpdateTsWindow(pBlock, pInfo->primarySrcSlotId);
2752 2753

      blockDataCleanup(pInfo->pRes);
2754
      doApplyScalarCalculation(pOperator, pBlock, order, scanFlag);
2755

H
Haojun Liao 已提交
2756 2757 2758
      if (pInfo->curGroupId == 0 || pInfo->curGroupId == pInfo->pRes->info.groupId) {
        pInfo->curGroupId = pInfo->pRes->info.groupId;  // the first data block
        pInfo->totalInputRows += pInfo->pRes->info.rows;
2759

H
Haojun Liao 已提交
2760 2761 2762 2763 2764
        if (order == pInfo->pFillInfo->order) {
          taosFillSetStartInfo(pInfo->pFillInfo, pInfo->pRes->info.rows, pBlock->info.window.ekey);
        } else {
          taosFillSetStartInfo(pInfo->pFillInfo, pInfo->pRes->info.rows, pBlock->info.window.skey);
        }
H
Haojun Liao 已提交
2765
        taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->pRes);
L
Liu Jicong 已提交
2766
      } else if (pInfo->curGroupId != pBlock->info.groupId) {  // the new group data block
2767 2768 2769 2770 2771
        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);
2772 2773 2774
      }
    }

2775 2776
    int32_t numOfResultRows = pOperator->resultInfo.capacity - pResBlock->info.rows;
    taosFillResultDataBlock(pInfo->pFillInfo, pResBlock, numOfResultRows);
2777 2778

    // current group has no more result to return
2779
    if (pResBlock->info.rows > 0) {
2780 2781
      // 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
2782
      if (pResBlock->info.rows > pResultInfo->threshold || pBlock == NULL || pInfo->existNewGroupBlock != NULL) {
2783
        pResBlock->info.groupId = pInfo->curGroupId;
2784
        return pResBlock;
2785 2786
      }

2787
      doHandleRemainBlockFromNewGroup(pOperator, pInfo, pResultInfo, pTaskInfo);
2788
      if (pResBlock->info.rows >= pOperator->resultInfo.threshold || pBlock == NULL) {
2789
        pResBlock->info.groupId = pInfo->curGroupId;
2790
        return pResBlock;
2791 2792 2793
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
2794 2795 2796 2797

      blockDataCleanup(pResBlock);

      doHandleRemainBlockForNewGroupImpl(pOperator, pInfo, pResultInfo, pTaskInfo);
2798
      if (pResBlock->info.rows > pResultInfo->threshold) {
2799
        pResBlock->info.groupId = pInfo->curGroupId;
2800
        return pResBlock;
2801 2802 2803 2804 2805 2806 2807
      }
    } else {
      return NULL;
    }
  }
}

S
slzhou 已提交
2808 2809 2810 2811 2812 2813 2814 2815
static SSDataBlock* doFill(SOperatorInfo* pOperator) {
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;

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

S
slzhou 已提交
2816
  SSDataBlock* fillResult = NULL;
S
slzhou 已提交
2817
  while (true) {
S
slzhou 已提交
2818
    fillResult = doFillImpl(pOperator);
S
slzhou 已提交
2819 2820 2821 2822 2823
    if (fillResult == NULL) {
      doSetOperatorCompleted(pOperator);
      break;
    }

2824
    doFilter(pInfo->pCondition, fillResult, pInfo->pColMatchColInfo);
S
slzhou 已提交
2825 2826 2827 2828 2829
    if (fillResult->info.rows > 0) {
      break;
    }
  }

S
slzhou 已提交
2830
  if (fillResult != NULL) {
2831
    pOperator->resultInfo.totalRows += fillResult->info.rows;
S
slzhou 已提交
2832
  }
S
slzhou 已提交
2833

S
slzhou 已提交
2834
  return fillResult;
S
slzhou 已提交
2835 2836
}

2837
void destroyExprInfo(SExprInfo* pExpr, int32_t numOfExprs) {
C
Cary Xu 已提交
2838 2839 2840 2841 2842
  for (int32_t i = 0; i < numOfExprs; ++i) {
    SExprInfo* pExprInfo = &pExpr[i];
    for (int32_t j = 0; j < pExprInfo->base.numOfParams; ++j) {
      if (pExprInfo->base.pParam[j].type == FUNC_PARAM_TYPE_COLUMN) {
        taosMemoryFreeClear(pExprInfo->base.pParam[j].pCol);
H
Haojun Liao 已提交
2843
      }
2844
    }
C
Cary Xu 已提交
2845 2846 2847

    taosMemoryFree(pExprInfo->base.pParam);
    taosMemoryFree(pExprInfo->pExpr);
H
Haojun Liao 已提交
2848 2849 2850
  }
}

2851 2852 2853 2854 2855
static void destroyOperatorInfo(SOperatorInfo* pOperator) {
  if (pOperator == NULL) {
    return;
  }

2856
  if (pOperator->fpSet.closeFn != NULL) {
2857
    pOperator->fpSet.closeFn(pOperator->info);
2858 2859
  }

H
Haojun Liao 已提交
2860
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
2861
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
2862
      destroyOperatorInfo(pOperator->pDownstream[i]);
2863 2864
    }

wafwerar's avatar
wafwerar 已提交
2865
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
2866
    pOperator->numOfDownstream = 0;
2867 2868
  }

2869
  cleanupExprSupp(&pOperator->exprSupp);
wafwerar's avatar
wafwerar 已提交
2870
  taosMemoryFreeClear(pOperator);
2871 2872
}

2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
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 已提交
2888 2889
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                         const char* pKey) {
L
Liu Jicong 已提交
2890
  int32_t    code = 0;
2891 2892
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

2893
  pAggSup->currentPageId = -1;
dengyihao's avatar
dengyihao 已提交
2894 2895
  pAggSup->resultRowSize = getResultRowSize(pCtx, numOfOutput);
  pAggSup->keyBuf = taosMemoryCalloc(1, keyBufSize + POINTER_BYTES + sizeof(int64_t));
2896
  pAggSup->pResultRowHashTable = tSimpleHashInit(10, hashFn);
2897

H
Haojun Liao 已提交
2898
  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowHashTable == NULL) {
2899 2900 2901
    return TSDB_CODE_OUT_OF_MEMORY;
  }

dengyihao's avatar
dengyihao 已提交
2902
  uint32_t defaultPgsz = 0;
2903 2904
  uint32_t defaultBufsz = 0;
  getBufferPgSize(pAggSup->resultRowSize, &defaultPgsz, &defaultBufsz);
H
Haojun Liao 已提交
2905

wafwerar's avatar
wafwerar 已提交
2906
  if (!osTempSpaceAvailable()) {
H
Haojun Liao 已提交
2907 2908 2909
    code = TSDB_CODE_NO_AVAIL_DISK;
    qError("Init stream agg supporter failed since %s, %s", terrstr(code), pKey);
    return code;
wafwerar's avatar
wafwerar 已提交
2910
  }
2911

H
Haojun Liao 已提交
2912
  code = createDiskbasedBuf(&pAggSup->pResultBuf, defaultPgsz, defaultBufsz, pKey, tsTempDir);
H
Haojun Liao 已提交
2913
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2914
    qError("Create agg result buf failed since %s, %s", tstrerror(code), pKey);
H
Haojun Liao 已提交
2915 2916 2917
    return code;
  }

H
Haojun Liao 已提交
2918
  return code;
2919 2920
}

2921
void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
2922
  taosMemoryFreeClear(pAggSup->keyBuf);
2923
  tSimpleHashCleanup(pAggSup->pResultRowHashTable);
H
Haojun Liao 已提交
2924
  destroyDiskbasedBuf(pAggSup->pResultBuf);
2925 2926
}

L
Liu Jicong 已提交
2927 2928
int32_t initAggInfo(SExprSupp* pSup, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols, size_t keyBufSize,
                    const char* pkey) {
2929 2930 2931 2932 2933
  int32_t code = initExprSupp(pSup, pExprInfo, numOfCols);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

2934 2935 2936 2937 2938
  code = doInitAggInfoSup(pAggSup, pSup->pCtx, numOfCols, keyBufSize, pkey);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

L
Liu Jicong 已提交
2939
  for (int32_t i = 0; i < numOfCols; ++i) {
2940
    pSup->pCtx[i].saveHandle.pBuf = pAggSup->pResultBuf;
2941 2942
  }

2943
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2944 2945
}

L
Liu Jicong 已提交
2946
void initResultSizeInfo(SResultInfo* pResultInfo, int32_t numOfRows) {
wmmhello's avatar
wmmhello 已提交
2947
  ASSERT(numOfRows != 0);
2948 2949
  pResultInfo->capacity = numOfRows;
  pResultInfo->threshold = numOfRows * 0.75;
2950

2951 2952
  if (pResultInfo->threshold == 0) {
    pResultInfo->threshold = numOfRows;
2953 2954 2955
  }
}

2956 2957 2958 2959 2960
void initBasicInfo(SOptrBasicInfo* pInfo, SSDataBlock* pBlock) {
  pInfo->pRes = pBlock;
  initResultRowInfo(&pInfo->resultRowInfo);
}

5
54liuyao 已提交
2961
void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
2962 2963 2964 2965 2966 2967 2968 2969 2970 2971
  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);
2972
    taosMemoryFreeClear(pCtx[i].subsidiaries.buf);
2973 2974 2975 2976 2977 2978 2979 2980
    taosMemoryFree(pCtx[i].input.pData);
    taosMemoryFree(pCtx[i].input.pColumnDataAgg);
  }

  taosMemoryFreeClear(pCtx);
  return NULL;
}

2981
int32_t initExprSupp(SExprSupp* pSup, SExprInfo* pExprInfo, int32_t numOfExpr) {
2982 2983 2984 2985
  pSup->pExprInfo = pExprInfo;
  pSup->numOfExprs = numOfExpr;
  if (pSup->pExprInfo != NULL) {
    pSup->pCtx = createSqlFunctionCtx(pExprInfo, numOfExpr, &pSup->rowEntryInfoOffset);
2986 2987 2988
    if (pSup->pCtx == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
2989
  }
2990 2991

  return TSDB_CODE_SUCCESS;
2992 2993
}

2994 2995 2996 2997
void cleanupExprSupp(SExprSupp* pSupp) {
  destroySqlFunctionCtx(pSupp->pCtx, pSupp->numOfExprs);
  if (pSupp->pExprInfo != NULL) {
    destroyExprInfo(pSupp->pExprInfo, pSupp->numOfExprs);
C
Cary Xu 已提交
2998
    taosMemoryFreeClear(pSupp->pExprInfo);
2999 3000 3001 3002
  }
  taosMemoryFree(pSupp->rowEntryInfoOffset);
}

L
Liu Jicong 已提交
3003
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
S
slzhou 已提交
3004
                                           SSDataBlock* pResultBlock, SNode* pCondition, SExprInfo* pScalarExprInfo,
3005
                                           int32_t numOfScalarExpr, bool mergeResult, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
3006
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
3007
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
3008 3009 3010
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
3011

dengyihao's avatar
dengyihao 已提交
3012
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
3013

3014
  initResultSizeInfo(&pOperator->resultInfo, 4096);
3015
  int32_t code = initAggInfo(&pOperator->exprSupp, &pInfo->aggSup, pExprInfo, numOfCols, keyBufSize, pTaskInfo->id.str);
L
Liu Jicong 已提交
3016
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3017 3018
    goto _error;
  }
H
Haojun Liao 已提交
3019

3020
  initBasicInfo(&pInfo->binfo, pResultBlock);
3021 3022 3023 3024
  code = initExprSupp(&pInfo->scalarExprSup, pScalarExprInfo, numOfScalarExpr);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
3025

3026
  pInfo->binfo.mergeResultBlock = mergeResult;
3027
  pInfo->groupId = UINT64_MAX;
S
slzhou 已提交
3028
  pInfo->pCondition = pCondition;
dengyihao's avatar
dengyihao 已提交
3029
  pOperator->name = "TableAggregate";
3030
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_HASH_AGG;
3031
  pOperator->blocking = true;
dengyihao's avatar
dengyihao 已提交
3032 3033 3034
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
3035

3036 3037
  pOperator->fpSet = createOperatorFpSet(doOpenAggregateOptr, getAggregateResult, NULL, NULL, destroyAggOperatorInfo,
                                         aggEncodeResultRow, aggDecodeResultRow, NULL);
H
Haojun Liao 已提交
3038

3039 3040 3041 3042 3043 3044
  if (downstream->operatorType == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
    STableScanInfo* pTableScanInfo = downstream->info;
    pTableScanInfo->pdInfo.pExprSup = &pOperator->exprSupp;
    pTableScanInfo->pdInfo.pAggSup = &pInfo->aggSup;
  }

H
Haojun Liao 已提交
3045 3046 3047 3048
  code = appendDownstream(pOperator, &downstream, 1);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
3049 3050

  return pOperator;
L
Liu Jicong 已提交
3051
_error:
3052
  destroyAggOperatorInfo(pInfo);
wafwerar's avatar
wafwerar 已提交
3053
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
3054 3055
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
3056 3057
}

3058
void cleanupBasicInfo(SOptrBasicInfo* pInfo) {
3059
  assert(pInfo != NULL);
H
Haojun Liao 已提交
3060
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
3061 3062
}

H
Haojun Liao 已提交
3063 3064 3065 3066 3067 3068 3069
static void freeItem(void* pItem) {
  void** p = pItem;
  if (*p != NULL) {
    taosMemoryFreeClear(*p);
  }
}

3070
void destroyAggOperatorInfo(void* param) {
L
Liu Jicong 已提交
3071
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
L
Liu Jicong 已提交
3072 3073
  cleanupBasicInfo(&pInfo->binfo);

H
Haojun Liao 已提交
3074
  cleanupAggSup(&pInfo->aggSup);
S
shenglian zhou 已提交
3075
  cleanupExprSupp(&pInfo->scalarExprSup);
H
Haojun Liao 已提交
3076
  cleanupGroupResInfo(&pInfo->groupResInfo);
D
dapan1121 已提交
3077
  taosMemoryFreeClear(param);
3078
}
3079

3080
void destroyFillOperatorInfo(void* param) {
L
Liu Jicong 已提交
3081
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
3082
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
3083
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
H
Haojun Liao 已提交
3084 3085 3086 3087 3088 3089 3090
  pInfo->pFinalRes = blockDataDestroy(pInfo->pFinalRes);

  if (pInfo->pNotFillExprInfo != NULL) {
    destroyExprInfo(pInfo->pNotFillExprInfo, pInfo->numOfNotFillExpr);
    taosMemoryFree(pInfo->pNotFillExprInfo);
  }

wafwerar's avatar
wafwerar 已提交
3091
  taosMemoryFreeClear(pInfo->p);
3092
  taosArrayDestroy(pInfo->pColMatchColInfo);
D
dapan1121 已提交
3093
  taosMemoryFreeClear(param);
3094 3095
}

3096
void destroyExchangeOperatorInfo(void* param) {
L
Liu Jicong 已提交
3097
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
3098 3099 3100
  taosRemoveRef(exchangeObjRefPool, pExInfo->self);
}

L
Liu Jicong 已提交
3101
void freeSourceDataInfo(void* p) {
3102 3103 3104 3105
  SSourceDataInfo* pInfo = (SSourceDataInfo*)p;
  taosMemoryFreeClear(pInfo->pRsp);
}

3106
void doDestroyExchangeOperatorInfo(void* param) {
X
Xiaoyu Wang 已提交
3107
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
3108

H
Haojun Liao 已提交
3109
  taosArrayDestroy(pExInfo->pSources);
3110
  taosArrayDestroyEx(pExInfo->pSourceDataInfo, freeSourceDataInfo);
3111 3112 3113 3114

  if (pExInfo->pResultBlockList != NULL) {
    taosArrayDestroyEx(pExInfo->pResultBlockList, freeBlock);
    pExInfo->pResultBlockList = NULL;
H
Haojun Liao 已提交
3115 3116
  }

3117
  blockDataDestroy(pExInfo->pDummyBlock);
L
Liu Jicong 已提交
3118

3119
  tsem_destroy(&pExInfo->ready);
D
dapan1121 已提交
3120
  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
3121 3122
}

H
Haojun Liao 已提交
3123 3124 3125 3126
static int32_t initFillInfo(SFillOperatorInfo* pInfo, SExprInfo* pExpr, int32_t numOfCols, SExprInfo* pNotFillExpr,
                            int32_t numOfNotFillCols, SNodeListNode* pValNode, STimeWindow win, int32_t capacity,
                            const char* id, SInterval* pInterval, int32_t fillType, int32_t order) {
  SFillColInfo* pColInfo = createFillColInfo(pExpr, numOfCols, pNotFillExpr, numOfNotFillCols, pValNode);
H
Haojun Liao 已提交
3127

H
Haojun Liao 已提交
3128 3129 3130
  int64_t     startKey = (order == TSDB_ORDER_ASC) ? win.skey : win.ekey;
  STimeWindow w = getAlignQueryTimeWindow(pInterval, pInterval->precision, startKey);
  w = getFirstQualifiedTimeWindow(startKey, &w, pInterval, order);
H
Haojun Liao 已提交
3131

L
Liu Jicong 已提交
3132 3133
  pInfo->pFillInfo = taosCreateFillInfo(w.skey, numOfCols, numOfNotFillCols, capacity, pInterval, fillType, pColInfo,
                                        pInfo->primaryTsCol, order, id);
H
Haojun Liao 已提交
3134

H
Haojun Liao 已提交
3135 3136 3137 3138 3139 3140 3141
  if (order == TSDB_ORDER_ASC) {
    pInfo->win.skey = win.skey;
    pInfo->win.ekey = win.ekey;
  } else {
    pInfo->win.skey = win.ekey;
    pInfo->win.ekey = win.skey;
  }
L
Liu Jicong 已提交
3142
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
3143

H
Haojun Liao 已提交
3144
  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
H
Haojun Liao 已提交
3145 3146
    taosMemoryFree(pInfo->pFillInfo);
    taosMemoryFree(pInfo->p);
H
Haojun Liao 已提交
3147 3148 3149 3150 3151 3152
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

3153 3154 3155 3156 3157 3158
static bool isWstartColumnExist(SFillOperatorInfo* pInfo) {
  if (pInfo->numOfNotFillExpr == 0) {
    return false;
  }
  for (int32_t i = 0; i < pInfo->numOfNotFillExpr; ++i) {
    SExprInfo* exprInfo = pInfo->pNotFillExprInfo + i;
3159
    if (exprInfo->pExpr->nodeType == QUERY_NODE_COLUMN && exprInfo->base.numOfParams == 1 &&
3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174
        exprInfo->base.pParam[0].pCol->colType == COLUMN_TYPE_WINDOW_START) {
      return true;
    }
  }
  return false;
}

static int32_t createWStartTsAsNotFillExpr(SFillOperatorInfo* pInfo, SFillPhysiNode* pPhyFillNode) {
  bool wstartExist = isWstartColumnExist(pInfo);
  if (wstartExist == false) {
    if (pPhyFillNode->pWStartTs->type != QUERY_NODE_TARGET) {
      qError("pWStartTs of fill physical node is not a target node");
      return TSDB_CODE_QRY_SYS_ERROR;
    }

3175 3176
    SExprInfo* notFillExprs =
        taosMemoryRealloc(pInfo->pNotFillExprInfo, (pInfo->numOfNotFillExpr + 1) * sizeof(SExprInfo));
3177 3178 3179 3180 3181 3182 3183 3184 3185 3186
    if (notFillExprs == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }

    createExprFromTargetNode(notFillExprs + pInfo->numOfNotFillExpr, (STargetNode*)pPhyFillNode->pWStartTs);

    ++pInfo->numOfNotFillExpr;
    pInfo->pNotFillExprInfo = notFillExprs;
    return TSDB_CODE_SUCCESS;
  }
3187

3188 3189 3190
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
3191 3192
SOperatorInfo* createFillOperatorInfo(SOperatorInfo* downstream, SFillPhysiNode* pPhyFillNode,
                                      SExecTaskInfo* pTaskInfo) {
3193 3194 3195 3196 3197 3198
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

L
Liu Jicong 已提交
3199
  SSDataBlock* pResBlock = createResDataBlock(pPhyFillNode->node.pOutputDataBlockDesc);
3200
  SExprInfo*   pExprInfo = createExprInfo(pPhyFillNode->pFillExprs, NULL, &pInfo->numOfExpr);
H
Haojun Liao 已提交
3201
  pInfo->pNotFillExprInfo = createExprInfo(pPhyFillNode->pNotFillExprs, NULL, &pInfo->numOfNotFillExpr);
3202 3203 3204 3205
  int32_t code = createWStartTsAsNotFillExpr(pInfo, pPhyFillNode);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
L
Liu Jicong 已提交
3206
  SInterval* pInterval =
3207
      QUERY_NODE_PHYSICAL_PLAN_MERGE_ALIGNED_INTERVAL == downstream->operatorType
L
Liu Jicong 已提交
3208 3209
          ? &((SMergeAlignedIntervalAggOperatorInfo*)downstream->info)->intervalAggOperatorInfo->interval
          : &((SIntervalAggOperatorInfo*)downstream->info)->interval;
3210

3211
  int32_t order = (pPhyFillNode->inputTsOrder == ORDER_ASC) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
3212
  int32_t type = convertFillType(pPhyFillNode->mode);
3213

H
Haojun Liao 已提交
3214
  SResultInfo* pResultInfo = &pOperator->resultInfo;
3215
  initResultSizeInfo(&pOperator->resultInfo, 4096);
H
Haojun Liao 已提交
3216
  blockDataEnsureCapacity(pResBlock, pOperator->resultInfo.capacity);
3217
  initExprSupp(&pOperator->exprSupp, pExprInfo, pInfo->numOfExpr);
H
Haojun Liao 已提交
3218

H
Haojun Liao 已提交
3219 3220
  pInfo->primaryTsCol = ((STargetNode*)pPhyFillNode->pWStartTs)->slotId;
  pInfo->primarySrcSlotId = ((SColumnNode*)((STargetNode*)pPhyFillNode->pWStartTs)->pExpr)->slotId;
3221

3222
  int32_t numOfOutputCols = 0;
3223
  SArray* pColMatchColInfo = extractColMatchInfo(pPhyFillNode->pFillExprs, pPhyFillNode->node.pOutputDataBlockDesc,
3224
                                                 &numOfOutputCols, COL_MATCH_FROM_SLOT_ID);
3225

3226
  code = initFillInfo(pInfo, pExprInfo, pInfo->numOfExpr, pInfo->pNotFillExprInfo, pInfo->numOfNotFillExpr,
3227 3228
                      (SNodeListNode*)pPhyFillNode->pValues, pPhyFillNode->timeRange, pResultInfo->capacity,
                      pTaskInfo->id.str, pInterval, type, order);
3229 3230 3231
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
3232

3233
  pInfo->pRes = pResBlock;
H
Haojun Liao 已提交
3234 3235 3236
  pInfo->pFinalRes = createOneDataBlock(pResBlock, false);
  blockDataEnsureCapacity(pInfo->pFinalRes, pOperator->resultInfo.capacity);

3237 3238 3239 3240 3241 3242 3243
  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;
3244
  pOperator->exprSupp.numOfExprs = pInfo->numOfExpr;
3245 3246
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
3247

L
Liu Jicong 已提交
3248
  pOperator->fpSet =
3249
      createOperatorFpSet(operatorDummyOpenFn, doFill, NULL, NULL, destroyFillOperatorInfo, NULL, NULL, NULL);
3250

3251
  code = appendDownstream(pOperator, &downstream, 1);
3252
  return pOperator;
H
Haojun Liao 已提交
3253

L
Liu Jicong 已提交
3254
_error:
wafwerar's avatar
wafwerar 已提交
3255 3256
  taosMemoryFreeClear(pOperator);
  taosMemoryFreeClear(pInfo);
H
Haojun Liao 已提交
3257
  return NULL;
3258 3259
}

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

3264
  pTaskInfo->schemaInfo.dbname = strdup(dbFName);
3265
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
3266
  pTaskInfo->id.queryId = queryId;
dengyihao's avatar
dengyihao 已提交
3267
  pTaskInfo->execModel = model;
H
Haojun Liao 已提交
3268

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

3273 3274
  return pTaskInfo;
}
H
Haojun Liao 已提交
3275

H
Haojun Liao 已提交
3276
static SArray* extractColumnInfo(SNodeList* pNodeList);
3277

H
Haojun Liao 已提交
3278 3279
SSchemaWrapper* extractQueriedColumnSchema(SScanPhysiNode* pScanNode);

3280
int32_t extractTableSchemaInfo(SReadHandle* pHandle, SScanPhysiNode* pScanNode, SExecTaskInfo* pTaskInfo) {
3281 3282
  SMetaReader mr = {0};
  metaReaderInit(&mr, pHandle->meta, 0);
3283
  int32_t code = metaGetTableEntryByUid(&mr, pScanNode->uid);
3284
  if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
3285 3286
    qError("failed to get the table meta, uid:0x%" PRIx64 ", suid:0x%" PRIx64 ", %s", pScanNode->uid, pScanNode->suid,
           GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
3287

D
dapan1121 已提交
3288
    metaReaderClear(&mr);
3289
    return terrno;
D
dapan1121 已提交
3290
  }
3291

3292 3293
  SSchemaInfo* pSchemaInfo = &pTaskInfo->schemaInfo;
  pSchemaInfo->tablename = strdup(mr.me.name);
3294 3295

  if (mr.me.type == TSDB_SUPER_TABLE) {
3296 3297
    pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.stbEntry.schemaRow);
    pSchemaInfo->tversion = mr.me.stbEntry.schemaTag.version;
3298
  } else if (mr.me.type == TSDB_CHILD_TABLE) {
3299 3300
    tDecoderClear(&mr.coder);

3301 3302
    tb_uid_t suid = mr.me.ctbEntry.suid;
    metaGetTableEntryByUid(&mr, suid);
3303 3304
    pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.stbEntry.schemaRow);
    pSchemaInfo->tversion = mr.me.stbEntry.schemaTag.version;
3305
  } else {
3306
    pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.ntbEntry.schemaRow);
3307
  }
3308 3309

  metaReaderClear(&mr);
3310

H
Haojun Liao 已提交
3311 3312 3313 3314 3315
  pSchemaInfo->qsw = extractQueriedColumnSchema(pScanNode);
  return TSDB_CODE_SUCCESS;
}

SSchemaWrapper* extractQueriedColumnSchema(SScanPhysiNode* pScanNode) {
3316 3317 3318
  int32_t numOfCols = LIST_LENGTH(pScanNode->pScanCols);
  int32_t numOfTags = LIST_LENGTH(pScanNode->pScanPseudoCols);

3319
  SSchemaWrapper* pqSw = taosMemoryCalloc(1, sizeof(SSchemaWrapper));
3320
  pqSw->pSchema = taosMemoryCalloc(numOfCols + numOfTags, sizeof(SSchema));
3321

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

H
Haojun Liao 已提交
3326 3327 3328 3329 3330
    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));
3331 3332
  }

3333
  // this the tags and pseudo function columns, we only keep the tag columns
3334
  for (int32_t i = 0; i < numOfTags; ++i) {
3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348
    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 已提交
3349
  return pqSw;
3350 3351
}

3352 3353
static void cleanupTableSchemaInfo(SSchemaInfo* pSchemaInfo) {
  taosMemoryFreeClear(pSchemaInfo->dbname);
3354
  taosMemoryFreeClear(pSchemaInfo->tablename);
3355 3356
  tDeleteSSchemaWrapper(pSchemaInfo->sw);
  tDeleteSSchemaWrapper(pSchemaInfo->qsw);
3357 3358
}

3359 3360 3361 3362
static void cleanupStreamInfo(SStreamTaskInfo* pStreamInfo) {
  tDeleteSSchemaWrapper(pStreamInfo->schema);
}

H
Haojun Liao 已提交
3363
static int32_t sortTableGroup(STableListInfo* pTableListInfo) {
wmmhello's avatar
wmmhello 已提交
3364
  taosArrayClear(pTableListInfo->pGroupList);
H
Haojun Liao 已提交
3365
  SArray* sortSupport = taosArrayInit(16, sizeof(uint64_t));
3366
  if (sortSupport == NULL) return TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
3367 3368
  for (int32_t i = 0; i < taosArrayGetSize(pTableListInfo->pTableList); i++) {
    STableKeyInfo* info = taosArrayGet(pTableListInfo->pTableList, i);
3369
    uint64_t*      groupId = taosHashGet(pTableListInfo->map, &info->uid, sizeof(uint64_t));
wmmhello's avatar
wmmhello 已提交
3370 3371

    int32_t index = taosArraySearchIdx(sortSupport, groupId, compareUint64Val, TD_EQ);
3372 3373 3374 3375
    if (index == -1) {
      void*   p = taosArraySearch(sortSupport, groupId, compareUint64Val, TD_GT);
      SArray* tGroup = taosArrayInit(8, sizeof(STableKeyInfo));
      if (tGroup == NULL) {
wmmhello's avatar
wmmhello 已提交
3376 3377 3378
        taosArrayDestroy(sortSupport);
        return TSDB_CODE_OUT_OF_MEMORY;
      }
3379
      if (taosArrayPush(tGroup, info) == NULL) {
wmmhello's avatar
wmmhello 已提交
3380 3381 3382 3383
        qError("taos push info array error");
        taosArrayDestroy(sortSupport);
        return TSDB_CODE_QRY_APP_ERROR;
      }
3384
      if (p == NULL) {
wmmhello's avatar
wmmhello 已提交
3385
        if (taosArrayPush(sortSupport, groupId) == NULL) {
wmmhello's avatar
wmmhello 已提交
3386 3387 3388 3389
          qError("taos push support array error");
          taosArrayDestroy(sortSupport);
          return TSDB_CODE_QRY_APP_ERROR;
        }
wmmhello's avatar
wmmhello 已提交
3390
        if (taosArrayPush(pTableListInfo->pGroupList, &tGroup) == NULL) {
wmmhello's avatar
wmmhello 已提交
3391 3392 3393 3394
          qError("taos push group array error");
          taosArrayDestroy(sortSupport);
          return TSDB_CODE_QRY_APP_ERROR;
        }
3395
      } else {
wmmhello's avatar
wmmhello 已提交
3396
        int32_t pos = TARRAY_ELEM_IDX(sortSupport, p);
3397
        if (taosArrayInsert(sortSupport, pos, groupId) == NULL) {
wmmhello's avatar
wmmhello 已提交
3398 3399 3400 3401
          qError("taos insert support array error");
          taosArrayDestroy(sortSupport);
          return TSDB_CODE_QRY_APP_ERROR;
        }
3402
        if (taosArrayInsert(pTableListInfo->pGroupList, pos, &tGroup) == NULL) {
wmmhello's avatar
wmmhello 已提交
3403 3404 3405 3406 3407
          qError("taos insert group array error");
          taosArrayDestroy(sortSupport);
          return TSDB_CODE_QRY_APP_ERROR;
        }
      }
3408
    } else {
wmmhello's avatar
wmmhello 已提交
3409
      SArray* tGroup = (SArray*)taosArrayGetP(pTableListInfo->pGroupList, index);
3410
      if (taosArrayPush(tGroup, info) == NULL) {
wmmhello's avatar
wmmhello 已提交
3411 3412 3413 3414 3415 3416 3417 3418 3419 3420
        qError("taos push uid array error");
        taosArrayDestroy(sortSupport);
        return TSDB_CODE_QRY_APP_ERROR;
      }
    }
  }
  taosArrayDestroy(sortSupport);
  return TDB_CODE_SUCCESS;
}

3421
bool groupbyTbname(SNodeList* pGroupList) {
3422
  bool bytbname = false;
H
Haojun Liao 已提交
3423
  if (LIST_LENGTH(pGroupList) > 0) {
3424 3425 3426 3427 3428 3429 3430 3431 3432 3433
    SNode* p = nodesListGetNode(pGroupList, 0);
    if (p->type == QUERY_NODE_FUNCTION) {
      // partition by tbname/group by tbname
      bytbname = (strcmp(((struct SFunctionNode*)p)->functionName, "tbname") == 0);
    }
  }

  return bytbname;
}

wmmhello's avatar
wmmhello 已提交
3434 3435
int32_t generateGroupIdMap(STableListInfo* pTableListInfo, SReadHandle* pHandle, SNodeList* group) {
  if (group == NULL) {
wmmhello's avatar
wmmhello 已提交
3436 3437 3438 3439 3440 3441 3442 3443
    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;
  }

3444 3445
  bool assignUid = groupbyTbname(group);

H
Haojun Liao 已提交
3446
  size_t numOfTables = taosArrayGetSize(pTableListInfo->pTableList);
3447

H
Haojun Liao 已提交
3448 3449 3450
  if (assignUid) {
    for (int32_t i = 0; i < numOfTables; i++) {
      STableKeyInfo* info = taosArrayGet(pTableListInfo->pTableList, i);
3451
      info->groupId = info->uid;
H
Haojun Liao 已提交
3452 3453 3454 3455 3456 3457
      taosHashPut(pTableListInfo->map, &(info->uid), sizeof(uint64_t), &info->groupId, sizeof(uint64_t));
    }
  } else {
    int32_t code = getColInfoResultForGroupby(pHandle->meta, group, pTableListInfo);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
wmmhello's avatar
wmmhello 已提交
3458 3459
    }
  }
3460

3461
  if (pTableListInfo->needSortTableByGroupId) {
H
Haojun Liao 已提交
3462
    return sortTableGroup(pTableListInfo);
3463 3464
  }

wmmhello's avatar
wmmhello 已提交
3465 3466 3467
  return TDB_CODE_SUCCESS;
}

3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484
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;
3485
  pCond->type = TIMEWINDOW_RANGE_CONTAINED;
3486
  pCond->startVersion = -1;
L
Liu Jicong 已提交
3487
  pCond->endVersion = -1;
3488 3489 3490 3491

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
3492
SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle,
L
Liu Jicong 已提交
3493 3494
                                  STableListInfo* pTableListInfo, SNode* pTagCond, SNode* pTagIndexCond,
                                  const char* pUser) {
3495 3496
  int32_t type = nodeType(pPhyNode);

X
Xiaoyu Wang 已提交
3497
  if (pPhyNode->pChildren == NULL || LIST_LENGTH(pPhyNode->pChildren) == 0) {
3498
    SOperatorInfo* pOperator = NULL;
H
Haojun Liao 已提交
3499
    if (QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN == type) {
dengyihao's avatar
dengyihao 已提交
3500
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
3501

L
Liu Jicong 已提交
3502 3503 3504
      int32_t code =
          createScanTableListInfo(&pTableScanNode->scan, pTableScanNode->pGroupTags, pTableScanNode->groupSort, pHandle,
                                  pTableListInfo, pTagCond, pTagIndexCond, GET_TASKID(pTaskInfo));
3505
      if (code) {
wmmhello's avatar
wmmhello 已提交
3506
        pTaskInfo->code = code;
3507
        qError("failed to createScanTableListInfo, code:%s, %s", tstrerror(code), GET_TASKID(pTaskInfo));
D
dapan1121 已提交
3508 3509
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
3510

3511
      code = extractTableSchemaInfo(pHandle, &pTableScanNode->scan, pTaskInfo);
S
slzhou 已提交
3512
      if (code) {
3513
        pTaskInfo->code = terrno;
wmmhello's avatar
wmmhello 已提交
3514 3515 3516
        return NULL;
      }

3517
      pOperator = createTableScanOperatorInfo(pTableScanNode, pHandle, pTaskInfo);
3518 3519
      STableScanInfo* pScanInfo = pOperator->info;
      pTaskInfo->cost.pRecoder = &pScanInfo->readRecorder;
S
slzhou 已提交
3520 3521
    } else if (QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN == type) {
      STableMergeScanPhysiNode* pTableScanNode = (STableMergeScanPhysiNode*)pPhyNode;
L
Liu Jicong 已提交
3522 3523 3524
      int32_t                   code =
          createScanTableListInfo(&pTableScanNode->scan, pTableScanNode->pGroupTags, pTableScanNode->groupSort, pHandle,
                                  pTableListInfo, pTagCond, pTagIndexCond, GET_TASKID(pTaskInfo));
L
Liu Jicong 已提交
3525
      if (code) {
wmmhello's avatar
wmmhello 已提交
3526
        pTaskInfo->code = code;
H
Haojun Liao 已提交
3527
        qError("failed to createScanTableListInfo, code: %s", tstrerror(code));
wmmhello's avatar
wmmhello 已提交
3528 3529
        return NULL;
      }
3530

3531
      code = extractTableSchemaInfo(pHandle, &pTableScanNode->scan, pTaskInfo);
wmmhello's avatar
wmmhello 已提交
3532 3533 3534 3535
      if (code) {
        pTaskInfo->code = terrno;
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
3536

3537
      pOperator = createTableMergeScanOperatorInfo(pTableScanNode, pTableListInfo, pHandle, pTaskInfo);
wmmhello's avatar
wmmhello 已提交
3538

3539 3540
      STableScanInfo* pScanInfo = pOperator->info;
      pTaskInfo->cost.pRecoder = &pScanInfo->readRecorder;
H
Haojun Liao 已提交
3541
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == type) {
D
dapan1121 已提交
3542
      pOperator = createExchangeOperatorInfo(pHandle ? pHandle->pMsgCb->clientRpc : NULL, (SExchangePhysiNode*)pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
3543
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == type) {
5
54liuyao 已提交
3544
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
5
54liuyao 已提交
3545
      if (pHandle->vnode) {
L
Liu Jicong 已提交
3546 3547 3548
        int32_t code =
            createScanTableListInfo(&pTableScanNode->scan, pTableScanNode->pGroupTags, pTableScanNode->groupSort,
                                    pHandle, pTableListInfo, pTagCond, pTagIndexCond, GET_TASKID(pTaskInfo));
L
Liu Jicong 已提交
3549
        if (code) {
wmmhello's avatar
wmmhello 已提交
3550
          pTaskInfo->code = code;
H
Haojun Liao 已提交
3551
          qError("failed to createScanTableListInfo, code: %s", tstrerror(code));
wmmhello's avatar
wmmhello 已提交
3552 3553
          return NULL;
        }
L
Liu Jicong 已提交
3554 3555 3556 3557 3558

#ifndef NDEBUG
        int32_t sz = taosArrayGetSize(pTableListInfo->pTableList);
        for (int32_t i = 0; i < sz; i++) {
          STableKeyInfo* pKeyInfo = taosArrayGet(pTableListInfo->pTableList, i);
S
Shengliang Guan 已提交
3559
          qDebug("creating stream task: add table %" PRId64, pKeyInfo->uid);
L
Liu Jicong 已提交
3560 3561
        }
#endif
3562
      }
3563

H
Haojun Liao 已提交
3564
      pTaskInfo->schemaInfo.qsw = extractQueriedColumnSchema(&pTableScanNode->scan);
3565
      pOperator = createStreamScanOperatorInfo(pHandle, pTableScanNode, pTagCond, pTaskInfo);
H
Haojun Liao 已提交
3566
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == type) {
L
Liu Jicong 已提交
3567
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
3568
      pOperator = createSysTableScanOperatorInfo(pHandle, pSysScanPhyNode, pUser, pTaskInfo);
3569
    } else if (QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN == type) {
X
Xiaoyu Wang 已提交
3570
      STagScanPhysiNode* pScanPhyNode = (STagScanPhysiNode*)pPhyNode;
3571
      int32_t code = getTableList(pHandle->meta, pHandle->vnode, pScanPhyNode, pTagCond, pTagIndexCond, pTableListInfo);
3572
      if (code != TSDB_CODE_SUCCESS) {
3573
        pTaskInfo->code = code;
H
Haojun Liao 已提交
3574
        qError("failed to getTableList, code: %s", tstrerror(code));
3575 3576 3577
        return NULL;
      }

3578
      pOperator = createTagScanOperatorInfo(pHandle, pScanPhyNode, pTableListInfo, pTaskInfo);
3579
    } else if (QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN == type) {
3580
      SBlockDistScanPhysiNode* pBlockNode = (SBlockDistScanPhysiNode*)pPhyNode;
3581 3582 3583
      pTableListInfo->pTableList = taosArrayInit(4, sizeof(STableKeyInfo));

      if (pBlockNode->tableType == TSDB_SUPER_TABLE) {
3584
        int32_t code = vnodeGetAllTableList(pHandle->vnode, pBlockNode->uid, pTableListInfo->pTableList);
3585 3586 3587 3588 3589
        if (code != TSDB_CODE_SUCCESS) {
          pTaskInfo->code = terrno;
          return NULL;
        }
      } else {  // Create one table group.
3590
        STableKeyInfo info = {.uid = pBlockNode->uid, .groupId = 0};
3591 3592 3593 3594
        taosArrayPush(pTableListInfo->pTableList, &info);
      }

      SQueryTableDataCond cond = {0};
L
Liu Jicong 已提交
3595
      int32_t             code = initTableblockDistQueryCond(pBlockNode->suid, &cond);
3596 3597
      if (code != TSDB_CODE_SUCCESS) {
        return NULL;
3598
      }
H
Haojun Liao 已提交
3599 3600 3601

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

3604
      pOperator = createDataBlockInfoScanOperator(pReader, pHandle, cond.suid, pBlockNode, pTaskInfo);
H
Haojun Liao 已提交
3605 3606 3607
    } else if (QUERY_NODE_PHYSICAL_PLAN_LAST_ROW_SCAN == type) {
      SLastRowScanPhysiNode* pScanNode = (SLastRowScanPhysiNode*)pPhyNode;

L
Liu Jicong 已提交
3608 3609
      int32_t code = createScanTableListInfo(&pScanNode->scan, pScanNode->pGroupTags, true, pHandle, pTableListInfo,
                                             pTagCond, pTagIndexCond, GET_TASKID(pTaskInfo));
3610 3611 3612 3613
      if (code != TSDB_CODE_SUCCESS) {
        pTaskInfo->code = code;
        return NULL;
      }
3614

3615
      code = extractTableSchemaInfo(pHandle, &pScanNode->scan, pTaskInfo);
3616 3617 3618
      if (code != TSDB_CODE_SUCCESS) {
        pTaskInfo->code = code;
        return NULL;
H
Haojun Liao 已提交
3619 3620
      }

3621
      pOperator = createCacherowsScanOperator(pScanNode, pHandle, pTaskInfo);
3622
    } else if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
3623
      pOperator = createProjectOperatorInfo(NULL, (SProjectPhysiNode*)pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
3624 3625
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
3626
    }
3627 3628 3629 3630 3631

    if (pOperator != NULL) {
      pOperator->resultDataBlockId = pPhyNode->pOutputDataBlockDesc->dataBlockId;
    }

3632
    return pOperator;
H
Haojun Liao 已提交
3633 3634
  }

3635 3636
  int32_t num = 0;
  size_t  size = LIST_LENGTH(pPhyNode->pChildren);
H
Haojun Liao 已提交
3637

3638
  SOperatorInfo** ops = taosMemoryCalloc(size, POINTER_BYTES);
dengyihao's avatar
dengyihao 已提交
3639
  for (int32_t i = 0; i < size; ++i) {
3640
    SPhysiNode* pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
3641
    ops[i] = createOperatorTree(pChildNode, pTaskInfo, pHandle, pTableListInfo, pTagCond, pTagIndexCond, pUser);
3642
    if (ops[i] == NULL) {
H
Haojun Liao 已提交
3643
      taosMemoryFree(ops);
3644 3645
      return NULL;
    }
3646 3647

    ops[i]->resultDataBlockId = pChildNode->pOutputDataBlockDesc->dataBlockId;
3648
  }
H
Haojun Liao 已提交
3649

3650
  SOperatorInfo* pOptr = NULL;
H
Haojun Liao 已提交
3651
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
3652
    pOptr = createProjectOperatorInfo(ops[0], (SProjectPhysiNode*)pPhyNode, pTaskInfo);
3653
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_AGG == type) {
H
Haojun Liao 已提交
3654 3655
    SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
    SExprInfo*     pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
3656
    SSDataBlock*   pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
3657

dengyihao's avatar
dengyihao 已提交
3658
    int32_t    numOfScalarExpr = 0;
3659 3660 3661 3662 3663
    SExprInfo* pScalarExprInfo = NULL;
    if (pAggNode->pExprs != NULL) {
      pScalarExprInfo = createExprInfo(pAggNode->pExprs, NULL, &numOfScalarExpr);
    }

H
Haojun Liao 已提交
3664 3665
    if (pAggNode->pGroupKeys != NULL) {
      SArray* pColList = extractColumnInfo(pAggNode->pGroupKeys);
dengyihao's avatar
dengyihao 已提交
3666
      pOptr = createGroupOperatorInfo(ops[0], pExprInfo, num, pResBlock, pColList, pAggNode->node.pConditions,
wmmhello's avatar
wmmhello 已提交
3667
                                      pScalarExprInfo, numOfScalarExpr, pTaskInfo);
H
Haojun Liao 已提交
3668
    } else {
L
Liu Jicong 已提交
3669
      pOptr = createAggregateOperatorInfo(ops[0], pExprInfo, num, pResBlock, pAggNode->node.pConditions,
3670
                                          pScalarExprInfo, numOfScalarExpr, pAggNode->mergeDataBlock, pTaskInfo);
H
Haojun Liao 已提交
3671
    }
3672
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_INTERVAL == type) {
H
Haojun Liao 已提交
3673
    SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
3674

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

dengyihao's avatar
dengyihao 已提交
3678 3679 3680 3681 3682 3683
    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 已提交
3684

X
Xiaoyu Wang 已提交
3685 3686 3687 3688 3689
    STimeWindowAggSupp as = {
        .waterMark = pIntervalPhyNode->window.watermark,
        .calTrigger = pIntervalPhyNode->window.triggerType,
        .maxTs = INT64_MIN,
    };
3690
    ASSERT(as.calTrigger != STREAM_TRIGGER_MAX_DELAY);
3691

3692
    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
L
Liu Jicong 已提交
3693
    bool    isStream = (QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type);
3694 3695
    pOptr = createIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId, &as, pIntervalPhyNode,
                                       pTaskInfo, isStream);
3696

3697
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type) {
3698
    pOptr = createStreamIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo);
3699 3700
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_ALIGNED_INTERVAL == type) {
    SMergeAlignedIntervalPhysiNode* pIntervalPhyNode = (SMergeAlignedIntervalPhysiNode*)pPhyNode;
3701
    pOptr = createMergeAlignedIntervalOperatorInfo(ops[0], pIntervalPhyNode, pTaskInfo);
S
shenglian zhou 已提交
3702
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_INTERVAL == type) {
X
Xiaoyu Wang 已提交
3703
    SMergeIntervalPhysiNode* pIntervalPhyNode = (SMergeIntervalPhysiNode*)pPhyNode;
3704
    pOptr = createMergeIntervalOperatorInfo(ops[0], pIntervalPhyNode, pTaskInfo);
5
54liuyao 已提交
3705
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SEMI_INTERVAL == type) {
3706
    int32_t children = 0;
5
54liuyao 已提交
3707 3708
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_FINAL_INTERVAL == type) {
5
54liuyao 已提交
3709
    int32_t children = pHandle->numOfVgroups;
5
54liuyao 已提交
3710
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
H
Haojun Liao 已提交
3711
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == type) {
3712
    pOptr = createSortOperatorInfo(ops[0], (SSortPhysiNode*)pPhyNode, pTaskInfo);
S
shenglian zhou 已提交
3713 3714
  } else if (QUERY_NODE_PHYSICAL_PLAN_GROUP_SORT == type) {
    pOptr = createGroupSortOperatorInfo(ops[0], (SGroupSortPhysiNode*)pPhyNode, pTaskInfo);
X
Xiaoyu Wang 已提交
3715
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE == type) {
3716
    SMergePhysiNode* pMergePhyNode = (SMergePhysiNode*)pPhyNode;
3717
    pOptr = createMultiwayMergeOperatorInfo(ops, size, pMergePhyNode, pTaskInfo);
3718
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_SESSION == type) {
H
Haojun Liao 已提交
3719
    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
3720
    pOptr = createSessionAggOperatorInfo(ops[0], pSessionNode, pTaskInfo);
3721
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION == type) {
3722 3723 3724 3725 3726
    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) {
3727
    int32_t children = pHandle->numOfVgroups;
3728
    pOptr = createStreamFinalSessionAggOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
H
Haojun Liao 已提交
3729
  } else if (QUERY_NODE_PHYSICAL_PLAN_PARTITION == type) {
3730
    pOptr = createPartitionOperatorInfo(ops[0], (SPartitionPhysiNode*)pPhyNode, pTaskInfo);
3731 3732
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_PARTITION == type) {
    pOptr = createStreamPartitionOperatorInfo(ops[0], (SPartitionPhysiNode*)pPhyNode, pTaskInfo);
3733
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_STATE == type) {
dengyihao's avatar
dengyihao 已提交
3734
    SStateWinodwPhysiNode* pStateNode = (SStateWinodwPhysiNode*)pPhyNode;
3735
    pOptr = createStatewindowOperatorInfo(ops[0], pStateNode, pTaskInfo);
3736
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_STATE == type) {
5
54liuyao 已提交
3737
    pOptr = createStreamStateAggOperatorInfo(ops[0], pPhyNode, pTaskInfo);
3738
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_JOIN == type) {
3739
    pOptr = createMergeJoinOperatorInfo(ops, size, (SSortMergeJoinPhysiNode*)pPhyNode, pTaskInfo);
3740
  } else if (QUERY_NODE_PHYSICAL_PLAN_FILL == type) {
H
Haojun Liao 已提交
3741
    pOptr = createFillOperatorInfo(ops[0], (SFillPhysiNode*)pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
3742 3743
  } else if (QUERY_NODE_PHYSICAL_PLAN_INDEF_ROWS_FUNC == type) {
    pOptr = createIndefinitOutputOperatorInfo(ops[0], pPhyNode, pTaskInfo);
3744 3745
  } else if (QUERY_NODE_PHYSICAL_PLAN_INTERP_FUNC == type) {
    pOptr = createTimeSliceOperatorInfo(ops[0], pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
3746 3747
  } else {
    ASSERT(0);
H
Haojun Liao 已提交
3748
  }
3749

3750
  taosMemoryFree(ops);
3751 3752 3753 3754
  if (pOptr) {
    pOptr->resultDataBlockId = pPhyNode->pOutputDataBlockDesc->dataBlockId;
  }

3755
  return pOptr;
3756
}
H
Haojun Liao 已提交
3757

H
Haojun Liao 已提交
3758
SArray* extractColumnInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
3759
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
3760 3761 3762 3763 3764 3765
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

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

3769 3770 3771
    if (nodeType(pNode->pExpr) == QUERY_NODE_COLUMN) {
      SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

3772
      SColumn c = extractColumnFromColumnNode(pColNode);
3773 3774
      taosArrayPush(pList, &c);
    } else if (nodeType(pNode->pExpr) == QUERY_NODE_VALUE) {
L
Liu Jicong 已提交
3775 3776
      SValueNode* pValNode = (SValueNode*)pNode->pExpr;
      SColumn     c = {0};
3777
      c.slotId = pNode->slotId;
L
Liu Jicong 已提交
3778 3779 3780 3781
      c.colId = pNode->slotId;
      c.type = pValNode->node.type;
      c.bytes = pValNode->node.resType.bytes;
      c.scale = pValNode->node.resType.scale;
3782 3783 3784 3785
      c.precision = pValNode->node.resType.precision;

      taosArrayPush(pList, &c);
    }
H
Haojun Liao 已提交
3786 3787 3788 3789 3790
  }

  return pList;
}

L
Liu Jicong 已提交
3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803
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 {
3804 3805 3806
    SStreamScanInfo* pInfo = pOperator->info;
    ASSERT(pInfo->pTableScanOp->operatorType == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN);
    *ppInfo = pInfo->pTableScanOp->info;
L
Liu Jicong 已提交
3807 3808 3809 3810
    return 0;
  }
}

3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832
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;
}

3833
#if 0
L
Liu Jicong 已提交
3834 3835 3836 3837 3838
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;
  }
3839

L
Liu Jicong 已提交
3840 3841 3842 3843
  STableScanPhysiNode* pNode = NULL;
  if (extractTableScanNode(plan->pNode, &pNode) < 0) {
    ASSERT(0);
  }
3844

H
Haojun Liao 已提交
3845
  tsdbReaderClose(pTableScanInfo->dataReader);
3846

L
Liu Jicong 已提交
3847
  STableListInfo info = {0};
H
Haojun Liao 已提交
3848
  pTableScanInfo->dataReader = doCreateDataReader(pNode, pHandle, &info, NULL);
L
Liu Jicong 已提交
3849 3850 3851 3852
  if (pTableScanInfo->dataReader == NULL) {
    ASSERT(0);
    qError("failed to create data reader");
    return TSDB_CODE_QRY_APP_ERROR;
3853
  }
L
Liu Jicong 已提交
3854
  // TODO: set uid and ts to data reader
3855 3856
  return 0;
}
3857
#endif
3858

C
Cary Xu 已提交
3859
int32_t encodeOperator(SOperatorInfo* ops, char** result, int32_t* length, int32_t* nOptrWithVal) {
wmmhello's avatar
wmmhello 已提交
3860
  int32_t code = TDB_CODE_SUCCESS;
3861
  char*   pCurrent = NULL;
wmmhello's avatar
wmmhello 已提交
3862
  int32_t currLength = 0;
3863
  if (ops->fpSet.encodeResultRow) {
C
Cary Xu 已提交
3864
    if (result == NULL || length == NULL || nOptrWithVal == NULL) {
wmmhello's avatar
wmmhello 已提交
3865 3866 3867
      return TSDB_CODE_TSC_INVALID_INPUT;
    }
    code = ops->fpSet.encodeResultRow(ops, &pCurrent, &currLength);
wmmhello's avatar
wmmhello 已提交
3868

3869 3870
    if (code != TDB_CODE_SUCCESS) {
      if (*result != NULL) {
wmmhello's avatar
wmmhello 已提交
3871 3872 3873 3874
        taosMemoryFree(*result);
        *result = NULL;
      }
      return code;
C
Cary Xu 已提交
3875 3876 3877
    } else if (currLength == 0) {
      ASSERT(!pCurrent);
      goto _downstream;
wmmhello's avatar
wmmhello 已提交
3878
    }
wmmhello's avatar
wmmhello 已提交
3879

C
Cary Xu 已提交
3880 3881
    ++(*nOptrWithVal);

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

3884
    if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
3885
      *result = (char*)taosMemoryCalloc(1, currLength + sizeof(int32_t));
wmmhello's avatar
wmmhello 已提交
3886 3887 3888 3889 3890 3891
      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);
3892
    } else {
wmmhello's avatar
wmmhello 已提交
3893
      int32_t sizePre = *(int32_t*)(*result);
3894
      char*   tmp = (char*)taosMemoryRealloc(*result, sizePre + currLength);
wmmhello's avatar
wmmhello 已提交
3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906
      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 已提交
3907 3908
  }

C
Cary Xu 已提交
3909
_downstream:
wmmhello's avatar
wmmhello 已提交
3910
  for (int32_t i = 0; i < ops->numOfDownstream; ++i) {
C
Cary Xu 已提交
3911
    code = encodeOperator(ops->pDownstream[i], result, length, nOptrWithVal);
3912
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
3913
      return code;
wmmhello's avatar
wmmhello 已提交
3914 3915
    }
  }
wmmhello's avatar
wmmhello 已提交
3916
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
3917 3918
}

H
Haojun Liao 已提交
3919
int32_t decodeOperator(SOperatorInfo* ops, const char* result, int32_t length) {
wmmhello's avatar
wmmhello 已提交
3920
  int32_t code = TDB_CODE_SUCCESS;
3921 3922
  if (ops->fpSet.decodeResultRow) {
    if (result == NULL) {
wmmhello's avatar
wmmhello 已提交
3923 3924
      return TSDB_CODE_TSC_INVALID_INPUT;
    }
H
Haojun Liao 已提交
3925

3926
    ASSERT(length == *(int32_t*)result);
H
Haojun Liao 已提交
3927 3928

    const char* data = result + sizeof(int32_t);
L
Liu Jicong 已提交
3929
    code = ops->fpSet.decodeResultRow(ops, (char*)data);
3930
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
3931 3932
      return code;
    }
wmmhello's avatar
wmmhello 已提交
3933

wmmhello's avatar
wmmhello 已提交
3934
    int32_t totalLength = *(int32_t*)result;
3935 3936
    int32_t dataLength = *(int32_t*)data;

3937
    if (totalLength == dataLength + sizeof(int32_t)) {  // the last data
wmmhello's avatar
wmmhello 已提交
3938 3939
      result = NULL;
      length = 0;
3940
    } else {
wmmhello's avatar
wmmhello 已提交
3941 3942 3943 3944
      result += dataLength;
      *(int32_t*)(result) = totalLength - dataLength;
      length = totalLength - dataLength;
    }
wmmhello's avatar
wmmhello 已提交
3945 3946
  }

wmmhello's avatar
wmmhello 已提交
3947 3948
  for (int32_t i = 0; i < ops->numOfDownstream; ++i) {
    code = decodeOperator(ops->pDownstream[i], result, length);
3949
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
3950
      return code;
wmmhello's avatar
wmmhello 已提交
3951 3952
    }
  }
wmmhello's avatar
wmmhello 已提交
3953
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
3954 3955
}

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

D
dapan1121 已提交
3959
  switch (pNode->type) {
D
dapan1121 已提交
3960 3961 3962 3963 3964 3965
    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 已提交
3966

D
dapan1121 已提交
3967 3968 3969
      *pParam = pInserterParam;
      break;
    }
D
dapan1121 已提交
3970
    case QUERY_NODE_PHYSICAL_PLAN_DELETE: {
3971
      SDeleterParam* pDeleterParam = taosMemoryCalloc(1, sizeof(SDeleterParam));
D
dapan1121 已提交
3972 3973 3974 3975
      if (NULL == pDeleterParam) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      int32_t tbNum = taosArrayGetSize(pTask->tableqinfoList.pTableList);
D
dapan1121 已提交
3976
      pDeleterParam->suid = pTask->tableqinfoList.suid;
D
dapan1121 已提交
3977 3978 3979 3980 3981 3982
      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) {
3983
        STableKeyInfo* pTable = taosArrayGet(pTask->tableqinfoList.pTableList, i);
D
dapan1121 已提交
3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996
        taosArrayPush(pDeleterParam->pUidList, &pTable->uid);
      }

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

  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
3997
int32_t createExecTaskInfoImpl(SSubplan* pPlan, SExecTaskInfo** pTaskInfo, SReadHandle* pHandle, uint64_t taskId,
D
dapan1121 已提交
3998
                               char* sql, EOPTR_EXEC_MODEL model) {
H
Haojun Liao 已提交
3999 4000
  uint64_t queryId = pPlan->id.queryId;

H
Haojun Liao 已提交
4001
  int32_t code = TSDB_CODE_SUCCESS;
D
dapan1121 已提交
4002
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model, pPlan->dbFName);
H
Haojun Liao 已提交
4003 4004 4005 4006
  if (*pTaskInfo == NULL) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _complete;
  }
H
Haojun Liao 已提交
4007

H
Haojun Liao 已提交
4008 4009 4010 4011
  if (pHandle && pHandle->pStateBackend) {
    (*pTaskInfo)->streamInfo.pState = pHandle->pStateBackend;
  }

4012
  (*pTaskInfo)->sql = sql;
D
dapan1121 已提交
4013
  sql = NULL;
4014
  (*pTaskInfo)->pSubplan = pPlan;
L
Liu Jicong 已提交
4015 4016
  (*pTaskInfo)->pRoot = createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, &(*pTaskInfo)->tableqinfoList,
                                           pPlan->pTagCond, pPlan->pTagIndexCond, pPlan->user);
L
Liu Jicong 已提交
4017

D
dapan1121 已提交
4018
  if (NULL == (*pTaskInfo)->pRoot) {
4019
    code = (*pTaskInfo)->code;
D
dapan1121 已提交
4020
    goto _complete;
4021 4022
  }

H
Haojun Liao 已提交
4023 4024
  return code;

H
Haojun Liao 已提交
4025
_complete:
D
dapan1121 已提交
4026
  taosMemoryFree(sql);
H
Haojun Liao 已提交
4027
  doDestroyTask(*pTaskInfo);
H
Haojun Liao 已提交
4028 4029
  terrno = code;
  return code;
H
Haojun Liao 已提交
4030 4031
}

4032
void doDestroyTableList(STableListInfo* pTableqinfoList) {
wmmhello's avatar
wmmhello 已提交
4033 4034
  taosArrayDestroy(pTableqinfoList->pTableList);
  taosHashCleanup(pTableqinfoList->map);
4035 4036
  if (pTableqinfoList->needSortTableByGroupId) {
    for (int32_t i = 0; i < taosArrayGetSize(pTableqinfoList->pGroupList); i++) {
wmmhello's avatar
wmmhello 已提交
4037
      SArray* tmp = taosArrayGetP(pTableqinfoList->pGroupList, i);
4038 4039 4040
      if (tmp == pTableqinfoList->pTableList) {
        continue;
      }
wmmhello's avatar
wmmhello 已提交
4041 4042 4043 4044
      taosArrayDestroy(tmp);
    }
  }
  taosArrayDestroy(pTableqinfoList->pGroupList);
4045

wmmhello's avatar
wmmhello 已提交
4046 4047
  pTableqinfoList->pTableList = NULL;
  pTableqinfoList->map = NULL;
4048 4049
}

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

wmmhello's avatar
wmmhello 已提交
4053
  doDestroyTableList(&pTaskInfo->tableqinfoList);
H
Haojun Liao 已提交
4054
  destroyOperatorInfo(pTaskInfo->pRoot);
4055
  cleanupTableSchemaInfo(&pTaskInfo->schemaInfo);
4056
  cleanupStreamInfo(&pTaskInfo->streamInfo);
4057

D
dapan1121 已提交
4058
  if (!pTaskInfo->localFetch.localExec) {
D
dapan1121 已提交
4059 4060 4061
    nodesDestroyNode((SNode*)pTaskInfo->pSubplan);
  }
  
wafwerar's avatar
wafwerar 已提交
4062 4063 4064
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
4065 4066 4067 4068
}

static int64_t getQuerySupportBufSize(size_t numOfTables) {
  size_t s1 = sizeof(STableQueryInfo);
L
Liu Jicong 已提交
4069 4070
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
4071 4072 4073 4074 4075 4076 4077
}

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 已提交
4078
    while (1) {
4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104
      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 已提交
4105

H
Haojun Liao 已提交
4106
int32_t getOperatorExplainExecInfo(SOperatorInfo* operatorInfo, SArray* pExecInfoList) {
4107
  SExplainExecInfo  execInfo = {0};
H
Haojun Liao 已提交
4108
  SExplainExecInfo* pExplainInfo = taosArrayPush(pExecInfoList, &execInfo);
4109

H
Haojun Liao 已提交
4110 4111 4112 4113 4114
  pExplainInfo->numOfRows = operatorInfo->resultInfo.totalRows;
  pExplainInfo->startupCost = operatorInfo->cost.openCost;
  pExplainInfo->totalCost = operatorInfo->cost.totalCost;
  pExplainInfo->verboseLen = 0;
  pExplainInfo->verboseInfo = NULL;
D
dapan1121 已提交
4115

4116
  if (operatorInfo->fpSet.getExplainFn) {
4117 4118
    int32_t code =
        operatorInfo->fpSet.getExplainFn(operatorInfo, &pExplainInfo->verboseInfo, &pExplainInfo->verboseLen);
D
dapan1121 已提交
4119
    if (code) {
4120
      qError("%s operator getExplainFn failed, code:%s", GET_TASKID(operatorInfo->pTaskInfo), tstrerror(code));
D
dapan1121 已提交
4121 4122 4123
      return code;
    }
  }
dengyihao's avatar
dengyihao 已提交
4124

D
dapan1121 已提交
4125
  int32_t code = 0;
D
dapan1121 已提交
4126
  for (int32_t i = 0; i < operatorInfo->numOfDownstream; ++i) {
H
Haojun Liao 已提交
4127 4128
    code = getOperatorExplainExecInfo(operatorInfo->pDownstream[i], pExecInfoList);
    if (code != TSDB_CODE_SUCCESS) {
4129
      //      taosMemoryFreeClear(*pRes);
D
dapan1121 已提交
4130 4131 4132 4133 4134
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
4135
}
5
54liuyao 已提交
4136

L
Liu Jicong 已提交
4137
int32_t initStreamAggSupporter(SStreamAggSupporter* pSup, const char* pKey, SqlFunctionCtx* pCtx, int32_t numOfOutput,
4138
                               int32_t size) {
4139
  pSup->currentPageId = -1;
4140
  pSup->resultRowSize = getResultRowSize(pCtx, numOfOutput);
5
54liuyao 已提交
4141 4142
  pSup->keySize = sizeof(int64_t) + sizeof(TSKEY);
  pSup->pKeyBuf = taosMemoryCalloc(1, pSup->keySize);
4143 4144
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);
  pSup->pResultRows = taosHashInit(1024, hashFn, false, HASH_NO_LOCK);
5
54liuyao 已提交
4145 4146 4147
  if (pSup->pKeyBuf == NULL || pSup->pResultRows == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
4148
  pSup->valueSize = size;
5
54liuyao 已提交
4149

4150
  pSup->pScanBlock = createSpecialDataBlock(STREAM_CLEAR);
5
54liuyao 已提交
4151 4152 4153 4154 4155 4156 4157 4158 4159
  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;
  }
wafwerar's avatar
wafwerar 已提交
4160 4161 4162 4163 4164 4165
  if (!osTempSpaceAvailable()) {
    terrno = TSDB_CODE_NO_AVAIL_DISK;
    qError("Init stream agg supporter failed since %s", terrstr(terrno));
    return terrno;
  }
  int32_t code = createDiskbasedBuf(&pSup->pResultBuf, pageSize, bufSize, pKey, tsTempDir);
L
Liu Jicong 已提交
4166
  for (int32_t i = 0; i < numOfOutput; ++i) {
4167
    pCtx[i].saveHandle.pBuf = pSup->pResultBuf;
4168
  }
4169

4170
  return code;
5
54liuyao 已提交
4171
}
4172 4173 4174 4175 4176 4177 4178 4179 4180 4181

int32_t setOutputBuf(STimeWindow* win, SResultRow** pResult, int64_t tableGroupId, SqlFunctionCtx* pCtx,
                     int32_t numOfOutput, int32_t* rowEntryInfoOffset, SAggSupporter* pAggSup,
                     SExecTaskInfo* pTaskInfo) {
  SWinKey key = {
      .ts = win->skey,
      .groupId = tableGroupId,
  };
  char*   value = NULL;
  int32_t size = pAggSup->resultRowSize;
5
54liuyao 已提交
4182 4183

  tSimpleHashPut(pAggSup->pResultRowHashTable, &key, sizeof(SWinKey), NULL, 0);
4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196
  if (streamStateAddIfNotExist(pTaskInfo->streamInfo.pState, &key, (void**)&value, &size) < 0) {
    return TSDB_CODE_QRY_OUT_OF_MEMORY;
  }
  *pResult = (SResultRow*)value;
  ASSERT(*pResult);
  // set time window for current result
  (*pResult)->win = (*win);
  setResultRowInitCtx(*pResult, pCtx, numOfOutput, rowEntryInfoOffset);
  return TSDB_CODE_SUCCESS;
}

int32_t releaseOutputBuf(SExecTaskInfo* pTaskInfo, SWinKey* pKey, SResultRow* pResult) {
  streamStateReleaseBuf(pTaskInfo->streamInfo.pState, pKey, pResult);
4197
  /*taosMemoryFree((*(void**)pResult));*/
4198 4199 4200
  return TSDB_CODE_SUCCESS;
}

5
54liuyao 已提交
4201
int32_t saveOutputBuf(SExecTaskInfo* pTaskInfo, SWinKey* pKey, SResultRow* pResult, int32_t resSize) {
4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256
  streamStatePut(pTaskInfo->streamInfo.pState, pKey, pResult, resSize);
  return TSDB_CODE_SUCCESS;
}

int32_t buildDataBlockFromGroupRes(SExecTaskInfo* pTaskInfo, SSDataBlock* pBlock, SExprSupp* pSup,
                                   SGroupResInfo* pGroupResInfo) {
  SExprInfo*      pExprInfo = pSup->pExprInfo;
  int32_t         numOfExprs = pSup->numOfExprs;
  int32_t*        rowEntryOffset = pSup->rowEntryInfoOffset;
  SqlFunctionCtx* pCtx = pSup->pCtx;

  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);

  for (int32_t i = pGroupResInfo->index; i < numOfRows; i += 1) {
    SResKeyPos* pPos = taosArrayGetP(pGroupResInfo->pRows, i);
    int32_t     size = 0;
    void*       pVal = NULL;
    SWinKey     key = {
            .ts = *(TSKEY*)pPos->key,
            .groupId = pPos->groupId,
    };
    int32_t code = streamStateGet(pTaskInfo->streamInfo.pState, &key, &pVal, &size);
    ASSERT(code == 0);
    SResultRow* pRow = (SResultRow*)pVal;
    doUpdateNumOfRows(pCtx, pRow, numOfExprs, rowEntryOffset);
    // no results, continue to check the next one
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
      releaseOutputBuf(pTaskInfo, &key, pRow);
      continue;
    }

    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) {
        releaseOutputBuf(pTaskInfo, &key, pRow);
        break;
      }
    }

    if (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
      ASSERT(pBlock->info.rows > 0);
      releaseOutputBuf(pTaskInfo, &key, pRow);
      break;
    }

    pGroupResInfo->index += 1;

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

      pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowEntryOffset);
      if (pCtx[j].fpSet.finalize) {
4257 4258 4259 4260
        int32_t code1 = pCtx[j].fpSet.finalize(&pCtx[j], pBlock);
        if (TAOS_FAILED(code1)) {
          qError("%s build result data block error, code %s", GET_TASKID(pTaskInfo), tstrerror(code1));
          T_LONG_JMP(pTaskInfo->env, code1);
4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273
        }
      } else if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
        // do nothing, todo refactor
      } else {
        // expand the result into multiple rows. E.g., _wstart, top(k, 20)
        // the _wstart needs to copy to 20 following rows, since the results of top-k expands to 20 different rows.
        SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId);
        char*            in = GET_ROWCELL_INTERBUF(pCtx[j].resultInfo);
        for (int32_t k = 0; k < pRow->numOfRows; ++k) {
          colDataAppend(pColInfoData, pBlock->info.rows + k, in, pCtx[j].resultInfo->isNullRes);
        }
      }
    }
5
54liuyao 已提交
4274

4275
    pBlock->info.rows += pRow->numOfRows;
5
54liuyao 已提交
4276
    releaseOutputBuf(pTaskInfo, &key, pRow);
4277 4278 4279 4280
  }
  blockDataUpdateTsWindow(pBlock, 0);
  return TSDB_CODE_SUCCESS;
}