executorimpl.c 123.4 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
#include "tcompare.h"
H
Haojun Liao 已提交
35
#include "thash.h"
36
#include "ttypes.h"
dengyihao's avatar
dengyihao 已提交
37
#include "vnode.h"
38

H
Haojun Liao 已提交
39
#define IS_MAIN_SCAN(runtime)          ((runtime)->scanFlag == MAIN_SCAN)
40 41 42 43 44 45
#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 已提交
46
  uint32_t v = taosRand();
47 48 49 50

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

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

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

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

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

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

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

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

87 88
static void destroyFillOperatorInfo(void* param);
static void destroyProjectOperatorInfo(void* param);
H
Haojun Liao 已提交
89
static void destroySortOperatorInfo(void* param);
90
static void destroyAggOperatorInfo(void* param);
X
Xiaoyu Wang 已提交
91

92
static void destroyIntervalOperatorInfo(void* param);
H
Haojun Liao 已提交
93

H
Haojun Liao 已提交
94
void setOperatorCompleted(SOperatorInfo* pOperator) {
95
  pOperator->status = OP_EXEC_DONE;
H
Haojun Liao 已提交
96
  ASSERT(pOperator->pTaskInfo != NULL);
97

98
  pOperator->cost.totalCost = (taosGetTimestampUs() - pOperator->pTaskInfo->cost.start * 1000) / 1000.0;
H
Haojun Liao 已提交
99
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
100
}
101

H
Haojun Liao 已提交
102 103 104 105 106 107 108 109 110 111
void setOperatorInfo(SOperatorInfo* pOperator, const char* name, int32_t type, bool blocking, int32_t status,
                     void* pInfo, SExecTaskInfo* pTaskInfo) {
  pOperator->name = (char*)name;
  pOperator->operatorType = type;
  pOperator->blocking = blocking;
  pOperator->status = status;
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
}

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

H
Haojun Liao 已提交
118 119
SOperatorFpSet createOperatorFpSet(__optr_open_fn_t openFn, __optr_fn_t nextFn, __optr_fn_t cleanup,
                                   __optr_close_fn_t closeFn, __optr_explain_fn_t explain) {
120 121 122 123 124 125 126 127 128 129 130
  SOperatorFpSet fpSet = {
      ._openFn = openFn,
      .getNextFn = nextFn,
      .cleanupFn = cleanup,
      .closeFn = closeFn,
      .getExplainFn = explain,
  };

  return fpSet;
}

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

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

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

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

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

    return existed;
  }

  return p1 != NULL;
}
174
#endif
175

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

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

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

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

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

203 204
  setBufPageDirty(pData, true);

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

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

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

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

230 231
  SResultRow* pResult = NULL;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

342 343 344 345 346 347 348 349 350 351 352 353 354 355
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 已提交
356
  pCtx->input.numOfRows = pStatus->numOfRows;
357 358 359 360 361
  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) {
362
  for (int32_t k = 0; k < numOfOutput; ++k) {
H
Haojun Liao 已提交
363
    // keep it temporarily
364 365
    SFunctionCtxStatus status = {0};
    functionCtxSave(&pCtx[k], &status);
366

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

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

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

      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);
380

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

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

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

408 409
static int32_t doSetInputDataBlock(SExprSupp* pExprSup, SSDataBlock* pBlock, int32_t order, int32_t scanFlag,
                                   bool createDummyCol);
410

411 412 413
static void doSetInputDataBlockInfo(SExprSupp* pExprSup, SSDataBlock* pBlock, int32_t order) {
  SqlFunctionCtx* pCtx = pExprSup->pCtx;
  for (int32_t i = 0; i < pExprSup->numOfExprs; ++i) {
414
    pCtx[i].order = order;
415
    pCtx[i].input.numOfRows = pBlock->info.rows;
416
    setBlockSMAInfo(&pCtx[i], &pExprSup->pExprInfo[i], pBlock);
417
    pCtx[i].pSrcBlock = pBlock;
418 419 420
  }
}

421
void setInputDataBlock(SExprSupp* pExprSup, SSDataBlock* pBlock, int32_t order, int32_t scanFlag, bool createDummyCol) {
422
  if (pBlock->pBlockAgg != NULL) {
423
    doSetInputDataBlockInfo(pExprSup, pBlock, order);
424
  } else {
425
    doSetInputDataBlock(pExprSup, 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
  }

H
Haojun Liao 已提交
447
  colInfoDataEnsureCapacity(pColInfo, numOfRows, false);
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);
    }
H
Haojun Liao 已提交
466
    taosMemoryFree(tmp);
467 468 469 470 471
  }

  return TSDB_CODE_SUCCESS;
}

472 473
static int32_t doSetInputDataBlock(SExprSupp* pExprSup, SSDataBlock* pBlock, int32_t order, int32_t scanFlag,
                                   bool createDummyCol) {
474
  int32_t         code = TSDB_CODE_SUCCESS;
475
  SqlFunctionCtx* pCtx = pExprSup->pCtx;
476

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

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

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

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

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

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

  return code;
H
Haojun Liao 已提交
523 524
}

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

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

  return TSDB_CODE_SUCCESS;
542 543
}

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

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

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

L
Liu Jicong 已提交
574 575 576 577
  if (pResult != pSrcBlock) {
    pResult->info.groupId = pSrcBlock->info.groupId;
    memcpy(pResult->info.parTbName, pSrcBlock->info.parTbName, TSDB_TABLE_NAME_LEN);
  }
H
Haojun Liao 已提交
578

579 580
  // if the source equals to the destination, it is to create a new column as the result of scalar
  // function or some operators.
581
  bool createNewColModel = (pResult == pSrcBlock);
582 583 584
  if (createNewColModel) {
    blockDataEnsureCapacity(pResult, pResult->info.rows);
  }
585

586 587
  int32_t numOfRows = 0;

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

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

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

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

      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);
        }
615
      }
616 617

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

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

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

dengyihao's avatar
dengyihao 已提交
632
      int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
633
      ASSERT(pResult->info.capacity > 0);
634

635
      colDataMergeCol(pResColData, startOffset, (int32_t*)&pResult->info.capacity, &idata, dest.numOfRows);
D
dapan1121 已提交
636
      colDataDestroy(&idata);
L
Liu Jicong 已提交
637

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

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

657 658 659 660 661
        // link pDstBlock to set selectivity value
        if (pfCtx->subsidiaries.num > 0) {
          pfCtx->pDstBlock = pResult;
        }

662 663 664 665 666
        int32_t code = pfCtx->fpSet.process(pfCtx);
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
        numOfRows = pResInfo->numOfRes;
H
Haojun Liao 已提交
667
      } else if (fmIsAggFunc(pfCtx->functionId)) {
G
Ganlin Zhao 已提交
668
        // selective value output should be set during corresponding function execution
669 670 671
        if (fmIsSelectValueFunc(pfCtx->functionId)) {
          continue;
        }
672 673
        // _group_key function for "partition by tbname" + csum(col_name) query
        SColumnInfoData* pOutput = taosArrayGet(pResult->pDataBlock, outputSlotId);
674
        int32_t          slotId = pfCtx->param[0].pCol->slotId;
675 676 677

        // todo handle the json tag
        SColumnInfoData* pInput = taosArrayGet(pSrcBlock->pDataBlock, slotId);
678
        for (int32_t f = 0; f < pSrcBlock->info.rows; ++f) {
679 680 681 682 683 684 685 686 687
          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 已提交
688 689 690
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
691

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

695
        SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
696
        int32_t      code = scalarCalculate((SNode*)pExpr[k].pExpr->_function.pFunctNode, pBlockList, &dest);
697 698 699 700
        if (code != TSDB_CODE_SUCCESS) {
          taosArrayDestroy(pBlockList);
          return code;
        }
701

dengyihao's avatar
dengyihao 已提交
702
        int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
703
        ASSERT(pResult->info.capacity > 0);
704
        colDataMergeCol(pResColData, startOffset, (int32_t*)&pResult->info.capacity, &idata, dest.numOfRows);
D
dapan1121 已提交
705
        colDataDestroy(&idata);
706 707

        numOfRows = dest.numOfRows;
H
Haojun Liao 已提交
708 709
        taosArrayDestroy(pBlockList);
      }
710
    } else {
711
      return TSDB_CODE_OPS_NOT_SUPPORT;
712 713
    }
  }
714

715 716 717
  if (!createNewColModel) {
    pResult->info.rows += numOfRows;
  }
718 719

  return TSDB_CODE_SUCCESS;
720 721
}

5
54liuyao 已提交
722
bool functionNeedToExecute(SqlFunctionCtx* pCtx) {
723
  struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
724

725 726 727 728 729
  // in case of timestamp column, always generated results.
  int32_t functionId = pCtx->functionId;
  if (functionId == -1) {
    return false;
  }
730

731 732
  if (pCtx->scanFlag == REPEAT_SCAN) {
    return fmIsRepeatScanFunc(pCtx->functionId);
733 734
  }

735 736
  if (isRowEntryCompleted(pResInfo)) {
    return false;
737 738
  }

739 740 741
  return true;
}

742 743 744 745 746 747 748
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;
    }
749

750 751 752
    // Set the correct column info (data type and bytes)
    pInput->pData[paramIndex]->info.type = type;
    pInput->pData[paramIndex]->info.bytes = tDataTypes[type].bytes;
753
  }
H
Haojun Liao 已提交
754

755 756 757 758 759 760
  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;
761 762
    }
  } else {
763
    da = pInput->pColumnDataAgg[paramIndex];
764 765
  }

766
  ASSERT(!IS_VAR_DATA_TYPE(type));
767

768 769
  if (type == TSDB_DATA_TYPE_BIGINT) {
    int64_t v = pFuncParam->param.i;
770
    *da = (SColumnDataAgg){.numOfNull = 0, .min = v, .max = v, .sum = v * numOfRows};
771 772
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
773
    *da = (SColumnDataAgg){.numOfNull = 0};
774

775 776 777 778 779 780
    *(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;

781
    *da = (SColumnDataAgg){.numOfNull = 0};
782 783 784 785 786
    *(bool*)&da->min = 0;
    *(bool*)&da->max = v;
    *(bool*)&da->sum = v * numOfRows;
  } else if (type == TSDB_DATA_TYPE_TIMESTAMP) {
    // do nothing
787
  } else {
788
    ASSERT(0);
789 790
  }

791 792
  return TSDB_CODE_SUCCESS;
}
793

794
void setBlockSMAInfo(SqlFunctionCtx* pCtx, SExprInfo* pExprInfo, SSDataBlock* pBlock) {
795 796 797 798 799 800 801 802 803
  int32_t numOfRows = pBlock->info.rows;

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

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

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

807 808
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
809 810 811 812
        pInput->pColumnDataAgg[j] = pBlock->pBlockAgg[slotId];
        if (pInput->pColumnDataAgg[j] == NULL) {
          pInput->colDataAggIsSet = false;
        }
813 814 815 816

        // 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);
817 818
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
        doCreateConstantValColumnAggInfo(pInput, pFuncParam, pFuncParam->param.nType, j, pBlock->info.rows);
819 820
      }
    }
821
  } else {
822
    pInput->colDataAggIsSet = false;
823 824 825
  }
}

L
Liu Jicong 已提交
826
bool isTaskKilled(SExecTaskInfo* pTaskInfo) {
827 828
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
L
Liu Jicong 已提交
829 830
  if (pTaskInfo->owner != 0 &&
      ((taosGetTimestampSec() - pTaskInfo->cost.start / 1000) > 10 * getMaximumIdleDurationSec())
831
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
832
    assert(pTaskInfo->cost.start != 0);
L
Liu Jicong 已提交
833 834 835
    //    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;
836 837 838 839 840
  }

  return false;
}

L
Liu Jicong 已提交
841
void setTaskKilled(SExecTaskInfo* pTaskInfo) { pTaskInfo->code = TSDB_CODE_TSC_QUERY_CANCELLED; }
842 843

/////////////////////////////////////////////////////////////////////////////////////////////
844
STimeWindow getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key) {
L
Liu Jicong 已提交
845
  STimeWindow win = {0};
846
  win.skey = taosTimeTruncate(key, pInterval, precision);
847 848

  /*
H
Haojun Liao 已提交
849
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
850 851
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
852 853 854
  win.ekey = taosTimeAdd(win.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
  if (win.ekey < win.skey) {
    win.ekey = INT64_MAX;
855
  }
856 857

  return win;
858 859
}

L
Liu Jicong 已提交
860 861
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
862
  *status = BLK_DATA_NOT_LOAD;
863

H
Haojun Liao 已提交
864
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
865
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
866

L
Liu Jicong 已提交
867 868
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
869

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

872 873
//  pCost->totalBlocks += 1;
//  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
874
#if 0
875 876 877
  // 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 已提交
878
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
879
    (*status) = BLK_DATA_DATA_LOAD;
880 881 882
  }

  // check if this data block is required to load
883
  if ((*status) != BLK_DATA_DATA_LOAD) {
884 885 886 887 888 889 890
    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 已提交
891
      bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
892 893 894 895 896 897
      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,
898
                                    pTableScanInfo->rowEntryInfoOffset);
899 900 901
      } else {
        if (setResultOutputBufByKey(pRuntimeEnv, pTableScanInfo->pResultRowInfo, pBlock->info.uid, &win, masterScan, &pResult, groupId,
                                    pTableScanInfo->pCtx, pTableScanInfo->numOfOutput,
902
                                    pTableScanInfo->rowEntryInfoOffset) != TSDB_CODE_SUCCESS) {
903
          T_LONG_JMP(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
904 905 906 907
        }
      }
    } else if (pQueryAttr->stableQuery && (!pQueryAttr->tsCompQuery) && (!pQueryAttr->diffQuery)) { // stable aggregate, not interval aggregate or normal column aggregate
      doSetTableGroupOutputBuf(pRuntimeEnv, pTableScanInfo->pResultRowInfo, pTableScanInfo->pCtx,
908
                               pTableScanInfo->rowEntryInfoOffset, pTableScanInfo->numOfOutput,
909 910 911 912 913 914
                               pRuntimeEnv->current->groupIndex);
    }

    if (needFilter) {
      (*status) = doFilterByBlockTimeWindow(pTableScanInfo, pBlock);
    } else {
915
      (*status) = BLK_DATA_DATA_LOAD;
916 917 918 919
    }
  }

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

922
  if ((*status) == BLK_DATA_NOT_LOAD || (*status) == BLK_DATA_FILTEROUT) {
923 924
    //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//           pBlockInfo->window.ekey, pBlockInfo->rows);
925
    pCost->skipBlocks += 1;
926
  } else if ((*status) == BLK_DATA_SMA_LOAD) {
927 928
    // this function never returns error?
    pCost->loadBlockStatis += 1;
929
//    tsdbRetrieveDatablockSMA(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
930 931

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
932
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
933 934 935
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
936
    assert((*status) == BLK_DATA_DATA_LOAD);
937 938 939

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
940
//    tsdbRetrieveDatablockSMA(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
941 942 943 944 945 946

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

H
Haojun Liao 已提交
947
          bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
948 949 950 951 952
          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,
953
                                      pTableScanInfo->rowEntryInfoOffset) != TSDB_CODE_SUCCESS) {
954
            T_LONG_JMP(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
955 956 957 958 959 960 961 962 963 964
          }
        }
      }
      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
965
            pCost->skipBlocks += 1;
966 967
            //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId,
//                   pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
968
            (*status) = BLK_DATA_FILTEROUT;
969 970 971 972 973 974 975
            return TSDB_CODE_SUCCESS;
          }
        }
      }
    }

    // current block has been discard due to filter applied
H
Haojun Liao 已提交
976
//    if (!doFilterByBlockSMA(pRuntimeEnv, pBlock->pBlockAgg, pTableScanInfo->pCtx, pBlockInfo->rows)) {
977
//      pCost->skipBlocks += 1;
978 979
//      qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//             pBlockInfo->window.ekey, pBlockInfo->rows);
980
//      (*status) = BLK_DATA_FILTEROUT;
981 982 983 984 985
//      return TSDB_CODE_SUCCESS;
//    }

    pCost->totalCheckedRows += pBlockInfo->rows;
    pCost->loadBlocks += 1;
986
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
987 988 989 990 991
//    if (pBlock->pDataBlock == NULL) {
//      return terrno;
//    }

//    if (pQueryAttr->pFilters != NULL) {
992
//      filterSetColFieldData(pQueryAttr->pFilters, taosArrayGetSize(pBlock->pDataBlock), pBlock->pDataBlock);
993
//    }
994

995 996 997 998
//    if (pQueryAttr->pFilters != NULL || pRuntimeEnv->pTsBuf != NULL) {
//      filterColRowsInDataBlock(pRuntimeEnv, pBlock, ascQuery);
//    }
  }
H
Haojun Liao 已提交
999
#endif
1000 1001 1002
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1003
void setTaskStatus(SExecTaskInfo* pTaskInfo, int8_t status) {
1004
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
1005
    pTaskInfo->status = status;
1006 1007
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
1008
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
1009
    pTaskInfo->status |= status;
1010 1011 1012
  }
}

1013
void setResultRowInitCtx(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowEntryInfoOffset) {
5
54liuyao 已提交
1014
  bool init = false;
1015
  for (int32_t i = 0; i < numOfOutput; ++i) {
1016
    pCtx[i].resultInfo = getResultEntryInfo(pResult, i, rowEntryInfoOffset);
5
54liuyao 已提交
1017 1018 1019
    if (init) {
      continue;
    }
1020 1021 1022 1023 1024

    struct SResultRowEntryInfo* pResInfo = pCtx[i].resultInfo;
    if (isRowEntryCompleted(pResInfo) && isRowEntryInitialized(pResInfo)) {
      continue;
    }
1025 1026 1027 1028 1029

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

1030 1031 1032 1033 1034 1035
    if (!pResInfo->initialized) {
      if (pCtx[i].functionId != -1) {
        pCtx[i].fpSet.init(&pCtx[i], pResInfo);
      } else {
        pResInfo->initialized = true;
      }
5
54liuyao 已提交
1036 1037
    } else {
      init = true;
1038 1039 1040 1041
    }
  }
}

1042 1043
static void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const SColumnInfoData* p, bool keep,
                                                int32_t status);
1044

H
Haojun Liao 已提交
1045 1046
void doFilter(SSDataBlock* pBlock, SFilterInfo* pFilterInfo, SColMatchInfo* pColMatchInfo) {
  if (pFilterInfo == NULL || pBlock->info.rows == 0) {
S
shenglian zhou 已提交
1047 1048
    return;
  }
1049

1050
  SFilterColumnParam param1 = {.numOfCols = taosArrayGetSize(pBlock->pDataBlock), .pDataBlock = pBlock->pDataBlock};
1051
  int32_t            code = filterSetDataFromSlotId(pFilterInfo, &param1);
1052

1053
  SColumnInfoData* p = NULL;
1054
  int32_t          status = 0;
H
Haojun Liao 已提交
1055

1056
  // todo the keep seems never to be True??
H
Haojun Liao 已提交
1057
  bool keep = filterExecute(pFilterInfo, pBlock, &p, NULL, param1.numOfCols, &status);
1058
  extractQualifiedTupleByFilterResult(pBlock, p, keep, status);
H
Haojun Liao 已提交
1059

1060
  if (pColMatchInfo != NULL) {
1061
    size_t size = taosArrayGetSize(pColMatchInfo->pList);
H
Haojun Liao 已提交
1062
    for (int32_t i = 0; i < size; ++i) {
H
Haojun Liao 已提交
1063
      SColMatchItem* pInfo = taosArrayGet(pColMatchInfo->pList, i);
1064
      if (pInfo->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
1065
        SColumnInfoData* pColData = taosArrayGet(pBlock->pDataBlock, pInfo->dstSlotId);
1066
        if (pColData->info.type == TSDB_DATA_TYPE_TIMESTAMP) {
H
Haojun Liao 已提交
1067
          blockDataUpdateTsWindow(pBlock, pInfo->dstSlotId);
1068 1069 1070 1071 1072 1073
          break;
        }
      }
    }
  }

1074 1075
  colDataDestroy(p);
  taosMemoryFree(p);
1076 1077
}

1078
void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const SColumnInfoData* p, bool keep, int32_t status) {
1079 1080 1081 1082
  if (keep) {
    return;
  }

H
Haojun Liao 已提交
1083 1084 1085
  int32_t totalRows = pBlock->info.rows;

  if (status == FILTER_RESULT_ALL_QUALIFIED) {
1086
    // here nothing needs to be done
H
Haojun Liao 已提交
1087
  } else if (status == FILTER_RESULT_NONE_QUALIFIED) {
1088
    pBlock->info.rows = 0;
H
Haojun Liao 已提交
1089
  } else {
1090
    SSDataBlock* px = createOneDataBlock(pBlock, true);
1091

1092 1093
    size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
    for (int32_t i = 0; i < numOfCols; ++i) {
1094 1095
      SColumnInfoData* pSrc = taosArrayGet(px->pDataBlock, i);
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, i);
1096
      // it is a reserved column for scalar function, and no data in this column yet.
1097
      if (pDst->pData == NULL || pSrc->pData == NULL) {
1098 1099 1100
        continue;
      }

1101 1102
      colInfoDataCleanup(pDst, pBlock->info.rows);

1103
      int32_t numOfRows = 0;
1104
      for (int32_t j = 0; j < totalRows; ++j) {
1105
        if (((int8_t*)p->pData)[j] == 0) {
D
dapan1121 已提交
1106 1107
          continue;
        }
1108

D
dapan1121 已提交
1109
        if (colDataIsNull_s(pSrc, j)) {
1110
          colDataAppendNULL(pDst, numOfRows);
D
dapan1121 已提交
1111
        } else {
1112
          colDataAppend(pDst, numOfRows, colDataGetData(pSrc, j), false);
D
dapan1121 已提交
1113
        }
1114
        numOfRows += 1;
H
Haojun Liao 已提交
1115
      }
1116

1117
      // todo this value can be assigned directly
1118 1119 1120 1121 1122
      if (pBlock->info.rows == totalRows) {
        pBlock->info.rows = numOfRows;
      } else {
        ASSERT(pBlock->info.rows == numOfRows);
      }
1123
    }
1124

dengyihao's avatar
dengyihao 已提交
1125
    blockDataDestroy(px);  // fix memory leak
1126 1127 1128
  }
}

1129
void doSetTableGroupOutputBuf(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId) {
1130
  // for simple group by query without interval, all the tables belong to one group result.
1131 1132 1133
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
  SAggOperatorInfo* pAggInfo = pOperator->info;

1134
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
1135 1136
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
  int32_t*        rowEntryInfoOffset = pOperator->exprSupp.rowEntryInfoOffset;
1137

1138
  SResultRow* pResultRow = doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, (char*)&groupId,
L
Liu Jicong 已提交
1139
                                                  sizeof(groupId), true, groupId, pTaskInfo, false, &pAggInfo->aggSup);
L
Liu Jicong 已提交
1140
  assert(pResultRow != NULL);
1141 1142 1143 1144 1145 1146

  /*
   * 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 已提交
1147 1148
    int32_t ret =
        addNewWindowResultBuf(pResultRow, pAggInfo->aggSup.pResultBuf, groupId, pAggInfo->binfo.pRes->info.rowSize);
1149 1150 1151 1152 1153
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

1154
  setResultRowInitCtx(pResultRow, pCtx, numOfOutput, rowEntryInfoOffset);
1155 1156
}

1157 1158 1159
static void setExecutionContext(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId) {
  SAggOperatorInfo* pAggInfo = pOperator->info;
  if (pAggInfo->groupId != UINT64_MAX && pAggInfo->groupId == groupId) {
1160 1161
    return;
  }
1162 1163

  doSetTableGroupOutputBuf(pOperator, numOfOutput, groupId);
1164 1165

  // record the current active group id
H
Haojun Liao 已提交
1166
  pAggInfo->groupId = groupId;
1167 1168
}

dengyihao's avatar
dengyihao 已提交
1169 1170
static void doUpdateNumOfRows(SqlFunctionCtx* pCtx, SResultRow* pRow, int32_t numOfExprs,
                              const int32_t* rowCellOffset) {
1171
  bool returnNotNull = false;
1172
  for (int32_t j = 0; j < numOfExprs; ++j) {
1173
    struct SResultRowEntryInfo* pResInfo = getResultEntryInfo(pRow, j, rowCellOffset);
1174 1175 1176 1177 1178 1179 1180
    if (!isRowEntryInitialized(pResInfo)) {
      continue;
    }

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

1182
    if (fmIsNotNullOutputFunc(pCtx[j].functionId)) {
1183 1184
      returnNotNull = true;
    }
1185
  }
S
shenglian zhou 已提交
1186 1187
  // 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
1188
  if (pRow->numOfRows == 0 && !returnNotNull) {
1189
    pRow->numOfRows = 1;
1190 1191 1192
  }
}

1193 1194
static void doCopyResultToDataBlock(SExprInfo* pExprInfo, int32_t numOfExprs, SResultRow* pRow, SqlFunctionCtx* pCtx,
                                    SSDataBlock* pBlock, const int32_t* rowEntryOffset, SExecTaskInfo* pTaskInfo) {
1195 1196 1197
  for (int32_t j = 0; j < numOfExprs; ++j) {
    int32_t slotId = pExprInfo[j].base.resSchema.slotId;

1198
    pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowEntryOffset);
1199
    if (pCtx[j].fpSet.finalize) {
1200
      if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_group_key") == 0) {
1201 1202
        // for groupkey along with functions that output multiple lines(e.g. Histogram)
        // need to match groupkey result for each output row of that function.
1203 1204 1205 1206 1207
        if (pCtx[j].resultInfo->numOfRes != 0) {
          pCtx[j].resultInfo->numOfRes = pRow->numOfRows;
        }
      }

1208 1209 1210
      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));
1211
        T_LONG_JMP(pTaskInfo->env, code);
1212 1213
      }
    } else if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
1214
      // do nothing
1215
    } else {
1216 1217
      // 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.
1218 1219 1220 1221 1222 1223 1224
      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);
      }
    }
  }
1225 1226
}

1227 1228 1229
// todo refactor. SResultRow has direct pointer in miainfo
int32_t finalizeResultRows(SDiskbasedBuf* pBuf, SResultRowPosition* resultRowPosition, SExprSupp* pSup,
                           SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo) {
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
  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);
1256 1257

  releaseBufPage(pBuf, page);
1258
  pBlock->info.rows += pRow->numOfRows;
1259 1260 1261
  return 0;
}

1262 1263 1264 1265 1266 1267 1268
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;

1269
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
1270

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

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

H
Haojun Liao 已提交
1277
    doUpdateNumOfRows(pCtx, pRow, numOfExprs, rowEntryOffset);
1278 1279

    // no results, continue to check the next one
1280 1281
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
1282
      releaseBufPage(pBuf, page);
1283 1284 1285
      continue;
    }

1286 1287 1288 1289 1290
    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) {
1291
        releaseBufPage(pBuf, page);
1292 1293 1294 1295
        break;
      }
    }

1296
    if (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
1297
      ASSERT(pBlock->info.rows > 0);
1298
      releaseBufPage(pBuf, page);
1299 1300 1301 1302
      break;
    }

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

1305
    releaseBufPage(pBuf, page);
1306
    pBlock->info.rows += pRow->numOfRows;
1307 1308
  }

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

1312
  blockDataUpdateTsWindow(pBlock, 0);
1313 1314 1315
  return 0;
}

1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
void doBuildStreamResBlock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SGroupResInfo* pGroupResInfo,
                           SDiskbasedBuf* pBuf) {
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SSDataBlock*   pBlock = pbInfo->pRes;

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

  blockDataCleanup(pBlock);
  if (!hasRemainResults(pGroupResInfo)) {
    return;
  }

  // clear the existed group id
  pBlock->info.groupId = 0;
  ASSERT(!pbInfo->mergeResultBlock);
  doCopyToSDataBlock(pTaskInfo, pBlock, &pOperator->exprSupp, pBuf, pGroupResInfo);

1334 1335 1336 1337 1338
  void* tbname = NULL;
  if (streamStateGetParName(pTaskInfo->streamInfo.pState, pBlock->info.groupId, &tbname) < 0) {
    pBlock->info.parTbName[0] = 0;
  } else {
    memcpy(pBlock->info.parTbName, tbname, TSDB_TABLE_NAME_LEN);
1339
  }
1340
  tdbFree(tbname);
1341 1342
}

X
Xiaoyu Wang 已提交
1343 1344
void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SGroupResInfo* pGroupResInfo,
                            SDiskbasedBuf* pBuf) {
1345
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
1346
  SSDataBlock*   pBlock = pbInfo->pRes;
1347

1348 1349 1350
  // set output datablock version
  pBlock->info.version = pTaskInfo->version;

1351
  blockDataCleanup(pBlock);
1352
  if (!hasRemainResults(pGroupResInfo)) {
1353 1354 1355
    return;
  }

1356 1357
  // clear the existed group id
  pBlock->info.groupId = 0;
1358 1359 1360
  if (!pbInfo->mergeResultBlock) {
    doCopyToSDataBlock(pTaskInfo, pBlock, &pOperator->exprSupp, pBuf, pGroupResInfo);
  } else {
dengyihao's avatar
dengyihao 已提交
1361
    while (hasRemainResults(pGroupResInfo)) {
1362 1363 1364
      doCopyToSDataBlock(pTaskInfo, pBlock, &pOperator->exprSupp, pBuf, pGroupResInfo);
      if (pBlock->info.rows >= pOperator->resultInfo.threshold) {
        break;
1365 1366
      }

1367 1368
      // clearing group id to continue to merge data that belong to different groups
      pBlock->info.groupId = 0;
1369
    }
1370 1371 1372

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

L
Liu Jicong 已提交
1376 1377
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
1378

1379 1380
  SFileBlockLoadRecorder* pRecorder = pSummary->pRecoder;
  if (pSummary->pRecoder != NULL) {
1381
    qDebug(
H
Haojun Liao 已提交
1382 1383 1384 1385 1386
        "%s :cost summary: elapsed time:%.2f ms, extract tableList:%.2f ms, createGroupIdMap:%.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, pSummary->extractListTime, pSummary->groupIdMapTime,
        pRecorder->totalBlocks, pRecorder->loadBlockStatis, pRecorder->loadBlocks, pRecorder->totalRows,
        pRecorder->totalCheckedRows);
1387
  }
1388 1389
}

L
Liu Jicong 已提交
1390 1391 1392
// static void updateOffsetVal(STaskRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
1393
//
L
Liu Jicong 已提交
1394
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
1395
//
L
Liu Jicong 已提交
1396 1397 1398 1399
//   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;
//   }
1400
//
L
Liu Jicong 已提交
1401 1402 1403 1404 1405
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     pQueryAttr->pos = (int32_t)pQueryAttr->limit.offset;
//   } else {
//     pQueryAttr->pos = pBlockInfo->rows - (int32_t)pQueryAttr->limit.offset - 1;
//   }
1406
//
L
Liu Jicong 已提交
1407
//   assert(pQueryAttr->pos >= 0 && pQueryAttr->pos <= pBlockInfo->rows - 1);
1408
//
L
Liu Jicong 已提交
1409 1410
//   SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//   SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
1411
//
L
Liu Jicong 已提交
1412 1413
//   // update the pQueryAttr->limit.offset value, and pQueryAttr->pos value
//   TSKEY *keys = (TSKEY *) pColInfoData->pData;
1414
//
L
Liu Jicong 已提交
1415 1416 1417
//   // update the offset value
//   pTableQueryInfo->lastKey = keys[pQueryAttr->pos];
//   pQueryAttr->limit.offset = 0;
1418
//
L
Liu Jicong 已提交
1419
//   int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
1420
//
L
Liu Jicong 已提交
1421 1422 1423 1424
//   //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);
// }
1425

L
Liu Jicong 已提交
1426 1427
// void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
1428
//
L
Liu Jicong 已提交
1429 1430 1431
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//     return;
//   }
1432
//
L
Liu Jicong 已提交
1433 1434
//   pQueryAttr->pos = 0;
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
1435
//
L
Liu Jicong 已提交
1436 1437
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//   TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
1438
//
L
Liu Jicong 已提交
1439 1440 1441
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pTsdbReadHandle)) {
//     if (isTaskKilled(pRuntimeEnv->qinfo)) {
1442
//       T_LONG_JMP(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
L
Liu Jicong 已提交
1443
//     }
1444
//
L
Liu Jicong 已提交
1445
//     tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
1446
//
L
Liu Jicong 已提交
1447 1448 1449 1450
//     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;
1451
//
L
Liu Jicong 已提交
1452 1453 1454 1455 1456 1457 1458
//       //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;
//     }
//   }
1459
//
L
Liu Jicong 已提交
1460
//   if (terrno != TSDB_CODE_SUCCESS) {
1461
//     T_LONG_JMP(pRuntimeEnv->env, terrno);
L
Liu Jicong 已提交
1462 1463 1464 1465 1466 1467 1468
//   }
// }

// static TSKEY doSkipIntervalProcess(STaskRuntimeEnv* pRuntimeEnv, STimeWindow* win, SDataBlockInfo* pBlockInfo,
// STableQueryInfo* pTableQueryInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
1469
//
L
Liu Jicong 已提交
1470 1471 1472
//   assert(pQueryAttr->limit.offset == 0);
//   STimeWindow tw = *win;
//   getNextTimeWindow(pQueryAttr, &tw);
1473
//
L
Liu Jicong 已提交
1474 1475
//   if ((tw.skey <= pBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) ||
//       (tw.ekey >= pBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
1476
//
L
Liu Jicong 已提交
1477 1478 1479 1480
//     // 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);
1481
//
L
Liu Jicong 已提交
1482 1483 1484 1485
//     tw = *win;
//     int32_t startPos =
//         getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1);
//     assert(startPos >= 0);
1486
//
L
Liu Jicong 已提交
1487 1488
//     // set the abort info
//     pQueryAttr->pos = startPos;
1489
//
L
Liu Jicong 已提交
1490 1491 1492 1493
//     // reset the query start timestamp
//     pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
//     pQueryAttr->window.skey = pTableQueryInfo->win.skey;
//     TSKEY key = pTableQueryInfo->win.skey;
1494
//
L
Liu Jicong 已提交
1495 1496
//     pWindowResInfo->prevSKey = tw.skey;
//     int32_t index = pRuntimeEnv->resultRowInfo.curIndex;
1497
//
L
Liu Jicong 已提交
1498 1499
//     int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//     pRuntimeEnv->resultRowInfo.curIndex = index;  // restore the window index
1500
//
L
Liu Jicong 已提交
1501 1502 1503 1504
//     //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);
1505
//
L
Liu Jicong 已提交
1506 1507 1508 1509 1510
//     return key;
//   } else {  // do nothing
//     pQueryAttr->window.skey      = tw.skey;
//     pWindowResInfo->prevSKey = tw.skey;
//     pTableQueryInfo->lastKey = tw.skey;
1511
//
L
Liu Jicong 已提交
1512 1513
//     return tw.skey;
//   }
1514
//
L
Liu Jicong 已提交
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
//   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);
//   }
1525
//
L
Liu Jicong 已提交
1526 1527 1528 1529 1530
//   // 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;
//   }
1531
//
L
Liu Jicong 已提交
1532 1533 1534 1535 1536 1537 1538
//   /*
//    * 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);
1539
//
L
Liu Jicong 已提交
1540 1541
//   STimeWindow w = TSWINDOW_INITIALIZER;
//   bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
1542
//
L
Liu Jicong 已提交
1543 1544
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//   STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
1545
//
L
Liu Jicong 已提交
1546 1547 1548
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pRuntimeEnv->pTsdbReadHandle)) {
//     tsdbRetrieveDataBlockInfo(pRuntimeEnv->pTsdbReadHandle, &blockInfo);
1549
//
L
Liu Jicong 已提交
1550 1551 1552 1553 1554 1555 1556 1557 1558
//     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;
//     }
1559
//
L
Liu Jicong 已提交
1560 1561
//     // the first time window
//     STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQueryAttr);
1562
//
L
Liu Jicong 已提交
1563 1564
//     while (pQueryAttr->limit.offset > 0) {
//       STimeWindow tw = win;
1565
//
L
Liu Jicong 已提交
1566 1567 1568
//       if ((win.ekey <= blockInfo.window.ekey && ascQuery) || (win.ekey >= blockInfo.window.skey && !ascQuery)) {
//         pQueryAttr->limit.offset -= 1;
//         pWindowResInfo->prevSKey = win.skey;
1569
//
L
Liu Jicong 已提交
1570 1571 1572 1573 1574 1575
//         // 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;
//         }
//       }
1576
//
L
Liu Jicong 已提交
1577 1578 1579 1580
//       if (pQueryAttr->limit.offset == 0) {
//         *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//         return true;
//       }
1581
//
L
Liu Jicong 已提交
1582 1583
//       // current window does not ended in current data block, try next data block
//       getNextTimeWindow(pQueryAttr, &tw);
1584
//
L
Liu Jicong 已提交
1585 1586 1587 1588 1589 1590 1591 1592 1593
//       /*
//        * 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)) {
1594
//
L
Liu Jicong 已提交
1595 1596
//         SArray *pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//         SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
1597
//
L
Liu Jicong 已提交
1598 1599 1600
//         if ((win.ekey > blockInfo.window.ekey && ascQuery) || (win.ekey < blockInfo.window.skey && !ascQuery)) {
//           pQueryAttr->limit.offset -= 1;
//         }
1601
//
L
Liu Jicong 已提交
1602 1603 1604 1605 1606 1607 1608 1609
//         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);
1610
//
L
Liu Jicong 已提交
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
//           // 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.
//       }
//     }
//   }
1622
//
L
Liu Jicong 已提交
1623 1624
//   // check for error
//   if (terrno != TSDB_CODE_SUCCESS) {
1625
//     T_LONG_JMP(pRuntimeEnv->env, terrno);
L
Liu Jicong 已提交
1626
//   }
1627
//
L
Liu Jicong 已提交
1628 1629
//   return true;
// }
1630

1631
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
1632
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
1633
    assert(p->numOfDownstream == 0);
1634 1635
  }

wafwerar's avatar
wafwerar 已提交
1636
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
1637 1638 1639 1640 1641 1642 1643
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

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

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

X
Xiaoyu Wang 已提交
1649
int32_t getTableScanInfo(SOperatorInfo* pOperator, int32_t* order, int32_t* scanFlag) {
1650
  // todo add more information about exchange operation
1651
  int32_t type = pOperator->operatorType;
X
Xiaoyu Wang 已提交
1652
  if (type == QUERY_NODE_PHYSICAL_PLAN_EXCHANGE || type == QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN ||
1653
      type == QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN || type == QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN ||
1654
      type == QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN || type == QUERY_NODE_PHYSICAL_PLAN_LAST_ROW_SCAN) {
1655 1656 1657
    *order = TSDB_ORDER_ASC;
    *scanFlag = MAIN_SCAN;
    return TSDB_CODE_SUCCESS;
1658
  } else if (type == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
1659
    STableScanInfo* pTableScanInfo = pOperator->info;
H
Haojun Liao 已提交
1660 1661
    *order = pTableScanInfo->base.cond.order;
    *scanFlag = pTableScanInfo->base.scanFlag;
1662
    return TSDB_CODE_SUCCESS;
1663 1664
  } else if (type == QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN) {
    STableMergeScanInfo* pTableScanInfo = pOperator->info;
H
Haojun Liao 已提交
1665 1666
    *order = pTableScanInfo->base.cond.order;
    *scanFlag = pTableScanInfo->base.scanFlag;
1667
    return TSDB_CODE_SUCCESS;
1668
  } else {
H
Haojun Liao 已提交
1669
    if (pOperator->pDownstream == NULL || pOperator->pDownstream[0] == NULL) {
1670
      return TSDB_CODE_INVALID_PARA;
H
Haojun Liao 已提交
1671
    } else {
1672
      return getTableScanInfo(pOperator->pDownstream[0], order, scanFlag);
1673 1674 1675
    }
  }
}
1676

1677
// this is a blocking operator
L
Liu Jicong 已提交
1678
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
1679 1680
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
1681 1682
  }

H
Haojun Liao 已提交
1683
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
1684
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
1685

1686 1687
  SExprSupp*     pSup = &pOperator->exprSupp;
  SOperatorInfo* downstream = pOperator->pDownstream[0];
1688

1689 1690
  int64_t st = taosGetTimestampUs();

1691 1692 1693
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;

H
Haojun Liao 已提交
1694
  while (1) {
1695
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
1696 1697 1698 1699
    if (pBlock == NULL) {
      break;
    }

1700 1701
    int32_t code = getTableScanInfo(pOperator, &order, &scanFlag);
    if (code != TSDB_CODE_SUCCESS) {
1702
      T_LONG_JMP(pTaskInfo->env, code);
1703
    }
1704

1705
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
1706 1707 1708
    if (pAggInfo->scalarExprSup.pExprInfo != NULL) {
      SExprSupp* pSup1 = &pAggInfo->scalarExprSup;
      code = projectApplyFunctions(pSup1->pExprInfo, pBlock, pBlock, pSup1->pCtx, pSup1->numOfExprs, NULL);
1709
      if (code != TSDB_CODE_SUCCESS) {
1710
        T_LONG_JMP(pTaskInfo->env, code);
1711
      }
1712 1713
    }

1714
    // the pDataBlock are always the same one, no need to call this again
1715
    setExecutionContext(pOperator, pOperator->exprSupp.numOfExprs, pBlock->info.groupId);
1716
    setInputDataBlock(pSup, pBlock, order, scanFlag, true);
1717
    code = doAggregateImpl(pOperator, pSup->pCtx);
1718
    if (code != 0) {
1719
      T_LONG_JMP(pTaskInfo->env, code);
1720
    }
1721 1722
  }

1723
  initGroupedResultInfo(&pAggInfo->groupResInfo, pAggInfo->aggSup.pResultRowHashTable, 0);
H
Haojun Liao 已提交
1724
  OPTR_SET_OPENED(pOperator);
1725

1726
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
1727 1728 1729
  return TSDB_CODE_SUCCESS;
}

1730
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
1731
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
1732 1733 1734 1735 1736 1737
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

L
Liu Jicong 已提交
1738
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
1739
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
H
Haojun Liao 已提交
1740
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1741
    setOperatorCompleted(pOperator);
H
Haojun Liao 已提交
1742 1743 1744
    return NULL;
  }

H
Haojun Liao 已提交
1745
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
S
slzhou 已提交
1746 1747
  while (1) {
    doBuildResultDatablock(pOperator, pInfo, &pAggInfo->groupResInfo, pAggInfo->aggSup.pResultBuf);
H
Haojun Liao 已提交
1748
    doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
S
slzhou 已提交
1749

1750
    if (!hasRemainResults(&pAggInfo->groupResInfo)) {
H
Haojun Liao 已提交
1751
      setOperatorCompleted(pOperator);
S
slzhou 已提交
1752 1753
      break;
    }
1754

S
slzhou 已提交
1755 1756 1757 1758
    if (pInfo->pRes->info.rows > 0) {
      break;
    }
  }
1759

1760
  size_t rows = blockDataGetNumOfRows(pInfo->pRes);
1761 1762
  pOperator->resultInfo.totalRows += rows;

1763
  return (rows == 0) ? NULL : pInfo->pRes;
1764 1765
}

wmmhello's avatar
wmmhello 已提交
1766
int32_t aggEncodeResultRow(SOperatorInfo* pOperator, char** result, int32_t* length) {
1767
  if (result == NULL || length == NULL) {
wmmhello's avatar
wmmhello 已提交
1768 1769 1770
    return TSDB_CODE_TSC_INVALID_INPUT;
  }
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)(pOperator->info);
1771
  SAggSupporter*  pSup = (SAggSupporter*)POINTER_SHIFT(pOperator->info, sizeof(SOptrBasicInfo));
1772
  int32_t         size = tSimpleHashGetSize(pSup->pResultRowHashTable);
1773 1774 1775
  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 已提交
1776

C
Cary Xu 已提交
1777 1778 1779 1780 1781 1782
  // no result
  if (getTotalBufSize(pSup->pResultBuf) == 0) {
    *result = NULL;
    *length = 0;
    return TSDB_CODE_SUCCESS;
  }
1783

wmmhello's avatar
wmmhello 已提交
1784
  *result = (char*)taosMemoryCalloc(1, totalSize);
L
Liu Jicong 已提交
1785
  if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
1786
    return TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
1787
  }
wmmhello's avatar
wmmhello 已提交
1788

wmmhello's avatar
wmmhello 已提交
1789
  int32_t offset = sizeof(int32_t);
wmmhello's avatar
wmmhello 已提交
1790 1791
  *(int32_t*)(*result + offset) = size;
  offset += sizeof(int32_t);
1792 1793

  // prepare memory
1794
  SResultRowPosition* pos = &pInfo->resultRowInfo.cur;
dengyihao's avatar
dengyihao 已提交
1795 1796
  void*               pPage = getBufPage(pSup->pResultBuf, pos->pageId);
  SResultRow*         pRow = (SResultRow*)((char*)pPage + pos->offset);
1797 1798
  setBufPageDirty(pPage, true);
  releaseBufPage(pSup->pResultBuf, pPage);
L
Liu Jicong 已提交
1799

1800 1801 1802 1803
  int32_t iter = 0;
  void*   pIter = NULL;
  while ((pIter = tSimpleHashIterate(pSup->pResultRowHashTable, pIter, &iter))) {
    void*               key = tSimpleHashGetKey(pIter, &keyLen);
1804
    SResultRowPosition* p1 = (SResultRowPosition*)pIter;
1805

dengyihao's avatar
dengyihao 已提交
1806
    pPage = (SFilePage*)getBufPage(pSup->pResultBuf, p1->pageId);
1807
    pRow = (SResultRow*)((char*)pPage + p1->offset);
1808 1809
    setBufPageDirty(pPage, true);
    releaseBufPage(pSup->pResultBuf, pPage);
wmmhello's avatar
wmmhello 已提交
1810 1811 1812

    // recalculate the result size
    int32_t realTotalSize = offset + sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize;
L
Liu Jicong 已提交
1813
    if (realTotalSize > totalSize) {
wmmhello's avatar
wmmhello 已提交
1814
      char* tmp = (char*)taosMemoryRealloc(*result, realTotalSize);
L
Liu Jicong 已提交
1815
      if (tmp == NULL) {
wafwerar's avatar
wafwerar 已提交
1816
        taosMemoryFree(*result);
wmmhello's avatar
wmmhello 已提交
1817
        *result = NULL;
wmmhello's avatar
wmmhello 已提交
1818
        return TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
1819
      } else {
wmmhello's avatar
wmmhello 已提交
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
        *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);
1832
    memcpy(*result + offset, pRow, pSup->resultRowSize);
wmmhello's avatar
wmmhello 已提交
1833 1834 1835
    offset += pSup->resultRowSize;
  }

wmmhello's avatar
wmmhello 已提交
1836 1837 1838 1839
  *(int32_t*)(*result) = offset;
  *length = offset;

  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1840 1841
}

1842 1843 1844 1845 1846
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);
1847
      return PROJECT_RETRIEVE_CONTINUE;
1848 1849 1850
    } else if (pLimitInfo->currentGroupId != pBlock->info.groupId) {
      // now it is the data from a new group
      pLimitInfo->remainGroupOffset -= 1;
1851 1852

      // ignore data block in current group
1853 1854
      if (pLimitInfo->remainGroupOffset > 0) {
        blockDataCleanup(pBlock);
1855 1856 1857 1858 1859
        return PROJECT_RETRIEVE_CONTINUE;
      }
    }

    // set current group id of the project operator
1860
    pLimitInfo->currentGroupId = pBlock->info.groupId;
1861 1862
  }

1863
  // here check for a new group data, we need to handle the data of the previous group.
1864 1865 1866
  if (pLimitInfo->currentGroupId != 0 && pLimitInfo->currentGroupId != pBlock->info.groupId) {
    pLimitInfo->numOfOutputGroups += 1;
    if ((pLimitInfo->slimit.limit > 0) && (pLimitInfo->slimit.limit <= pLimitInfo->numOfOutputGroups)) {
1867
      pOperator->status = OP_EXEC_DONE;
1868
      blockDataCleanup(pBlock);
1869 1870 1871 1872 1873

      return PROJECT_RETRIEVE_DONE;
    }

    // reset the value for a new group data
1874 1875
    pLimitInfo->numOfOutputRows = 0;
    pLimitInfo->remainOffset = pLimitInfo->limit.offset;
1876 1877 1878 1879 1880

    // existing rows that belongs to previous group.
    if (pBlock->info.rows > 0) {
      return PROJECT_RETRIEVE_DONE;
    }
1881 1882 1883 1884 1885
  }

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

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

1888 1889 1890
  if (pLimitInfo->remainOffset >= pBlock->info.rows) {
    pLimitInfo->remainOffset -= pBlock->info.rows;
    blockDataCleanup(pBlock);
1891
    return PROJECT_RETRIEVE_CONTINUE;
1892 1893 1894
  } else if (pLimitInfo->remainOffset < pBlock->info.rows && pLimitInfo->remainOffset > 0) {
    blockDataTrimFirstNRows(pBlock, pLimitInfo->remainOffset);
    pLimitInfo->remainOffset = 0;
1895 1896
  }

1897
  // check for the limitation in each group
1898 1899 1900 1901
  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) {
1902 1903 1904
      pOperator->status = OP_EXEC_DONE;
    }

1905
    return PROJECT_RETRIEVE_DONE;
1906
  }
1907

1908
  // todo optimize performance
1909 1910
  // 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.
1911 1912
  if ((!holdDataInBuf) || (pBlock->info.rows >= pOperator->resultInfo.threshold) || pLimitInfo->slimit.offset != -1 ||
      pLimitInfo->slimit.limit != -1) {
1913
    return PROJECT_RETRIEVE_DONE;
L
Liu Jicong 已提交
1914
  } else {  // not full enough, continue to accumulate the output data in the buffer.
1915 1916 1917 1918
    return PROJECT_RETRIEVE_CONTINUE;
  }
}

1919
static void doApplyScalarCalculation(SOperatorInfo* pOperator, SSDataBlock* pBlock, int32_t order, int32_t scanFlag);
L
Liu Jicong 已提交
1920 1921
static void doHandleRemainBlockForNewGroupImpl(SOperatorInfo* pOperator, SFillOperatorInfo* pInfo,
                                               SResultInfo* pResultInfo, SExecTaskInfo* pTaskInfo) {
1922
  pInfo->totalInputRows = pInfo->existNewGroupBlock->info.rows;
1923 1924 1925 1926 1927
  SSDataBlock* pResBlock = pInfo->pFinalRes;

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

5
54liuyao 已提交
1929
  int64_t ekey = pInfo->existNewGroupBlock->info.window.ekey;
1930 1931
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

1932
  blockDataCleanup(pInfo->pRes);
1933 1934 1935 1936
  doApplyScalarCalculation(pOperator, pInfo->existNewGroupBlock, order, scanFlag);

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

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

1941
  pInfo->curGroupId = pInfo->existNewGroupBlock->info.groupId;
1942 1943 1944
  pInfo->existNewGroupBlock = NULL;
}

L
Liu Jicong 已提交
1945 1946
static void doHandleRemainBlockFromNewGroup(SOperatorInfo* pOperator, SFillOperatorInfo* pInfo,
                                            SResultInfo* pResultInfo, SExecTaskInfo* pTaskInfo) {
1947
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
H
Haojun Liao 已提交
1948 1949
    int32_t numOfResultRows = pResultInfo->capacity - pInfo->pFinalRes->info.rows;
    taosFillResultDataBlock(pInfo->pFillInfo, pInfo->pFinalRes, numOfResultRows);
1950 1951
    pInfo->pRes->info.groupId = pInfo->curGroupId;
    return;
1952 1953 1954 1955
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
1956 1957 1958 1959 1960 1961
    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 已提交
1962
  SExprSupp*         pSup = &pOperator->exprSupp;
1963
  setInputDataBlock(pSup, pBlock, order, scanFlag, false);
1964 1965
  projectApplyFunctions(pSup->pExprInfo, pInfo->pRes, pBlock, pSup->pCtx, pSup->numOfExprs, NULL);

1966 1967 1968 1969
  // reset the row value before applying the no-fill functions to the input data block, which is "pBlock" in this case.
  pInfo->pRes->info.rows = 0;
  SExprSupp* pNoFillSupp = &pInfo->noFillExprSupp;
  setInputDataBlock(pNoFillSupp, pBlock, order, scanFlag, false);
1970

1971 1972
  projectApplyFunctions(pNoFillSupp->pExprInfo, pInfo->pRes, pBlock, pNoFillSupp->pCtx, pNoFillSupp->numOfExprs, NULL);
  pInfo->pRes->info.groupId = pBlock->info.groupId;
1973 1974
}

S
slzhou 已提交
1975
static SSDataBlock* doFillImpl(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
1976 1977
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
1978

H
Haojun Liao 已提交
1979
  SResultInfo* pResultInfo = &pOperator->resultInfo;
H
Haojun Liao 已提交
1980
  SSDataBlock* pResBlock = pInfo->pFinalRes;
1981 1982

  blockDataCleanup(pResBlock);
1983

H
Haojun Liao 已提交
1984 1985
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;
1986
  getTableScanInfo(pOperator, &order, &scanFlag);
1987

1988
  doHandleRemainBlockFromNewGroup(pOperator, pInfo, pResultInfo, pTaskInfo);
1989
  if (pResBlock->info.rows > 0) {
1990
    pResBlock->info.groupId = pInfo->curGroupId;
1991
    return pResBlock;
H
Haojun Liao 已提交
1992
  }
1993

H
Haojun Liao 已提交
1994
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
1995
  while (1) {
1996
    SSDataBlock* pBlock = pDownstream->fpSet.getNextFn(pDownstream);
1997 1998
    if (pBlock == NULL) {
      if (pInfo->totalInputRows == 0) {
H
Haojun Liao 已提交
1999
        setOperatorCompleted(pOperator);
2000 2001
        return NULL;
      }
2002

2003
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pInfo->win.ekey);
2004
    } else {
2005
      blockDataUpdateTsWindow(pBlock, pInfo->primarySrcSlotId);
2006 2007

      blockDataCleanup(pInfo->pRes);
2008 2009
      blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);
      blockDataEnsureCapacity(pInfo->pFinalRes, pBlock->info.rows);
2010
      doApplyScalarCalculation(pOperator, pBlock, order, scanFlag);
2011

H
Haojun Liao 已提交
2012 2013 2014
      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;
2015

H
Haojun Liao 已提交
2016 2017 2018 2019 2020
        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 已提交
2021
        taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->pRes);
L
Liu Jicong 已提交
2022
      } else if (pInfo->curGroupId != pBlock->info.groupId) {  // the new group data block
2023 2024 2025 2026 2027
        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);
2028 2029 2030
      }
    }

2031 2032
    int32_t numOfResultRows = pOperator->resultInfo.capacity - pResBlock->info.rows;
    taosFillResultDataBlock(pInfo->pFillInfo, pResBlock, numOfResultRows);
2033 2034

    // current group has no more result to return
2035
    if (pResBlock->info.rows > 0) {
2036 2037
      // 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
2038
      if (pResBlock->info.rows > pResultInfo->threshold || pBlock == NULL || pInfo->existNewGroupBlock != NULL) {
2039
        pResBlock->info.groupId = pInfo->curGroupId;
2040
        return pResBlock;
2041 2042
      }

2043
      doHandleRemainBlockFromNewGroup(pOperator, pInfo, pResultInfo, pTaskInfo);
2044
      if (pResBlock->info.rows >= pOperator->resultInfo.threshold || pBlock == NULL) {
2045
        pResBlock->info.groupId = pInfo->curGroupId;
2046
        return pResBlock;
2047 2048 2049
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
2050 2051 2052 2053

      blockDataCleanup(pResBlock);

      doHandleRemainBlockForNewGroupImpl(pOperator, pInfo, pResultInfo, pTaskInfo);
2054
      if (pResBlock->info.rows > pResultInfo->threshold) {
2055
        pResBlock->info.groupId = pInfo->curGroupId;
2056
        return pResBlock;
2057 2058 2059 2060 2061 2062 2063
      }
    } else {
      return NULL;
    }
  }
}

S
slzhou 已提交
2064 2065 2066 2067 2068 2069 2070 2071
static SSDataBlock* doFill(SOperatorInfo* pOperator) {
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;

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

S
slzhou 已提交
2072
  SSDataBlock* fillResult = NULL;
S
slzhou 已提交
2073
  while (true) {
S
slzhou 已提交
2074
    fillResult = doFillImpl(pOperator);
S
slzhou 已提交
2075
    if (fillResult == NULL) {
H
Haojun Liao 已提交
2076
      setOperatorCompleted(pOperator);
S
slzhou 已提交
2077 2078 2079
      break;
    }

2080
    doFilter(fillResult, pOperator->exprSupp.pFilterInfo, &pInfo->matchInfo);
S
slzhou 已提交
2081 2082 2083 2084 2085
    if (fillResult->info.rows > 0) {
      break;
    }
  }

S
slzhou 已提交
2086
  if (fillResult != NULL) {
2087
    pOperator->resultInfo.totalRows += fillResult->info.rows;
S
slzhou 已提交
2088
  }
S
slzhou 已提交
2089

S
slzhou 已提交
2090
  return fillResult;
S
slzhou 已提交
2091 2092
}

2093
void destroyExprInfo(SExprInfo* pExpr, int32_t numOfExprs) {
C
Cary Xu 已提交
2094 2095 2096 2097 2098
  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 已提交
2099
      }
2100
    }
C
Cary Xu 已提交
2101 2102 2103

    taosMemoryFree(pExprInfo->base.pParam);
    taosMemoryFree(pExprInfo->pExpr);
H
Haojun Liao 已提交
2104 2105 2106
  }
}

5
54liuyao 已提交
2107
void destroyOperatorInfo(SOperatorInfo* pOperator) {
2108 2109 2110 2111
  if (pOperator == NULL) {
    return;
  }

2112
  if (pOperator->fpSet.closeFn != NULL) {
2113
    pOperator->fpSet.closeFn(pOperator->info);
2114 2115
  }

H
Haojun Liao 已提交
2116
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
2117
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
2118
      destroyOperatorInfo(pOperator->pDownstream[i]);
2119 2120
    }

wafwerar's avatar
wafwerar 已提交
2121
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
2122
    pOperator->numOfDownstream = 0;
2123 2124
  }

2125
  cleanupExprSupp(&pOperator->exprSupp);
wafwerar's avatar
wafwerar 已提交
2126
  taosMemoryFreeClear(pOperator);
2127 2128
}

2129 2130 2131 2132 2133 2134
int32_t getBufferPgSize(int32_t rowSize, uint32_t* defaultPgsz, uint32_t* defaultBufsz) {
  *defaultPgsz = 4096;
  while (*defaultPgsz < rowSize * 4) {
    *defaultPgsz <<= 1u;
  }

2135
  // The default buffer for each operator in query is 10MB.
2136
  // at least four pages need to be in buffer
2137 2138
  // TODO: make this variable to be configurable.
  *defaultBufsz = 4096 * 2560;
2139 2140 2141 2142 2143 2144 2145
  if ((*defaultBufsz) <= (*defaultPgsz)) {
    (*defaultBufsz) = (*defaultPgsz) * 4;
  }

  return 0;
}

dengyihao's avatar
dengyihao 已提交
2146 2147
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                         const char* pKey) {
L
Liu Jicong 已提交
2148
  int32_t    code = 0;
2149 2150
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

2151
  pAggSup->currentPageId = -1;
dengyihao's avatar
dengyihao 已提交
2152 2153
  pAggSup->resultRowSize = getResultRowSize(pCtx, numOfOutput);
  pAggSup->keyBuf = taosMemoryCalloc(1, keyBufSize + POINTER_BYTES + sizeof(int64_t));
2154
  pAggSup->pResultRowHashTable = tSimpleHashInit(10, hashFn);
2155

H
Haojun Liao 已提交
2156
  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowHashTable == NULL) {
2157 2158 2159
    return TSDB_CODE_OUT_OF_MEMORY;
  }

dengyihao's avatar
dengyihao 已提交
2160
  uint32_t defaultPgsz = 0;
2161 2162
  uint32_t defaultBufsz = 0;
  getBufferPgSize(pAggSup->resultRowSize, &defaultPgsz, &defaultBufsz);
H
Haojun Liao 已提交
2163

wafwerar's avatar
wafwerar 已提交
2164
  if (!osTempSpaceAvailable()) {
H
Haojun Liao 已提交
2165 2166 2167
    code = TSDB_CODE_NO_AVAIL_DISK;
    qError("Init stream agg supporter failed since %s, %s", terrstr(code), pKey);
    return code;
wafwerar's avatar
wafwerar 已提交
2168
  }
2169

H
Haojun Liao 已提交
2170
  code = createDiskbasedBuf(&pAggSup->pResultBuf, defaultPgsz, defaultBufsz, pKey, tsTempDir);
H
Haojun Liao 已提交
2171
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2172
    qError("Create agg result buf failed since %s, %s", tstrerror(code), pKey);
H
Haojun Liao 已提交
2173 2174 2175
    return code;
  }

H
Haojun Liao 已提交
2176
  return code;
2177 2178
}

2179
void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
2180
  taosMemoryFreeClear(pAggSup->keyBuf);
2181
  tSimpleHashCleanup(pAggSup->pResultRowHashTable);
H
Haojun Liao 已提交
2182
  destroyDiskbasedBuf(pAggSup->pResultBuf);
2183 2184
}

L
Liu Jicong 已提交
2185 2186
int32_t initAggInfo(SExprSupp* pSup, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols, size_t keyBufSize,
                    const char* pkey) {
2187 2188 2189 2190 2191
  int32_t code = initExprSupp(pSup, pExprInfo, numOfCols);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

2192 2193 2194 2195 2196
  code = doInitAggInfoSup(pAggSup, pSup->pCtx, numOfCols, keyBufSize, pkey);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

L
Liu Jicong 已提交
2197
  for (int32_t i = 0; i < numOfCols; ++i) {
2198
    pSup->pCtx[i].saveHandle.pBuf = pAggSup->pResultBuf;
2199 2200
  }

2201
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2202 2203
}

L
Liu Jicong 已提交
2204
void initResultSizeInfo(SResultInfo* pResultInfo, int32_t numOfRows) {
wmmhello's avatar
wmmhello 已提交
2205
  ASSERT(numOfRows != 0);
2206 2207
  pResultInfo->capacity = numOfRows;
  pResultInfo->threshold = numOfRows * 0.75;
2208

2209 2210
  if (pResultInfo->threshold == 0) {
    pResultInfo->threshold = numOfRows;
2211 2212 2213
  }
}

2214 2215 2216 2217 2218
void initBasicInfo(SOptrBasicInfo* pInfo, SSDataBlock* pBlock) {
  pInfo->pRes = pBlock;
  initResultRowInfo(&pInfo->resultRowInfo);
}

5
54liuyao 已提交
2219
void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
  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);
2230
    taosMemoryFreeClear(pCtx[i].subsidiaries.buf);
2231 2232 2233 2234 2235 2236 2237 2238
    taosMemoryFree(pCtx[i].input.pData);
    taosMemoryFree(pCtx[i].input.pColumnDataAgg);
  }

  taosMemoryFreeClear(pCtx);
  return NULL;
}

2239
int32_t initExprSupp(SExprSupp* pSup, SExprInfo* pExprInfo, int32_t numOfExpr) {
2240 2241 2242 2243
  pSup->pExprInfo = pExprInfo;
  pSup->numOfExprs = numOfExpr;
  if (pSup->pExprInfo != NULL) {
    pSup->pCtx = createSqlFunctionCtx(pExprInfo, numOfExpr, &pSup->rowEntryInfoOffset);
2244 2245 2246
    if (pSup->pCtx == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
2247
  }
2248 2249

  return TSDB_CODE_SUCCESS;
2250 2251
}

2252 2253 2254 2255
void cleanupExprSupp(SExprSupp* pSupp) {
  destroySqlFunctionCtx(pSupp->pCtx, pSupp->numOfExprs);
  if (pSupp->pExprInfo != NULL) {
    destroyExprInfo(pSupp->pExprInfo, pSupp->numOfExprs);
C
Cary Xu 已提交
2256
    taosMemoryFreeClear(pSupp->pExprInfo);
2257
  }
H
Haojun Liao 已提交
2258 2259 2260 2261 2262 2263

  if (pSupp->pFilterInfo != NULL) {
    filterFreeInfo(pSupp->pFilterInfo);
    pSupp->pFilterInfo = NULL;
  }

2264 2265 2266
  taosMemoryFree(pSupp->rowEntryInfoOffset);
}

2267 2268
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SAggPhysiNode* pAggNode,
                                           SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
2269
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
2270
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
2271 2272 2273
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
2274

H
Haojun Liao 已提交
2275 2276 2277 2278
  SSDataBlock* pResBlock = createResDataBlock(pAggNode->node.pOutputDataBlockDesc);
  initBasicInfo(&pInfo->binfo, pResBlock);

  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
2279
  initResultSizeInfo(&pOperator->resultInfo, 4096);
H
Haojun Liao 已提交
2280

2281 2282 2283
  int32_t    num = 0;
  SExprInfo* pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
  int32_t    code = initAggInfo(&pOperator->exprSupp, &pInfo->aggSup, pExprInfo, num, keyBufSize, pTaskInfo->id.str);
L
Liu Jicong 已提交
2284
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2285 2286
    goto _error;
  }
H
Haojun Liao 已提交
2287

H
Haojun Liao 已提交
2288 2289 2290 2291 2292 2293
  int32_t    numOfScalarExpr = 0;
  SExprInfo* pScalarExprInfo = NULL;
  if (pAggNode->pExprs != NULL) {
    pScalarExprInfo = createExprInfo(pAggNode->pExprs, NULL, &numOfScalarExpr);
  }

2294 2295 2296 2297
  code = initExprSupp(&pInfo->scalarExprSup, pScalarExprInfo, numOfScalarExpr);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2298

H
Haojun Liao 已提交
2299 2300 2301 2302 2303
  code = filterInitFromNode((SNode*)pAggNode->node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

H
Haojun Liao 已提交
2304
  pInfo->binfo.mergeResultBlock = pAggNode->mergeDataBlock;
2305
  pInfo->groupId = UINT64_MAX;
H
Haojun Liao 已提交
2306

2307 2308 2309
  setOperatorInfo(pOperator, "TableAggregate", QUERY_NODE_PHYSICAL_PLAN_HASH_AGG, true, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
  pOperator->fpSet = createOperatorFpSet(doOpenAggregateOptr, getAggregateResult, NULL, destroyAggOperatorInfo, NULL);
H
Haojun Liao 已提交
2310

2311 2312
  if (downstream->operatorType == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
    STableScanInfo* pTableScanInfo = downstream->info;
H
Haojun Liao 已提交
2313 2314
    pTableScanInfo->base.pdInfo.pExprSup = &pOperator->exprSupp;
    pTableScanInfo->base.pdInfo.pAggSup = &pInfo->aggSup;
2315 2316
  }

H
Haojun Liao 已提交
2317 2318 2319 2320
  code = appendDownstream(pOperator, &downstream, 1);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2321 2322

  return pOperator;
H
Haojun Liao 已提交
2323

2324
_error:
H
Haojun Liao 已提交
2325 2326 2327 2328
  if (pInfo != NULL) {
    destroyAggOperatorInfo(pInfo);
  }

2329 2330 2331
  if (pOperator != NULL) {
    cleanupExprSupp(&pOperator->exprSupp);
  }
H
Haojun Liao 已提交
2332

2333
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
2334
  pTaskInfo->code = code;
H
Haojun Liao 已提交
2335
  return NULL;
2336 2337
}

2338
void cleanupBasicInfo(SOptrBasicInfo* pInfo) {
2339
  assert(pInfo != NULL);
H
Haojun Liao 已提交
2340
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
2341 2342
}

H
Haojun Liao 已提交
2343 2344 2345 2346 2347 2348 2349
static void freeItem(void* pItem) {
  void** p = pItem;
  if (*p != NULL) {
    taosMemoryFreeClear(*p);
  }
}

2350
void destroyAggOperatorInfo(void* param) {
L
Liu Jicong 已提交
2351
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
L
Liu Jicong 已提交
2352 2353
  cleanupBasicInfo(&pInfo->binfo);

H
Haojun Liao 已提交
2354
  cleanupAggSup(&pInfo->aggSup);
S
shenglian zhou 已提交
2355
  cleanupExprSupp(&pInfo->scalarExprSup);
H
Haojun Liao 已提交
2356
  cleanupGroupResInfo(&pInfo->groupResInfo);
D
dapan1121 已提交
2357
  taosMemoryFreeClear(param);
2358
}
2359

2360
void destroyFillOperatorInfo(void* param) {
L
Liu Jicong 已提交
2361
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
2362
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
2363
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
H
Haojun Liao 已提交
2364 2365
  pInfo->pFinalRes = blockDataDestroy(pInfo->pFinalRes);

2366
  cleanupExprSupp(&pInfo->noFillExprSupp);
H
Haojun Liao 已提交
2367

wafwerar's avatar
wafwerar 已提交
2368
  taosMemoryFreeClear(pInfo->p);
H
Haojun Liao 已提交
2369
  taosArrayDestroy(pInfo->matchInfo.pList);
D
dapan1121 已提交
2370
  taosMemoryFreeClear(param);
2371 2372
}

H
Haojun Liao 已提交
2373 2374 2375 2376
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 已提交
2377

H
Haojun Liao 已提交
2378 2379 2380
  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 已提交
2381

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

H
Haojun Liao 已提交
2385 2386 2387 2388 2389 2390 2391
  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 已提交
2392
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
2393

H
Haojun Liao 已提交
2394
  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
H
Haojun Liao 已提交
2395 2396
    taosMemoryFree(pInfo->pFillInfo);
    taosMemoryFree(pInfo->p);
H
Haojun Liao 已提交
2397 2398 2399 2400 2401 2402
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

2403
static bool isWstartColumnExist(SFillOperatorInfo* pInfo) {
2404
  if (pInfo->noFillExprSupp.numOfExprs == 0) {
2405 2406
    return false;
  }
2407 2408 2409

  for (int32_t i = 0; i < pInfo->noFillExprSupp.numOfExprs; ++i) {
    SExprInfo* exprInfo = pInfo->noFillExprSupp.pExprInfo + i;
2410
    if (exprInfo->pExpr->nodeType == QUERY_NODE_COLUMN && exprInfo->base.numOfParams == 1 &&
2411 2412 2413 2414 2415 2416 2417
        exprInfo->base.pParam[0].pCol->colType == COLUMN_TYPE_WINDOW_START) {
      return true;
    }
  }
  return false;
}

2418 2419
static int32_t createPrimaryTsExprIfNeeded(SFillOperatorInfo* pInfo, SFillPhysiNode* pPhyFillNode, SExprSupp* pExprSupp,
                                           const char* idStr) {
2420
  bool wstartExist = isWstartColumnExist(pInfo);
2421

2422 2423
  if (wstartExist == false) {
    if (pPhyFillNode->pWStartTs->type != QUERY_NODE_TARGET) {
2424
      qError("pWStartTs of fill physical node is not a target node, %s", idStr);
2425 2426 2427
      return TSDB_CODE_QRY_SYS_ERROR;
    }

2428 2429
    SExprInfo* pExpr = taosMemoryRealloc(pExprSupp->pExprInfo, (pExprSupp->numOfExprs + 1) * sizeof(SExprInfo));
    if (pExpr == NULL) {
2430 2431 2432
      return TSDB_CODE_OUT_OF_MEMORY;
    }

2433 2434 2435
    createExprFromTargetNode(&pExpr[pExprSupp->numOfExprs], (STargetNode*)pPhyFillNode->pWStartTs);
    pExprSupp->numOfExprs += 1;
    pExprSupp->pExprInfo = pExpr;
2436
  }
2437

2438 2439 2440
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
2441 2442
SOperatorInfo* createFillOperatorInfo(SOperatorInfo* downstream, SFillPhysiNode* pPhyFillNode,
                                      SExecTaskInfo* pTaskInfo) {
2443 2444 2445 2446 2447 2448
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

H
Haojun Liao 已提交
2449 2450 2451 2452
  pInfo->pRes = createResDataBlock(pPhyFillNode->node.pOutputDataBlockDesc);
  SExprInfo* pExprInfo = createExprInfo(pPhyFillNode->pFillExprs, NULL, &pInfo->numOfExpr);
  pOperator->exprSupp.pExprInfo = pExprInfo;

2453 2454 2455 2456 2457 2458 2459 2460
  SExprSupp* pNoFillSupp = &pInfo->noFillExprSupp;
  pNoFillSupp->pExprInfo = createExprInfo(pPhyFillNode->pNotFillExprs, NULL, &pNoFillSupp->numOfExprs);
  int32_t code = createPrimaryTsExprIfNeeded(pInfo, pPhyFillNode, pNoFillSupp, pTaskInfo->id.str);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

  code = initExprSupp(pNoFillSupp, pNoFillSupp->pExprInfo, pNoFillSupp->numOfExprs);
2461 2462 2463
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
2464

L
Liu Jicong 已提交
2465
  SInterval* pInterval =
2466
      QUERY_NODE_PHYSICAL_PLAN_MERGE_ALIGNED_INTERVAL == downstream->operatorType
2467 2468
          ? &((SMergeAlignedIntervalAggOperatorInfo*)downstream->info)->intervalAggOperatorInfo->interval
          : &((SIntervalAggOperatorInfo*)downstream->info)->interval;
2469

2470
  int32_t order = (pPhyFillNode->inputTsOrder == ORDER_ASC) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
2471
  int32_t type = convertFillType(pPhyFillNode->mode);
2472

H
Haojun Liao 已提交
2473
  SResultInfo* pResultInfo = &pOperator->resultInfo;
H
Haojun Liao 已提交
2474

2475
  initResultSizeInfo(&pOperator->resultInfo, 4096);
H
Haojun Liao 已提交
2476 2477 2478 2479 2480
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
  code = initExprSupp(&pOperator->exprSupp, pExprInfo, pInfo->numOfExpr);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
2481

H
Haojun Liao 已提交
2482 2483
  pInfo->primaryTsCol = ((STargetNode*)pPhyFillNode->pWStartTs)->slotId;
  pInfo->primarySrcSlotId = ((SColumnNode*)((STargetNode*)pPhyFillNode->pWStartTs)->pExpr)->slotId;
2484

2485
  int32_t numOfOutputCols = 0;
H
Haojun Liao 已提交
2486 2487
  code = extractColMatchInfo(pPhyFillNode->pFillExprs, pPhyFillNode->node.pOutputDataBlockDesc, &numOfOutputCols,
                             COL_MATCH_FROM_SLOT_ID, &pInfo->matchInfo);
2488

2489
  code = initFillInfo(pInfo, pExprInfo, pInfo->numOfExpr, pNoFillSupp->pExprInfo, pNoFillSupp->numOfExprs,
2490 2491
                      (SNodeListNode*)pPhyFillNode->pValues, pPhyFillNode->timeRange, pResultInfo->capacity,
                      pTaskInfo->id.str, pInterval, type, order);
2492 2493 2494
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2495

H
Haojun Liao 已提交
2496
  pInfo->pFinalRes = createOneDataBlock(pInfo->pRes, false);
H
Haojun Liao 已提交
2497 2498
  blockDataEnsureCapacity(pInfo->pFinalRes, pOperator->resultInfo.capacity);

H
Haojun Liao 已提交
2499 2500 2501 2502 2503
  code = filterInitFromNode((SNode*)pPhyFillNode->node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

H
Haojun Liao 已提交
2504
  setOperatorInfo(pOperator, "FillOperator", QUERY_NODE_PHYSICAL_PLAN_FILL, false, OP_NOT_OPENED, pInfo, pTaskInfo);
2505
  pOperator->exprSupp.numOfExprs = pInfo->numOfExpr;
H
Haojun Liao 已提交
2506
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doFill, NULL, destroyFillOperatorInfo, NULL);
2507

2508
  code = appendDownstream(pOperator, &downstream, 1);
2509
  return pOperator;
H
Haojun Liao 已提交
2510

2511
_error:
H
Haojun Liao 已提交
2512 2513 2514 2515
  if (pInfo != NULL) {
    destroyFillOperatorInfo(pInfo);
  }

2516
  pTaskInfo->code = code;
wafwerar's avatar
wafwerar 已提交
2517
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
2518
  return NULL;
2519 2520
}

D
dapan1121 已提交
2521
static SExecTaskInfo* createExecTaskInfo(uint64_t queryId, uint64_t taskId, EOPTR_EXEC_MODEL model, char* dbFName) {
wafwerar's avatar
wafwerar 已提交
2522
  SExecTaskInfo* pTaskInfo = taosMemoryCalloc(1, sizeof(SExecTaskInfo));
H
Haojun Liao 已提交
2523 2524 2525 2526 2527
  if (pTaskInfo == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

2528
  setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
2529

2530
  pTaskInfo->schemaInfo.dbname = strdup(dbFName);
2531
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
2532
  pTaskInfo->id.queryId = queryId;
dengyihao's avatar
dengyihao 已提交
2533
  pTaskInfo->execModel = model;
H
Haojun Liao 已提交
2534
  pTaskInfo->pTableInfoList = tableListCreate();
D
dapan1121 已提交
2535
  pTaskInfo->stopInfo.pStopInfo = taosArrayInit(4, sizeof(SExchangeOpStopInfo));
H
Haojun Liao 已提交
2536

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

2541 2542
  return pTaskInfo;
}
H
Haojun Liao 已提交
2543

H
Haojun Liao 已提交
2544 2545
SSchemaWrapper* extractQueriedColumnSchema(SScanPhysiNode* pScanNode);

2546
int32_t extractTableSchemaInfo(SReadHandle* pHandle, SScanPhysiNode* pScanNode, SExecTaskInfo* pTaskInfo) {
2547 2548
  SMetaReader mr = {0};
  metaReaderInit(&mr, pHandle->meta, 0);
2549
  int32_t code = metaGetTableEntryByUid(&mr, pScanNode->uid);
2550
  if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
2551 2552
    qError("failed to get the table meta, uid:0x%" PRIx64 ", suid:0x%" PRIx64 ", %s", pScanNode->uid, pScanNode->suid,
           GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
2553

D
dapan1121 已提交
2554
    metaReaderClear(&mr);
2555
    return terrno;
D
dapan1121 已提交
2556
  }
2557

2558 2559
  SSchemaInfo* pSchemaInfo = &pTaskInfo->schemaInfo;
  pSchemaInfo->tablename = strdup(mr.me.name);
2560 2561

  if (mr.me.type == TSDB_SUPER_TABLE) {
2562 2563
    pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.stbEntry.schemaRow);
    pSchemaInfo->tversion = mr.me.stbEntry.schemaTag.version;
2564
  } else if (mr.me.type == TSDB_CHILD_TABLE) {
2565 2566
    tDecoderClear(&mr.coder);

2567 2568
    tb_uid_t suid = mr.me.ctbEntry.suid;
    metaGetTableEntryByUid(&mr, suid);
2569 2570
    pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.stbEntry.schemaRow);
    pSchemaInfo->tversion = mr.me.stbEntry.schemaTag.version;
2571
  } else {
2572
    pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.ntbEntry.schemaRow);
2573
  }
2574 2575

  metaReaderClear(&mr);
2576

H
Haojun Liao 已提交
2577 2578 2579 2580 2581
  pSchemaInfo->qsw = extractQueriedColumnSchema(pScanNode);
  return TSDB_CODE_SUCCESS;
}

SSchemaWrapper* extractQueriedColumnSchema(SScanPhysiNode* pScanNode) {
2582 2583 2584
  int32_t numOfCols = LIST_LENGTH(pScanNode->pScanCols);
  int32_t numOfTags = LIST_LENGTH(pScanNode->pScanPseudoCols);

2585
  SSchemaWrapper* pqSw = taosMemoryCalloc(1, sizeof(SSchemaWrapper));
2586
  pqSw->pSchema = taosMemoryCalloc(numOfCols + numOfTags, sizeof(SSchema));
2587

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

H
Haojun Liao 已提交
2592 2593 2594
    SSchema* pSchema = &pqSw->pSchema[pqSw->nCols++];
    pSchema->colId = pColNode->colId;
    pSchema->type = pColNode->node.resType.type;
H
Haojun Liao 已提交
2595 2596
    pSchema->bytes = pColNode->node.resType.bytes;
    tstrncpy(pSchema->name, pColNode->colName, tListLen(pSchema->name));
2597 2598
  }

2599
  // this the tags and pseudo function columns, we only keep the tag columns
2600
  for (int32_t i = 0; i < numOfTags; ++i) {
2601 2602 2603 2604 2605 2606 2607 2608 2609
    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;
H
Haojun Liao 已提交
2610
      pSchema->bytes = pColNode->node.resType.bytes;
H
Haojun Liao 已提交
2611
      tstrncpy(pSchema->name, pColNode->colName, tListLen(pSchema->name));
2612 2613 2614
    }
  }

H
Haojun Liao 已提交
2615
  return pqSw;
2616 2617
}

2618 2619
static void cleanupTableSchemaInfo(SSchemaInfo* pSchemaInfo) {
  taosMemoryFreeClear(pSchemaInfo->dbname);
2620
  taosMemoryFreeClear(pSchemaInfo->tablename);
2621 2622
  tDeleteSSchemaWrapper(pSchemaInfo->sw);
  tDeleteSSchemaWrapper(pSchemaInfo->qsw);
2623 2624
}

2625
static void cleanupStreamInfo(SStreamTaskInfo* pStreamInfo) { tDeleteSSchemaWrapper(pStreamInfo->schema); }
2626

2627
bool groupbyTbname(SNodeList* pGroupList) {
2628
  bool bytbname = false;
2629
  if (LIST_LENGTH(pGroupList) == 1) {
2630 2631 2632 2633 2634 2635 2636 2637 2638 2639
    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;
}

2640 2641
SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle, SNode* pTagCond,
                                  SNode* pTagIndexCond, const char* pUser) {
2642
  int32_t         type = nodeType(pPhyNode);
2643
  STableListInfo* pTableListInfo = pTaskInfo->pTableInfoList;
2644
  const char*     idstr = GET_TASKID(pTaskInfo);
2645

X
Xiaoyu Wang 已提交
2646
  if (pPhyNode->pChildren == NULL || LIST_LENGTH(pPhyNode->pChildren) == 0) {
2647
    SOperatorInfo* pOperator = NULL;
H
Haojun Liao 已提交
2648
    if (QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN == type) {
dengyihao's avatar
dengyihao 已提交
2649
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
2650

2651 2652 2653 2654 2655 2656
      // NOTE: this is an patch to fix the physical plan
      // TODO remove it later
      if (pTableScanNode->scan.node.pLimit != NULL) {
        pTableScanNode->groupSort = true;
      }

L
Liu Jicong 已提交
2657 2658
      int32_t code =
          createScanTableListInfo(&pTableScanNode->scan, pTableScanNode->pGroupTags, pTableScanNode->groupSort, pHandle,
H
Haojun Liao 已提交
2659
                                  pTableListInfo, pTagCond, pTagIndexCond, pTaskInfo);
2660
      if (code) {
wmmhello's avatar
wmmhello 已提交
2661
        pTaskInfo->code = code;
2662
        qError("failed to createScanTableListInfo, code:%s, %s", tstrerror(code), idstr);
D
dapan1121 已提交
2663 2664
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
2665

2666
      code = extractTableSchemaInfo(pHandle, &pTableScanNode->scan, pTaskInfo);
S
slzhou 已提交
2667
      if (code) {
2668
        pTaskInfo->code = terrno;
wmmhello's avatar
wmmhello 已提交
2669 2670 2671
        return NULL;
      }

2672
      pOperator = createTableScanOperatorInfo(pTableScanNode, pHandle, pTaskInfo);
D
dapan1121 已提交
2673 2674 2675 2676 2677
      if (NULL == pOperator) {
        pTaskInfo->code = terrno;
        return NULL;
      }

2678
      STableScanInfo* pScanInfo = pOperator->info;
H
Haojun Liao 已提交
2679
      pTaskInfo->cost.pRecoder = &pScanInfo->base.readRecorder;
S
slzhou 已提交
2680 2681
    } else if (QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN == type) {
      STableMergeScanPhysiNode* pTableScanNode = (STableMergeScanPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
2682 2683 2684

      int32_t code = createScanTableListInfo(&pTableScanNode->scan, pTableScanNode->pGroupTags, true, pHandle,
                                             pTableListInfo, pTagCond, pTagIndexCond, pTaskInfo);
L
Liu Jicong 已提交
2685
      if (code) {
wmmhello's avatar
wmmhello 已提交
2686
        pTaskInfo->code = code;
H
Haojun Liao 已提交
2687
        qError("failed to createScanTableListInfo, code: %s", tstrerror(code));
wmmhello's avatar
wmmhello 已提交
2688 2689
        return NULL;
      }
2690

2691
      code = extractTableSchemaInfo(pHandle, &pTableScanNode->scan, pTaskInfo);
wmmhello's avatar
wmmhello 已提交
2692 2693 2694 2695
      if (code) {
        pTaskInfo->code = terrno;
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
2696

H
Haojun Liao 已提交
2697
      pOperator = createTableMergeScanOperatorInfo(pTableScanNode, pHandle, pTaskInfo);
D
dapan1121 已提交
2698 2699 2700 2701
      if (NULL == pOperator) {
        pTaskInfo->code = terrno;
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
2702

2703
      STableScanInfo* pScanInfo = pOperator->info;
H
Haojun Liao 已提交
2704
      pTaskInfo->cost.pRecoder = &pScanInfo->base.readRecorder;
H
Haojun Liao 已提交
2705
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == type) {
2706 2707
      pOperator = createExchangeOperatorInfo(pHandle ? pHandle->pMsgCb->clientRpc : NULL, (SExchangePhysiNode*)pPhyNode,
                                             pTaskInfo);
H
Haojun Liao 已提交
2708
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == type) {
5
54liuyao 已提交
2709
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
5
54liuyao 已提交
2710
      if (pHandle->vnode) {
L
Liu Jicong 已提交
2711 2712
        int32_t code =
            createScanTableListInfo(&pTableScanNode->scan, pTableScanNode->pGroupTags, pTableScanNode->groupSort,
H
Haojun Liao 已提交
2713
                                    pHandle, pTableListInfo, pTagCond, pTagIndexCond, pTaskInfo);
L
Liu Jicong 已提交
2714
        if (code) {
wmmhello's avatar
wmmhello 已提交
2715
          pTaskInfo->code = code;
H
Haojun Liao 已提交
2716
          qError("failed to createScanTableListInfo, code: %s", tstrerror(code));
wmmhello's avatar
wmmhello 已提交
2717 2718
          return NULL;
        }
L
Liu Jicong 已提交
2719 2720

#ifndef NDEBUG
H
Haojun Liao 已提交
2721
        int32_t sz = tableListGetSize(pTableListInfo);
H
Haojun Liao 已提交
2722 2723
        qDebug("create stream task, total:%d", sz);

L
Liu Jicong 已提交
2724
        for (int32_t i = 0; i < sz; i++) {
H
Haojun Liao 已提交
2725
          STableKeyInfo* pKeyInfo = tableListGetInfo(pTableListInfo, i);
2726
          qDebug("add table uid:%" PRIu64 ", gid:%" PRIu64, pKeyInfo->uid, pKeyInfo->groupId);
L
Liu Jicong 已提交
2727 2728
        }
#endif
2729
      }
2730

H
Haojun Liao 已提交
2731
      pTaskInfo->schemaInfo.qsw = extractQueriedColumnSchema(&pTableScanNode->scan);
2732
      pOperator = createStreamScanOperatorInfo(pHandle, pTableScanNode, pTagCond, pTaskInfo);
H
Haojun Liao 已提交
2733
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == type) {
L
Liu Jicong 已提交
2734
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
2735
      pOperator = createSysTableScanOperatorInfo(pHandle, pSysScanPhyNode, pUser, pTaskInfo);
2736
    } else if (QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN == type) {
X
Xiaoyu Wang 已提交
2737
      STagScanPhysiNode* pScanPhyNode = (STagScanPhysiNode*)pPhyNode;
2738 2739

      int32_t code = createScanTableListInfo(pScanPhyNode, NULL, false, pHandle, pTableListInfo, pTagCond,
H
Haojun Liao 已提交
2740
                                             pTagIndexCond, pTaskInfo);
2741
      if (code != TSDB_CODE_SUCCESS) {
2742
        pTaskInfo->code = code;
H
Haojun Liao 已提交
2743
        qError("failed to getTableList, code: %s", tstrerror(code));
2744 2745 2746
        return NULL;
      }

2747
      pOperator = createTagScanOperatorInfo(pHandle, pScanPhyNode, pTableListInfo, pTaskInfo);
2748
    } else if (QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN == type) {
2749
      SBlockDistScanPhysiNode* pBlockNode = (SBlockDistScanPhysiNode*)pPhyNode;
2750 2751

      if (pBlockNode->tableType == TSDB_SUPER_TABLE) {
H
Haojun Liao 已提交
2752 2753
        SArray* pList = taosArrayInit(4, sizeof(STableKeyInfo));
        int32_t code = vnodeGetAllTableList(pHandle->vnode, pBlockNode->uid, pList);
2754 2755 2756 2757
        if (code != TSDB_CODE_SUCCESS) {
          pTaskInfo->code = terrno;
          return NULL;
        }
H
Haojun Liao 已提交
2758

2759
        for (int32_t i = 0; i < tableListGetSize(pTableListInfo); ++i) {
H
Haojun Liao 已提交
2760
          STableKeyInfo* p = taosArrayGet(pList, i);
H
Haojun Liao 已提交
2761
          tableListAddTableInfo(pTableListInfo, p->uid, 0);
H
Haojun Liao 已提交
2762 2763
        }
        taosArrayDestroy(pList);
2764
      } else {  // Create group with only one table
H
Haojun Liao 已提交
2765
        tableListAddTableInfo(pTableListInfo, pBlockNode->uid, 0);
2766 2767
      }

2768
      pOperator = createDataBlockInfoScanOperator(pHandle, pBlockNode, pTaskInfo);
H
Haojun Liao 已提交
2769 2770 2771
    } else if (QUERY_NODE_PHYSICAL_PLAN_LAST_ROW_SCAN == type) {
      SLastRowScanPhysiNode* pScanNode = (SLastRowScanPhysiNode*)pPhyNode;

L
Liu Jicong 已提交
2772
      int32_t code = createScanTableListInfo(&pScanNode->scan, pScanNode->pGroupTags, true, pHandle, pTableListInfo,
H
Haojun Liao 已提交
2773
                                             pTagCond, pTagIndexCond, pTaskInfo);
2774 2775 2776 2777
      if (code != TSDB_CODE_SUCCESS) {
        pTaskInfo->code = code;
        return NULL;
      }
2778

2779
      code = extractTableSchemaInfo(pHandle, &pScanNode->scan, pTaskInfo);
2780 2781 2782
      if (code != TSDB_CODE_SUCCESS) {
        pTaskInfo->code = code;
        return NULL;
H
Haojun Liao 已提交
2783 2784
      }

2785
      pOperator = createCacherowsScanOperator(pScanNode, pHandle, pTaskInfo);
2786
    } else if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
2787
      pOperator = createProjectOperatorInfo(NULL, (SProjectPhysiNode*)pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
2788 2789
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
2790
    }
2791 2792 2793 2794 2795

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

2796
    return pOperator;
H
Haojun Liao 已提交
2797 2798
  }

2799
  size_t          size = LIST_LENGTH(pPhyNode->pChildren);
2800
  SOperatorInfo** ops = taosMemoryCalloc(size, POINTER_BYTES);
2801 2802 2803 2804
  if (ops == NULL) {
    return NULL;
  }

dengyihao's avatar
dengyihao 已提交
2805
  for (int32_t i = 0; i < size; ++i) {
2806
    SPhysiNode* pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
2807
    ops[i] = createOperatorTree(pChildNode, pTaskInfo, pHandle, pTagCond, pTagIndexCond, pUser);
2808
    if (ops[i] == NULL) {
H
Haojun Liao 已提交
2809
      taosMemoryFree(ops);
2810 2811
      return NULL;
    }
2812
  }
H
Haojun Liao 已提交
2813

2814
  SOperatorInfo* pOptr = NULL;
H
Haojun Liao 已提交
2815
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
2816
    pOptr = createProjectOperatorInfo(ops[0], (SProjectPhysiNode*)pPhyNode, pTaskInfo);
2817
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_AGG == type) {
H
Haojun Liao 已提交
2818 2819
    SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
    if (pAggNode->pGroupKeys != NULL) {
H
Haojun Liao 已提交
2820
      pOptr = createGroupOperatorInfo(ops[0], pAggNode, pTaskInfo);
H
Haojun Liao 已提交
2821
    } else {
H
Haojun Liao 已提交
2822
      pOptr = createAggregateOperatorInfo(ops[0], pAggNode, pTaskInfo);
H
Haojun Liao 已提交
2823
    }
2824
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_INTERVAL == type) {
H
Haojun Liao 已提交
2825
    SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
2826

H
Haojun Liao 已提交
2827 2828
    bool isStream = (QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type);
    pOptr = createIntervalOperatorInfo(ops[0], pIntervalPhyNode, pTaskInfo, isStream);
2829
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type) {
2830
    pOptr = createStreamIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo);
2831 2832
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_ALIGNED_INTERVAL == type) {
    SMergeAlignedIntervalPhysiNode* pIntervalPhyNode = (SMergeAlignedIntervalPhysiNode*)pPhyNode;
2833
    pOptr = createMergeAlignedIntervalOperatorInfo(ops[0], pIntervalPhyNode, pTaskInfo);
S
shenglian zhou 已提交
2834
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_INTERVAL == type) {
X
Xiaoyu Wang 已提交
2835
    SMergeIntervalPhysiNode* pIntervalPhyNode = (SMergeIntervalPhysiNode*)pPhyNode;
2836
    pOptr = createMergeIntervalOperatorInfo(ops[0], pIntervalPhyNode, pTaskInfo);
5
54liuyao 已提交
2837
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SEMI_INTERVAL == type) {
2838
    int32_t children = 0;
5
54liuyao 已提交
2839 2840
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_FINAL_INTERVAL == type) {
5
54liuyao 已提交
2841
    int32_t children = pHandle->numOfVgroups;
5
54liuyao 已提交
2842
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
H
Haojun Liao 已提交
2843
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == type) {
2844
    pOptr = createSortOperatorInfo(ops[0], (SSortPhysiNode*)pPhyNode, pTaskInfo);
S
shenglian zhou 已提交
2845 2846
  } else if (QUERY_NODE_PHYSICAL_PLAN_GROUP_SORT == type) {
    pOptr = createGroupSortOperatorInfo(ops[0], (SGroupSortPhysiNode*)pPhyNode, pTaskInfo);
X
Xiaoyu Wang 已提交
2847
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE == type) {
2848
    SMergePhysiNode* pMergePhyNode = (SMergePhysiNode*)pPhyNode;
2849
    pOptr = createMultiwayMergeOperatorInfo(ops, size, pMergePhyNode, pTaskInfo);
2850
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_SESSION == type) {
H
Haojun Liao 已提交
2851
    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
2852
    pOptr = createSessionAggOperatorInfo(ops[0], pSessionNode, pTaskInfo);
2853
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION == type) {
2854 2855 2856 2857 2858
    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) {
2859
    int32_t children = pHandle->numOfVgroups;
2860
    pOptr = createStreamFinalSessionAggOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
H
Haojun Liao 已提交
2861
  } else if (QUERY_NODE_PHYSICAL_PLAN_PARTITION == type) {
2862
    pOptr = createPartitionOperatorInfo(ops[0], (SPartitionPhysiNode*)pPhyNode, pTaskInfo);
2863
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_PARTITION == type) {
2864
    pOptr = createStreamPartitionOperatorInfo(ops[0], (SStreamPartitionPhysiNode*)pPhyNode, pTaskInfo);
2865
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_STATE == type) {
dengyihao's avatar
dengyihao 已提交
2866
    SStateWinodwPhysiNode* pStateNode = (SStateWinodwPhysiNode*)pPhyNode;
2867
    pOptr = createStatewindowOperatorInfo(ops[0], pStateNode, pTaskInfo);
2868
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_STATE == type) {
5
54liuyao 已提交
2869
    pOptr = createStreamStateAggOperatorInfo(ops[0], pPhyNode, pTaskInfo);
2870
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_JOIN == type) {
2871
    pOptr = createMergeJoinOperatorInfo(ops, size, (SSortMergeJoinPhysiNode*)pPhyNode, pTaskInfo);
2872
  } else if (QUERY_NODE_PHYSICAL_PLAN_FILL == type) {
H
Haojun Liao 已提交
2873
    pOptr = createFillOperatorInfo(ops[0], (SFillPhysiNode*)pPhyNode, pTaskInfo);
5
54liuyao 已提交
2874 2875
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_FILL == type) {
    pOptr = createStreamFillOperatorInfo(ops[0], (SStreamFillPhysiNode*)pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
2876 2877
  } else if (QUERY_NODE_PHYSICAL_PLAN_INDEF_ROWS_FUNC == type) {
    pOptr = createIndefinitOutputOperatorInfo(ops[0], pPhyNode, pTaskInfo);
2878 2879
  } else if (QUERY_NODE_PHYSICAL_PLAN_INTERP_FUNC == type) {
    pOptr = createTimeSliceOperatorInfo(ops[0], pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
2880 2881
  } else {
    ASSERT(0);
H
Haojun Liao 已提交
2882
  }
2883

2884
  taosMemoryFree(ops);
2885 2886 2887 2888
  if (pOptr) {
    pOptr->resultDataBlockId = pPhyNode->pOutputDataBlockDesc->dataBlockId;
  }

2889
  return pOptr;
2890
}
H
Haojun Liao 已提交
2891

L
Liu Jicong 已提交
2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904
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 {
2905 2906 2907
    SStreamScanInfo* pInfo = pOperator->info;
    ASSERT(pInfo->pTableScanOp->operatorType == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN);
    *ppInfo = pInfo->pTableScanOp->info;
L
Liu Jicong 已提交
2908 2909 2910 2911
    return 0;
  }
}

2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933
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;
}

2934
#if 0
L
Liu Jicong 已提交
2935 2936 2937 2938 2939
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;
  }
2940

L
Liu Jicong 已提交
2941 2942 2943 2944
  STableScanPhysiNode* pNode = NULL;
  if (extractTableScanNode(plan->pNode, &pNode) < 0) {
    ASSERT(0);
  }
2945

H
Haojun Liao 已提交
2946
  tsdbReaderClose(pTableScanInfo->dataReader);
2947

L
Liu Jicong 已提交
2948
  STableListInfo info = {0};
H
Haojun Liao 已提交
2949
  pTableScanInfo->dataReader = doCreateDataReader(pNode, pHandle, &info, NULL);
L
Liu Jicong 已提交
2950 2951 2952 2953
  if (pTableScanInfo->dataReader == NULL) {
    ASSERT(0);
    qError("failed to create data reader");
    return TSDB_CODE_QRY_APP_ERROR;
2954
  }
L
Liu Jicong 已提交
2955
  // TODO: set uid and ts to data reader
2956 2957
  return 0;
}
2958
#endif
2959

C
Cary Xu 已提交
2960
int32_t encodeOperator(SOperatorInfo* ops, char** result, int32_t* length, int32_t* nOptrWithVal) {
wmmhello's avatar
wmmhello 已提交
2961
  int32_t code = TDB_CODE_SUCCESS;
2962
  char*   pCurrent = NULL;
wmmhello's avatar
wmmhello 已提交
2963
  int32_t currLength = 0;
2964
  if (ops->fpSet.encodeResultRow) {
C
Cary Xu 已提交
2965
    if (result == NULL || length == NULL || nOptrWithVal == NULL) {
wmmhello's avatar
wmmhello 已提交
2966 2967 2968
      return TSDB_CODE_TSC_INVALID_INPUT;
    }
    code = ops->fpSet.encodeResultRow(ops, &pCurrent, &currLength);
wmmhello's avatar
wmmhello 已提交
2969

2970 2971
    if (code != TDB_CODE_SUCCESS) {
      if (*result != NULL) {
wmmhello's avatar
wmmhello 已提交
2972 2973 2974 2975
        taosMemoryFree(*result);
        *result = NULL;
      }
      return code;
C
Cary Xu 已提交
2976 2977 2978
    } else if (currLength == 0) {
      ASSERT(!pCurrent);
      goto _downstream;
wmmhello's avatar
wmmhello 已提交
2979
    }
wmmhello's avatar
wmmhello 已提交
2980

C
Cary Xu 已提交
2981 2982
    ++(*nOptrWithVal);

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

2985
    if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
2986
      *result = (char*)taosMemoryCalloc(1, currLength + sizeof(int32_t));
wmmhello's avatar
wmmhello 已提交
2987 2988 2989 2990 2991 2992
      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);
2993
    } else {
wmmhello's avatar
wmmhello 已提交
2994
      int32_t sizePre = *(int32_t*)(*result);
2995
      char*   tmp = (char*)taosMemoryRealloc(*result, sizePre + currLength);
wmmhello's avatar
wmmhello 已提交
2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007
      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 已提交
3008 3009
  }

3010
_downstream:
wmmhello's avatar
wmmhello 已提交
3011
  for (int32_t i = 0; i < ops->numOfDownstream; ++i) {
C
Cary Xu 已提交
3012
    code = encodeOperator(ops->pDownstream[i], result, length, nOptrWithVal);
3013
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
3014
      return code;
wmmhello's avatar
wmmhello 已提交
3015 3016
    }
  }
wmmhello's avatar
wmmhello 已提交
3017
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
3018 3019
}

H
Haojun Liao 已提交
3020
int32_t decodeOperator(SOperatorInfo* ops, const char* result, int32_t length) {
wmmhello's avatar
wmmhello 已提交
3021
  int32_t code = TDB_CODE_SUCCESS;
3022 3023
  if (ops->fpSet.decodeResultRow) {
    if (result == NULL) {
wmmhello's avatar
wmmhello 已提交
3024 3025
      return TSDB_CODE_TSC_INVALID_INPUT;
    }
H
Haojun Liao 已提交
3026

3027
    ASSERT(length == *(int32_t*)result);
H
Haojun Liao 已提交
3028 3029

    const char* data = result + sizeof(int32_t);
L
Liu Jicong 已提交
3030
    code = ops->fpSet.decodeResultRow(ops, (char*)data);
3031
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
3032 3033
      return code;
    }
wmmhello's avatar
wmmhello 已提交
3034

wmmhello's avatar
wmmhello 已提交
3035
    int32_t totalLength = *(int32_t*)result;
3036 3037
    int32_t dataLength = *(int32_t*)data;

3038
    if (totalLength == dataLength + sizeof(int32_t)) {  // the last data
wmmhello's avatar
wmmhello 已提交
3039 3040
      result = NULL;
      length = 0;
3041
    } else {
wmmhello's avatar
wmmhello 已提交
3042 3043 3044 3045
      result += dataLength;
      *(int32_t*)(result) = totalLength - dataLength;
      length = totalLength - dataLength;
    }
wmmhello's avatar
wmmhello 已提交
3046 3047
  }

wmmhello's avatar
wmmhello 已提交
3048 3049
  for (int32_t i = 0; i < ops->numOfDownstream; ++i) {
    code = decodeOperator(ops->pDownstream[i], result, length);
3050
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
3051
      return code;
wmmhello's avatar
wmmhello 已提交
3052 3053
    }
  }
wmmhello's avatar
wmmhello 已提交
3054
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
3055 3056
}

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

D
dapan1121 已提交
3060
  switch (pNode->type) {
D
dapan1121 已提交
3061 3062 3063 3064 3065 3066
    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 已提交
3067

D
dapan1121 已提交
3068 3069 3070
      *pParam = pInserterParam;
      break;
    }
D
dapan1121 已提交
3071
    case QUERY_NODE_PHYSICAL_PLAN_DELETE: {
3072
      SDeleterParam* pDeleterParam = taosMemoryCalloc(1, sizeof(SDeleterParam));
D
dapan1121 已提交
3073 3074 3075
      if (NULL == pDeleterParam) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
H
Haojun Liao 已提交
3076 3077 3078 3079
      int32_t tbNum = tableListGetSize(pTask->pTableInfoList);
      pDeleterParam->suid = tableListGetSuid(pTask->pTableInfoList);

      // TODO extract uid list
D
dapan1121 已提交
3080 3081 3082 3083 3084
      pDeleterParam->pUidList = taosArrayInit(tbNum, sizeof(uint64_t));
      if (NULL == pDeleterParam->pUidList) {
        taosMemoryFree(pDeleterParam);
        return TSDB_CODE_OUT_OF_MEMORY;
      }
H
Haojun Liao 已提交
3085

D
dapan1121 已提交
3086
      for (int32_t i = 0; i < tbNum; ++i) {
H
Haojun Liao 已提交
3087
        STableKeyInfo* pTable = tableListGetInfo(pTask->pTableInfoList, i);
D
dapan1121 已提交
3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100
        taosArrayPush(pDeleterParam->pUidList, &pTable->uid);
      }

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

  return TSDB_CODE_SUCCESS;
}

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

D
dapan1121 已提交
3105
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model, pPlan->dbFName);
H
Haojun Liao 已提交
3106 3107 3108
  if (*pTaskInfo == NULL) {
    goto _complete;
  }
H
Haojun Liao 已提交
3109

3110
  if (pHandle) {
L
Liu Jicong 已提交
3111
    /*(*pTaskInfo)->streamInfo.fillHistoryVer1 = pHandle->fillHistoryVer1;*/
3112 3113 3114
    if (pHandle->pStateBackend) {
      (*pTaskInfo)->streamInfo.pState = pHandle->pStateBackend;
    }
H
Haojun Liao 已提交
3115 3116
  }

3117
  (*pTaskInfo)->sql = sql;
D
dapan1121 已提交
3118
  sql = NULL;
H
Haojun Liao 已提交
3119

3120
  (*pTaskInfo)->pSubplan = pPlan;
3121 3122
  (*pTaskInfo)->pRoot =
      createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, pPlan->pTagCond, pPlan->pTagIndexCond, pPlan->user);
L
Liu Jicong 已提交
3123

D
dapan1121 已提交
3124
  if (NULL == (*pTaskInfo)->pRoot) {
H
Haojun Liao 已提交
3125
    terrno = (*pTaskInfo)->code;
D
dapan1121 已提交
3126
    goto _complete;
3127 3128
  }

H
Haojun Liao 已提交
3129
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
3130

H
Haojun Liao 已提交
3131
_complete:
D
dapan1121 已提交
3132
  taosMemoryFree(sql);
H
Haojun Liao 已提交
3133
  doDestroyTask(*pTaskInfo);
H
Haojun Liao 已提交
3134
  return terrno;
H
Haojun Liao 已提交
3135 3136
}

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

H
Haojun Liao 已提交
3140
  pTaskInfo->pTableInfoList = tableListDestroy(pTaskInfo->pTableInfoList);
H
Haojun Liao 已提交
3141
  destroyOperatorInfo(pTaskInfo->pRoot);
3142
  cleanupTableSchemaInfo(&pTaskInfo->schemaInfo);
3143
  cleanupStreamInfo(&pTaskInfo->streamInfo);
3144

D
dapan1121 已提交
3145
  if (!pTaskInfo->localFetch.localExec) {
D
dapan1121 已提交
3146 3147
    nodesDestroyNode((SNode*)pTaskInfo->pSubplan);
  }
3148

D
dapan1121 已提交
3149
  taosArrayDestroy(pTaskInfo->stopInfo.pStopInfo);
wafwerar's avatar
wafwerar 已提交
3150 3151 3152
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
3153 3154 3155 3156
}

static int64_t getQuerySupportBufSize(size_t numOfTables) {
  size_t s1 = sizeof(STableQueryInfo);
L
Liu Jicong 已提交
3157 3158
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
3159 3160 3161 3162 3163 3164 3165
}

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 已提交
3166
    while (1) {
3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192
      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 已提交
3193

H
Haojun Liao 已提交
3194
int32_t getOperatorExplainExecInfo(SOperatorInfo* operatorInfo, SArray* pExecInfoList) {
3195
  SExplainExecInfo  execInfo = {0};
H
Haojun Liao 已提交
3196
  SExplainExecInfo* pExplainInfo = taosArrayPush(pExecInfoList, &execInfo);
3197

H
Haojun Liao 已提交
3198 3199 3200 3201 3202
  pExplainInfo->numOfRows = operatorInfo->resultInfo.totalRows;
  pExplainInfo->startupCost = operatorInfo->cost.openCost;
  pExplainInfo->totalCost = operatorInfo->cost.totalCost;
  pExplainInfo->verboseLen = 0;
  pExplainInfo->verboseInfo = NULL;
D
dapan1121 已提交
3203

3204
  if (operatorInfo->fpSet.getExplainFn) {
3205 3206
    int32_t code =
        operatorInfo->fpSet.getExplainFn(operatorInfo, &pExplainInfo->verboseInfo, &pExplainInfo->verboseLen);
D
dapan1121 已提交
3207
    if (code) {
3208
      qError("%s operator getExplainFn failed, code:%s", GET_TASKID(operatorInfo->pTaskInfo), tstrerror(code));
D
dapan1121 已提交
3209 3210 3211
      return code;
    }
  }
dengyihao's avatar
dengyihao 已提交
3212

D
dapan1121 已提交
3213
  int32_t code = 0;
D
dapan1121 已提交
3214
  for (int32_t i = 0; i < operatorInfo->numOfDownstream; ++i) {
H
Haojun Liao 已提交
3215 3216
    code = getOperatorExplainExecInfo(operatorInfo->pDownstream[i], pExecInfoList);
    if (code != TSDB_CODE_SUCCESS) {
3217
      //      taosMemoryFreeClear(*pRes);
D
dapan1121 已提交
3218 3219 3220 3221 3222
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
3223
}
5
54liuyao 已提交
3224

3225 3226
int32_t setOutputBuf(SStreamState* pState, STimeWindow* win, SResultRow** pResult, int64_t tableGroupId,
                     SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowEntryInfoOffset, SAggSupporter* pAggSup) {
3227 3228 3229 3230 3231 3232
  SWinKey key = {
      .ts = win->skey,
      .groupId = tableGroupId,
  };
  char*   value = NULL;
  int32_t size = pAggSup->resultRowSize;
5
54liuyao 已提交
3233

3234
  if (streamStateAddIfNotExist(pState, &key, (void**)&value, &size) < 0) {
3235 3236 3237 3238 3239 3240 3241 3242 3243 3244
    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;
}

3245 3246
int32_t releaseOutputBuf(SStreamState* pState, SWinKey* pKey, SResultRow* pResult) {
  streamStateReleaseBuf(pState, pKey, pResult);
3247 3248 3249
  return TSDB_CODE_SUCCESS;
}

3250 3251
int32_t saveOutputBuf(SStreamState* pState, SWinKey* pKey, SResultRow* pResult, int32_t resSize) {
  streamStatePut(pState, pKey, pResult, resSize);
3252 3253 3254
  return TSDB_CODE_SUCCESS;
}

3255
int32_t buildDataBlockFromGroupRes(SOperatorInfo* pOperator, SStreamState* pState, SSDataBlock* pBlock, SExprSupp* pSup,
3256
                                   SGroupResInfo* pGroupResInfo) {
3257
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269
  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 = {
3270 3271
            .ts = *(TSKEY*)pPos->key,
            .groupId = pPos->groupId,
3272
    };
3273
    int32_t code = streamStateGet(pState, &key, &pVal, &size);
3274 3275 3276 3277 3278 3279
    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;
3280
      releaseOutputBuf(pState, &key, pRow);
3281 3282 3283 3284 3285
      continue;
    }

    if (pBlock->info.groupId == 0) {
      pBlock->info.groupId = pPos->groupId;
3286 3287
      void* tbname = NULL;
      if (streamStateGetParName(pTaskInfo->streamInfo.pState, pBlock->info.groupId, &tbname) < 0) {
L
Liu Jicong 已提交
3288
        pBlock->info.parTbName[0] = 0;
3289 3290
      } else {
        memcpy(pBlock->info.parTbName, tbname, TSDB_TABLE_NAME_LEN);
3291
      }
3292
      tdbFree(tbname);
3293 3294 3295
    } else {
      // current value belongs to different group, it can't be packed into one datablock
      if (pBlock->info.groupId != pPos->groupId) {
3296
        releaseOutputBuf(pState, &key, pRow);
3297 3298 3299 3300 3301 3302
        break;
      }
    }

    if (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
      ASSERT(pBlock->info.rows > 0);
3303
      releaseOutputBuf(pState, &key, pRow);
3304 3305 3306 3307 3308 3309 3310 3311 3312 3313
      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) {
3314 3315 3316 3317
        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);
3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330
        }
      } 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 已提交
3331

3332
    pBlock->info.rows += pRow->numOfRows;
3333
    releaseOutputBuf(pState, &key, pRow);
3334 3335 3336 3337
  }
  blockDataUpdateTsWindow(pBlock, 0);
  return TSDB_CODE_SUCCESS;
}
5
54liuyao 已提交
3338 3339 3340 3341 3342 3343 3344

int32_t saveSessionDiscBuf(SStreamState* pState, SSessionKey* key, void* buf, int32_t size) {
  streamStateSessionPut(pState, key, (const void*)buf, size);
  releaseOutputBuf(pState, NULL, (SResultRow*)buf);
  return TSDB_CODE_SUCCESS;
}

3345
int32_t buildSessionResultDataBlock(SOperatorInfo* pOperator, SStreamState* pState, SSDataBlock* pBlock,
5
54liuyao 已提交
3346
                                    SExprSupp* pSup, SGroupResInfo* pGroupResInfo) {
3347
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
5
54liuyao 已提交
3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360
  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) {
    SSessionKey* pKey = taosArrayGet(pGroupResInfo->pRows, i);
    int32_t      size = 0;
    void*        pVal = NULL;
    int32_t      code = streamStateSessionGet(pState, pKey, &pVal, &size);
    ASSERT(code == 0);
3361 3362
    if (code == -1) {
      // coverity scan
5
54liuyao 已提交
3363
      pGroupResInfo->index += 1;
3364 3365
      continue;
    }
5
54liuyao 已提交
3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376
    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(pState, NULL, pRow);
      continue;
    }

    if (pBlock->info.groupId == 0) {
      pBlock->info.groupId = pKey->groupId;
3377

3378 3379 3380
      void* tbname = NULL;
      if (streamStateGetParName(pTaskInfo->streamInfo.pState, pBlock->info.groupId, &tbname) < 0) {
        pBlock->info.parTbName[0] = 0;
3381
      } else {
3382
        memcpy(pBlock->info.parTbName, tbname, TSDB_TABLE_NAME_LEN);
3383
      }
3384
      tdbFree(tbname);
5
54liuyao 已提交
3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429
    } else {
      // current value belongs to different group, it can't be packed into one datablock
      if (pBlock->info.groupId != pKey->groupId) {
        releaseOutputBuf(pState, NULL, pRow);
        break;
      }
    }

    if (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
      ASSERT(pBlock->info.rows > 0);
      releaseOutputBuf(pState, NULL, 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) {
        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);
        }
      } 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);
        }
      }
    }

    pBlock->info.rows += pRow->numOfRows;
    // saveSessionDiscBuf(pState, pKey, pVal, size);
    releaseOutputBuf(pState, NULL, pRow);
  }
  blockDataUpdateTsWindow(pBlock, 0);
  return TSDB_CODE_SUCCESS;
3430
}