executorimpl.c 115.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"
23

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

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

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

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

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

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

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

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

H
Haojun Liao 已提交
79 80 81 82 83 84 85 86 87
typedef struct SAggOperatorInfo {
  SOptrBasicInfo   binfo;
  SAggSupporter    aggSup;
  STableQueryInfo* current;
  uint64_t         groupId;
  SGroupResInfo    groupResInfo;
  SExprSupp        scalarExprSup;
} SAggOperatorInfo;

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

90
static void setBlockSMAInfo(SqlFunctionCtx* pCtx, SExprInfo* pExpr, SSDataBlock* pBlock);
91

X
Xiaoyu Wang 已提交
92
static void releaseQueryBuf(size_t numOfTables);
93

H
Haojun Liao 已提交
94 95 96 97 98 99 100 101 102 103 104
static void    destroyFillOperatorInfo(void* param);
static void    destroyAggOperatorInfo(void* param);
static void    initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size);
static void    doSetTableGroupOutputBuf(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId);
static void    doApplyScalarCalculation(SOperatorInfo* pOperator, SSDataBlock* pBlock, int32_t order, int32_t scanFlag);
static int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                                const char* pKey);
static void    extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const SColumnInfoData* p, bool keep,
                                                   int32_t status);
static int32_t doSetInputDataBlock(SExprSupp* pExprSup, SSDataBlock* pBlock, int32_t order, int32_t scanFlag,
                                   bool createDummyCol);
H
Haojun Liao 已提交
105

H
Haojun Liao 已提交
106
void setOperatorCompleted(SOperatorInfo* pOperator) {
107
  pOperator->status = OP_EXEC_DONE;
H
Haojun Liao 已提交
108
  ASSERT(pOperator->pTaskInfo != NULL);
109

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

H
Haojun Liao 已提交
114 115 116 117 118 119 120 121 122 123
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 已提交
124
int32_t operatorDummyOpenFn(SOperatorInfo* pOperator) {
125
  OPTR_SET_OPENED(pOperator);
126
  pOperator->cost.openCost = 0;
H
Haojun Liao 已提交
127
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
128 129
}

H
Haojun Liao 已提交
130 131
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) {
132 133 134 135 136 137 138 139 140 141 142
  SOperatorFpSet fpSet = {
      ._openFn = openFn,
      .getNextFn = nextFn,
      .cleanupFn = cleanup,
      .closeFn = closeFn,
      .getExplainFn = explain,
  };

  return fpSet;
}

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

146
SResultRow* getNewResultRow(SDiskbasedBuf* pResultBuf, int32_t* currentPageId, int32_t interBufSize) {
L
Liu Jicong 已提交
147
  SFilePage* pData = NULL;
148 149 150

  // in the first scan, new space needed for results
  int32_t pageId = -1;
151
  if (*currentPageId == -1) {
152
    pData = getNewBufPage(pResultBuf, &pageId);
153 154
    pData->num = sizeof(SFilePage);
  } else {
155 156
    pData = getBufPage(pResultBuf, *currentPageId);
    pageId = *currentPageId;
157

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

162
      pData = getNewBufPage(pResultBuf, &pageId);
163 164 165 166 167 168 169 170 171 172
      if (pData != NULL) {
        pData->num = sizeof(SFilePage);
      }
    }
  }

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

173 174
  setBufPageDirty(pData, true);

175 176 177 178
  // 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;
179
  *currentPageId = pageId;
180

wmmhello's avatar
wmmhello 已提交
181
  pData->num += interBufSize;
182 183 184
  return pResultRow;
}

185 186 187 188 189 190 191
/**
 * the struct of key in hash table
 * +----------+---------------+
 * | group id |   key data    |
 * | 8 bytes  | actual length |
 * +----------+---------------+
 */
192 193 194
SResultRow* doSetResultOutBufByKey(SDiskbasedBuf* pResultBuf, SResultRowInfo* pResultRowInfo, char* pData,
                                   int16_t bytes, bool masterscan, uint64_t groupId, SExecTaskInfo* pTaskInfo,
                                   bool isIntervalQuery, SAggSupporter* pSup) {
195
  SET_RES_WINDOW_KEY(pSup->keyBuf, pData, bytes, groupId);
H
Haojun Liao 已提交
196

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

200 201
  SResultRow* pResult = NULL;

H
Haojun Liao 已提交
202 203
  // in case of repeat scan/reverse scan, no new time window added.
  if (isIntervalQuery) {
204
    if (masterscan && p1 != NULL) {  // the *p1 may be NULL in case of sliding+offset exists.
205
      pResult = getResultRowByPos(pResultBuf, p1, true);
206
      ASSERT(pResult->pageId == p1->pageId && pResult->offset == p1->offset);
H
Haojun Liao 已提交
207 208
    }
  } else {
dengyihao's avatar
dengyihao 已提交
209 210
    // In case of group by column query, the required SResultRow object must be existInCurrentResusltRowInfo in the
    // pResultRowInfo object.
H
Haojun Liao 已提交
211
    if (p1 != NULL) {
212
      // todo
213
      pResult = getResultRowByPos(pResultBuf, p1, true);
214
      ASSERT(pResult->pageId == p1->pageId && pResult->offset == p1->offset);
H
Haojun Liao 已提交
215 216 217
    }
  }

L
Liu Jicong 已提交
218
  // 1. close current opened time window
219
  if (pResultRowInfo->cur.pageId != -1 && ((pResult == NULL) || (pResult->pageId != pResultRowInfo->cur.pageId))) {
220
    SResultRowPosition pos = pResultRowInfo->cur;
X
Xiaoyu Wang 已提交
221
    SFilePage*         pPage = getBufPage(pResultBuf, pos.pageId);
222 223 224 225 226
    releaseBufPage(pResultBuf, pPage);
  }

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

230 231
    // add a new result set for a new group
    SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
232
    tSimpleHashPut(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pos,
L
Liu Jicong 已提交
233
                   sizeof(SResultRowPosition));
H
Haojun Liao 已提交
234 235
  }

236 237 238
  // 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 已提交
239
  // too many time window in query
240
  if (pTaskInfo->execModel == OPTR_EXEC_MODEL_BATCH &&
241
      tSimpleHashGetSize(pSup->pResultRowHashTable) > MAX_INTERVAL_TIME_WINDOW) {
242
    T_LONG_JMP(pTaskInfo->env, TSDB_CODE_QRY_TOO_MANY_TIMEWINDOW);
H
Haojun Liao 已提交
243 244
  }

H
Haojun Liao 已提交
245
  return pResult;
H
Haojun Liao 已提交
246 247
}

248
// a new buffer page for each table. Needs to opt this design
L
Liu Jicong 已提交
249
static int32_t addNewWindowResultBuf(SResultRow* pWindowRes, SDiskbasedBuf* pResultBuf, int32_t tid, uint32_t size) {
250 251 252 253
  if (pWindowRes->pageId != -1) {
    return 0;
  }

L
Liu Jicong 已提交
254
  SFilePage* pData = NULL;
255 256 257

  // in the first scan, new space needed for results
  int32_t pageId = -1;
258
  SArray* list = getDataBufPagesIdList(pResultBuf);
259 260

  if (taosArrayGetSize(list) == 0) {
261
    pData = getNewBufPage(pResultBuf, &pageId);
262
    pData->num = sizeof(SFilePage);
263 264
  } else {
    SPageInfo* pi = getLastPageInfo(list);
265
    pData = getBufPage(pResultBuf, getPageId(pi));
266
    pageId = getPageId(pi);
267

268
    if (pData->num + size > getBufPageSize(pResultBuf)) {
269
      // release current page first, and prepare the next one
270
      releaseBufPageInfo(pResultBuf, pi);
271

272
      pData = getNewBufPage(pResultBuf, &pageId);
273
      if (pData != NULL) {
274
        pData->num = sizeof(SFilePage);
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
      }
    }
  }

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

295
//  query_range_start, query_range_end, window_duration, window_start, window_end
296
void initExecTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pQueryWindow) {
297 298 299
  pColData->info.type = TSDB_DATA_TYPE_TIMESTAMP;
  pColData->info.bytes = sizeof(int64_t);

H
Haojun Liao 已提交
300
  colInfoDataEnsureCapacity(pColData, 5, false);
301 302 303 304 305 306 307 308 309
  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);
}

310 311 312 313 314 315 316
typedef struct {
  bool    hasAgg;
  int32_t numOfRows;
  int32_t startOffset;
} SFunctionCtxStatus;

static void functionCtxSave(SqlFunctionCtx* pCtx, SFunctionCtxStatus* pStatus) {
H
Haojun Liao 已提交
317
  pStatus->hasAgg = pCtx->input.colDataSMAIsSet;
318 319 320 321 322
  pStatus->numOfRows = pCtx->input.numOfRows;
  pStatus->startOffset = pCtx->input.startRowIndex;
}

static void functionCtxRestore(SqlFunctionCtx* pCtx, SFunctionCtxStatus* pStatus) {
H
Haojun Liao 已提交
323
  pCtx->input.colDataSMAIsSet = pStatus->hasAgg;
H
Haojun Liao 已提交
324
  pCtx->input.numOfRows = pStatus->numOfRows;
325 326 327
  pCtx->input.startRowIndex = pStatus->startOffset;
}

H
Haojun Liao 已提交
328 329
void applyAggFunctionOnPartialTuples(SExecTaskInfo* taskInfo, SqlFunctionCtx* pCtx, SColumnInfoData* pTimeWindowData,
                                     int32_t offset, int32_t forwardStep, int32_t numOfTotal, int32_t numOfOutput) {
330
  for (int32_t k = 0; k < numOfOutput; ++k) {
H
Haojun Liao 已提交
331
    // keep it temporarily
332 333
    SFunctionCtxStatus status = {0};
    functionCtxSave(&pCtx[k], &status);
334

335
    pCtx[k].input.startRowIndex = offset;
336
    pCtx[k].input.numOfRows = forwardStep;
337 338 339

    // not a whole block involved in query processing, statistics data can not be used
    // NOTE: the original value of isSet have been changed here
H
Haojun Liao 已提交
340 341
    if (pCtx[k].input.colDataSMAIsSet && forwardStep < numOfTotal) {
      pCtx[k].input.colDataSMAIsSet = false;
342 343
    }

344 345
    if (fmIsWindowPseudoColumnFunc(pCtx[k].functionId)) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
346 347

      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);
348

349
      SColumnInfoData idata = {0};
dengyihao's avatar
dengyihao 已提交
350
      idata.info.type = TSDB_DATA_TYPE_BIGINT;
351
      idata.info.bytes = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
dengyihao's avatar
dengyihao 已提交
352
      idata.pData = p;
353 354 355 356

      SScalarParam out = {.columnData = &idata};
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
      pCtx[k].sfp.process(&tw, 1, &out);
357
      pEntryInfo->numOfRes = 1;
358 359 360 361 362 363 364 365
    } 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;
366
          T_LONG_JMP(taskInfo->env, code);
367
        }
368
      }
369

370
      // restore it
371
      functionCtxRestore(&pCtx[k], &status);
372
    }
373 374 375
  }
}

376 377 378
static void doSetInputDataBlockInfo(SExprSupp* pExprSup, SSDataBlock* pBlock, int32_t order) {
  SqlFunctionCtx* pCtx = pExprSup->pCtx;
  for (int32_t i = 0; i < pExprSup->numOfExprs; ++i) {
379
    pCtx[i].order = order;
380
    pCtx[i].input.numOfRows = pBlock->info.rows;
381
    setBlockSMAInfo(&pCtx[i], &pExprSup->pExprInfo[i], pBlock);
382
    pCtx[i].pSrcBlock = pBlock;
383 384 385
  }
}

386
void setInputDataBlock(SExprSupp* pExprSup, SSDataBlock* pBlock, int32_t order, int32_t scanFlag, bool createDummyCol) {
387
  if (pBlock->pBlockAgg != NULL) {
388
    doSetInputDataBlockInfo(pExprSup, pBlock, order);
389
  } else {
390
    doSetInputDataBlock(pExprSup, pBlock, order, scanFlag, createDummyCol);
H
Haojun Liao 已提交
391
  }
392 393
}

L
Liu Jicong 已提交
394 395
static int32_t doCreateConstantValColumnInfo(SInputColumnInfoData* pInput, SFunctParam* pFuncParam, int32_t paramIndex,
                                             int32_t numOfRows) {
396 397 398 399 400 401 402 403
  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)
404 405
    pColInfo->info.type = pFuncParam->param.nType;
    pColInfo->info.bytes = pFuncParam->param.nLen;
406 407

    pInput->pData[paramIndex] = pColInfo;
408 409
  } else {
    pColInfo = pInput->pData[paramIndex];
410 411
  }

H
Haojun Liao 已提交
412
  colInfoDataEnsureCapacity(pColInfo, numOfRows, false);
413

414
  int8_t type = pFuncParam->param.nType;
415 416
  if (type == TSDB_DATA_TYPE_BIGINT || type == TSDB_DATA_TYPE_UBIGINT) {
    int64_t v = pFuncParam->param.i;
dengyihao's avatar
dengyihao 已提交
417
    for (int32_t i = 0; i < numOfRows; ++i) {
418 419 420 421
      colDataAppendInt64(pColInfo, i, &v);
    }
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
dengyihao's avatar
dengyihao 已提交
422
    for (int32_t i = 0; i < numOfRows; ++i) {
423 424
      colDataAppendDouble(pColInfo, i, &v);
    }
425
  } else if (type == TSDB_DATA_TYPE_VARCHAR) {
L
Liu Jicong 已提交
426
    char* tmp = taosMemoryMalloc(pFuncParam->param.nLen + VARSTR_HEADER_SIZE);
427
    STR_WITH_SIZE_TO_VARSTR(tmp, pFuncParam->param.pz, pFuncParam->param.nLen);
L
Liu Jicong 已提交
428
    for (int32_t i = 0; i < numOfRows; ++i) {
429 430
      colDataAppend(pColInfo, i, tmp, false);
    }
H
Haojun Liao 已提交
431
    taosMemoryFree(tmp);
432 433 434 435 436
  }

  return TSDB_CODE_SUCCESS;
}

437 438
static int32_t doSetInputDataBlock(SExprSupp* pExprSup, SSDataBlock* pBlock, int32_t order, int32_t scanFlag,
                                   bool createDummyCol) {
439
  int32_t         code = TSDB_CODE_SUCCESS;
440
  SqlFunctionCtx* pCtx = pExprSup->pCtx;
441

442
  for (int32_t i = 0; i < pExprSup->numOfExprs; ++i) {
L
Liu Jicong 已提交
443
    pCtx[i].order = order;
444 445
    pCtx[i].input.numOfRows = pBlock->info.rows;

L
Liu Jicong 已提交
446
    pCtx[i].pSrcBlock = pBlock;
X
Xiaoyu Wang 已提交
447
    pCtx[i].scanFlag = scanFlag;
H
Haojun Liao 已提交
448

449
    SInputColumnInfoData* pInput = &pCtx[i].input;
450
    pInput->uid = pBlock->info.uid;
H
Haojun Liao 已提交
451
    pInput->colDataSMAIsSet = false;
452

453
    SExprInfo* pOneExpr = &pExprSup->pExprInfo[i];
454
    for (int32_t j = 0; j < pOneExpr->base.numOfParams; ++j) {
dengyihao's avatar
dengyihao 已提交
455
      SFunctParam* pFuncParam = &pOneExpr->base.pParam[j];
G
Ganlin Zhao 已提交
456 457
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
dengyihao's avatar
dengyihao 已提交
458
        pInput->pData[j] = taosArrayGet(pBlock->pDataBlock, slotId);
459 460 461
        pInput->totalRows = pBlock->info.rows;
        pInput->numOfRows = pBlock->info.rows;
        pInput->startRowIndex = 0;
462

463
        // NOTE: the last parameter is the primary timestamp column
H
Haojun Liao 已提交
464
        // todo: refactor this
465
        if (fmIsImplicitTsFunc(pCtx[i].functionId) && (j == pOneExpr->base.numOfParams - 1)) {
L
Liu Jicong 已提交
466
          pInput->pPTS = pInput->pData[j];  // in case of merge function, this is not always the ts column data.
467
          //          ASSERT(pInput->pPTS->info.type == TSDB_DATA_TYPE_TIMESTAMP);
468
        }
469 470
        ASSERT(pInput->pData[j] != NULL);
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
471 472 473
        // 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) {
474 475 476 477
          pInput->totalRows = pBlock->info.rows;
          pInput->numOfRows = pBlock->info.rows;
          pInput->startRowIndex = 0;

478
          code = doCreateConstantValColumnInfo(pInput, pFuncParam, j, pBlock->info.rows);
479 480 481
          if (code != TSDB_CODE_SUCCESS) {
            return code;
          }
482
        }
G
Ganlin Zhao 已提交
483 484
      }
    }
H
Haojun Liao 已提交
485
  }
486 487

  return code;
H
Haojun Liao 已提交
488 489
}

490
static int32_t doAggregateImpl(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx) {
491
  for (int32_t k = 0; k < pOperator->exprSupp.numOfExprs; ++k) {
H
Haojun Liao 已提交
492
    if (functionNeedToExecute(&pCtx[k])) {
493
      // todo add a dummy funtion to avoid process check
494 495 496
      if (pCtx[k].fpSet.process == NULL) {
        continue;
      }
H
Haojun Liao 已提交
497

498 499 500 501
      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;
502
      }
503 504
    }
  }
505 506

  return TSDB_CODE_SUCCESS;
507 508
}

H
Haojun Liao 已提交
509
static void setPseudoOutputColInfo(SSDataBlock* pResult, SqlFunctionCtx* pCtx, SArray* pPseudoList) {
dengyihao's avatar
dengyihao 已提交
510
  size_t num = (pPseudoList != NULL) ? taosArrayGetSize(pPseudoList) : 0;
H
Haojun Liao 已提交
511 512 513 514 515
  for (int32_t i = 0; i < num; ++i) {
    pCtx[i].pOutput = taosArrayGet(pResult->pDataBlock, i);
  }
}

516
int32_t projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBlock* pSrcBlock, SqlFunctionCtx* pCtx,
X
Xiaoyu Wang 已提交
517
                              int32_t numOfOutput, SArray* pPseudoList) {
H
Haojun Liao 已提交
518
  setPseudoOutputColInfo(pResult, pCtx, pPseudoList);
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538

  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 已提交
539 540 541 542
  if (pResult != pSrcBlock) {
    pResult->info.groupId = pSrcBlock->info.groupId;
    memcpy(pResult->info.parTbName, pSrcBlock->info.parTbName, TSDB_TABLE_NAME_LEN);
  }
H
Haojun Liao 已提交
543

544 545
  // if the source equals to the destination, it is to create a new column as the result of scalar
  // function or some operators.
546
  bool createNewColModel = (pResult == pSrcBlock);
547 548 549
  if (createNewColModel) {
    blockDataEnsureCapacity(pResult, pResult->info.rows);
  }
550

551 552
  int32_t numOfRows = 0;

553
  for (int32_t k = 0; k < numOfOutput; ++k) {
554 555
    int32_t               outputSlotId = pExpr[k].base.resSchema.slotId;
    SqlFunctionCtx*       pfCtx = &pCtx[k];
556
    SInputColumnInfoData* pInputData = &pfCtx->input;
557

L
Liu Jicong 已提交
558
    if (pExpr[k].pExpr->nodeType == QUERY_NODE_COLUMN) {  // it is a project query
559
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
560
      if (pResult->info.rows > 0 && !createNewColModel) {
561
        colDataMergeCol(pColInfoData, pResult->info.rows, (int32_t*)&pResult->info.capacity, pInputData->pData[0],
562
                        pInputData->numOfRows);
563
      } else {
564
        colDataAssign(pColInfoData, pInputData->pData[0], pInputData->numOfRows, &pResult->info);
565
      }
566

567
      numOfRows = pInputData->numOfRows;
568
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_VALUE) {
569
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
570

dengyihao's avatar
dengyihao 已提交
571
      int32_t offset = createNewColModel ? 0 : pResult->info.rows;
572 573 574 575 576 577 578 579

      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);
        }
580
      }
581 582

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

587
      SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
588
      SColumnInfoData  idata = {.info = pResColData->info, .hasNull = true};
589

590
      SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
591
      int32_t      code = scalarCalculate(pExpr[k].pExpr->_optrRoot.pRootNode, pBlockList, &dest);
592 593 594 595
      if (code != TSDB_CODE_SUCCESS) {
        taosArrayDestroy(pBlockList);
        return code;
      }
596

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

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

603
      numOfRows = dest.numOfRows;
604 605
      taosArrayDestroy(pBlockList);
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_FUNCTION) {
606 607
      // _rowts/_c0, not tbname column
      if (fmIsPseudoColumnFunc(pfCtx->functionId) && (!fmIsScanPseudoColumnFunc(pfCtx->functionId))) {
H
Haojun Liao 已提交
608
        // do nothing
609
      } else if (fmIsIndefiniteRowsFunc(pfCtx->functionId)) {
610 611
        SResultRowEntryInfo* pResInfo = GET_RES_INFO(pfCtx);
        pfCtx->fpSet.init(pfCtx, pResInfo);
612 613 614 615 616 617 618 619 620 621

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

622 623 624 625 626
        // link pDstBlock to set selectivity value
        if (pfCtx->subsidiaries.num > 0) {
          pfCtx->pDstBlock = pResult;
        }

627 628 629 630 631
        int32_t code = pfCtx->fpSet.process(pfCtx);
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
        numOfRows = pResInfo->numOfRes;
H
Haojun Liao 已提交
632
      } else if (fmIsAggFunc(pfCtx->functionId)) {
G
Ganlin Zhao 已提交
633
        // selective value output should be set during corresponding function execution
634 635 636
        if (fmIsSelectValueFunc(pfCtx->functionId)) {
          continue;
        }
637 638
        // _group_key function for "partition by tbname" + csum(col_name) query
        SColumnInfoData* pOutput = taosArrayGet(pResult->pDataBlock, outputSlotId);
639
        int32_t          slotId = pfCtx->param[0].pCol->slotId;
640 641 642

        // todo handle the json tag
        SColumnInfoData* pInput = taosArrayGet(pSrcBlock->pDataBlock, slotId);
643
        for (int32_t f = 0; f < pSrcBlock->info.rows; ++f) {
644 645 646 647 648 649 650 651 652
          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 已提交
653 654 655
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
656

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

660
        SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
661
        int32_t      code = scalarCalculate((SNode*)pExpr[k].pExpr->_function.pFunctNode, pBlockList, &dest);
662 663 664 665
        if (code != TSDB_CODE_SUCCESS) {
          taosArrayDestroy(pBlockList);
          return code;
        }
666

dengyihao's avatar
dengyihao 已提交
667
        int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
668
        ASSERT(pResult->info.capacity > 0);
669
        colDataMergeCol(pResColData, startOffset, (int32_t*)&pResult->info.capacity, &idata, dest.numOfRows);
D
dapan1121 已提交
670
        colDataDestroy(&idata);
671 672

        numOfRows = dest.numOfRows;
H
Haojun Liao 已提交
673 674
        taosArrayDestroy(pBlockList);
      }
675
    } else {
676
      return TSDB_CODE_OPS_NOT_SUPPORT;
677 678
    }
  }
679

680 681 682
  if (!createNewColModel) {
    pResult->info.rows += numOfRows;
  }
683 684

  return TSDB_CODE_SUCCESS;
685 686
}

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

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

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

700 701
  if (isRowEntryCompleted(pResInfo)) {
    return false;
702 703
  }

704 705 706
  return true;
}

707 708 709 710 711 712 713
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;
    }
714

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

720 721 722 723 724 725
  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;
726 727
    }
  } else {
728
    da = pInput->pColumnDataAgg[paramIndex];
729 730
  }

731
  ASSERT(!IS_VAR_DATA_TYPE(type));
732

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

740 741 742 743 744 745
    *(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;

746
    *da = (SColumnDataAgg){.numOfNull = 0};
747 748 749 750 751
    *(bool*)&da->min = 0;
    *(bool*)&da->max = v;
    *(bool*)&da->sum = v * numOfRows;
  } else if (type == TSDB_DATA_TYPE_TIMESTAMP) {
    // do nothing
752
  } else {
753
    ASSERT(0);
754 755
  }

756 757
  return TSDB_CODE_SUCCESS;
}
758

759
void setBlockSMAInfo(SqlFunctionCtx* pCtx, SExprInfo* pExprInfo, SSDataBlock* pBlock) {
760 761 762 763 764 765 766
  int32_t numOfRows = pBlock->info.rows;

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

  if (pBlock->pBlockAgg != NULL) {
H
Haojun Liao 已提交
767
    pInput->colDataSMAIsSet = true;
768

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

772 773
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
774 775
        pInput->pColumnDataAgg[j] = pBlock->pBlockAgg[slotId];
        if (pInput->pColumnDataAgg[j] == NULL) {
H
Haojun Liao 已提交
776
          pInput->colDataSMAIsSet = false;
777
        }
778 779 780 781

        // 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);
782 783
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
        doCreateConstantValColumnAggInfo(pInput, pFuncParam, pFuncParam->param.nType, j, pBlock->info.rows);
784 785
      }
    }
786
  } else {
H
Haojun Liao 已提交
787
    pInput->colDataSMAIsSet = false;
788 789 790
  }
}

L
Liu Jicong 已提交
791
bool isTaskKilled(SExecTaskInfo* pTaskInfo) {
792 793
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
L
Liu Jicong 已提交
794 795
  if (pTaskInfo->owner != 0 &&
      ((taosGetTimestampSec() - pTaskInfo->cost.start / 1000) > 10 * getMaximumIdleDurationSec())
796
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
797
    assert(pTaskInfo->cost.start != 0);
L
Liu Jicong 已提交
798 799 800
    //    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;
801 802 803 804 805
  }

  return false;
}

L
Liu Jicong 已提交
806
void setTaskKilled(SExecTaskInfo* pTaskInfo) { pTaskInfo->code = TSDB_CODE_TSC_QUERY_CANCELLED; }
807 808

/////////////////////////////////////////////////////////////////////////////////////////////
809
STimeWindow getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key) {
L
Liu Jicong 已提交
810
  STimeWindow win = {0};
811
  win.skey = taosTimeTruncate(key, pInterval, precision);
812 813

  /*
H
Haojun Liao 已提交
814
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
815 816
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
817 818 819
  win.ekey = taosTimeAdd(win.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
  if (win.ekey < win.skey) {
    win.ekey = INT64_MAX;
820
  }
821 822

  return win;
823 824
}

L
Liu Jicong 已提交
825 826
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
827
  *status = BLK_DATA_NOT_LOAD;
828

H
Haojun Liao 已提交
829
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
830
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
831

L
Liu Jicong 已提交
832 833
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
834

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

837 838
//  pCost->totalBlocks += 1;
//  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
839
#if 0
840 841 842
  // 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 已提交
843
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
844
    (*status) = BLK_DATA_DATA_LOAD;
845 846 847
  }

  // check if this data block is required to load
848
  if ((*status) != BLK_DATA_DATA_LOAD) {
849 850 851 852 853 854 855
    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 已提交
856
      bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
857 858 859 860 861 862
      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,
863
                                    pTableScanInfo->rowEntryInfoOffset);
864 865 866
      } else {
        if (setResultOutputBufByKey(pRuntimeEnv, pTableScanInfo->pResultRowInfo, pBlock->info.uid, &win, masterScan, &pResult, groupId,
                                    pTableScanInfo->pCtx, pTableScanInfo->numOfOutput,
867
                                    pTableScanInfo->rowEntryInfoOffset) != TSDB_CODE_SUCCESS) {
868
          T_LONG_JMP(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
869 870 871 872
        }
      }
    } else if (pQueryAttr->stableQuery && (!pQueryAttr->tsCompQuery) && (!pQueryAttr->diffQuery)) { // stable aggregate, not interval aggregate or normal column aggregate
      doSetTableGroupOutputBuf(pRuntimeEnv, pTableScanInfo->pResultRowInfo, pTableScanInfo->pCtx,
873
                               pTableScanInfo->rowEntryInfoOffset, pTableScanInfo->numOfOutput,
874 875 876 877 878 879
                               pRuntimeEnv->current->groupIndex);
    }

    if (needFilter) {
      (*status) = doFilterByBlockTimeWindow(pTableScanInfo, pBlock);
    } else {
880
      (*status) = BLK_DATA_DATA_LOAD;
881 882 883 884
    }
  }

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

887
  if ((*status) == BLK_DATA_NOT_LOAD || (*status) == BLK_DATA_FILTEROUT) {
888 889
    //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//           pBlockInfo->window.ekey, pBlockInfo->rows);
890
    pCost->skipBlocks += 1;
891
  } else if ((*status) == BLK_DATA_SMA_LOAD) {
892 893
    // this function never returns error?
    pCost->loadBlockStatis += 1;
894
//    tsdbRetrieveDatablockSMA(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
895 896

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
897
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
898 899 900
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
901
    assert((*status) == BLK_DATA_DATA_LOAD);
902 903 904

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
905
//    tsdbRetrieveDatablockSMA(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
906 907 908 909 910 911

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

H
Haojun Liao 已提交
912
          bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
913 914 915 916 917
          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,
918
                                      pTableScanInfo->rowEntryInfoOffset) != TSDB_CODE_SUCCESS) {
919
            T_LONG_JMP(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
920 921 922 923 924 925 926 927 928 929
          }
        }
      }
      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
930
            pCost->skipBlocks += 1;
931 932
            //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId,
//                   pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
933
            (*status) = BLK_DATA_FILTEROUT;
934 935 936 937 938 939 940
            return TSDB_CODE_SUCCESS;
          }
        }
      }
    }

    // current block has been discard due to filter applied
H
Haojun Liao 已提交
941
//    if (!doFilterByBlockSMA(pRuntimeEnv, pBlock->pBlockAgg, pTableScanInfo->pCtx, pBlockInfo->rows)) {
942
//      pCost->skipBlocks += 1;
943 944
//      qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//             pBlockInfo->window.ekey, pBlockInfo->rows);
945
//      (*status) = BLK_DATA_FILTEROUT;
946 947 948 949 950
//      return TSDB_CODE_SUCCESS;
//    }

    pCost->totalCheckedRows += pBlockInfo->rows;
    pCost->loadBlocks += 1;
951
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
952 953 954 955 956
//    if (pBlock->pDataBlock == NULL) {
//      return terrno;
//    }

//    if (pQueryAttr->pFilters != NULL) {
957
//      filterSetColFieldData(pQueryAttr->pFilters, taosArrayGetSize(pBlock->pDataBlock), pBlock->pDataBlock);
958
//    }
959

960 961 962 963
//    if (pQueryAttr->pFilters != NULL || pRuntimeEnv->pTsBuf != NULL) {
//      filterColRowsInDataBlock(pRuntimeEnv, pBlock, ascQuery);
//    }
  }
H
Haojun Liao 已提交
964
#endif
965 966 967
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
968
void setTaskStatus(SExecTaskInfo* pTaskInfo, int8_t status) {
969
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
970
    pTaskInfo->status = status;
971 972
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
973
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
974
    pTaskInfo->status |= status;
975 976 977
  }
}

978
void setResultRowInitCtx(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowEntryInfoOffset) {
5
54liuyao 已提交
979
  bool init = false;
980
  for (int32_t i = 0; i < numOfOutput; ++i) {
981
    pCtx[i].resultInfo = getResultEntryInfo(pResult, i, rowEntryInfoOffset);
5
54liuyao 已提交
982 983 984
    if (init) {
      continue;
    }
985 986 987 988 989

    struct SResultRowEntryInfo* pResInfo = pCtx[i].resultInfo;
    if (isRowEntryCompleted(pResInfo) && isRowEntryInitialized(pResInfo)) {
      continue;
    }
990 991 992 993 994

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

995 996 997 998 999 1000
    if (!pResInfo->initialized) {
      if (pCtx[i].functionId != -1) {
        pCtx[i].fpSet.init(&pCtx[i], pResInfo);
      } else {
        pResInfo->initialized = true;
      }
5
54liuyao 已提交
1001 1002
    } else {
      init = true;
1003 1004 1005 1006
    }
  }
}

H
Haojun Liao 已提交
1007 1008
void doFilter(SSDataBlock* pBlock, SFilterInfo* pFilterInfo, SColMatchInfo* pColMatchInfo) {
  if (pFilterInfo == NULL || pBlock->info.rows == 0) {
S
shenglian zhou 已提交
1009 1010
    return;
  }
1011

1012
  SFilterColumnParam param1 = {.numOfCols = taosArrayGetSize(pBlock->pDataBlock), .pDataBlock = pBlock->pDataBlock};
1013
  int32_t            code = filterSetDataFromSlotId(pFilterInfo, &param1);
1014

1015
  SColumnInfoData* p = NULL;
1016
  int32_t          status = 0;
H
Haojun Liao 已提交
1017

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

1022
  if (pColMatchInfo != NULL) {
1023
    size_t size = taosArrayGetSize(pColMatchInfo->pList);
H
Haojun Liao 已提交
1024
    for (int32_t i = 0; i < size; ++i) {
H
Haojun Liao 已提交
1025
      SColMatchItem* pInfo = taosArrayGet(pColMatchInfo->pList, i);
1026
      if (pInfo->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
1027
        SColumnInfoData* pColData = taosArrayGet(pBlock->pDataBlock, pInfo->dstSlotId);
1028
        if (pColData->info.type == TSDB_DATA_TYPE_TIMESTAMP) {
H
Haojun Liao 已提交
1029
          blockDataUpdateTsWindow(pBlock, pInfo->dstSlotId);
1030 1031 1032 1033 1034 1035
          break;
        }
      }
    }
  }

1036 1037
  colDataDestroy(p);
  taosMemoryFree(p);
1038 1039
}

1040
void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const SColumnInfoData* p, bool keep, int32_t status) {
1041 1042 1043 1044
  if (keep) {
    return;
  }

H
Haojun Liao 已提交
1045 1046 1047
  int32_t totalRows = pBlock->info.rows;

  if (status == FILTER_RESULT_ALL_QUALIFIED) {
1048
    // here nothing needs to be done
H
Haojun Liao 已提交
1049
  } else if (status == FILTER_RESULT_NONE_QUALIFIED) {
1050
    pBlock->info.rows = 0;
H
Haojun Liao 已提交
1051
  } else {
1052
    SSDataBlock* px = createOneDataBlock(pBlock, true);
1053

1054 1055
    size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
    for (int32_t i = 0; i < numOfCols; ++i) {
1056 1057
      SColumnInfoData* pSrc = taosArrayGet(px->pDataBlock, i);
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, i);
1058
      // it is a reserved column for scalar function, and no data in this column yet.
1059
      if (pDst->pData == NULL || pSrc->pData == NULL) {
1060 1061 1062
        continue;
      }

1063 1064
      colInfoDataCleanup(pDst, pBlock->info.rows);

1065
      int32_t numOfRows = 0;
1066
      for (int32_t j = 0; j < totalRows; ++j) {
1067
        if (((int8_t*)p->pData)[j] == 0) {
D
dapan1121 已提交
1068 1069
          continue;
        }
1070

D
dapan1121 已提交
1071
        if (colDataIsNull_s(pSrc, j)) {
1072
          colDataAppendNULL(pDst, numOfRows);
D
dapan1121 已提交
1073
        } else {
1074
          colDataAppend(pDst, numOfRows, colDataGetData(pSrc, j), false);
D
dapan1121 已提交
1075
        }
1076
        numOfRows += 1;
H
Haojun Liao 已提交
1077
      }
1078

1079
      // todo this value can be assigned directly
1080 1081 1082 1083 1084
      if (pBlock->info.rows == totalRows) {
        pBlock->info.rows = numOfRows;
      } else {
        ASSERT(pBlock->info.rows == numOfRows);
      }
1085
    }
1086

dengyihao's avatar
dengyihao 已提交
1087
    blockDataDestroy(px);  // fix memory leak
1088 1089 1090
  }
}

1091
void doSetTableGroupOutputBuf(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId) {
1092
  // for simple group by query without interval, all the tables belong to one group result.
1093 1094 1095
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
  SAggOperatorInfo* pAggInfo = pOperator->info;

1096
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
1097 1098
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
  int32_t*        rowEntryInfoOffset = pOperator->exprSupp.rowEntryInfoOffset;
1099

1100
  SResultRow* pResultRow = doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, (char*)&groupId,
L
Liu Jicong 已提交
1101
                                                  sizeof(groupId), true, groupId, pTaskInfo, false, &pAggInfo->aggSup);
L
Liu Jicong 已提交
1102
  assert(pResultRow != NULL);
1103 1104 1105 1106 1107 1108

  /*
   * 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 已提交
1109 1110
    int32_t ret =
        addNewWindowResultBuf(pResultRow, pAggInfo->aggSup.pResultBuf, groupId, pAggInfo->binfo.pRes->info.rowSize);
1111 1112 1113 1114 1115
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

1116
  setResultRowInitCtx(pResultRow, pCtx, numOfOutput, rowEntryInfoOffset);
1117 1118
}

1119 1120 1121
static void setExecutionContext(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId) {
  SAggOperatorInfo* pAggInfo = pOperator->info;
  if (pAggInfo->groupId != UINT64_MAX && pAggInfo->groupId == groupId) {
1122 1123
    return;
  }
1124 1125

  doSetTableGroupOutputBuf(pOperator, numOfOutput, groupId);
1126 1127

  // record the current active group id
H
Haojun Liao 已提交
1128
  pAggInfo->groupId = groupId;
1129 1130
}

dengyihao's avatar
dengyihao 已提交
1131 1132
static void doUpdateNumOfRows(SqlFunctionCtx* pCtx, SResultRow* pRow, int32_t numOfExprs,
                              const int32_t* rowCellOffset) {
1133
  bool returnNotNull = false;
1134
  for (int32_t j = 0; j < numOfExprs; ++j) {
1135
    struct SResultRowEntryInfo* pResInfo = getResultEntryInfo(pRow, j, rowCellOffset);
1136 1137 1138 1139 1140 1141 1142
    if (!isRowEntryInitialized(pResInfo)) {
      continue;
    }

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

1144
    if (fmIsNotNullOutputFunc(pCtx[j].functionId)) {
1145 1146
      returnNotNull = true;
    }
1147
  }
S
shenglian zhou 已提交
1148 1149
  // 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
1150
  if (pRow->numOfRows == 0 && !returnNotNull) {
1151
    pRow->numOfRows = 1;
1152 1153 1154
  }
}

1155 1156
static void doCopyResultToDataBlock(SExprInfo* pExprInfo, int32_t numOfExprs, SResultRow* pRow, SqlFunctionCtx* pCtx,
                                    SSDataBlock* pBlock, const int32_t* rowEntryOffset, SExecTaskInfo* pTaskInfo) {
1157 1158 1159
  for (int32_t j = 0; j < numOfExprs; ++j) {
    int32_t slotId = pExprInfo[j].base.resSchema.slotId;

1160
    pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowEntryOffset);
1161
    if (pCtx[j].fpSet.finalize) {
1162
      if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_group_key") == 0) {
1163 1164
        // for groupkey along with functions that output multiple lines(e.g. Histogram)
        // need to match groupkey result for each output row of that function.
1165 1166 1167 1168 1169
        if (pCtx[j].resultInfo->numOfRes != 0) {
          pCtx[j].resultInfo->numOfRes = pRow->numOfRows;
        }
      }

1170 1171 1172
      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));
1173
        T_LONG_JMP(pTaskInfo->env, code);
1174 1175
      }
    } else if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
1176
      // do nothing
1177
    } else {
1178 1179
      // 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.
1180 1181 1182 1183 1184 1185 1186
      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);
      }
    }
  }
1187 1188
}

1189 1190 1191
// todo refactor. SResultRow has direct pointer in miainfo
int32_t finalizeResultRows(SDiskbasedBuf* pBuf, SResultRowPosition* resultRowPosition, SExprSupp* pSup,
                           SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo) {
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
  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);
1218 1219

  releaseBufPage(pBuf, page);
1220
  pBlock->info.rows += pRow->numOfRows;
1221 1222 1223
  return 0;
}

1224 1225 1226 1227 1228 1229 1230
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;

1231
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
1232

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

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

H
Haojun Liao 已提交
1239
    doUpdateNumOfRows(pCtx, pRow, numOfExprs, rowEntryOffset);
1240 1241

    // no results, continue to check the next one
1242 1243
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
1244
      releaseBufPage(pBuf, page);
1245 1246 1247
      continue;
    }

1248 1249 1250 1251 1252
    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) {
1253
        releaseBufPage(pBuf, page);
1254 1255 1256 1257
        break;
      }
    }

1258
    if (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
1259
      ASSERT(pBlock->info.rows > 0);
1260
      releaseBufPage(pBuf, page);
1261 1262 1263 1264
      break;
    }

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

1267
    releaseBufPage(pBuf, page);
1268
    pBlock->info.rows += pRow->numOfRows;
1269 1270
  }

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

1274
  blockDataUpdateTsWindow(pBlock, 0);
1275 1276 1277
  return 0;
}

1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
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);

1296 1297 1298 1299 1300
  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);
1301
  }
1302
  tdbFree(tbname);
1303 1304
}

X
Xiaoyu Wang 已提交
1305 1306
void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SGroupResInfo* pGroupResInfo,
                            SDiskbasedBuf* pBuf) {
1307
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
1308
  SSDataBlock*   pBlock = pbInfo->pRes;
1309

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

1313
  blockDataCleanup(pBlock);
1314
  if (!hasRemainResults(pGroupResInfo)) {
1315 1316 1317
    return;
  }

1318 1319
  // clear the existed group id
  pBlock->info.groupId = 0;
1320 1321 1322
  if (!pbInfo->mergeResultBlock) {
    doCopyToSDataBlock(pTaskInfo, pBlock, &pOperator->exprSupp, pBuf, pGroupResInfo);
  } else {
dengyihao's avatar
dengyihao 已提交
1323
    while (hasRemainResults(pGroupResInfo)) {
1324 1325 1326
      doCopyToSDataBlock(pTaskInfo, pBlock, &pOperator->exprSupp, pBuf, pGroupResInfo);
      if (pBlock->info.rows >= pOperator->resultInfo.threshold) {
        break;
1327 1328
      }

1329 1330
      // clearing group id to continue to merge data that belong to different groups
      pBlock->info.groupId = 0;
1331
    }
1332 1333 1334

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

L
Liu Jicong 已提交
1338 1339
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
1340

1341 1342
  SFileBlockLoadRecorder* pRecorder = pSummary->pRecoder;
  if (pSummary->pRecoder != NULL) {
1343
    qDebug(
H
Haojun Liao 已提交
1344 1345 1346 1347 1348
        "%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);
1349
  }
1350 1351
}

L
Liu Jicong 已提交
1352 1353
// void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
1354
//
L
Liu Jicong 已提交
1355 1356 1357
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//     return;
//   }
1358
//
L
Liu Jicong 已提交
1359 1360
//   pQueryAttr->pos = 0;
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
1361
//
L
Liu Jicong 已提交
1362 1363
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//   TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
1364
//
L
Liu Jicong 已提交
1365 1366 1367
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pTsdbReadHandle)) {
//     if (isTaskKilled(pRuntimeEnv->qinfo)) {
1368
//       T_LONG_JMP(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
L
Liu Jicong 已提交
1369
//     }
1370
//
L
Liu Jicong 已提交
1371
//     tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
1372
//
L
Liu Jicong 已提交
1373 1374 1375 1376
//     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;
1377
//
L
Liu Jicong 已提交
1378 1379 1380 1381 1382 1383 1384
//       //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;
//     }
//   }
1385
//
L
Liu Jicong 已提交
1386
//   if (terrno != TSDB_CODE_SUCCESS) {
1387
//     T_LONG_JMP(pRuntimeEnv->env, terrno);
L
Liu Jicong 已提交
1388 1389 1390 1391 1392 1393 1394
//   }
// }

// static TSKEY doSkipIntervalProcess(STaskRuntimeEnv* pRuntimeEnv, STimeWindow* win, SDataBlockInfo* pBlockInfo,
// STableQueryInfo* pTableQueryInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
1395
//
L
Liu Jicong 已提交
1396 1397 1398
//   assert(pQueryAttr->limit.offset == 0);
//   STimeWindow tw = *win;
//   getNextTimeWindow(pQueryAttr, &tw);
1399
//
L
Liu Jicong 已提交
1400 1401
//   if ((tw.skey <= pBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) ||
//       (tw.ekey >= pBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
1402
//
L
Liu Jicong 已提交
1403 1404 1405 1406
//     // 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);
1407
//
L
Liu Jicong 已提交
1408 1409 1410 1411
//     tw = *win;
//     int32_t startPos =
//         getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1);
//     assert(startPos >= 0);
1412
//
L
Liu Jicong 已提交
1413 1414
//     // set the abort info
//     pQueryAttr->pos = startPos;
1415
//
L
Liu Jicong 已提交
1416 1417 1418 1419
//     // reset the query start timestamp
//     pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
//     pQueryAttr->window.skey = pTableQueryInfo->win.skey;
//     TSKEY key = pTableQueryInfo->win.skey;
1420
//
L
Liu Jicong 已提交
1421 1422
//     pWindowResInfo->prevSKey = tw.skey;
//     int32_t index = pRuntimeEnv->resultRowInfo.curIndex;
1423
//
L
Liu Jicong 已提交
1424 1425
//     int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//     pRuntimeEnv->resultRowInfo.curIndex = index;  // restore the window index
1426
//
L
Liu Jicong 已提交
1427 1428 1429 1430
//     //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);
1431
//
L
Liu Jicong 已提交
1432 1433 1434 1435 1436
//     return key;
//   } else {  // do nothing
//     pQueryAttr->window.skey      = tw.skey;
//     pWindowResInfo->prevSKey = tw.skey;
//     pTableQueryInfo->lastKey = tw.skey;
1437
//
L
Liu Jicong 已提交
1438 1439
//     return tw.skey;
//   }
1440
//
L
Liu Jicong 已提交
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
//   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);
//   }
1451
//
L
Liu Jicong 已提交
1452 1453 1454 1455 1456
//   // 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;
//   }
1457
//
L
Liu Jicong 已提交
1458 1459 1460 1461 1462 1463 1464
//   /*
//    * 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);
1465
//
L
Liu Jicong 已提交
1466 1467
//   STimeWindow w = TSWINDOW_INITIALIZER;
//   bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
1468
//
L
Liu Jicong 已提交
1469 1470
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//   STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
1471
//
L
Liu Jicong 已提交
1472 1473 1474
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pRuntimeEnv->pTsdbReadHandle)) {
//     tsdbRetrieveDataBlockInfo(pRuntimeEnv->pTsdbReadHandle, &blockInfo);
1475
//
L
Liu Jicong 已提交
1476 1477 1478 1479 1480 1481 1482 1483 1484
//     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;
//     }
1485
//
L
Liu Jicong 已提交
1486 1487
//     // the first time window
//     STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQueryAttr);
1488
//
L
Liu Jicong 已提交
1489 1490
//     while (pQueryAttr->limit.offset > 0) {
//       STimeWindow tw = win;
1491
//
L
Liu Jicong 已提交
1492 1493 1494
//       if ((win.ekey <= blockInfo.window.ekey && ascQuery) || (win.ekey >= blockInfo.window.skey && !ascQuery)) {
//         pQueryAttr->limit.offset -= 1;
//         pWindowResInfo->prevSKey = win.skey;
1495
//
L
Liu Jicong 已提交
1496 1497 1498 1499 1500 1501
//         // 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;
//         }
//       }
1502
//
L
Liu Jicong 已提交
1503 1504 1505 1506
//       if (pQueryAttr->limit.offset == 0) {
//         *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//         return true;
//       }
1507
//
L
Liu Jicong 已提交
1508 1509
//       // current window does not ended in current data block, try next data block
//       getNextTimeWindow(pQueryAttr, &tw);
1510
//
L
Liu Jicong 已提交
1511 1512 1513 1514 1515 1516 1517 1518 1519
//       /*
//        * 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)) {
1520
//
L
Liu Jicong 已提交
1521 1522
//         SArray *pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//         SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
1523
//
L
Liu Jicong 已提交
1524 1525 1526
//         if ((win.ekey > blockInfo.window.ekey && ascQuery) || (win.ekey < blockInfo.window.skey && !ascQuery)) {
//           pQueryAttr->limit.offset -= 1;
//         }
1527
//
L
Liu Jicong 已提交
1528 1529 1530 1531 1532 1533 1534 1535
//         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);
1536
//
L
Liu Jicong 已提交
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
//           // 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.
//       }
//     }
//   }
1548
//
L
Liu Jicong 已提交
1549 1550
//   // check for error
//   if (terrno != TSDB_CODE_SUCCESS) {
1551
//     T_LONG_JMP(pRuntimeEnv->env, terrno);
L
Liu Jicong 已提交
1552
//   }
1553
//
L
Liu Jicong 已提交
1554 1555
//   return true;
// }
1556

1557
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
1558
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
1559
    assert(p->numOfDownstream == 0);
1560 1561
  }

wafwerar's avatar
wafwerar 已提交
1562
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
1563 1564 1565 1566 1567 1568 1569
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

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

X
Xiaoyu Wang 已提交
1572
int32_t getTableScanInfo(SOperatorInfo* pOperator, int32_t* order, int32_t* scanFlag) {
1573
  // todo add more information about exchange operation
1574
  int32_t type = pOperator->operatorType;
X
Xiaoyu Wang 已提交
1575
  if (type == QUERY_NODE_PHYSICAL_PLAN_EXCHANGE || type == QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN ||
1576
      type == QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN || type == QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN ||
1577
      type == QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN || type == QUERY_NODE_PHYSICAL_PLAN_LAST_ROW_SCAN) {
1578 1579 1580
    *order = TSDB_ORDER_ASC;
    *scanFlag = MAIN_SCAN;
    return TSDB_CODE_SUCCESS;
1581
  } else if (type == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
1582
    STableScanInfo* pTableScanInfo = pOperator->info;
H
Haojun Liao 已提交
1583 1584
    *order = pTableScanInfo->base.cond.order;
    *scanFlag = pTableScanInfo->base.scanFlag;
1585
    return TSDB_CODE_SUCCESS;
1586 1587
  } else if (type == QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN) {
    STableMergeScanInfo* pTableScanInfo = pOperator->info;
H
Haojun Liao 已提交
1588 1589
    *order = pTableScanInfo->base.cond.order;
    *scanFlag = pTableScanInfo->base.scanFlag;
1590
    return TSDB_CODE_SUCCESS;
1591
  } else {
H
Haojun Liao 已提交
1592
    if (pOperator->pDownstream == NULL || pOperator->pDownstream[0] == NULL) {
1593
      return TSDB_CODE_INVALID_PARA;
H
Haojun Liao 已提交
1594
    } else {
1595
      return getTableScanInfo(pOperator->pDownstream[0], order, scanFlag);
1596 1597 1598
    }
  }
}
1599

1600
// this is a blocking operator
L
Liu Jicong 已提交
1601
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
1602 1603
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
1604 1605
  }

H
Haojun Liao 已提交
1606
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
1607
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
1608

1609 1610
  SExprSupp*     pSup = &pOperator->exprSupp;
  SOperatorInfo* downstream = pOperator->pDownstream[0];
1611

1612 1613
  int64_t st = taosGetTimestampUs();

1614 1615 1616
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;

H
Haojun Liao 已提交
1617
  while (1) {
1618
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
1619 1620 1621 1622
    if (pBlock == NULL) {
      break;
    }

1623 1624
    int32_t code = getTableScanInfo(pOperator, &order, &scanFlag);
    if (code != TSDB_CODE_SUCCESS) {
1625
      T_LONG_JMP(pTaskInfo->env, code);
1626
    }
1627

1628
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
1629 1630 1631
    if (pAggInfo->scalarExprSup.pExprInfo != NULL) {
      SExprSupp* pSup1 = &pAggInfo->scalarExprSup;
      code = projectApplyFunctions(pSup1->pExprInfo, pBlock, pBlock, pSup1->pCtx, pSup1->numOfExprs, NULL);
1632
      if (code != TSDB_CODE_SUCCESS) {
1633
        T_LONG_JMP(pTaskInfo->env, code);
1634
      }
1635 1636
    }

1637
    // the pDataBlock are always the same one, no need to call this again
1638
    setExecutionContext(pOperator, pOperator->exprSupp.numOfExprs, pBlock->info.groupId);
1639
    setInputDataBlock(pSup, pBlock, order, scanFlag, true);
1640
    code = doAggregateImpl(pOperator, pSup->pCtx);
1641
    if (code != 0) {
1642
      T_LONG_JMP(pTaskInfo->env, code);
1643
    }
1644 1645
  }

1646 1647 1648 1649 1650
  // the downstream operator may return with error code, so let's check the code before generating results.
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
    T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
  }

1651
  initGroupedResultInfo(&pAggInfo->groupResInfo, pAggInfo->aggSup.pResultRowHashTable, 0);
H
Haojun Liao 已提交
1652
  OPTR_SET_OPENED(pOperator);
1653

1654
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
1655
  return pTaskInfo->code;
H
Haojun Liao 已提交
1656 1657
}

1658
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
1659
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
1660 1661 1662 1663 1664 1665
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

L
Liu Jicong 已提交
1666
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
1667
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
H
Haojun Liao 已提交
1668
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1669
    setOperatorCompleted(pOperator);
H
Haojun Liao 已提交
1670 1671 1672
    return NULL;
  }

H
Haojun Liao 已提交
1673
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
S
slzhou 已提交
1674 1675
  while (1) {
    doBuildResultDatablock(pOperator, pInfo, &pAggInfo->groupResInfo, pAggInfo->aggSup.pResultBuf);
H
Haojun Liao 已提交
1676
    doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
S
slzhou 已提交
1677

1678
    if (!hasRemainResults(&pAggInfo->groupResInfo)) {
H
Haojun Liao 已提交
1679
      setOperatorCompleted(pOperator);
S
slzhou 已提交
1680 1681
      break;
    }
1682

S
slzhou 已提交
1683 1684 1685 1686
    if (pInfo->pRes->info.rows > 0) {
      break;
    }
  }
1687

1688
  size_t rows = blockDataGetNumOfRows(pInfo->pRes);
1689 1690
  pOperator->resultInfo.totalRows += rows;

1691
  return (rows == 0) ? NULL : pInfo->pRes;
1692 1693
}

L
Liu Jicong 已提交
1694 1695
static void doHandleRemainBlockForNewGroupImpl(SOperatorInfo* pOperator, SFillOperatorInfo* pInfo,
                                               SResultInfo* pResultInfo, SExecTaskInfo* pTaskInfo) {
1696
  pInfo->totalInputRows = pInfo->existNewGroupBlock->info.rows;
1697 1698 1699 1700 1701
  SSDataBlock* pResBlock = pInfo->pFinalRes;

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

5
54liuyao 已提交
1703
  int64_t ekey = pInfo->existNewGroupBlock->info.window.ekey;
1704 1705
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

1706
  blockDataCleanup(pInfo->pRes);
1707 1708 1709 1710
  doApplyScalarCalculation(pOperator, pInfo->existNewGroupBlock, order, scanFlag);

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

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

1715
  pInfo->curGroupId = pInfo->existNewGroupBlock->info.groupId;
1716 1717 1718
  pInfo->existNewGroupBlock = NULL;
}

L
Liu Jicong 已提交
1719 1720
static void doHandleRemainBlockFromNewGroup(SOperatorInfo* pOperator, SFillOperatorInfo* pInfo,
                                            SResultInfo* pResultInfo, SExecTaskInfo* pTaskInfo) {
1721
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
H
Haojun Liao 已提交
1722 1723
    int32_t numOfResultRows = pResultInfo->capacity - pInfo->pFinalRes->info.rows;
    taosFillResultDataBlock(pInfo->pFillInfo, pInfo->pFinalRes, numOfResultRows);
1724 1725
    pInfo->pRes->info.groupId = pInfo->curGroupId;
    return;
1726 1727 1728 1729
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
1730 1731 1732 1733 1734 1735
    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 已提交
1736
  SExprSupp*         pSup = &pOperator->exprSupp;
1737
  setInputDataBlock(pSup, pBlock, order, scanFlag, false);
1738 1739
  projectApplyFunctions(pSup->pExprInfo, pInfo->pRes, pBlock, pSup->pCtx, pSup->numOfExprs, NULL);

1740 1741 1742 1743
  // 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);
1744

1745 1746
  projectApplyFunctions(pNoFillSupp->pExprInfo, pInfo->pRes, pBlock, pNoFillSupp->pCtx, pNoFillSupp->numOfExprs, NULL);
  pInfo->pRes->info.groupId = pBlock->info.groupId;
1747 1748
}

S
slzhou 已提交
1749
static SSDataBlock* doFillImpl(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
1750 1751
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
1752

H
Haojun Liao 已提交
1753
  SResultInfo* pResultInfo = &pOperator->resultInfo;
H
Haojun Liao 已提交
1754
  SSDataBlock* pResBlock = pInfo->pFinalRes;
1755 1756

  blockDataCleanup(pResBlock);
1757

H
Haojun Liao 已提交
1758 1759
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;
1760
  getTableScanInfo(pOperator, &order, &scanFlag);
1761

1762
  doHandleRemainBlockFromNewGroup(pOperator, pInfo, pResultInfo, pTaskInfo);
1763
  if (pResBlock->info.rows > 0) {
1764
    pResBlock->info.groupId = pInfo->curGroupId;
1765
    return pResBlock;
H
Haojun Liao 已提交
1766
  }
1767

H
Haojun Liao 已提交
1768
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
1769
  while (1) {
1770
    SSDataBlock* pBlock = pDownstream->fpSet.getNextFn(pDownstream);
1771 1772
    if (pBlock == NULL) {
      if (pInfo->totalInputRows == 0) {
H
Haojun Liao 已提交
1773
        setOperatorCompleted(pOperator);
1774 1775
        return NULL;
      }
1776

1777
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pInfo->win.ekey);
1778
    } else {
1779
      blockDataUpdateTsWindow(pBlock, pInfo->primarySrcSlotId);
1780 1781

      blockDataCleanup(pInfo->pRes);
1782 1783
      blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);
      blockDataEnsureCapacity(pInfo->pFinalRes, pBlock->info.rows);
1784
      doApplyScalarCalculation(pOperator, pBlock, order, scanFlag);
1785

H
Haojun Liao 已提交
1786 1787 1788
      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;
1789

H
Haojun Liao 已提交
1790 1791 1792 1793 1794
        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 已提交
1795
        taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->pRes);
L
Liu Jicong 已提交
1796
      } else if (pInfo->curGroupId != pBlock->info.groupId) {  // the new group data block
1797 1798 1799 1800 1801
        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);
1802 1803 1804
      }
    }

1805 1806
    int32_t numOfResultRows = pOperator->resultInfo.capacity - pResBlock->info.rows;
    taosFillResultDataBlock(pInfo->pFillInfo, pResBlock, numOfResultRows);
1807 1808

    // current group has no more result to return
1809
    if (pResBlock->info.rows > 0) {
1810 1811
      // 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
1812
      if (pResBlock->info.rows > pResultInfo->threshold || pBlock == NULL || pInfo->existNewGroupBlock != NULL) {
1813
        pResBlock->info.groupId = pInfo->curGroupId;
1814
        return pResBlock;
1815 1816
      }

1817
      doHandleRemainBlockFromNewGroup(pOperator, pInfo, pResultInfo, pTaskInfo);
1818
      if (pResBlock->info.rows >= pOperator->resultInfo.threshold || pBlock == NULL) {
1819
        pResBlock->info.groupId = pInfo->curGroupId;
1820
        return pResBlock;
1821 1822 1823
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
1824 1825 1826 1827

      blockDataCleanup(pResBlock);

      doHandleRemainBlockForNewGroupImpl(pOperator, pInfo, pResultInfo, pTaskInfo);
1828
      if (pResBlock->info.rows > pResultInfo->threshold) {
1829
        pResBlock->info.groupId = pInfo->curGroupId;
1830
        return pResBlock;
1831 1832 1833 1834 1835 1836 1837
      }
    } else {
      return NULL;
    }
  }
}

S
slzhou 已提交
1838 1839 1840 1841 1842 1843 1844 1845
static SSDataBlock* doFill(SOperatorInfo* pOperator) {
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;

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

S
slzhou 已提交
1846
  SSDataBlock* fillResult = NULL;
S
slzhou 已提交
1847
  while (true) {
S
slzhou 已提交
1848
    fillResult = doFillImpl(pOperator);
S
slzhou 已提交
1849
    if (fillResult == NULL) {
H
Haojun Liao 已提交
1850
      setOperatorCompleted(pOperator);
S
slzhou 已提交
1851 1852 1853
      break;
    }

1854
    doFilter(fillResult, pOperator->exprSupp.pFilterInfo, &pInfo->matchInfo);
S
slzhou 已提交
1855 1856 1857 1858 1859
    if (fillResult->info.rows > 0) {
      break;
    }
  }

S
slzhou 已提交
1860
  if (fillResult != NULL) {
1861
    pOperator->resultInfo.totalRows += fillResult->info.rows;
S
slzhou 已提交
1862
  }
S
slzhou 已提交
1863

S
slzhou 已提交
1864
  return fillResult;
S
slzhou 已提交
1865 1866
}

1867
void destroyExprInfo(SExprInfo* pExpr, int32_t numOfExprs) {
C
Cary Xu 已提交
1868 1869 1870 1871 1872
  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);
5
54liuyao 已提交
1873 1874
      } else if (pExprInfo->base.pParam[j].type == FUNC_PARAM_TYPE_VALUE) {
        taosVariantDestroy(&pExprInfo->base.pParam[j].param);
H
Haojun Liao 已提交
1875
      }
1876
    }
C
Cary Xu 已提交
1877 1878 1879

    taosMemoryFree(pExprInfo->base.pParam);
    taosMemoryFree(pExprInfo->pExpr);
H
Haojun Liao 已提交
1880 1881 1882
  }
}

5
54liuyao 已提交
1883
void destroyOperatorInfo(SOperatorInfo* pOperator) {
1884 1885 1886 1887
  if (pOperator == NULL) {
    return;
  }

1888
  if (pOperator->fpSet.closeFn != NULL) {
1889
    pOperator->fpSet.closeFn(pOperator->info);
1890 1891
  }

H
Haojun Liao 已提交
1892
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
1893
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
1894
      destroyOperatorInfo(pOperator->pDownstream[i]);
1895 1896
    }

wafwerar's avatar
wafwerar 已提交
1897
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
1898
    pOperator->numOfDownstream = 0;
1899 1900
  }

1901
  cleanupExprSupp(&pOperator->exprSupp);
wafwerar's avatar
wafwerar 已提交
1902
  taosMemoryFreeClear(pOperator);
1903 1904
}

1905 1906 1907 1908 1909 1910
int32_t getBufferPgSize(int32_t rowSize, uint32_t* defaultPgsz, uint32_t* defaultBufsz) {
  *defaultPgsz = 4096;
  while (*defaultPgsz < rowSize * 4) {
    *defaultPgsz <<= 1u;
  }

1911
  // The default buffer for each operator in query is 10MB.
1912
  // at least four pages need to be in buffer
1913 1914
  // TODO: make this variable to be configurable.
  *defaultBufsz = 4096 * 2560;
1915 1916 1917 1918 1919 1920 1921
  if ((*defaultBufsz) <= (*defaultPgsz)) {
    (*defaultBufsz) = (*defaultPgsz) * 4;
  }

  return 0;
}

dengyihao's avatar
dengyihao 已提交
1922 1923
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                         const char* pKey) {
L
Liu Jicong 已提交
1924
  int32_t    code = 0;
1925 1926
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

1927
  pAggSup->currentPageId = -1;
dengyihao's avatar
dengyihao 已提交
1928 1929
  pAggSup->resultRowSize = getResultRowSize(pCtx, numOfOutput);
  pAggSup->keyBuf = taosMemoryCalloc(1, keyBufSize + POINTER_BYTES + sizeof(int64_t));
1930
  pAggSup->pResultRowHashTable = tSimpleHashInit(10, hashFn);
1931

H
Haojun Liao 已提交
1932
  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowHashTable == NULL) {
1933 1934 1935
    return TSDB_CODE_OUT_OF_MEMORY;
  }

dengyihao's avatar
dengyihao 已提交
1936
  uint32_t defaultPgsz = 0;
1937 1938
  uint32_t defaultBufsz = 0;
  getBufferPgSize(pAggSup->resultRowSize, &defaultPgsz, &defaultBufsz);
H
Haojun Liao 已提交
1939

wafwerar's avatar
wafwerar 已提交
1940
  if (!osTempSpaceAvailable()) {
H
Haojun Liao 已提交
1941 1942 1943
    code = TSDB_CODE_NO_AVAIL_DISK;
    qError("Init stream agg supporter failed since %s, %s", terrstr(code), pKey);
    return code;
wafwerar's avatar
wafwerar 已提交
1944
  }
1945

H
Haojun Liao 已提交
1946
  code = createDiskbasedBuf(&pAggSup->pResultBuf, defaultPgsz, defaultBufsz, pKey, tsTempDir);
H
Haojun Liao 已提交
1947
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1948
    qError("Create agg result buf failed since %s, %s", tstrerror(code), pKey);
H
Haojun Liao 已提交
1949 1950 1951
    return code;
  }

H
Haojun Liao 已提交
1952
  return code;
1953 1954
}

1955
void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
1956
  taosMemoryFreeClear(pAggSup->keyBuf);
1957
  tSimpleHashCleanup(pAggSup->pResultRowHashTable);
H
Haojun Liao 已提交
1958
  destroyDiskbasedBuf(pAggSup->pResultBuf);
1959 1960
}

L
Liu Jicong 已提交
1961 1962
int32_t initAggInfo(SExprSupp* pSup, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols, size_t keyBufSize,
                    const char* pkey) {
1963 1964 1965 1966 1967
  int32_t code = initExprSupp(pSup, pExprInfo, numOfCols);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

1968 1969 1970 1971 1972
  code = doInitAggInfoSup(pAggSup, pSup->pCtx, numOfCols, keyBufSize, pkey);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

L
Liu Jicong 已提交
1973
  for (int32_t i = 0; i < numOfCols; ++i) {
1974
    pSup->pCtx[i].saveHandle.pBuf = pAggSup->pResultBuf;
1975 1976
  }

1977
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1978 1979
}

L
Liu Jicong 已提交
1980
void initResultSizeInfo(SResultInfo* pResultInfo, int32_t numOfRows) {
wmmhello's avatar
wmmhello 已提交
1981
  ASSERT(numOfRows != 0);
1982 1983
  pResultInfo->capacity = numOfRows;
  pResultInfo->threshold = numOfRows * 0.75;
1984

1985 1986
  if (pResultInfo->threshold == 0) {
    pResultInfo->threshold = numOfRows;
1987 1988 1989
  }
}

1990 1991 1992 1993 1994
void initBasicInfo(SOptrBasicInfo* pInfo, SSDataBlock* pBlock) {
  pInfo->pRes = pBlock;
  initResultRowInfo(&pInfo->resultRowInfo);
}

5
54liuyao 已提交
1995
void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
  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);
2006
    taosMemoryFreeClear(pCtx[i].subsidiaries.buf);
2007 2008 2009 2010 2011 2012 2013 2014
    taosMemoryFree(pCtx[i].input.pData);
    taosMemoryFree(pCtx[i].input.pColumnDataAgg);
  }

  taosMemoryFreeClear(pCtx);
  return NULL;
}

2015
int32_t initExprSupp(SExprSupp* pSup, SExprInfo* pExprInfo, int32_t numOfExpr) {
2016 2017 2018 2019
  pSup->pExprInfo = pExprInfo;
  pSup->numOfExprs = numOfExpr;
  if (pSup->pExprInfo != NULL) {
    pSup->pCtx = createSqlFunctionCtx(pExprInfo, numOfExpr, &pSup->rowEntryInfoOffset);
2020 2021 2022
    if (pSup->pCtx == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
2023
  }
2024 2025

  return TSDB_CODE_SUCCESS;
2026 2027
}

2028 2029 2030 2031
void cleanupExprSupp(SExprSupp* pSupp) {
  destroySqlFunctionCtx(pSupp->pCtx, pSupp->numOfExprs);
  if (pSupp->pExprInfo != NULL) {
    destroyExprInfo(pSupp->pExprInfo, pSupp->numOfExprs);
C
Cary Xu 已提交
2032
    taosMemoryFreeClear(pSupp->pExprInfo);
2033
  }
H
Haojun Liao 已提交
2034 2035 2036 2037 2038 2039

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

2040 2041 2042
  taosMemoryFree(pSupp->rowEntryInfoOffset);
}

2043 2044
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SAggPhysiNode* pAggNode,
                                           SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
2045
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
2046
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
2047 2048 2049
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
2050

H
Haojun Liao 已提交
2051
  SSDataBlock* pResBlock = createDataBlockFromDescNode(pAggNode->node.pOutputDataBlockDesc);
H
Haojun Liao 已提交
2052 2053 2054
  initBasicInfo(&pInfo->binfo, pResBlock);

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

2057 2058 2059
  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 已提交
2060
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2061 2062
    goto _error;
  }
H
Haojun Liao 已提交
2063

H
Haojun Liao 已提交
2064 2065 2066 2067 2068 2069
  int32_t    numOfScalarExpr = 0;
  SExprInfo* pScalarExprInfo = NULL;
  if (pAggNode->pExprs != NULL) {
    pScalarExprInfo = createExprInfo(pAggNode->pExprs, NULL, &numOfScalarExpr);
  }

2070 2071 2072 2073
  code = initExprSupp(&pInfo->scalarExprSup, pScalarExprInfo, numOfScalarExpr);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2074

H
Haojun Liao 已提交
2075 2076 2077 2078 2079
  code = filterInitFromNode((SNode*)pAggNode->node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

H
Haojun Liao 已提交
2080
  pInfo->binfo.mergeResultBlock = pAggNode->mergeDataBlock;
2081
  pInfo->groupId = UINT64_MAX;
H
Haojun Liao 已提交
2082

2083 2084 2085
  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 已提交
2086

2087 2088
  if (downstream->operatorType == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
    STableScanInfo* pTableScanInfo = downstream->info;
H
Haojun Liao 已提交
2089 2090
    pTableScanInfo->base.pdInfo.pExprSup = &pOperator->exprSupp;
    pTableScanInfo->base.pdInfo.pAggSup = &pInfo->aggSup;
2091 2092
  }

H
Haojun Liao 已提交
2093 2094 2095 2096
  code = appendDownstream(pOperator, &downstream, 1);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2097 2098

  return pOperator;
H
Haojun Liao 已提交
2099

2100
_error:
H
Haojun Liao 已提交
2101 2102 2103 2104
  if (pInfo != NULL) {
    destroyAggOperatorInfo(pInfo);
  }

2105 2106 2107
  if (pOperator != NULL) {
    cleanupExprSupp(&pOperator->exprSupp);
  }
H
Haojun Liao 已提交
2108

2109
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
2110
  pTaskInfo->code = code;
H
Haojun Liao 已提交
2111
  return NULL;
2112 2113
}

2114
void cleanupBasicInfo(SOptrBasicInfo* pInfo) {
2115
  assert(pInfo != NULL);
H
Haojun Liao 已提交
2116
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
2117 2118
}

H
Haojun Liao 已提交
2119 2120 2121 2122 2123 2124 2125
static void freeItem(void* pItem) {
  void** p = pItem;
  if (*p != NULL) {
    taosMemoryFreeClear(*p);
  }
}

2126
void destroyAggOperatorInfo(void* param) {
L
Liu Jicong 已提交
2127
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
L
Liu Jicong 已提交
2128 2129
  cleanupBasicInfo(&pInfo->binfo);

H
Haojun Liao 已提交
2130
  cleanupAggSup(&pInfo->aggSup);
S
shenglian zhou 已提交
2131
  cleanupExprSupp(&pInfo->scalarExprSup);
H
Haojun Liao 已提交
2132
  cleanupGroupResInfo(&pInfo->groupResInfo);
D
dapan1121 已提交
2133
  taosMemoryFreeClear(param);
2134
}
2135

2136
void destroyFillOperatorInfo(void* param) {
L
Liu Jicong 已提交
2137
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
2138
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
2139
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
H
Haojun Liao 已提交
2140 2141
  pInfo->pFinalRes = blockDataDestroy(pInfo->pFinalRes);

2142
  cleanupExprSupp(&pInfo->noFillExprSupp);
H
Haojun Liao 已提交
2143

wafwerar's avatar
wafwerar 已提交
2144
  taosMemoryFreeClear(pInfo->p);
H
Haojun Liao 已提交
2145
  taosArrayDestroy(pInfo->matchInfo.pList);
D
dapan1121 已提交
2146
  taosMemoryFreeClear(param);
2147 2148
}

H
Haojun Liao 已提交
2149 2150 2151 2152
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 已提交
2153

H
Haojun Liao 已提交
2154 2155 2156
  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 已提交
2157

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

H
Haojun Liao 已提交
2161 2162 2163 2164 2165 2166 2167
  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 已提交
2168
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
2169

H
Haojun Liao 已提交
2170
  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
H
Haojun Liao 已提交
2171 2172
    taosMemoryFree(pInfo->pFillInfo);
    taosMemoryFree(pInfo->p);
H
Haojun Liao 已提交
2173 2174 2175 2176 2177 2178
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

2179
static bool isWstartColumnExist(SFillOperatorInfo* pInfo) {
2180
  if (pInfo->noFillExprSupp.numOfExprs == 0) {
2181 2182
    return false;
  }
2183 2184 2185

  for (int32_t i = 0; i < pInfo->noFillExprSupp.numOfExprs; ++i) {
    SExprInfo* exprInfo = pInfo->noFillExprSupp.pExprInfo + i;
2186
    if (exprInfo->pExpr->nodeType == QUERY_NODE_COLUMN && exprInfo->base.numOfParams == 1 &&
2187 2188 2189 2190 2191 2192 2193
        exprInfo->base.pParam[0].pCol->colType == COLUMN_TYPE_WINDOW_START) {
      return true;
    }
  }
  return false;
}

2194 2195
static int32_t createPrimaryTsExprIfNeeded(SFillOperatorInfo* pInfo, SFillPhysiNode* pPhyFillNode, SExprSupp* pExprSupp,
                                           const char* idStr) {
2196
  bool wstartExist = isWstartColumnExist(pInfo);
2197

2198 2199
  if (wstartExist == false) {
    if (pPhyFillNode->pWStartTs->type != QUERY_NODE_TARGET) {
2200
      qError("pWStartTs of fill physical node is not a target node, %s", idStr);
2201 2202 2203
      return TSDB_CODE_QRY_SYS_ERROR;
    }

2204 2205
    SExprInfo* pExpr = taosMemoryRealloc(pExprSupp->pExprInfo, (pExprSupp->numOfExprs + 1) * sizeof(SExprInfo));
    if (pExpr == NULL) {
2206 2207 2208
      return TSDB_CODE_OUT_OF_MEMORY;
    }

2209 2210 2211
    createExprFromTargetNode(&pExpr[pExprSupp->numOfExprs], (STargetNode*)pPhyFillNode->pWStartTs);
    pExprSupp->numOfExprs += 1;
    pExprSupp->pExprInfo = pExpr;
2212
  }
2213

2214 2215 2216
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
2217 2218
SOperatorInfo* createFillOperatorInfo(SOperatorInfo* downstream, SFillPhysiNode* pPhyFillNode,
                                      SExecTaskInfo* pTaskInfo) {
2219 2220 2221 2222 2223 2224
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

H
Haojun Liao 已提交
2225
  pInfo->pRes = createDataBlockFromDescNode(pPhyFillNode->node.pOutputDataBlockDesc);
H
Haojun Liao 已提交
2226 2227 2228
  SExprInfo* pExprInfo = createExprInfo(pPhyFillNode->pFillExprs, NULL, &pInfo->numOfExpr);
  pOperator->exprSupp.pExprInfo = pExprInfo;

2229 2230 2231 2232 2233 2234 2235 2236
  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);
2237 2238 2239
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
2240

L
Liu Jicong 已提交
2241
  SInterval* pInterval =
2242
      QUERY_NODE_PHYSICAL_PLAN_MERGE_ALIGNED_INTERVAL == downstream->operatorType
2243 2244
          ? &((SMergeAlignedIntervalAggOperatorInfo*)downstream->info)->intervalAggOperatorInfo->interval
          : &((SIntervalAggOperatorInfo*)downstream->info)->interval;
2245

2246
  int32_t order = (pPhyFillNode->inputTsOrder == ORDER_ASC) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
2247
  int32_t type = convertFillType(pPhyFillNode->mode);
2248

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

2251
  initResultSizeInfo(&pOperator->resultInfo, 4096);
H
Haojun Liao 已提交
2252 2253 2254 2255 2256
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
  code = initExprSupp(&pOperator->exprSupp, pExprInfo, pInfo->numOfExpr);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
2257

H
Haojun Liao 已提交
2258 2259
  pInfo->primaryTsCol = ((STargetNode*)pPhyFillNode->pWStartTs)->slotId;
  pInfo->primarySrcSlotId = ((SColumnNode*)((STargetNode*)pPhyFillNode->pWStartTs)->pExpr)->slotId;
2260

2261
  int32_t numOfOutputCols = 0;
H
Haojun Liao 已提交
2262 2263
  code = extractColMatchInfo(pPhyFillNode->pFillExprs, pPhyFillNode->node.pOutputDataBlockDesc, &numOfOutputCols,
                             COL_MATCH_FROM_SLOT_ID, &pInfo->matchInfo);
2264

2265
  code = initFillInfo(pInfo, pExprInfo, pInfo->numOfExpr, pNoFillSupp->pExprInfo, pNoFillSupp->numOfExprs,
2266 2267
                      (SNodeListNode*)pPhyFillNode->pValues, pPhyFillNode->timeRange, pResultInfo->capacity,
                      pTaskInfo->id.str, pInterval, type, order);
2268 2269 2270
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2271

H
Haojun Liao 已提交
2272
  pInfo->pFinalRes = createOneDataBlock(pInfo->pRes, false);
H
Haojun Liao 已提交
2273 2274
  blockDataEnsureCapacity(pInfo->pFinalRes, pOperator->resultInfo.capacity);

H
Haojun Liao 已提交
2275 2276 2277 2278 2279
  code = filterInitFromNode((SNode*)pPhyFillNode->node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

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

2284
  code = appendDownstream(pOperator, &downstream, 1);
2285
  return pOperator;
H
Haojun Liao 已提交
2286

2287
_error:
H
Haojun Liao 已提交
2288 2289 2290 2291
  if (pInfo != NULL) {
    destroyFillOperatorInfo(pInfo);
  }

2292
  pTaskInfo->code = code;
wafwerar's avatar
wafwerar 已提交
2293
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
2294
  return NULL;
2295 2296
}

D
dapan1121 已提交
2297
static SExecTaskInfo* createExecTaskInfo(uint64_t queryId, uint64_t taskId, EOPTR_EXEC_MODEL model, char* dbFName) {
wafwerar's avatar
wafwerar 已提交
2298
  SExecTaskInfo* pTaskInfo = taosMemoryCalloc(1, sizeof(SExecTaskInfo));
H
Haojun Liao 已提交
2299 2300 2301 2302 2303
  if (pTaskInfo == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

2304
  setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
2305

2306
  pTaskInfo->schemaInfo.dbname = strdup(dbFName);
2307
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
2308
  pTaskInfo->id.queryId = queryId;
dengyihao's avatar
dengyihao 已提交
2309
  pTaskInfo->execModel = model;
H
Haojun Liao 已提交
2310
  pTaskInfo->pTableInfoList = tableListCreate();
D
dapan1121 已提交
2311
  pTaskInfo->stopInfo.pStopInfo = taosArrayInit(4, sizeof(SExchangeOpStopInfo));
H
Haojun Liao 已提交
2312
  pTaskInfo->pResultBlockList = taosArrayInit(128, POINTER_BYTES);
H
Haojun Liao 已提交
2313

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

2318 2319
  return pTaskInfo;
}
H
Haojun Liao 已提交
2320

H
Haojun Liao 已提交
2321 2322
SSchemaWrapper* extractQueriedColumnSchema(SScanPhysiNode* pScanNode);

2323
int32_t extractTableSchemaInfo(SReadHandle* pHandle, SScanPhysiNode* pScanNode, SExecTaskInfo* pTaskInfo) {
2324 2325
  SMetaReader mr = {0};
  metaReaderInit(&mr, pHandle->meta, 0);
H
Haojun Liao 已提交
2326
  int32_t code = metaGetTableEntryByUidCache(&mr, pScanNode->uid);
2327
  if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
2328 2329
    qError("failed to get the table meta, uid:0x%" PRIx64 ", suid:0x%" PRIx64 ", %s", pScanNode->uid, pScanNode->suid,
           GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
2330

D
dapan1121 已提交
2331
    metaReaderClear(&mr);
2332
    return terrno;
D
dapan1121 已提交
2333
  }
2334

2335 2336
  SSchemaInfo* pSchemaInfo = &pTaskInfo->schemaInfo;
  pSchemaInfo->tablename = strdup(mr.me.name);
2337 2338

  if (mr.me.type == TSDB_SUPER_TABLE) {
2339 2340
    pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.stbEntry.schemaRow);
    pSchemaInfo->tversion = mr.me.stbEntry.schemaTag.version;
2341
  } else if (mr.me.type == TSDB_CHILD_TABLE) {
2342 2343
    tDecoderClear(&mr.coder);

2344
    tb_uid_t suid = mr.me.ctbEntry.suid;
H
Haojun Liao 已提交
2345
    metaGetTableEntryByUidCache(&mr, suid);
2346 2347
    pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.stbEntry.schemaRow);
    pSchemaInfo->tversion = mr.me.stbEntry.schemaTag.version;
2348
  } else {
2349
    pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.ntbEntry.schemaRow);
2350
  }
2351 2352

  metaReaderClear(&mr);
2353

H
Haojun Liao 已提交
2354 2355 2356 2357 2358
  pSchemaInfo->qsw = extractQueriedColumnSchema(pScanNode);
  return TSDB_CODE_SUCCESS;
}

SSchemaWrapper* extractQueriedColumnSchema(SScanPhysiNode* pScanNode) {
2359 2360 2361
  int32_t numOfCols = LIST_LENGTH(pScanNode->pScanCols);
  int32_t numOfTags = LIST_LENGTH(pScanNode->pScanPseudoCols);

2362
  SSchemaWrapper* pqSw = taosMemoryCalloc(1, sizeof(SSchemaWrapper));
2363
  pqSw->pSchema = taosMemoryCalloc(numOfCols + numOfTags, sizeof(SSchema));
2364

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

H
Haojun Liao 已提交
2369 2370 2371
    SSchema* pSchema = &pqSw->pSchema[pqSw->nCols++];
    pSchema->colId = pColNode->colId;
    pSchema->type = pColNode->node.resType.type;
H
Haojun Liao 已提交
2372 2373
    pSchema->bytes = pColNode->node.resType.bytes;
    tstrncpy(pSchema->name, pColNode->colName, tListLen(pSchema->name));
2374 2375
  }

2376
  // this the tags and pseudo function columns, we only keep the tag columns
2377
  for (int32_t i = 0; i < numOfTags; ++i) {
2378 2379 2380 2381 2382 2383 2384 2385 2386
    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 已提交
2387
      pSchema->bytes = pColNode->node.resType.bytes;
H
Haojun Liao 已提交
2388
      tstrncpy(pSchema->name, pColNode->colName, tListLen(pSchema->name));
2389 2390 2391
    }
  }

H
Haojun Liao 已提交
2392
  return pqSw;
2393 2394
}

2395 2396
static void cleanupTableSchemaInfo(SSchemaInfo* pSchemaInfo) {
  taosMemoryFreeClear(pSchemaInfo->dbname);
2397
  taosMemoryFreeClear(pSchemaInfo->tablename);
2398 2399
  tDeleteSSchemaWrapper(pSchemaInfo->sw);
  tDeleteSSchemaWrapper(pSchemaInfo->qsw);
2400 2401
}

2402
static void cleanupStreamInfo(SStreamTaskInfo* pStreamInfo) { tDeleteSSchemaWrapper(pStreamInfo->schema); }
2403

2404
bool groupbyTbname(SNodeList* pGroupList) {
2405
  bool bytbname = false;
2406
  if (LIST_LENGTH(pGroupList) == 1) {
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
    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;
}

2417 2418
SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle, SNode* pTagCond,
                                  SNode* pTagIndexCond, const char* pUser) {
2419
  int32_t         type = nodeType(pPhyNode);
2420
  STableListInfo* pTableListInfo = pTaskInfo->pTableInfoList;
2421
  const char*     idstr = GET_TASKID(pTaskInfo);
2422

X
Xiaoyu Wang 已提交
2423
  if (pPhyNode->pChildren == NULL || LIST_LENGTH(pPhyNode->pChildren) == 0) {
2424
    SOperatorInfo* pOperator = NULL;
H
Haojun Liao 已提交
2425
    if (QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN == type) {
dengyihao's avatar
dengyihao 已提交
2426
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
2427

2428 2429 2430 2431 2432 2433
      // 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 已提交
2434 2435
      int32_t code =
          createScanTableListInfo(&pTableScanNode->scan, pTableScanNode->pGroupTags, pTableScanNode->groupSort, pHandle,
H
Haojun Liao 已提交
2436
                                  pTableListInfo, pTagCond, pTagIndexCond, pTaskInfo);
2437
      if (code) {
wmmhello's avatar
wmmhello 已提交
2438
        pTaskInfo->code = code;
2439
        qError("failed to createScanTableListInfo, code:%s, %s", tstrerror(code), idstr);
D
dapan1121 已提交
2440 2441
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
2442

2443
      code = extractTableSchemaInfo(pHandle, &pTableScanNode->scan, pTaskInfo);
S
slzhou 已提交
2444
      if (code) {
2445
        pTaskInfo->code = terrno;
wmmhello's avatar
wmmhello 已提交
2446 2447 2448
        return NULL;
      }

2449
      pOperator = createTableScanOperatorInfo(pTableScanNode, pHandle, pTaskInfo);
D
dapan1121 已提交
2450 2451 2452 2453 2454
      if (NULL == pOperator) {
        pTaskInfo->code = terrno;
        return NULL;
      }

2455
      STableScanInfo* pScanInfo = pOperator->info;
H
Haojun Liao 已提交
2456
      pTaskInfo->cost.pRecoder = &pScanInfo->base.readRecorder;
S
slzhou 已提交
2457 2458
    } else if (QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN == type) {
      STableMergeScanPhysiNode* pTableScanNode = (STableMergeScanPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
2459 2460 2461

      int32_t code = createScanTableListInfo(&pTableScanNode->scan, pTableScanNode->pGroupTags, true, pHandle,
                                             pTableListInfo, pTagCond, pTagIndexCond, pTaskInfo);
L
Liu Jicong 已提交
2462
      if (code) {
wmmhello's avatar
wmmhello 已提交
2463
        pTaskInfo->code = code;
H
Haojun Liao 已提交
2464
        qError("failed to createScanTableListInfo, code: %s", tstrerror(code));
wmmhello's avatar
wmmhello 已提交
2465 2466
        return NULL;
      }
2467

2468
      code = extractTableSchemaInfo(pHandle, &pTableScanNode->scan, pTaskInfo);
wmmhello's avatar
wmmhello 已提交
2469 2470 2471 2472
      if (code) {
        pTaskInfo->code = terrno;
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
2473

H
Haojun Liao 已提交
2474
      pOperator = createTableMergeScanOperatorInfo(pTableScanNode, pHandle, pTaskInfo);
D
dapan1121 已提交
2475 2476 2477 2478
      if (NULL == pOperator) {
        pTaskInfo->code = terrno;
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
2479

2480
      STableScanInfo* pScanInfo = pOperator->info;
H
Haojun Liao 已提交
2481
      pTaskInfo->cost.pRecoder = &pScanInfo->base.readRecorder;
H
Haojun Liao 已提交
2482
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == type) {
2483 2484
      pOperator = createExchangeOperatorInfo(pHandle ? pHandle->pMsgCb->clientRpc : NULL, (SExchangePhysiNode*)pPhyNode,
                                             pTaskInfo);
H
Haojun Liao 已提交
2485
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == type) {
5
54liuyao 已提交
2486
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
5
54liuyao 已提交
2487
      if (pHandle->vnode) {
L
Liu Jicong 已提交
2488 2489
        int32_t code =
            createScanTableListInfo(&pTableScanNode->scan, pTableScanNode->pGroupTags, pTableScanNode->groupSort,
H
Haojun Liao 已提交
2490
                                    pHandle, pTableListInfo, pTagCond, pTagIndexCond, pTaskInfo);
L
Liu Jicong 已提交
2491
        if (code) {
wmmhello's avatar
wmmhello 已提交
2492
          pTaskInfo->code = code;
H
Haojun Liao 已提交
2493
          qError("failed to createScanTableListInfo, code: %s", tstrerror(code));
wmmhello's avatar
wmmhello 已提交
2494 2495
          return NULL;
        }
L
Liu Jicong 已提交
2496 2497

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

L
Liu Jicong 已提交
2501
        for (int32_t i = 0; i < sz; i++) {
H
Haojun Liao 已提交
2502
          STableKeyInfo* pKeyInfo = tableListGetInfo(pTableListInfo, i);
2503
          qDebug("add table uid:%" PRIu64 ", gid:%" PRIu64, pKeyInfo->uid, pKeyInfo->groupId);
L
Liu Jicong 已提交
2504 2505
        }
#endif
2506
      }
2507

H
Haojun Liao 已提交
2508
      pTaskInfo->schemaInfo.qsw = extractQueriedColumnSchema(&pTableScanNode->scan);
2509
      pOperator = createStreamScanOperatorInfo(pHandle, pTableScanNode, pTagCond, pTaskInfo);
H
Haojun Liao 已提交
2510
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == type) {
L
Liu Jicong 已提交
2511
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
2512
      pOperator = createSysTableScanOperatorInfo(pHandle, pSysScanPhyNode, pUser, pTaskInfo);
2513
    } else if (QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN == type) {
X
Xiaoyu Wang 已提交
2514
      STagScanPhysiNode* pScanPhyNode = (STagScanPhysiNode*)pPhyNode;
2515 2516

      int32_t code = createScanTableListInfo(pScanPhyNode, NULL, false, pHandle, pTableListInfo, pTagCond,
H
Haojun Liao 已提交
2517
                                             pTagIndexCond, pTaskInfo);
2518
      if (code != TSDB_CODE_SUCCESS) {
2519
        pTaskInfo->code = code;
H
Haojun Liao 已提交
2520
        qError("failed to getTableList, code: %s", tstrerror(code));
2521 2522 2523
        return NULL;
      }

H
Haojun Liao 已提交
2524
      pOperator = createTagScanOperatorInfo(pHandle, pScanPhyNode, pTaskInfo);
2525
    } else if (QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN == type) {
2526
      SBlockDistScanPhysiNode* pBlockNode = (SBlockDistScanPhysiNode*)pPhyNode;
2527 2528

      if (pBlockNode->tableType == TSDB_SUPER_TABLE) {
H
Haojun Liao 已提交
2529 2530
        SArray* pList = taosArrayInit(4, sizeof(STableKeyInfo));
        int32_t code = vnodeGetAllTableList(pHandle->vnode, pBlockNode->uid, pList);
2531 2532 2533 2534
        if (code != TSDB_CODE_SUCCESS) {
          pTaskInfo->code = terrno;
          return NULL;
        }
H
Haojun Liao 已提交
2535

2536
        for (int32_t i = 0; i < tableListGetSize(pTableListInfo); ++i) {
H
Haojun Liao 已提交
2537
          STableKeyInfo* p = taosArrayGet(pList, i);
H
Haojun Liao 已提交
2538
          tableListAddTableInfo(pTableListInfo, p->uid, 0);
H
Haojun Liao 已提交
2539 2540
        }
        taosArrayDestroy(pList);
2541
      } else {  // Create group with only one table
H
Haojun Liao 已提交
2542
        tableListAddTableInfo(pTableListInfo, pBlockNode->uid, 0);
2543 2544
      }

2545
      pOperator = createDataBlockInfoScanOperator(pHandle, pBlockNode, pTaskInfo);
H
Haojun Liao 已提交
2546 2547 2548
    } else if (QUERY_NODE_PHYSICAL_PLAN_LAST_ROW_SCAN == type) {
      SLastRowScanPhysiNode* pScanNode = (SLastRowScanPhysiNode*)pPhyNode;

L
Liu Jicong 已提交
2549
      int32_t code = createScanTableListInfo(&pScanNode->scan, pScanNode->pGroupTags, true, pHandle, pTableListInfo,
H
Haojun Liao 已提交
2550
                                             pTagCond, pTagIndexCond, pTaskInfo);
2551 2552 2553 2554
      if (code != TSDB_CODE_SUCCESS) {
        pTaskInfo->code = code;
        return NULL;
      }
2555

2556
      code = extractTableSchemaInfo(pHandle, &pScanNode->scan, pTaskInfo);
2557 2558 2559
      if (code != TSDB_CODE_SUCCESS) {
        pTaskInfo->code = code;
        return NULL;
H
Haojun Liao 已提交
2560 2561
      }

2562
      pOperator = createCacherowsScanOperator(pScanNode, pHandle, pTaskInfo);
2563
    } else if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
2564
      pOperator = createProjectOperatorInfo(NULL, (SProjectPhysiNode*)pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
2565 2566
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
2567
    }
2568 2569 2570 2571 2572

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

2573
    return pOperator;
H
Haojun Liao 已提交
2574 2575
  }

2576
  size_t          size = LIST_LENGTH(pPhyNode->pChildren);
2577
  SOperatorInfo** ops = taosMemoryCalloc(size, POINTER_BYTES);
2578 2579 2580 2581
  if (ops == NULL) {
    return NULL;
  }

dengyihao's avatar
dengyihao 已提交
2582
  for (int32_t i = 0; i < size; ++i) {
2583
    SPhysiNode* pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
2584
    ops[i] = createOperatorTree(pChildNode, pTaskInfo, pHandle, pTagCond, pTagIndexCond, pUser);
2585
    if (ops[i] == NULL) {
H
Haojun Liao 已提交
2586
      taosMemoryFree(ops);
2587 2588
      return NULL;
    }
2589
  }
H
Haojun Liao 已提交
2590

2591
  SOperatorInfo* pOptr = NULL;
H
Haojun Liao 已提交
2592
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
2593
    pOptr = createProjectOperatorInfo(ops[0], (SProjectPhysiNode*)pPhyNode, pTaskInfo);
2594
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_AGG == type) {
H
Haojun Liao 已提交
2595 2596
    SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
    if (pAggNode->pGroupKeys != NULL) {
H
Haojun Liao 已提交
2597
      pOptr = createGroupOperatorInfo(ops[0], pAggNode, pTaskInfo);
H
Haojun Liao 已提交
2598
    } else {
H
Haojun Liao 已提交
2599
      pOptr = createAggregateOperatorInfo(ops[0], pAggNode, pTaskInfo);
H
Haojun Liao 已提交
2600
    }
2601
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_INTERVAL == type) {
H
Haojun Liao 已提交
2602
    SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
2603

H
Haojun Liao 已提交
2604 2605
    bool isStream = (QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type);
    pOptr = createIntervalOperatorInfo(ops[0], pIntervalPhyNode, pTaskInfo, isStream);
2606
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type) {
2607
    pOptr = createStreamIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo);
2608 2609
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_ALIGNED_INTERVAL == type) {
    SMergeAlignedIntervalPhysiNode* pIntervalPhyNode = (SMergeAlignedIntervalPhysiNode*)pPhyNode;
2610
    pOptr = createMergeAlignedIntervalOperatorInfo(ops[0], pIntervalPhyNode, pTaskInfo);
S
shenglian zhou 已提交
2611
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_INTERVAL == type) {
X
Xiaoyu Wang 已提交
2612
    SMergeIntervalPhysiNode* pIntervalPhyNode = (SMergeIntervalPhysiNode*)pPhyNode;
2613
    pOptr = createMergeIntervalOperatorInfo(ops[0], pIntervalPhyNode, pTaskInfo);
5
54liuyao 已提交
2614
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SEMI_INTERVAL == type) {
2615
    int32_t children = 0;
5
54liuyao 已提交
2616 2617
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_FINAL_INTERVAL == type) {
5
54liuyao 已提交
2618
    int32_t children = pHandle->numOfVgroups;
5
54liuyao 已提交
2619
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
H
Haojun Liao 已提交
2620
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == type) {
2621
    pOptr = createSortOperatorInfo(ops[0], (SSortPhysiNode*)pPhyNode, pTaskInfo);
S
shenglian zhou 已提交
2622 2623
  } else if (QUERY_NODE_PHYSICAL_PLAN_GROUP_SORT == type) {
    pOptr = createGroupSortOperatorInfo(ops[0], (SGroupSortPhysiNode*)pPhyNode, pTaskInfo);
X
Xiaoyu Wang 已提交
2624
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE == type) {
2625
    SMergePhysiNode* pMergePhyNode = (SMergePhysiNode*)pPhyNode;
2626
    pOptr = createMultiwayMergeOperatorInfo(ops, size, pMergePhyNode, pTaskInfo);
2627
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_SESSION == type) {
H
Haojun Liao 已提交
2628
    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
2629
    pOptr = createSessionAggOperatorInfo(ops[0], pSessionNode, pTaskInfo);
2630
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION == type) {
2631 2632 2633 2634 2635
    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) {
2636
    int32_t children = pHandle->numOfVgroups;
2637
    pOptr = createStreamFinalSessionAggOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
H
Haojun Liao 已提交
2638
  } else if (QUERY_NODE_PHYSICAL_PLAN_PARTITION == type) {
2639
    pOptr = createPartitionOperatorInfo(ops[0], (SPartitionPhysiNode*)pPhyNode, pTaskInfo);
2640
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_PARTITION == type) {
2641
    pOptr = createStreamPartitionOperatorInfo(ops[0], (SStreamPartitionPhysiNode*)pPhyNode, pTaskInfo);
2642
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_STATE == type) {
dengyihao's avatar
dengyihao 已提交
2643
    SStateWinodwPhysiNode* pStateNode = (SStateWinodwPhysiNode*)pPhyNode;
2644
    pOptr = createStatewindowOperatorInfo(ops[0], pStateNode, pTaskInfo);
2645
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_STATE == type) {
5
54liuyao 已提交
2646
    pOptr = createStreamStateAggOperatorInfo(ops[0], pPhyNode, pTaskInfo);
2647
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_JOIN == type) {
2648
    pOptr = createMergeJoinOperatorInfo(ops, size, (SSortMergeJoinPhysiNode*)pPhyNode, pTaskInfo);
2649
  } else if (QUERY_NODE_PHYSICAL_PLAN_FILL == type) {
H
Haojun Liao 已提交
2650
    pOptr = createFillOperatorInfo(ops[0], (SFillPhysiNode*)pPhyNode, pTaskInfo);
5
54liuyao 已提交
2651 2652
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_FILL == type) {
    pOptr = createStreamFillOperatorInfo(ops[0], (SStreamFillPhysiNode*)pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
2653 2654
  } else if (QUERY_NODE_PHYSICAL_PLAN_INDEF_ROWS_FUNC == type) {
    pOptr = createIndefinitOutputOperatorInfo(ops[0], pPhyNode, pTaskInfo);
2655 2656
  } else if (QUERY_NODE_PHYSICAL_PLAN_INTERP_FUNC == type) {
    pOptr = createTimeSliceOperatorInfo(ops[0], pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
2657 2658
  } else {
    ASSERT(0);
H
Haojun Liao 已提交
2659
  }
2660

2661
  taosMemoryFree(ops);
2662 2663 2664 2665
  if (pOptr) {
    pOptr->resultDataBlockId = pPhyNode->pOutputDataBlockDesc->dataBlockId;
  }

2666
  return pOptr;
2667
}
H
Haojun Liao 已提交
2668

L
Liu Jicong 已提交
2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681
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 {
2682 2683 2684
    SStreamScanInfo* pInfo = pOperator->info;
    ASSERT(pInfo->pTableScanOp->operatorType == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN);
    *ppInfo = pInfo->pTableScanOp->info;
L
Liu Jicong 已提交
2685 2686 2687 2688
    return 0;
  }
}

2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710
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;
}

2711
#if 0
L
Liu Jicong 已提交
2712 2713 2714 2715 2716
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;
  }
2717

L
Liu Jicong 已提交
2718 2719 2720 2721
  STableScanPhysiNode* pNode = NULL;
  if (extractTableScanNode(plan->pNode, &pNode) < 0) {
    ASSERT(0);
  }
2722

H
Haojun Liao 已提交
2723
  tsdbReaderClose(pTableScanInfo->dataReader);
2724

L
Liu Jicong 已提交
2725
  STableListInfo info = {0};
H
Haojun Liao 已提交
2726
  pTableScanInfo->dataReader = doCreateDataReader(pNode, pHandle, &info, NULL);
L
Liu Jicong 已提交
2727 2728 2729 2730
  if (pTableScanInfo->dataReader == NULL) {
    ASSERT(0);
    qError("failed to create data reader");
    return TSDB_CODE_QRY_APP_ERROR;
2731
  }
L
Liu Jicong 已提交
2732
  // TODO: set uid and ts to data reader
2733 2734
  return 0;
}
2735
#endif
2736

C
Cary Xu 已提交
2737
int32_t encodeOperator(SOperatorInfo* ops, char** result, int32_t* length, int32_t* nOptrWithVal) {
wmmhello's avatar
wmmhello 已提交
2738
  int32_t code = TDB_CODE_SUCCESS;
2739
  char*   pCurrent = NULL;
wmmhello's avatar
wmmhello 已提交
2740
  int32_t currLength = 0;
2741
  if (ops->fpSet.encodeResultRow) {
C
Cary Xu 已提交
2742
    if (result == NULL || length == NULL || nOptrWithVal == NULL) {
wmmhello's avatar
wmmhello 已提交
2743 2744 2745
      return TSDB_CODE_TSC_INVALID_INPUT;
    }
    code = ops->fpSet.encodeResultRow(ops, &pCurrent, &currLength);
wmmhello's avatar
wmmhello 已提交
2746

2747 2748
    if (code != TDB_CODE_SUCCESS) {
      if (*result != NULL) {
wmmhello's avatar
wmmhello 已提交
2749 2750 2751 2752
        taosMemoryFree(*result);
        *result = NULL;
      }
      return code;
C
Cary Xu 已提交
2753 2754 2755
    } else if (currLength == 0) {
      ASSERT(!pCurrent);
      goto _downstream;
wmmhello's avatar
wmmhello 已提交
2756
    }
wmmhello's avatar
wmmhello 已提交
2757

C
Cary Xu 已提交
2758 2759
    ++(*nOptrWithVal);

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

2762
    if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
2763
      *result = (char*)taosMemoryCalloc(1, currLength + sizeof(int32_t));
wmmhello's avatar
wmmhello 已提交
2764 2765 2766 2767 2768 2769
      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);
2770
    } else {
wmmhello's avatar
wmmhello 已提交
2771
      int32_t sizePre = *(int32_t*)(*result);
2772
      char*   tmp = (char*)taosMemoryRealloc(*result, sizePre + currLength);
wmmhello's avatar
wmmhello 已提交
2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784
      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 已提交
2785 2786
  }

2787
_downstream:
wmmhello's avatar
wmmhello 已提交
2788
  for (int32_t i = 0; i < ops->numOfDownstream; ++i) {
C
Cary Xu 已提交
2789
    code = encodeOperator(ops->pDownstream[i], result, length, nOptrWithVal);
2790
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
2791
      return code;
wmmhello's avatar
wmmhello 已提交
2792 2793
    }
  }
wmmhello's avatar
wmmhello 已提交
2794
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
2795 2796
}

H
Haojun Liao 已提交
2797
int32_t decodeOperator(SOperatorInfo* ops, const char* result, int32_t length) {
wmmhello's avatar
wmmhello 已提交
2798
  int32_t code = TDB_CODE_SUCCESS;
2799 2800
  if (ops->fpSet.decodeResultRow) {
    if (result == NULL) {
wmmhello's avatar
wmmhello 已提交
2801 2802
      return TSDB_CODE_TSC_INVALID_INPUT;
    }
H
Haojun Liao 已提交
2803

2804
    ASSERT(length == *(int32_t*)result);
H
Haojun Liao 已提交
2805 2806

    const char* data = result + sizeof(int32_t);
L
Liu Jicong 已提交
2807
    code = ops->fpSet.decodeResultRow(ops, (char*)data);
2808
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
2809 2810
      return code;
    }
wmmhello's avatar
wmmhello 已提交
2811

wmmhello's avatar
wmmhello 已提交
2812
    int32_t totalLength = *(int32_t*)result;
2813 2814
    int32_t dataLength = *(int32_t*)data;

2815
    if (totalLength == dataLength + sizeof(int32_t)) {  // the last data
wmmhello's avatar
wmmhello 已提交
2816 2817
      result = NULL;
      length = 0;
2818
    } else {
wmmhello's avatar
wmmhello 已提交
2819 2820 2821 2822
      result += dataLength;
      *(int32_t*)(result) = totalLength - dataLength;
      length = totalLength - dataLength;
    }
wmmhello's avatar
wmmhello 已提交
2823 2824
  }

wmmhello's avatar
wmmhello 已提交
2825 2826
  for (int32_t i = 0; i < ops->numOfDownstream; ++i) {
    code = decodeOperator(ops->pDownstream[i], result, length);
2827
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
2828
      return code;
wmmhello's avatar
wmmhello 已提交
2829 2830
    }
  }
wmmhello's avatar
wmmhello 已提交
2831
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
2832 2833
}

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

D
dapan1121 已提交
2837
  switch (pNode->type) {
D
dapan1121 已提交
2838 2839 2840 2841 2842 2843
    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 已提交
2844

D
dapan1121 已提交
2845 2846 2847
      *pParam = pInserterParam;
      break;
    }
D
dapan1121 已提交
2848
    case QUERY_NODE_PHYSICAL_PLAN_DELETE: {
2849
      SDeleterParam* pDeleterParam = taosMemoryCalloc(1, sizeof(SDeleterParam));
D
dapan1121 已提交
2850 2851 2852
      if (NULL == pDeleterParam) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
H
Haojun Liao 已提交
2853 2854 2855 2856
      int32_t tbNum = tableListGetSize(pTask->pTableInfoList);
      pDeleterParam->suid = tableListGetSuid(pTask->pTableInfoList);

      // TODO extract uid list
D
dapan1121 已提交
2857 2858 2859 2860 2861
      pDeleterParam->pUidList = taosArrayInit(tbNum, sizeof(uint64_t));
      if (NULL == pDeleterParam->pUidList) {
        taosMemoryFree(pDeleterParam);
        return TSDB_CODE_OUT_OF_MEMORY;
      }
H
Haojun Liao 已提交
2862

D
dapan1121 已提交
2863
      for (int32_t i = 0; i < tbNum; ++i) {
H
Haojun Liao 已提交
2864
        STableKeyInfo* pTable = tableListGetInfo(pTask->pTableInfoList, i);
D
dapan1121 已提交
2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877
        taosArrayPush(pDeleterParam->pUidList, &pTable->uid);
      }

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

  return TSDB_CODE_SUCCESS;
}

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

D
dapan1121 已提交
2882
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model, pPlan->dbFName);
H
Haojun Liao 已提交
2883 2884 2885
  if (*pTaskInfo == NULL) {
    goto _complete;
  }
H
Haojun Liao 已提交
2886

2887
  if (pHandle) {
L
Liu Jicong 已提交
2888
    /*(*pTaskInfo)->streamInfo.fillHistoryVer1 = pHandle->fillHistoryVer1;*/
2889 2890 2891
    if (pHandle->pStateBackend) {
      (*pTaskInfo)->streamInfo.pState = pHandle->pStateBackend;
    }
H
Haojun Liao 已提交
2892 2893
  }

2894
  (*pTaskInfo)->sql = sql;
D
dapan1121 已提交
2895
  sql = NULL;
H
Haojun Liao 已提交
2896

2897
  (*pTaskInfo)->pSubplan = pPlan;
2898 2899
  (*pTaskInfo)->pRoot =
      createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, pPlan->pTagCond, pPlan->pTagIndexCond, pPlan->user);
L
Liu Jicong 已提交
2900

D
dapan1121 已提交
2901
  if (NULL == (*pTaskInfo)->pRoot) {
H
Haojun Liao 已提交
2902
    terrno = (*pTaskInfo)->code;
D
dapan1121 已提交
2903
    goto _complete;
2904 2905
  }

H
Haojun Liao 已提交
2906
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2907

H
Haojun Liao 已提交
2908
_complete:
D
dapan1121 已提交
2909
  taosMemoryFree(sql);
H
Haojun Liao 已提交
2910
  doDestroyTask(*pTaskInfo);
H
Haojun Liao 已提交
2911
  return terrno;
H
Haojun Liao 已提交
2912 2913
}

H
Haojun Liao 已提交
2914 2915 2916 2917 2918
static void freeBlock(void* pParam) {
  SSDataBlock* pBlock = *(SSDataBlock**)pParam;
  blockDataDestroy(pBlock);
}

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

H
Haojun Liao 已提交
2922
  pTaskInfo->pTableInfoList = tableListDestroy(pTaskInfo->pTableInfoList);
H
Haojun Liao 已提交
2923
  destroyOperatorInfo(pTaskInfo->pRoot);
2924
  cleanupTableSchemaInfo(&pTaskInfo->schemaInfo);
2925
  cleanupStreamInfo(&pTaskInfo->streamInfo);
2926

D
dapan1121 已提交
2927
  if (!pTaskInfo->localFetch.localExec) {
D
dapan1121 已提交
2928 2929
    nodesDestroyNode((SNode*)pTaskInfo->pSubplan);
  }
2930

H
Haojun Liao 已提交
2931
  taosArrayDestroyEx(pTaskInfo->pResultBlockList, freeBlock);
D
dapan1121 已提交
2932
  taosArrayDestroy(pTaskInfo->stopInfo.pStopInfo);
wafwerar's avatar
wafwerar 已提交
2933 2934 2935
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
2936 2937 2938 2939
}

static int64_t getQuerySupportBufSize(size_t numOfTables) {
  size_t s1 = sizeof(STableQueryInfo);
L
Liu Jicong 已提交
2940 2941
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
2942 2943 2944 2945 2946 2947 2948
}

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 已提交
2949
    while (1) {
2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975
      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 已提交
2976

H
Haojun Liao 已提交
2977
int32_t getOperatorExplainExecInfo(SOperatorInfo* operatorInfo, SArray* pExecInfoList) {
2978
  SExplainExecInfo  execInfo = {0};
H
Haojun Liao 已提交
2979
  SExplainExecInfo* pExplainInfo = taosArrayPush(pExecInfoList, &execInfo);
2980

H
Haojun Liao 已提交
2981 2982 2983 2984 2985
  pExplainInfo->numOfRows = operatorInfo->resultInfo.totalRows;
  pExplainInfo->startupCost = operatorInfo->cost.openCost;
  pExplainInfo->totalCost = operatorInfo->cost.totalCost;
  pExplainInfo->verboseLen = 0;
  pExplainInfo->verboseInfo = NULL;
D
dapan1121 已提交
2986

2987
  if (operatorInfo->fpSet.getExplainFn) {
2988 2989
    int32_t code =
        operatorInfo->fpSet.getExplainFn(operatorInfo, &pExplainInfo->verboseInfo, &pExplainInfo->verboseLen);
D
dapan1121 已提交
2990
    if (code) {
2991
      qError("%s operator getExplainFn failed, code:%s", GET_TASKID(operatorInfo->pTaskInfo), tstrerror(code));
D
dapan1121 已提交
2992 2993 2994
      return code;
    }
  }
dengyihao's avatar
dengyihao 已提交
2995

D
dapan1121 已提交
2996
  int32_t code = 0;
D
dapan1121 已提交
2997
  for (int32_t i = 0; i < operatorInfo->numOfDownstream; ++i) {
H
Haojun Liao 已提交
2998 2999
    code = getOperatorExplainExecInfo(operatorInfo->pDownstream[i], pExecInfoList);
    if (code != TSDB_CODE_SUCCESS) {
3000
      //      taosMemoryFreeClear(*pRes);
D
dapan1121 已提交
3001 3002 3003 3004 3005
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
3006
}
5
54liuyao 已提交
3007

3008 3009
int32_t setOutputBuf(SStreamState* pState, STimeWindow* win, SResultRow** pResult, int64_t tableGroupId,
                     SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowEntryInfoOffset, SAggSupporter* pAggSup) {
3010 3011 3012 3013 3014 3015
  SWinKey key = {
      .ts = win->skey,
      .groupId = tableGroupId,
  };
  char*   value = NULL;
  int32_t size = pAggSup->resultRowSize;
5
54liuyao 已提交
3016

3017
  if (streamStateAddIfNotExist(pState, &key, (void**)&value, &size) < 0) {
3018 3019 3020 3021 3022 3023 3024 3025 3026 3027
    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;
}

3028 3029
int32_t releaseOutputBuf(SStreamState* pState, SWinKey* pKey, SResultRow* pResult) {
  streamStateReleaseBuf(pState, pKey, pResult);
3030 3031 3032
  return TSDB_CODE_SUCCESS;
}

3033 3034
int32_t saveOutputBuf(SStreamState* pState, SWinKey* pKey, SResultRow* pResult, int32_t resSize) {
  streamStatePut(pState, pKey, pResult, resSize);
3035 3036 3037
  return TSDB_CODE_SUCCESS;
}

3038
int32_t buildDataBlockFromGroupRes(SOperatorInfo* pOperator, SStreamState* pState, SSDataBlock* pBlock, SExprSupp* pSup,
3039
                                   SGroupResInfo* pGroupResInfo) {
3040
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052
  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 = {
3053 3054
            .ts = *(TSKEY*)pPos->key,
            .groupId = pPos->groupId,
3055
    };
3056
    int32_t code = streamStateGet(pState, &key, &pVal, &size);
3057 3058 3059 3060 3061 3062
    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;
3063
      releaseOutputBuf(pState, &key, pRow);
3064 3065 3066 3067 3068
      continue;
    }

    if (pBlock->info.groupId == 0) {
      pBlock->info.groupId = pPos->groupId;
3069 3070
      void* tbname = NULL;
      if (streamStateGetParName(pTaskInfo->streamInfo.pState, pBlock->info.groupId, &tbname) < 0) {
L
Liu Jicong 已提交
3071
        pBlock->info.parTbName[0] = 0;
3072 3073
      } else {
        memcpy(pBlock->info.parTbName, tbname, TSDB_TABLE_NAME_LEN);
3074
      }
3075
      tdbFree(tbname);
3076 3077 3078
    } else {
      // current value belongs to different group, it can't be packed into one datablock
      if (pBlock->info.groupId != pPos->groupId) {
3079
        releaseOutputBuf(pState, &key, pRow);
3080 3081 3082 3083 3084 3085
        break;
      }
    }

    if (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
      ASSERT(pBlock->info.rows > 0);
3086
      releaseOutputBuf(pState, &key, pRow);
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096
      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) {
3097 3098 3099 3100
        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);
3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113
        }
      } 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 已提交
3114

3115
    pBlock->info.rows += pRow->numOfRows;
3116
    releaseOutputBuf(pState, &key, pRow);
3117 3118 3119 3120
  }
  blockDataUpdateTsWindow(pBlock, 0);
  return TSDB_CODE_SUCCESS;
}
5
54liuyao 已提交
3121 3122 3123 3124 3125 3126 3127

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

3128
int32_t buildSessionResultDataBlock(SOperatorInfo* pOperator, SStreamState* pState, SSDataBlock* pBlock,
5
54liuyao 已提交
3129
                                    SExprSupp* pSup, SGroupResInfo* pGroupResInfo) {
3130
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
5
54liuyao 已提交
3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143
  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);
3144 3145
    if (code == -1) {
      // coverity scan
5
54liuyao 已提交
3146
      pGroupResInfo->index += 1;
3147 3148
      continue;
    }
5
54liuyao 已提交
3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159
    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;
3160

3161 3162 3163
      void* tbname = NULL;
      if (streamStateGetParName(pTaskInfo->streamInfo.pState, pBlock->info.groupId, &tbname) < 0) {
        pBlock->info.parTbName[0] = 0;
3164
      } else {
3165
        memcpy(pBlock->info.parTbName, tbname, TSDB_TABLE_NAME_LEN);
3166
      }
3167
      tdbFree(tbname);
5
54liuyao 已提交
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 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
    } 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;
3213
}